Fix typo in 9b54bd30006c008b4a951331b273613d5bac3abf
[pm.git] / db / sqlite3 / src / sqlite3.c
blob320d6355e3bac58c1a27a9777338c410816be7eb
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.21.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.
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 *******************************************/
27 ** 2010 February 23
29 ** The author disclaims copyright to this source code. In place of
30 ** a legal notice, here is a blessing:
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.
36 *************************************************************************
38 ** This file implements routines used to report what compile-time options
39 ** SQLite was built with.
42 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
45 ** Include the configuration header output by 'configure' if we're using the
46 ** autoconf-based build
48 #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
49 #include "config.h"
50 #define SQLITECONFIG_H 1
51 #endif
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)
59 ** An array of names of all compile-time options. This array should
60 ** be sorted A-Z.
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.
66 static const char * const sqlite3azCompileOpt[] = {
68 /*
69 ** BEGIN CODE GENERATED BY tool/mkctime.tcl
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_BATCH_ATOMIC_WRITE
213 "ENABLE_BATCH_ATOMIC_WRITE",
214 #endif
215 #if SQLITE_ENABLE_CEROD
216 "ENABLE_CEROD",
217 #endif
218 #if SQLITE_ENABLE_COLUMN_METADATA
219 "ENABLE_COLUMN_METADATA",
220 #endif
221 #if SQLITE_ENABLE_COLUMN_USED_MASK
222 "ENABLE_COLUMN_USED_MASK",
223 #endif
224 #if SQLITE_ENABLE_COSTMULT
225 "ENABLE_COSTMULT",
226 #endif
227 #if SQLITE_ENABLE_CURSOR_HINTS
228 "ENABLE_CURSOR_HINTS",
229 #endif
230 #if SQLITE_ENABLE_DBSTAT_VTAB
231 "ENABLE_DBSTAT_VTAB",
232 #endif
233 #if SQLITE_ENABLE_EXPENSIVE_ASSERT
234 "ENABLE_EXPENSIVE_ASSERT",
235 #endif
236 #if SQLITE_ENABLE_FTS1
237 "ENABLE_FTS1",
238 #endif
239 #if SQLITE_ENABLE_FTS2
240 "ENABLE_FTS2",
241 #endif
242 #if SQLITE_ENABLE_FTS3
243 "ENABLE_FTS3",
244 #endif
245 #if SQLITE_ENABLE_FTS3_PARENTHESIS
246 "ENABLE_FTS3_PARENTHESIS",
247 #endif
248 #if SQLITE_ENABLE_FTS3_TOKENIZER
249 "ENABLE_FTS3_TOKENIZER",
250 #endif
251 #if SQLITE_ENABLE_FTS4
252 "ENABLE_FTS4",
253 #endif
254 #if SQLITE_ENABLE_FTS5
255 "ENABLE_FTS5",
256 #endif
257 #if SQLITE_ENABLE_HIDDEN_COLUMNS
258 "ENABLE_HIDDEN_COLUMNS",
259 #endif
260 #if SQLITE_ENABLE_ICU
261 "ENABLE_ICU",
262 #endif
263 #if SQLITE_ENABLE_IOTRACE
264 "ENABLE_IOTRACE",
265 #endif
266 #if SQLITE_ENABLE_JSON1
267 "ENABLE_JSON1",
268 #endif
269 #if SQLITE_ENABLE_LOAD_EXTENSION
270 "ENABLE_LOAD_EXTENSION",
271 #endif
272 #ifdef SQLITE_ENABLE_LOCKING_STYLE
273 "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
274 #endif
275 #if SQLITE_ENABLE_MEMORY_MANAGEMENT
276 "ENABLE_MEMORY_MANAGEMENT",
277 #endif
278 #if SQLITE_ENABLE_MEMSYS3
279 "ENABLE_MEMSYS3",
280 #endif
281 #if SQLITE_ENABLE_MEMSYS5
282 "ENABLE_MEMSYS5",
283 #endif
284 #if SQLITE_ENABLE_MULTIPLEX
285 "ENABLE_MULTIPLEX",
286 #endif
287 #if SQLITE_ENABLE_NULL_TRIM
288 "ENABLE_NULL_TRIM",
289 #endif
290 #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
291 "ENABLE_OVERSIZE_CELL_CHECK",
292 #endif
293 #if SQLITE_ENABLE_PREUPDATE_HOOK
294 "ENABLE_PREUPDATE_HOOK",
295 #endif
296 #if SQLITE_ENABLE_QPSG
297 "ENABLE_QPSG",
298 #endif
299 #if SQLITE_ENABLE_RBU
300 "ENABLE_RBU",
301 #endif
302 #if SQLITE_ENABLE_RTREE
303 "ENABLE_RTREE",
304 #endif
305 #if SQLITE_ENABLE_SELECTTRACE
306 "ENABLE_SELECTTRACE",
307 #endif
308 #if SQLITE_ENABLE_SESSION
309 "ENABLE_SESSION",
310 #endif
311 #if SQLITE_ENABLE_SNAPSHOT
312 "ENABLE_SNAPSHOT",
313 #endif
314 #if SQLITE_ENABLE_SQLLOG
315 "ENABLE_SQLLOG",
316 #endif
317 #if defined(SQLITE_ENABLE_STAT4)
318 "ENABLE_STAT4",
319 #elif defined(SQLITE_ENABLE_STAT3)
320 "ENABLE_STAT3",
321 #endif
322 #if SQLITE_ENABLE_STMTVTAB
323 "ENABLE_STMTVTAB",
324 #endif
325 #if SQLITE_ENABLE_STMT_SCANSTATUS
326 "ENABLE_STMT_SCANSTATUS",
327 #endif
328 #if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
329 "ENABLE_UNKNOWN_SQL_FUNCTION",
330 #endif
331 #if SQLITE_ENABLE_UNLOCK_NOTIFY
332 "ENABLE_UNLOCK_NOTIFY",
333 #endif
334 #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
335 "ENABLE_UPDATE_DELETE_LIMIT",
336 #endif
337 #if SQLITE_ENABLE_URI_00_ERROR
338 "ENABLE_URI_00_ERROR",
339 #endif
340 #if SQLITE_ENABLE_VFSTRACE
341 "ENABLE_VFSTRACE",
342 #endif
343 #if SQLITE_ENABLE_WHERETRACE
344 "ENABLE_WHERETRACE",
345 #endif
346 #if SQLITE_ENABLE_ZIPVFS
347 "ENABLE_ZIPVFS",
348 #endif
349 #if SQLITE_EXPLAIN_ESTIMATED_ROWS
350 "EXPLAIN_ESTIMATED_ROWS",
351 #endif
352 #if SQLITE_EXTRA_IFNULLROW
353 "EXTRA_IFNULLROW",
354 #endif
355 #ifdef SQLITE_EXTRA_INIT
356 "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
357 #endif
358 #ifdef SQLITE_EXTRA_SHUTDOWN
359 "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
360 #endif
361 #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
362 "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
363 #endif
364 #if SQLITE_FTS5_ENABLE_TEST_MI
365 "FTS5_ENABLE_TEST_MI",
366 #endif
367 #if SQLITE_FTS5_NO_WITHOUT_ROWID
368 "FTS5_NO_WITHOUT_ROWID",
369 #endif
370 #if SQLITE_HAS_CODEC
371 "HAS_CODEC",
372 #endif
373 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
374 "HAVE_ISNAN",
375 #endif
376 #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
377 "HOMEGROWN_RECURSIVE_MUTEX",
378 #endif
379 #if SQLITE_IGNORE_AFP_LOCK_ERRORS
380 "IGNORE_AFP_LOCK_ERRORS",
381 #endif
382 #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
383 "IGNORE_FLOCK_LOCK_ERRORS",
384 #endif
385 #if SQLITE_INLINE_MEMCPY
386 "INLINE_MEMCPY",
387 #endif
388 #if SQLITE_INT64_TYPE
389 "INT64_TYPE",
390 #endif
391 #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
392 "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
393 #endif
394 #if SQLITE_LIKE_DOESNT_MATCH_BLOBS
395 "LIKE_DOESNT_MATCH_BLOBS",
396 #endif
397 #if SQLITE_LOCK_TRACE
398 "LOCK_TRACE",
399 #endif
400 #if SQLITE_LOG_CACHE_SPILL
401 "LOG_CACHE_SPILL",
402 #endif
403 #ifdef SQLITE_MALLOC_SOFT_LIMIT
404 "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
405 #endif
406 #ifdef SQLITE_MAX_ATTACHED
407 "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
408 #endif
409 #ifdef SQLITE_MAX_COLUMN
410 "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
411 #endif
412 #ifdef SQLITE_MAX_COMPOUND_SELECT
413 "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
414 #endif
415 #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
416 "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
417 #endif
418 #ifdef SQLITE_MAX_EXPR_DEPTH
419 "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
420 #endif
421 #ifdef SQLITE_MAX_FUNCTION_ARG
422 "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
423 #endif
424 #ifdef SQLITE_MAX_LENGTH
425 "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
426 #endif
427 #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
428 "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
429 #endif
430 #ifdef SQLITE_MAX_MEMORY
431 "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
432 #endif
433 #ifdef SQLITE_MAX_MMAP_SIZE
434 "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
435 #endif
436 #ifdef SQLITE_MAX_MMAP_SIZE_
437 "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
438 #endif
439 #ifdef SQLITE_MAX_PAGE_COUNT
440 "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
441 #endif
442 #ifdef SQLITE_MAX_PAGE_SIZE
443 "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
444 #endif
445 #ifdef SQLITE_MAX_SCHEMA_RETRY
446 "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
447 #endif
448 #ifdef SQLITE_MAX_SQL_LENGTH
449 "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
450 #endif
451 #ifdef SQLITE_MAX_TRIGGER_DEPTH
452 "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
453 #endif
454 #ifdef SQLITE_MAX_VARIABLE_NUMBER
455 "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
456 #endif
457 #ifdef SQLITE_MAX_VDBE_OP
458 "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
459 #endif
460 #ifdef SQLITE_MAX_WORKER_THREADS
461 "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
462 #endif
463 #if SQLITE_MEMDEBUG
464 "MEMDEBUG",
465 #endif
466 #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
467 "MIXED_ENDIAN_64BIT_FLOAT",
468 #endif
469 #if SQLITE_MMAP_READWRITE
470 "MMAP_READWRITE",
471 #endif
472 #if SQLITE_MUTEX_NOOP
473 "MUTEX_NOOP",
474 #endif
475 #if SQLITE_MUTEX_NREF
476 "MUTEX_NREF",
477 #endif
478 #if SQLITE_MUTEX_OMIT
479 "MUTEX_OMIT",
480 #endif
481 #if SQLITE_MUTEX_PTHREADS
482 "MUTEX_PTHREADS",
483 #endif
484 #if SQLITE_MUTEX_W32
485 "MUTEX_W32",
486 #endif
487 #if SQLITE_NEED_ERR_NAME
488 "NEED_ERR_NAME",
489 #endif
490 #if SQLITE_NOINLINE
491 "NOINLINE",
492 #endif
493 #if SQLITE_NO_SYNC
494 "NO_SYNC",
495 #endif
496 #if SQLITE_OMIT_ALTERTABLE
497 "OMIT_ALTERTABLE",
498 #endif
499 #if SQLITE_OMIT_ANALYZE
500 "OMIT_ANALYZE",
501 #endif
502 #if SQLITE_OMIT_ATTACH
503 "OMIT_ATTACH",
504 #endif
505 #if SQLITE_OMIT_AUTHORIZATION
506 "OMIT_AUTHORIZATION",
507 #endif
508 #if SQLITE_OMIT_AUTOINCREMENT
509 "OMIT_AUTOINCREMENT",
510 #endif
511 #if SQLITE_OMIT_AUTOINIT
512 "OMIT_AUTOINIT",
513 #endif
514 #if SQLITE_OMIT_AUTOMATIC_INDEX
515 "OMIT_AUTOMATIC_INDEX",
516 #endif
517 #if SQLITE_OMIT_AUTORESET
518 "OMIT_AUTORESET",
519 #endif
520 #if SQLITE_OMIT_AUTOVACUUM
521 "OMIT_AUTOVACUUM",
522 #endif
523 #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
524 "OMIT_BETWEEN_OPTIMIZATION",
525 #endif
526 #if SQLITE_OMIT_BLOB_LITERAL
527 "OMIT_BLOB_LITERAL",
528 #endif
529 #if SQLITE_OMIT_BTREECOUNT
530 "OMIT_BTREECOUNT",
531 #endif
532 #if SQLITE_OMIT_CAST
533 "OMIT_CAST",
534 #endif
535 #if SQLITE_OMIT_CHECK
536 "OMIT_CHECK",
537 #endif
538 #if SQLITE_OMIT_COMPLETE
539 "OMIT_COMPLETE",
540 #endif
541 #if SQLITE_OMIT_COMPOUND_SELECT
542 "OMIT_COMPOUND_SELECT",
543 #endif
544 #if SQLITE_OMIT_CONFLICT_CLAUSE
545 "OMIT_CONFLICT_CLAUSE",
546 #endif
547 #if SQLITE_OMIT_CTE
548 "OMIT_CTE",
549 #endif
550 #if SQLITE_OMIT_DATETIME_FUNCS
551 "OMIT_DATETIME_FUNCS",
552 #endif
553 #if SQLITE_OMIT_DECLTYPE
554 "OMIT_DECLTYPE",
555 #endif
556 #if SQLITE_OMIT_DEPRECATED
557 "OMIT_DEPRECATED",
558 #endif
559 #if SQLITE_OMIT_DISKIO
560 "OMIT_DISKIO",
561 #endif
562 #if SQLITE_OMIT_EXPLAIN
563 "OMIT_EXPLAIN",
564 #endif
565 #if SQLITE_OMIT_FLAG_PRAGMAS
566 "OMIT_FLAG_PRAGMAS",
567 #endif
568 #if SQLITE_OMIT_FLOATING_POINT
569 "OMIT_FLOATING_POINT",
570 #endif
571 #if SQLITE_OMIT_FOREIGN_KEY
572 "OMIT_FOREIGN_KEY",
573 #endif
574 #if SQLITE_OMIT_GET_TABLE
575 "OMIT_GET_TABLE",
576 #endif
577 #if SQLITE_OMIT_HEX_INTEGER
578 "OMIT_HEX_INTEGER",
579 #endif
580 #if SQLITE_OMIT_INCRBLOB
581 "OMIT_INCRBLOB",
582 #endif
583 #if SQLITE_OMIT_INTEGRITY_CHECK
584 "OMIT_INTEGRITY_CHECK",
585 #endif
586 #if SQLITE_OMIT_LIKE_OPTIMIZATION
587 "OMIT_LIKE_OPTIMIZATION",
588 #endif
589 #if SQLITE_OMIT_LOAD_EXTENSION
590 "OMIT_LOAD_EXTENSION",
591 #endif
592 #if SQLITE_OMIT_LOCALTIME
593 "OMIT_LOCALTIME",
594 #endif
595 #if SQLITE_OMIT_LOOKASIDE
596 "OMIT_LOOKASIDE",
597 #endif
598 #if SQLITE_OMIT_MEMORYDB
599 "OMIT_MEMORYDB",
600 #endif
601 #if SQLITE_OMIT_OR_OPTIMIZATION
602 "OMIT_OR_OPTIMIZATION",
603 #endif
604 #if SQLITE_OMIT_PAGER_PRAGMAS
605 "OMIT_PAGER_PRAGMAS",
606 #endif
607 #if SQLITE_OMIT_PARSER_TRACE
608 "OMIT_PARSER_TRACE",
609 #endif
610 #if SQLITE_OMIT_POPEN
611 "OMIT_POPEN",
612 #endif
613 #if SQLITE_OMIT_PRAGMA
614 "OMIT_PRAGMA",
615 #endif
616 #if SQLITE_OMIT_PROGRESS_CALLBACK
617 "OMIT_PROGRESS_CALLBACK",
618 #endif
619 #if SQLITE_OMIT_QUICKBALANCE
620 "OMIT_QUICKBALANCE",
621 #endif
622 #if SQLITE_OMIT_REINDEX
623 "OMIT_REINDEX",
624 #endif
625 #if SQLITE_OMIT_SCHEMA_PRAGMAS
626 "OMIT_SCHEMA_PRAGMAS",
627 #endif
628 #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
629 "OMIT_SCHEMA_VERSION_PRAGMAS",
630 #endif
631 #if SQLITE_OMIT_SHARED_CACHE
632 "OMIT_SHARED_CACHE",
633 #endif
634 #if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
635 "OMIT_SHUTDOWN_DIRECTORIES",
636 #endif
637 #if SQLITE_OMIT_SUBQUERY
638 "OMIT_SUBQUERY",
639 #endif
640 #if SQLITE_OMIT_TCL_VARIABLE
641 "OMIT_TCL_VARIABLE",
642 #endif
643 #if SQLITE_OMIT_TEMPDB
644 "OMIT_TEMPDB",
645 #endif
646 #if SQLITE_OMIT_TEST_CONTROL
647 "OMIT_TEST_CONTROL",
648 #endif
649 #if SQLITE_OMIT_TRACE
650 "OMIT_TRACE",
651 #endif
652 #if SQLITE_OMIT_TRIGGER
653 "OMIT_TRIGGER",
654 #endif
655 #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
656 "OMIT_TRUNCATE_OPTIMIZATION",
657 #endif
658 #if SQLITE_OMIT_UTF16
659 "OMIT_UTF16",
660 #endif
661 #if SQLITE_OMIT_VACUUM
662 "OMIT_VACUUM",
663 #endif
664 #if SQLITE_OMIT_VIEW
665 "OMIT_VIEW",
666 #endif
667 #if SQLITE_OMIT_VIRTUALTABLE
668 "OMIT_VIRTUALTABLE",
669 #endif
670 #if SQLITE_OMIT_WAL
671 "OMIT_WAL",
672 #endif
673 #if SQLITE_OMIT_WSD
674 "OMIT_WSD",
675 #endif
676 #if SQLITE_OMIT_XFER_OPT
677 "OMIT_XFER_OPT",
678 #endif
679 #if SQLITE_PCACHE_SEPARATE_HEADER
680 "PCACHE_SEPARATE_HEADER",
681 #endif
682 #if SQLITE_PERFORMANCE_TRACE
683 "PERFORMANCE_TRACE",
684 #endif
685 #if SQLITE_POWERSAFE_OVERWRITE
686 "POWERSAFE_OVERWRITE",
687 #endif
688 #if SQLITE_PREFER_PROXY_LOCKING
689 "PREFER_PROXY_LOCKING",
690 #endif
691 #if SQLITE_PROXY_DEBUG
692 "PROXY_DEBUG",
693 #endif
694 #if SQLITE_REVERSE_UNORDERED_SELECTS
695 "REVERSE_UNORDERED_SELECTS",
696 #endif
697 #if SQLITE_RTREE_INT_ONLY
698 "RTREE_INT_ONLY",
699 #endif
700 #if SQLITE_SECURE_DELETE
701 "SECURE_DELETE",
702 #endif
703 #if SQLITE_SMALL_STACK
704 "SMALL_STACK",
705 #endif
706 #ifdef SQLITE_SORTER_PMASZ
707 "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
708 #endif
709 #if SQLITE_SOUNDEX
710 "SOUNDEX",
711 #endif
712 #ifdef SQLITE_STAT4_SAMPLES
713 "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
714 #endif
715 #ifdef SQLITE_STMTJRNL_SPILL
716 "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
717 #endif
718 #if SQLITE_SUBSTR_COMPATIBILITY
719 "SUBSTR_COMPATIBILITY",
720 #endif
721 #if SQLITE_SYSTEM_MALLOC
722 "SYSTEM_MALLOC",
723 #endif
724 #if SQLITE_TCL
725 "TCL",
726 #endif
727 #ifdef SQLITE_TEMP_STORE
728 "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
729 #endif
730 #if SQLITE_TEST
731 "TEST",
732 #endif
733 #if defined(SQLITE_THREADSAFE)
734 "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
735 #elif defined(THREADSAFE)
736 "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
737 #else
738 "THREADSAFE=1",
739 #endif
740 #if SQLITE_UNLINK_AFTER_CLOSE
741 "UNLINK_AFTER_CLOSE",
742 #endif
743 #if SQLITE_UNTESTABLE
744 "UNTESTABLE",
745 #endif
746 #if SQLITE_USER_AUTHENTICATION
747 "USER_AUTHENTICATION",
748 #endif
749 #if SQLITE_USE_ALLOCA
750 "USE_ALLOCA",
751 #endif
752 #if SQLITE_USE_FCNTL_TRACE
753 "USE_FCNTL_TRACE",
754 #endif
755 #if SQLITE_USE_URI
756 "USE_URI",
757 #endif
758 #if SQLITE_VDBE_COVERAGE
759 "VDBE_COVERAGE",
760 #endif
761 #if SQLITE_WIN32_MALLOC
762 "WIN32_MALLOC",
763 #endif
764 #if SQLITE_ZERO_MALLOC
765 "ZERO_MALLOC",
766 #endif
768 ** END CODE GENERATED BY tool/mkctime.tcl
772 SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
773 *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
774 return (const char**)sqlite3azCompileOpt;
777 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
779 /************** End of ctime.c ***********************************************/
780 /************** Begin file sqliteInt.h ***************************************/
782 ** 2001 September 15
784 ** The author disclaims copyright to this source code. In place of
785 ** a legal notice, here is a blessing:
787 ** May you do good and not evil.
788 ** May you find forgiveness for yourself and forgive others.
789 ** May you share freely, never taking more than you give.
791 *************************************************************************
792 ** Internal interface definitions for SQLite.
795 #ifndef SQLITEINT_H
796 #define SQLITEINT_H
798 /* Special Comments:
800 ** Some comments have special meaning to the tools that measure test
801 ** coverage:
803 ** NO_TEST - The branches on this line are not
804 ** measured by branch coverage. This is
805 ** used on lines of code that actually
806 ** implement parts of coverage testing.
808 ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
809 ** and the correct answer is still obtained,
810 ** though perhaps more slowly.
812 ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
813 ** and the correct answer is still obtained,
814 ** though perhaps more slowly.
816 ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
817 ** that would be harmless and undetectable
818 ** if it did occur.
820 ** In all cases, the special comment must be enclosed in the usual
821 ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
822 ** asterisks and the comment text.
826 ** Make sure the Tcl calling convention macro is defined. This macro is
827 ** only used by test code and Tcl integration code.
829 #ifndef SQLITE_TCLAPI
830 # define SQLITE_TCLAPI
831 #endif
834 ** Include the header file used to customize the compiler options for MSVC.
835 ** This should be done first so that it can successfully prevent spurious
836 ** compiler warnings due to subsequent content in this file and other files
837 ** that are included by this file.
839 /************** Include msvc.h in the middle of sqliteInt.h ******************/
840 /************** Begin file msvc.h ********************************************/
842 ** 2015 January 12
844 ** The author disclaims copyright to this source code. In place of
845 ** a legal notice, here is a blessing:
847 ** May you do good and not evil.
848 ** May you find forgiveness for yourself and forgive others.
849 ** May you share freely, never taking more than you give.
851 ******************************************************************************
853 ** This file contains code that is specific to MSVC.
855 #ifndef SQLITE_MSVC_H
856 #define SQLITE_MSVC_H
858 #if defined(_MSC_VER)
859 #pragma warning(disable : 4054)
860 #pragma warning(disable : 4055)
861 #pragma warning(disable : 4100)
862 #pragma warning(disable : 4127)
863 #pragma warning(disable : 4130)
864 #pragma warning(disable : 4152)
865 #pragma warning(disable : 4189)
866 #pragma warning(disable : 4206)
867 #pragma warning(disable : 4210)
868 #pragma warning(disable : 4232)
869 #pragma warning(disable : 4244)
870 #pragma warning(disable : 4305)
871 #pragma warning(disable : 4306)
872 #pragma warning(disable : 4702)
873 #pragma warning(disable : 4706)
874 #endif /* defined(_MSC_VER) */
876 #endif /* SQLITE_MSVC_H */
878 /************** End of msvc.h ************************************************/
879 /************** Continuing where we left off in sqliteInt.h ******************/
882 ** Special setup for VxWorks
884 /************** Include vxworks.h in the middle of sqliteInt.h ***************/
885 /************** Begin file vxworks.h *****************************************/
887 ** 2015-03-02
889 ** The author disclaims copyright to this source code. In place of
890 ** a legal notice, here is a blessing:
892 ** May you do good and not evil.
893 ** May you find forgiveness for yourself and forgive others.
894 ** May you share freely, never taking more than you give.
896 ******************************************************************************
898 ** This file contains code that is specific to Wind River's VxWorks
900 #if defined(__RTP__) || defined(_WRS_KERNEL)
901 /* This is VxWorks. Set up things specially for that OS
903 #include <vxWorks.h>
904 #include <pthread.h> /* amalgamator: dontcache */
905 #define OS_VXWORKS 1
906 #define SQLITE_OS_OTHER 0
907 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
908 #define SQLITE_OMIT_LOAD_EXTENSION 1
909 #define SQLITE_ENABLE_LOCKING_STYLE 0
910 #define HAVE_UTIME 1
911 #else
912 /* This is not VxWorks. */
913 #define OS_VXWORKS 0
914 #define HAVE_FCHOWN 1
915 #define HAVE_READLINK 1
916 #define HAVE_LSTAT 1
917 #endif /* defined(_WRS_KERNEL) */
919 /************** End of vxworks.h *********************************************/
920 /************** Continuing where we left off in sqliteInt.h ******************/
923 ** These #defines should enable >2GB file support on POSIX if the
924 ** underlying operating system supports it. If the OS lacks
925 ** large file support, or if the OS is windows, these should be no-ops.
927 ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
928 ** system #includes. Hence, this block of code must be the very first
929 ** code in all source files.
931 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
932 ** on the compiler command line. This is necessary if you are compiling
933 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
934 ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
935 ** without this option, LFS is enable. But LFS does not exist in the kernel
936 ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
937 ** portability you should omit LFS.
939 ** The previous paragraph was written in 2005. (This paragraph is written
940 ** on 2008-11-28.) These days, all Linux kernels support large files, so
941 ** you should probably leave LFS enabled. But some embedded platforms might
942 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
944 ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
946 #ifndef SQLITE_DISABLE_LFS
947 # define _LARGE_FILE 1
948 # ifndef _FILE_OFFSET_BITS
949 # define _FILE_OFFSET_BITS 64
950 # endif
951 # define _LARGEFILE_SOURCE 1
952 #endif
954 /* The GCC_VERSION and MSVC_VERSION macros are used to
955 ** conditionally include optimizations for each of these compilers. A
956 ** value of 0 means that compiler is not being used. The
957 ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
958 ** optimizations, and hence set all compiler macros to 0
960 ** There was once also a CLANG_VERSION macro. However, we learn that the
961 ** version numbers in clang are for "marketing" only and are inconsistent
962 ** and unreliable. Fortunately, all versions of clang also recognize the
963 ** gcc version numbers and have reasonable settings for gcc version numbers,
964 ** so the GCC_VERSION macro will be set to a correct non-zero value even
965 ** when compiling with clang.
967 #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
968 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
969 #else
970 # define GCC_VERSION 0
971 #endif
972 #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
973 # define MSVC_VERSION _MSC_VER
974 #else
975 # define MSVC_VERSION 0
976 #endif
978 /* Needed for various definitions... */
979 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
980 # define _GNU_SOURCE
981 #endif
983 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
984 # define _BSD_SOURCE
985 #endif
988 ** For MinGW, check to see if we can include the header file containing its
989 ** version information, among other things. Normally, this internal MinGW
990 ** header file would [only] be included automatically by other MinGW header
991 ** files; however, the contained version information is now required by this
992 ** header file to work around binary compatibility issues (see below) and
993 ** this is the only known way to reliably obtain it. This entire #if block
994 ** would be completely unnecessary if there was any other way of detecting
995 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
996 ** some MinGW-specific macros). When compiling for MinGW, either the
997 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
998 ** defined; otherwise, detection of conditions specific to MinGW will be
999 ** disabled.
1001 #if defined(_HAVE_MINGW_H)
1002 # include "mingw.h"
1003 #elif defined(_HAVE__MINGW_H)
1004 # include "_mingw.h"
1005 #endif
1008 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
1009 ** define is required to maintain binary compatibility with the MSVC runtime
1010 ** library in use (e.g. for Windows XP).
1012 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
1013 defined(_WIN32) && !defined(_WIN64) && \
1014 defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
1015 defined(__MSVCRT__)
1016 # define _USE_32BIT_TIME_T
1017 #endif
1019 /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
1020 ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
1021 ** MinGW.
1023 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
1024 /************** Begin file sqlite3.h *****************************************/
1026 ** 2001-09-15
1028 ** The author disclaims copyright to this source code. In place of
1029 ** a legal notice, here is a blessing:
1031 ** May you do good and not evil.
1032 ** May you find forgiveness for yourself and forgive others.
1033 ** May you share freely, never taking more than you give.
1035 *************************************************************************
1036 ** This header file defines the interface that the SQLite library
1037 ** presents to client programs. If a C-function, structure, datatype,
1038 ** or constant definition does not appear in this file, then it is
1039 ** not a published API of SQLite, is subject to change without
1040 ** notice, and should not be referenced by programs that use SQLite.
1042 ** Some of the definitions that are in this file are marked as
1043 ** "experimental". Experimental interfaces are normally new
1044 ** features recently added to SQLite. We do not anticipate changes
1045 ** to experimental interfaces but reserve the right to make minor changes
1046 ** if experience from use "in the wild" suggest such changes are prudent.
1048 ** The official C-language API documentation for SQLite is derived
1049 ** from comments in this file. This file is the authoritative source
1050 ** on how SQLite interfaces are supposed to operate.
1052 ** The name of this file under configuration management is "sqlite.h.in".
1053 ** The makefile makes some minor changes to this file (such as inserting
1054 ** the version number) and changes its name to "sqlite3.h" as
1055 ** part of the build process.
1057 #ifndef SQLITE3_H
1058 #define SQLITE3_H
1059 #include <stdarg.h> /* Needed for the definition of va_list */
1062 ** Make sure we can call this stuff from C++.
1064 #if 0
1065 extern "C" {
1066 #endif
1070 ** Provide the ability to override linkage features of the interface.
1072 #ifndef SQLITE_EXTERN
1073 # define SQLITE_EXTERN extern
1074 #endif
1075 #ifndef SQLITE_API
1076 # define SQLITE_API
1077 #endif
1078 #ifndef SQLITE_CDECL
1079 # define SQLITE_CDECL
1080 #endif
1081 #ifndef SQLITE_APICALL
1082 # define SQLITE_APICALL
1083 #endif
1084 #ifndef SQLITE_STDCALL
1085 # define SQLITE_STDCALL SQLITE_APICALL
1086 #endif
1087 #ifndef SQLITE_CALLBACK
1088 # define SQLITE_CALLBACK
1089 #endif
1090 #ifndef SQLITE_SYSAPI
1091 # define SQLITE_SYSAPI
1092 #endif
1095 ** These no-op macros are used in front of interfaces to mark those
1096 ** interfaces as either deprecated or experimental. New applications
1097 ** should not use deprecated interfaces - they are supported for backwards
1098 ** compatibility only. Application writers should be aware that
1099 ** experimental interfaces are subject to change in point releases.
1101 ** These macros used to resolve to various kinds of compiler magic that
1102 ** would generate warning messages when they were used. But that
1103 ** compiler magic ended up generating such a flurry of bug reports
1104 ** that we have taken it all out and gone back to using simple
1105 ** noop macros.
1107 #define SQLITE_DEPRECATED
1108 #define SQLITE_EXPERIMENTAL
1111 ** Ensure these symbols were not defined by some previous header file.
1113 #ifdef SQLITE_VERSION
1114 # undef SQLITE_VERSION
1115 #endif
1116 #ifdef SQLITE_VERSION_NUMBER
1117 # undef SQLITE_VERSION_NUMBER
1118 #endif
1121 ** CAPI3REF: Compile-Time Library Version Numbers
1123 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
1124 ** evaluates to a string literal that is the SQLite version in the
1125 ** format "X.Y.Z" where X is the major version number (always 3 for
1126 ** SQLite3) and Y is the minor version number and Z is the release number.)^
1127 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
1128 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
1129 ** numbers used in [SQLITE_VERSION].)^
1130 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
1131 ** be larger than the release from which it is derived. Either Y will
1132 ** be held constant and Z will be incremented or else Y will be incremented
1133 ** and Z will be reset to zero.
1135 ** Since [version 3.6.18] ([dateof:3.6.18]),
1136 ** SQLite source code has been stored in the
1137 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
1138 ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
1139 ** a string which identifies a particular check-in of SQLite
1140 ** within its configuration management system. ^The SQLITE_SOURCE_ID
1141 ** string contains the date and time of the check-in (UTC) and a SHA1
1142 ** or SHA3-256 hash of the entire source tree. If the source code has
1143 ** been edited in any way since it was last checked in, then the last
1144 ** four hexadecimal digits of the hash may be modified.
1146 ** See also: [sqlite3_libversion()],
1147 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
1148 ** [sqlite_version()] and [sqlite_source_id()].
1150 #define SQLITE_VERSION "3.21.0"
1151 #define SQLITE_VERSION_NUMBER 3021000
1152 #define SQLITE_SOURCE_ID "2017-10-24 18:55:49 1a584e499906b5c87ec7d43d4abce641fdf017c42125b083109bc77c4de48827"
1155 ** CAPI3REF: Run-Time Library Version Numbers
1156 ** KEYWORDS: sqlite3_version sqlite3_sourceid
1158 ** These interfaces provide the same information as the [SQLITE_VERSION],
1159 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
1160 ** but are associated with the library instead of the header file. ^(Cautious
1161 ** programmers might include assert() statements in their application to
1162 ** verify that values returned by these interfaces match the macros in
1163 ** the header, and thus ensure that the application is
1164 ** compiled with matching library and header files.
1166 ** <blockquote><pre>
1167 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
1168 ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
1169 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
1170 ** </pre></blockquote>)^
1172 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
1173 ** macro. ^The sqlite3_libversion() function returns a pointer to the
1174 ** to the sqlite3_version[] string constant. The sqlite3_libversion()
1175 ** function is provided for use in DLLs since DLL users usually do not have
1176 ** direct access to string constants within the DLL. ^The
1177 ** sqlite3_libversion_number() function returns an integer equal to
1178 ** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
1179 ** a pointer to a string constant whose value is the same as the
1180 ** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
1181 ** using an edited copy of [the amalgamation], then the last four characters
1182 ** of the hash might be different from [SQLITE_SOURCE_ID].)^
1184 ** See also: [sqlite_version()] and [sqlite_source_id()].
1186 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
1187 SQLITE_API const char *sqlite3_libversion(void);
1188 SQLITE_API const char *sqlite3_sourceid(void);
1189 SQLITE_API int sqlite3_libversion_number(void);
1192 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
1194 ** ^The sqlite3_compileoption_used() function returns 0 or 1
1195 ** indicating whether the specified option was defined at
1196 ** compile time. ^The SQLITE_ prefix may be omitted from the
1197 ** option name passed to sqlite3_compileoption_used().
1199 ** ^The sqlite3_compileoption_get() function allows iterating
1200 ** over the list of options that were defined at compile time by
1201 ** returning the N-th compile time option string. ^If N is out of range,
1202 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
1203 ** prefix is omitted from any strings returned by
1204 ** sqlite3_compileoption_get().
1206 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
1207 ** and sqlite3_compileoption_get() may be omitted by specifying the
1208 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
1210 ** See also: SQL functions [sqlite_compileoption_used()] and
1211 ** [sqlite_compileoption_get()] and the [compile_options pragma].
1213 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
1214 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
1215 SQLITE_API const char *sqlite3_compileoption_get(int N);
1216 #endif
1219 ** CAPI3REF: Test To See If The Library Is Threadsafe
1221 ** ^The sqlite3_threadsafe() function returns zero if and only if
1222 ** SQLite was compiled with mutexing code omitted due to the
1223 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
1225 ** SQLite can be compiled with or without mutexes. When
1226 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
1227 ** are enabled and SQLite is threadsafe. When the
1228 ** [SQLITE_THREADSAFE] macro is 0,
1229 ** the mutexes are omitted. Without the mutexes, it is not safe
1230 ** to use SQLite concurrently from more than one thread.
1232 ** Enabling mutexes incurs a measurable performance penalty.
1233 ** So if speed is of utmost importance, it makes sense to disable
1234 ** the mutexes. But for maximum safety, mutexes should be enabled.
1235 ** ^The default behavior is for mutexes to be enabled.
1237 ** This interface can be used by an application to make sure that the
1238 ** version of SQLite that it is linking against was compiled with
1239 ** the desired setting of the [SQLITE_THREADSAFE] macro.
1241 ** This interface only reports on the compile-time mutex setting
1242 ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
1243 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
1244 ** can be fully or partially disabled using a call to [sqlite3_config()]
1245 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
1246 ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
1247 ** sqlite3_threadsafe() function shows only the compile-time setting of
1248 ** thread safety, not any run-time changes to that setting made by
1249 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
1250 ** is unchanged by calls to sqlite3_config().)^
1252 ** See the [threading mode] documentation for additional information.
1254 SQLITE_API int sqlite3_threadsafe(void);
1257 ** CAPI3REF: Database Connection Handle
1258 ** KEYWORDS: {database connection} {database connections}
1260 ** Each open SQLite database is represented by a pointer to an instance of
1261 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
1262 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
1263 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
1264 ** and [sqlite3_close_v2()] are its destructors. There are many other
1265 ** interfaces (such as
1266 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
1267 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
1268 ** sqlite3 object.
1270 typedef struct sqlite3 sqlite3;
1273 ** CAPI3REF: 64-Bit Integer Types
1274 ** KEYWORDS: sqlite_int64 sqlite_uint64
1276 ** Because there is no cross-platform way to specify 64-bit integer types
1277 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
1279 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
1280 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
1281 ** compatibility only.
1283 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
1284 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
1285 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
1286 ** between 0 and +18446744073709551615 inclusive.
1288 #ifdef SQLITE_INT64_TYPE
1289 typedef SQLITE_INT64_TYPE sqlite_int64;
1290 # ifdef SQLITE_UINT64_TYPE
1291 typedef SQLITE_UINT64_TYPE sqlite_uint64;
1292 # else
1293 typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
1294 # endif
1295 #elif defined(_MSC_VER) || defined(__BORLANDC__)
1296 typedef __int64 sqlite_int64;
1297 typedef unsigned __int64 sqlite_uint64;
1298 #else
1299 typedef long long int sqlite_int64;
1300 typedef unsigned long long int sqlite_uint64;
1301 #endif
1302 typedef sqlite_int64 sqlite3_int64;
1303 typedef sqlite_uint64 sqlite3_uint64;
1306 ** If compiling for a processor that lacks floating point support,
1307 ** substitute integer for floating-point.
1309 #ifdef SQLITE_OMIT_FLOATING_POINT
1310 # define double sqlite3_int64
1311 #endif
1314 ** CAPI3REF: Closing A Database Connection
1315 ** DESTRUCTOR: sqlite3
1317 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
1318 ** for the [sqlite3] object.
1319 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
1320 ** the [sqlite3] object is successfully destroyed and all associated
1321 ** resources are deallocated.
1323 ** ^If the database connection is associated with unfinalized prepared
1324 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
1325 ** will leave the database connection open and return [SQLITE_BUSY].
1326 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
1327 ** and/or unfinished sqlite3_backups, then the database connection becomes
1328 ** an unusable "zombie" which will automatically be deallocated when the
1329 ** last prepared statement is finalized or the last sqlite3_backup is
1330 ** finished. The sqlite3_close_v2() interface is intended for use with
1331 ** host languages that are garbage collected, and where the order in which
1332 ** destructors are called is arbitrary.
1334 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
1335 ** [sqlite3_blob_close | close] all [BLOB handles], and
1336 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
1337 ** with the [sqlite3] object prior to attempting to close the object. ^If
1338 ** sqlite3_close_v2() is called on a [database connection] that still has
1339 ** outstanding [prepared statements], [BLOB handles], and/or
1340 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
1341 ** of resources is deferred until all [prepared statements], [BLOB handles],
1342 ** and [sqlite3_backup] objects are also destroyed.
1344 ** ^If an [sqlite3] object is destroyed while a transaction is open,
1345 ** the transaction is automatically rolled back.
1347 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
1348 ** must be either a NULL
1349 ** pointer or an [sqlite3] object pointer obtained
1350 ** from [sqlite3_open()], [sqlite3_open16()], or
1351 ** [sqlite3_open_v2()], and not previously closed.
1352 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
1353 ** argument is a harmless no-op.
1355 SQLITE_API int sqlite3_close(sqlite3*);
1356 SQLITE_API int sqlite3_close_v2(sqlite3*);
1359 ** The type for a callback function.
1360 ** This is legacy and deprecated. It is included for historical
1361 ** compatibility and is not documented.
1363 typedef int (*sqlite3_callback)(void*,int,char**, char**);
1366 ** CAPI3REF: One-Step Query Execution Interface
1367 ** METHOD: sqlite3
1369 ** The sqlite3_exec() interface is a convenience wrapper around
1370 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
1371 ** that allows an application to run multiple statements of SQL
1372 ** without having to use a lot of C code.
1374 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
1375 ** semicolon-separate SQL statements passed into its 2nd argument,
1376 ** in the context of the [database connection] passed in as its 1st
1377 ** argument. ^If the callback function of the 3rd argument to
1378 ** sqlite3_exec() is not NULL, then it is invoked for each result row
1379 ** coming out of the evaluated SQL statements. ^The 4th argument to
1380 ** sqlite3_exec() is relayed through to the 1st argument of each
1381 ** callback invocation. ^If the callback pointer to sqlite3_exec()
1382 ** is NULL, then no callback is ever invoked and result rows are
1383 ** ignored.
1385 ** ^If an error occurs while evaluating the SQL statements passed into
1386 ** sqlite3_exec(), then execution of the current statement stops and
1387 ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
1388 ** is not NULL then any error message is written into memory obtained
1389 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
1390 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
1391 ** on error message strings returned through the 5th parameter of
1392 ** sqlite3_exec() after the error message string is no longer needed.
1393 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
1394 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
1395 ** NULL before returning.
1397 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
1398 ** routine returns SQLITE_ABORT without invoking the callback again and
1399 ** without running any subsequent SQL statements.
1401 ** ^The 2nd argument to the sqlite3_exec() callback function is the
1402 ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
1403 ** callback is an array of pointers to strings obtained as if from
1404 ** [sqlite3_column_text()], one for each column. ^If an element of a
1405 ** result row is NULL then the corresponding string pointer for the
1406 ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
1407 ** sqlite3_exec() callback is an array of pointers to strings where each
1408 ** entry represents the name of corresponding result column as obtained
1409 ** from [sqlite3_column_name()].
1411 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
1412 ** to an empty string, or a pointer that contains only whitespace and/or
1413 ** SQL comments, then no SQL statements are evaluated and the database
1414 ** is not changed.
1416 ** Restrictions:
1418 ** <ul>
1419 ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
1420 ** is a valid and open [database connection].
1421 ** <li> The application must not close the [database connection] specified by
1422 ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
1423 ** <li> The application must not modify the SQL statement text passed into
1424 ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
1425 ** </ul>
1427 SQLITE_API int sqlite3_exec(
1428 sqlite3*, /* An open database */
1429 const char *sql, /* SQL to be evaluated */
1430 int (*callback)(void*,int,char**,char**), /* Callback function */
1431 void *, /* 1st argument to callback */
1432 char **errmsg /* Error msg written here */
1436 ** CAPI3REF: Result Codes
1437 ** KEYWORDS: {result code definitions}
1439 ** Many SQLite functions return an integer result code from the set shown
1440 ** here in order to indicate success or failure.
1442 ** New error codes may be added in future versions of SQLite.
1444 ** See also: [extended result code definitions]
1446 #define SQLITE_OK 0 /* Successful result */
1447 /* beginning-of-error-codes */
1448 #define SQLITE_ERROR 1 /* Generic error */
1449 #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
1450 #define SQLITE_PERM 3 /* Access permission denied */
1451 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
1452 #define SQLITE_BUSY 5 /* The database file is locked */
1453 #define SQLITE_LOCKED 6 /* A table in the database is locked */
1454 #define SQLITE_NOMEM 7 /* A malloc() failed */
1455 #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
1456 #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
1457 #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
1458 #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
1459 #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
1460 #define SQLITE_FULL 13 /* Insertion failed because database is full */
1461 #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
1462 #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
1463 #define SQLITE_EMPTY 16 /* Internal use only */
1464 #define SQLITE_SCHEMA 17 /* The database schema changed */
1465 #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
1466 #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
1467 #define SQLITE_MISMATCH 20 /* Data type mismatch */
1468 #define SQLITE_MISUSE 21 /* Library used incorrectly */
1469 #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
1470 #define SQLITE_AUTH 23 /* Authorization denied */
1471 #define SQLITE_FORMAT 24 /* Not used */
1472 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
1473 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
1474 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
1475 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
1476 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
1477 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
1478 /* end-of-error-codes */
1481 ** CAPI3REF: Extended Result Codes
1482 ** KEYWORDS: {extended result code definitions}
1484 ** In its default configuration, SQLite API routines return one of 30 integer
1485 ** [result codes]. However, experience has shown that many of
1486 ** these result codes are too coarse-grained. They do not provide as
1487 ** much information about problems as programmers might like. In an effort to
1488 ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
1489 ** and later) include
1490 ** support for additional result codes that provide more detailed information
1491 ** about errors. These [extended result codes] are enabled or disabled
1492 ** on a per database connection basis using the
1493 ** [sqlite3_extended_result_codes()] API. Or, the extended code for
1494 ** the most recent error can be obtained using
1495 ** [sqlite3_extended_errcode()].
1497 #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
1498 #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
1499 #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
1500 #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
1501 #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
1502 #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
1503 #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
1504 #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
1505 #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
1506 #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
1507 #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
1508 #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
1509 #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
1510 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1511 #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
1512 #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
1513 #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
1514 #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
1515 #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
1516 #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
1517 #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
1518 #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
1519 #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
1520 #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
1521 #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
1522 #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
1523 #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
1524 #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
1525 #define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
1526 #define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
1527 #define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
1528 #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
1529 #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
1530 #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
1531 #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
1532 #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
1533 #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
1534 #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
1535 #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
1536 #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
1537 #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
1538 #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
1539 #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
1540 #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
1541 #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
1542 #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
1543 #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
1544 #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
1545 #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
1546 #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
1547 #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
1548 #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
1549 #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
1550 #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
1551 #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
1552 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
1553 #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
1554 #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
1555 #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
1558 ** CAPI3REF: Flags For File Open Operations
1560 ** These bit values are intended for use in the
1561 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1562 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1564 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
1565 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
1566 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
1567 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
1568 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
1569 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
1570 #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
1571 #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
1572 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
1573 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
1574 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
1575 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
1576 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
1577 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
1578 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
1579 #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
1580 #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
1581 #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
1582 #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
1583 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
1585 /* Reserved: 0x00F00000 */
1588 ** CAPI3REF: Device Characteristics
1590 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1591 ** object returns an integer which is a vector of these
1592 ** bit values expressing I/O characteristics of the mass storage
1593 ** device that holds the file that the [sqlite3_io_methods]
1594 ** refers to.
1596 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1597 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1598 ** mean that writes of blocks that are nnn bytes in size and
1599 ** are aligned to an address which is an integer multiple of
1600 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1601 ** that when data is appended to a file, the data is appended
1602 ** first then the size of the file is extended, never the other
1603 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1604 ** information is written to disk in the same order as calls
1605 ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1606 ** after reboot following a crash or power loss, the only bytes in a
1607 ** file that were written at the application level might have changed
1608 ** and that adjacent bytes, even bytes within the same sector are
1609 ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
1610 ** flag indicates that a file cannot be deleted when open. The
1611 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
1612 ** read-only media and cannot be changed even by processes with
1613 ** elevated privileges.
1615 ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
1616 ** filesystem supports doing multiple write operations atomically when those
1617 ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
1618 ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
1620 #define SQLITE_IOCAP_ATOMIC 0x00000001
1621 #define SQLITE_IOCAP_ATOMIC512 0x00000002
1622 #define SQLITE_IOCAP_ATOMIC1K 0x00000004
1623 #define SQLITE_IOCAP_ATOMIC2K 0x00000008
1624 #define SQLITE_IOCAP_ATOMIC4K 0x00000010
1625 #define SQLITE_IOCAP_ATOMIC8K 0x00000020
1626 #define SQLITE_IOCAP_ATOMIC16K 0x00000040
1627 #define SQLITE_IOCAP_ATOMIC32K 0x00000080
1628 #define SQLITE_IOCAP_ATOMIC64K 0x00000100
1629 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
1630 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
1631 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
1632 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
1633 #define SQLITE_IOCAP_IMMUTABLE 0x00002000
1634 #define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
1637 ** CAPI3REF: File Locking Levels
1639 ** SQLite uses one of these integer values as the second
1640 ** argument to calls it makes to the xLock() and xUnlock() methods
1641 ** of an [sqlite3_io_methods] object.
1643 #define SQLITE_LOCK_NONE 0
1644 #define SQLITE_LOCK_SHARED 1
1645 #define SQLITE_LOCK_RESERVED 2
1646 #define SQLITE_LOCK_PENDING 3
1647 #define SQLITE_LOCK_EXCLUSIVE 4
1650 ** CAPI3REF: Synchronization Type Flags
1652 ** When SQLite invokes the xSync() method of an
1653 ** [sqlite3_io_methods] object it uses a combination of
1654 ** these integer values as the second argument.
1656 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1657 ** sync operation only needs to flush data to mass storage. Inode
1658 ** information need not be flushed. If the lower four bits of the flag
1659 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1660 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1661 ** to use Mac OS X style fullsync instead of fsync().
1663 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1664 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1665 ** settings. The [synchronous pragma] determines when calls to the
1666 ** xSync VFS method occur and applies uniformly across all platforms.
1667 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1668 ** energetic or rigorous or forceful the sync operations are and
1669 ** only make a difference on Mac OSX for the default SQLite code.
1670 ** (Third-party VFS implementations might also make the distinction
1671 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1672 ** operating systems natively supported by SQLite, only Mac OSX
1673 ** cares about the difference.)
1675 #define SQLITE_SYNC_NORMAL 0x00002
1676 #define SQLITE_SYNC_FULL 0x00003
1677 #define SQLITE_SYNC_DATAONLY 0x00010
1680 ** CAPI3REF: OS Interface Open File Handle
1682 ** An [sqlite3_file] object represents an open file in the
1683 ** [sqlite3_vfs | OS interface layer]. Individual OS interface
1684 ** implementations will
1685 ** want to subclass this object by appending additional fields
1686 ** for their own use. The pMethods entry is a pointer to an
1687 ** [sqlite3_io_methods] object that defines methods for performing
1688 ** I/O operations on the open file.
1690 typedef struct sqlite3_file sqlite3_file;
1691 struct sqlite3_file {
1692 const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
1696 ** CAPI3REF: OS Interface File Virtual Methods Object
1698 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1699 ** [sqlite3_file] object (or, more commonly, a subclass of the
1700 ** [sqlite3_file] object) with a pointer to an instance of this object.
1701 ** This object defines the methods used to perform various operations
1702 ** against the open file represented by the [sqlite3_file] object.
1704 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1705 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1706 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
1707 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1708 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1709 ** to NULL.
1711 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1712 ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
1713 ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
1714 ** flag may be ORed in to indicate that only the data of the file
1715 ** and not its inode needs to be synced.
1717 ** The integer values to xLock() and xUnlock() are one of
1718 ** <ul>
1719 ** <li> [SQLITE_LOCK_NONE],
1720 ** <li> [SQLITE_LOCK_SHARED],
1721 ** <li> [SQLITE_LOCK_RESERVED],
1722 ** <li> [SQLITE_LOCK_PENDING], or
1723 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1724 ** </ul>
1725 ** xLock() increases the lock. xUnlock() decreases the lock.
1726 ** The xCheckReservedLock() method checks whether any database connection,
1727 ** either in this process or in some other process, is holding a RESERVED,
1728 ** PENDING, or EXCLUSIVE lock on the file. It returns true
1729 ** if such a lock exists and false otherwise.
1731 ** The xFileControl() method is a generic interface that allows custom
1732 ** VFS implementations to directly control an open file using the
1733 ** [sqlite3_file_control()] interface. The second "op" argument is an
1734 ** integer opcode. The third argument is a generic pointer intended to
1735 ** point to a structure that may contain arguments or space in which to
1736 ** write return values. Potential uses for xFileControl() might be
1737 ** functions to enable blocking locks with timeouts, to change the
1738 ** locking strategy (for example to use dot-file locks), to inquire
1739 ** about the status of a lock, or to break stale locks. The SQLite
1740 ** core reserves all opcodes less than 100 for its own use.
1741 ** A [file control opcodes | list of opcodes] less than 100 is available.
1742 ** Applications that define a custom xFileControl method should use opcodes
1743 ** greater than 100 to avoid conflicts. VFS implementations should
1744 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1745 ** recognize.
1747 ** The xSectorSize() method returns the sector size of the
1748 ** device that underlies the file. The sector size is the
1749 ** minimum write that can be performed without disturbing
1750 ** other bytes in the file. The xDeviceCharacteristics()
1751 ** method returns a bit vector describing behaviors of the
1752 ** underlying device:
1754 ** <ul>
1755 ** <li> [SQLITE_IOCAP_ATOMIC]
1756 ** <li> [SQLITE_IOCAP_ATOMIC512]
1757 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1758 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1759 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1760 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1761 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1762 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1763 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1764 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1765 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1766 ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
1767 ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
1768 ** <li> [SQLITE_IOCAP_IMMUTABLE]
1769 ** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
1770 ** </ul>
1772 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1773 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1774 ** mean that writes of blocks that are nnn bytes in size and
1775 ** are aligned to an address which is an integer multiple of
1776 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1777 ** that when data is appended to a file, the data is appended
1778 ** first then the size of the file is extended, never the other
1779 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1780 ** information is written to disk in the same order as calls
1781 ** to xWrite().
1783 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1784 ** in the unread portions of the buffer with zeros. A VFS that
1785 ** fails to zero-fill short reads might seem to work. However,
1786 ** failure to zero-fill short reads will eventually lead to
1787 ** database corruption.
1789 typedef struct sqlite3_io_methods sqlite3_io_methods;
1790 struct sqlite3_io_methods {
1791 int iVersion;
1792 int (*xClose)(sqlite3_file*);
1793 int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1794 int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1795 int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1796 int (*xSync)(sqlite3_file*, int flags);
1797 int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1798 int (*xLock)(sqlite3_file*, int);
1799 int (*xUnlock)(sqlite3_file*, int);
1800 int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1801 int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1802 int (*xSectorSize)(sqlite3_file*);
1803 int (*xDeviceCharacteristics)(sqlite3_file*);
1804 /* Methods above are valid for version 1 */
1805 int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1806 int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1807 void (*xShmBarrier)(sqlite3_file*);
1808 int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1809 /* Methods above are valid for version 2 */
1810 int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1811 int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1812 /* Methods above are valid for version 3 */
1813 /* Additional methods may be added in future releases */
1817 ** CAPI3REF: Standard File Control Opcodes
1818 ** KEYWORDS: {file control opcodes} {file control opcode}
1820 ** These integer constants are opcodes for the xFileControl method
1821 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1822 ** interface.
1824 ** <ul>
1825 ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1826 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1827 ** opcode causes the xFileControl method to write the current state of
1828 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1829 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1830 ** into an integer that the pArg argument points to. This capability
1831 ** is used during testing and is only available when the SQLITE_TEST
1832 ** compile-time option is used.
1834 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1835 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1836 ** layer a hint of how large the database file will grow to be during the
1837 ** current transaction. This hint is not guaranteed to be accurate but it
1838 ** is often close. The underlying VFS might choose to preallocate database
1839 ** file space based on this hint in order to help writes to the database
1840 ** file run faster.
1842 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1843 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1844 ** extends and truncates the database file in chunks of a size specified
1845 ** by the user. The fourth argument to [sqlite3_file_control()] should
1846 ** point to an integer (type int) containing the new chunk-size to use
1847 ** for the nominated database. Allocating database file space in large
1848 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1849 ** improve performance on some systems.
1851 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1852 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1853 ** to the [sqlite3_file] object associated with a particular database
1854 ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
1856 ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1857 ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1858 ** to the [sqlite3_file] object associated with the journal file (either
1859 ** the [rollback journal] or the [write-ahead log]) for a particular database
1860 ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
1862 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1863 ** No longer in use.
1865 ** <li>[[SQLITE_FCNTL_SYNC]]
1866 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1867 ** sent to the VFS immediately before the xSync method is invoked on a
1868 ** database file descriptor. Or, if the xSync method is not invoked
1869 ** because the user has configured SQLite with
1870 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1871 ** of the xSync method. In most cases, the pointer argument passed with
1872 ** this file-control is NULL. However, if the database file is being synced
1873 ** as part of a multi-database commit, the argument points to a nul-terminated
1874 ** string containing the transactions master-journal file name. VFSes that
1875 ** do not need this signal should silently ignore this opcode. Applications
1876 ** should not call [sqlite3_file_control()] with this opcode as doing so may
1877 ** disrupt the operation of the specialized VFSes that do require it.
1879 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1880 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1881 ** and sent to the VFS after a transaction has been committed immediately
1882 ** but before the database is unlocked. VFSes that do not need this signal
1883 ** should silently ignore this opcode. Applications should not call
1884 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1885 ** operation of the specialized VFSes that do require it.
1887 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1888 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1889 ** retry counts and intervals for certain disk I/O operations for the
1890 ** windows [VFS] in order to provide robustness in the presence of
1891 ** anti-virus programs. By default, the windows VFS will retry file read,
1892 ** file write, and file delete operations up to 10 times, with a delay
1893 ** of 25 milliseconds before the first retry and with the delay increasing
1894 ** by an additional 25 milliseconds with each subsequent retry. This
1895 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1896 ** to be adjusted. The values are changed for all database connections
1897 ** within the same process. The argument is a pointer to an array of two
1898 ** integers where the first integer is the new retry count and the second
1899 ** integer is the delay. If either integer is negative, then the setting
1900 ** is not changed but instead the prior value of that setting is written
1901 ** into the array entry, allowing the current retry settings to be
1902 ** interrogated. The zDbName parameter is ignored.
1904 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1905 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1906 ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
1907 ** write ahead log and shared memory files used for transaction control
1908 ** are automatically deleted when the latest connection to the database
1909 ** closes. Setting persistent WAL mode causes those files to persist after
1910 ** close. Persisting the files is useful when other processes that do not
1911 ** have write permission on the directory containing the database file want
1912 ** to read the database file, as the WAL and shared memory files must exist
1913 ** in order for the database to be readable. The fourth parameter to
1914 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1915 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1916 ** WAL mode. If the integer is -1, then it is overwritten with the current
1917 ** WAL persistence setting.
1919 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1920 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1921 ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1922 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1923 ** xDeviceCharacteristics methods. The fourth parameter to
1924 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1925 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1926 ** mode. If the integer is -1, then it is overwritten with the current
1927 ** zero-damage mode setting.
1929 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1930 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1931 ** a write transaction to indicate that, unless it is rolled back for some
1932 ** reason, the entire database file will be overwritten by the current
1933 ** transaction. This is used by VACUUM operations.
1935 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1936 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1937 ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
1938 ** final bottom-level VFS are written into memory obtained from
1939 ** [sqlite3_malloc()] and the result is stored in the char* variable
1940 ** that the fourth parameter of [sqlite3_file_control()] points to.
1941 ** The caller is responsible for freeing the memory when done. As with
1942 ** all file-control actions, there is no guarantee that this will actually
1943 ** do anything. Callers should initialize the char* variable to a NULL
1944 ** pointer in case this file-control is not implemented. This file-control
1945 ** is intended for diagnostic use only.
1947 ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1948 ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1949 ** [VFSes] currently in use. ^(The argument X in
1950 ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1951 ** of type "[sqlite3_vfs] **". This opcodes will set *X
1952 ** to a pointer to the top-level VFS.)^
1953 ** ^When there are multiple VFS shims in the stack, this opcode finds the
1954 ** upper-most shim only.
1956 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1957 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1958 ** file control is sent to the open [sqlite3_file] object corresponding
1959 ** to the database file to which the pragma statement refers. ^The argument
1960 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1961 ** pointers to strings (char**) in which the second element of the array
1962 ** is the name of the pragma and the third element is the argument to the
1963 ** pragma or NULL if the pragma has no argument. ^The handler for an
1964 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1965 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1966 ** or the equivalent and that string will become the result of the pragma or
1967 ** the error message if the pragma fails. ^If the
1968 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1969 ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1970 ** file control returns [SQLITE_OK], then the parser assumes that the
1971 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1972 ** prepared statement if result string is NULL, or that returns a copy
1973 ** of the result string if the string is non-NULL.
1974 ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1975 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1976 ** that the VFS encountered an error while handling the [PRAGMA] and the
1977 ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1978 ** file control occurs at the beginning of pragma statement analysis and so
1979 ** it is able to override built-in [PRAGMA] statements.
1981 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1982 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1983 ** file-control may be invoked by SQLite on the database file handle
1984 ** shortly after it is opened in order to provide a custom VFS with access
1985 ** to the connections busy-handler callback. The argument is of type (void **)
1986 ** - an array of two (void *) values. The first (void *) actually points
1987 ** to a function of type (int (*)(void *)). In order to invoke the connections
1988 ** busy-handler, this function should be invoked with the second (void *) in
1989 ** the array as the only argument. If it returns non-zero, then the operation
1990 ** should be retried. If it returns zero, the custom VFS should abandon the
1991 ** current operation.
1993 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1994 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1995 ** to have SQLite generate a
1996 ** temporary filename using the same algorithm that is followed to generate
1997 ** temporary filenames for TEMP tables and other internal uses. The
1998 ** argument should be a char** which will be filled with the filename
1999 ** written into memory obtained from [sqlite3_malloc()]. The caller should
2000 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
2002 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
2003 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
2004 ** maximum number of bytes that will be used for memory-mapped I/O.
2005 ** The argument is a pointer to a value of type sqlite3_int64 that
2006 ** is an advisory maximum number of bytes in the file to memory map. The
2007 ** pointer is overwritten with the old value. The limit is not changed if
2008 ** the value originally pointed to is negative, and so the current limit
2009 ** can be queried by passing in a pointer to a negative number. This
2010 ** file-control is used internally to implement [PRAGMA mmap_size].
2012 ** <li>[[SQLITE_FCNTL_TRACE]]
2013 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
2014 ** to the VFS about what the higher layers of the SQLite stack are doing.
2015 ** This file control is used by some VFS activity tracing [shims].
2016 ** The argument is a zero-terminated string. Higher layers in the
2017 ** SQLite stack may generate instances of this file control if
2018 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
2020 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
2021 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
2022 ** pointer to an integer and it writes a boolean into that integer depending
2023 ** on whether or not the file has been renamed, moved, or deleted since it
2024 ** was first opened.
2026 ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
2027 ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
2028 ** underlying native file handle associated with a file handle. This file
2029 ** control interprets its argument as a pointer to a native file handle and
2030 ** writes the resulting value there.
2032 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
2033 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
2034 ** opcode causes the xFileControl method to swap the file handle with the one
2035 ** pointed to by the pArg argument. This capability is used during testing
2036 ** and only needs to be supported when SQLITE_TEST is defined.
2038 ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
2039 ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
2040 ** be advantageous to block on the next WAL lock if the lock is not immediately
2041 ** available. The WAL subsystem issues this signal during rare
2042 ** circumstances in order to fix a problem with priority inversion.
2043 ** Applications should <em>not</em> use this file-control.
2045 ** <li>[[SQLITE_FCNTL_ZIPVFS]]
2046 ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
2047 ** VFS should return SQLITE_NOTFOUND for this opcode.
2049 ** <li>[[SQLITE_FCNTL_RBU]]
2050 ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
2051 ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
2052 ** this opcode.
2054 ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
2055 ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
2056 ** the file descriptor is placed in "batch write mode", which
2057 ** means all subsequent write operations will be deferred and done
2058 ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
2059 ** that do not support batch atomic writes will return SQLITE_NOTFOUND.
2060 ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
2061 ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
2062 ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
2063 ** no VFS interface calls on the same [sqlite3_file] file descriptor
2064 ** except for calls to the xWrite method and the xFileControl method
2065 ** with [SQLITE_FCNTL_SIZE_HINT].
2067 ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
2068 ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
2069 ** operations since the previous successful call to
2070 ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
2071 ** This file control returns [SQLITE_OK] if and only if the writes were
2072 ** all performed successfully and have been committed to persistent storage.
2073 ** ^Regardless of whether or not it is successful, this file control takes
2074 ** the file descriptor out of batch write mode so that all subsequent
2075 ** write operations are independent.
2076 ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
2077 ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
2079 ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
2080 ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
2081 ** operations since the previous successful call to
2082 ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
2083 ** ^This file control takes the file descriptor out of batch write mode
2084 ** so that all subsequent write operations are independent.
2085 ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
2086 ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
2087 ** </ul>
2089 #define SQLITE_FCNTL_LOCKSTATE 1
2090 #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
2091 #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
2092 #define SQLITE_FCNTL_LAST_ERRNO 4
2093 #define SQLITE_FCNTL_SIZE_HINT 5
2094 #define SQLITE_FCNTL_CHUNK_SIZE 6
2095 #define SQLITE_FCNTL_FILE_POINTER 7
2096 #define SQLITE_FCNTL_SYNC_OMITTED 8
2097 #define SQLITE_FCNTL_WIN32_AV_RETRY 9
2098 #define SQLITE_FCNTL_PERSIST_WAL 10
2099 #define SQLITE_FCNTL_OVERWRITE 11
2100 #define SQLITE_FCNTL_VFSNAME 12
2101 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
2102 #define SQLITE_FCNTL_PRAGMA 14
2103 #define SQLITE_FCNTL_BUSYHANDLER 15
2104 #define SQLITE_FCNTL_TEMPFILENAME 16
2105 #define SQLITE_FCNTL_MMAP_SIZE 18
2106 #define SQLITE_FCNTL_TRACE 19
2107 #define SQLITE_FCNTL_HAS_MOVED 20
2108 #define SQLITE_FCNTL_SYNC 21
2109 #define SQLITE_FCNTL_COMMIT_PHASETWO 22
2110 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
2111 #define SQLITE_FCNTL_WAL_BLOCK 24
2112 #define SQLITE_FCNTL_ZIPVFS 25
2113 #define SQLITE_FCNTL_RBU 26
2114 #define SQLITE_FCNTL_VFS_POINTER 27
2115 #define SQLITE_FCNTL_JOURNAL_POINTER 28
2116 #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
2117 #define SQLITE_FCNTL_PDB 30
2118 #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
2119 #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
2120 #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
2122 /* deprecated names */
2123 #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
2124 #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
2125 #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
2129 ** CAPI3REF: Mutex Handle
2131 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
2132 ** abstract type for a mutex object. The SQLite core never looks
2133 ** at the internal representation of an [sqlite3_mutex]. It only
2134 ** deals with pointers to the [sqlite3_mutex] object.
2136 ** Mutexes are created using [sqlite3_mutex_alloc()].
2138 typedef struct sqlite3_mutex sqlite3_mutex;
2141 ** CAPI3REF: Loadable Extension Thunk
2143 ** A pointer to the opaque sqlite3_api_routines structure is passed as
2144 ** the third parameter to entry points of [loadable extensions]. This
2145 ** structure must be typedefed in order to work around compiler warnings
2146 ** on some platforms.
2148 typedef struct sqlite3_api_routines sqlite3_api_routines;
2151 ** CAPI3REF: OS Interface Object
2153 ** An instance of the sqlite3_vfs object defines the interface between
2154 ** the SQLite core and the underlying operating system. The "vfs"
2155 ** in the name of the object stands for "virtual file system". See
2156 ** the [VFS | VFS documentation] for further information.
2158 ** The value of the iVersion field is initially 1 but may be larger in
2159 ** future versions of SQLite. Additional fields may be appended to this
2160 ** object when the iVersion value is increased. Note that the structure
2161 ** of the sqlite3_vfs object changes in the transaction between
2162 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
2163 ** modified.
2165 ** The szOsFile field is the size of the subclassed [sqlite3_file]
2166 ** structure used by this VFS. mxPathname is the maximum length of
2167 ** a pathname in this VFS.
2169 ** Registered sqlite3_vfs objects are kept on a linked list formed by
2170 ** the pNext pointer. The [sqlite3_vfs_register()]
2171 ** and [sqlite3_vfs_unregister()] interfaces manage this list
2172 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
2173 ** searches the list. Neither the application code nor the VFS
2174 ** implementation should use the pNext pointer.
2176 ** The pNext field is the only field in the sqlite3_vfs
2177 ** structure that SQLite will ever modify. SQLite will only access
2178 ** or modify this field while holding a particular static mutex.
2179 ** The application should never modify anything within the sqlite3_vfs
2180 ** object once the object has been registered.
2182 ** The zName field holds the name of the VFS module. The name must
2183 ** be unique across all VFS modules.
2185 ** [[sqlite3_vfs.xOpen]]
2186 ** ^SQLite guarantees that the zFilename parameter to xOpen
2187 ** is either a NULL pointer or string obtained
2188 ** from xFullPathname() with an optional suffix added.
2189 ** ^If a suffix is added to the zFilename parameter, it will
2190 ** consist of a single "-" character followed by no more than
2191 ** 11 alphanumeric and/or "-" characters.
2192 ** ^SQLite further guarantees that
2193 ** the string will be valid and unchanged until xClose() is
2194 ** called. Because of the previous sentence,
2195 ** the [sqlite3_file] can safely store a pointer to the
2196 ** filename if it needs to remember the filename for some reason.
2197 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
2198 ** must invent its own temporary name for the file. ^Whenever the
2199 ** xFilename parameter is NULL it will also be the case that the
2200 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
2202 ** The flags argument to xOpen() includes all bits set in
2203 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
2204 ** or [sqlite3_open16()] is used, then flags includes at least
2205 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
2206 ** If xOpen() opens a file read-only then it sets *pOutFlags to
2207 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
2209 ** ^(SQLite will also add one of the following flags to the xOpen()
2210 ** call, depending on the object being opened:
2212 ** <ul>
2213 ** <li> [SQLITE_OPEN_MAIN_DB]
2214 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
2215 ** <li> [SQLITE_OPEN_TEMP_DB]
2216 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
2217 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
2218 ** <li> [SQLITE_OPEN_SUBJOURNAL]
2219 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
2220 ** <li> [SQLITE_OPEN_WAL]
2221 ** </ul>)^
2223 ** The file I/O implementation can use the object type flags to
2224 ** change the way it deals with files. For example, an application
2225 ** that does not care about crash recovery or rollback might make
2226 ** the open of a journal file a no-op. Writes to this journal would
2227 ** also be no-ops, and any attempt to read the journal would return
2228 ** SQLITE_IOERR. Or the implementation might recognize that a database
2229 ** file will be doing page-aligned sector reads and writes in a random
2230 ** order and set up its I/O subsystem accordingly.
2232 ** SQLite might also add one of the following flags to the xOpen method:
2234 ** <ul>
2235 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
2236 ** <li> [SQLITE_OPEN_EXCLUSIVE]
2237 ** </ul>
2239 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
2240 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
2241 ** will be set for TEMP databases and their journals, transient
2242 ** databases, and subjournals.
2244 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
2245 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
2246 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
2247 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
2248 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
2249 ** be created, and that it is an error if it already exists.
2250 ** It is <i>not</i> used to indicate the file should be opened
2251 ** for exclusive access.
2253 ** ^At least szOsFile bytes of memory are allocated by SQLite
2254 ** to hold the [sqlite3_file] structure passed as the third
2255 ** argument to xOpen. The xOpen method does not have to
2256 ** allocate the structure; it should just fill it in. Note that
2257 ** the xOpen method must set the sqlite3_file.pMethods to either
2258 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
2259 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
2260 ** element will be valid after xOpen returns regardless of the success
2261 ** or failure of the xOpen call.
2263 ** [[sqlite3_vfs.xAccess]]
2264 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
2265 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
2266 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
2267 ** to test whether a file is at least readable. The file can be a
2268 ** directory.
2270 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
2271 ** output buffer xFullPathname. The exact size of the output buffer
2272 ** is also passed as a parameter to both methods. If the output buffer
2273 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
2274 ** handled as a fatal error by SQLite, vfs implementations should endeavor
2275 ** to prevent this by setting mxPathname to a sufficiently large value.
2277 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
2278 ** interfaces are not strictly a part of the filesystem, but they are
2279 ** included in the VFS structure for completeness.
2280 ** The xRandomness() function attempts to return nBytes bytes
2281 ** of good-quality randomness into zOut. The return value is
2282 ** the actual number of bytes of randomness obtained.
2283 ** The xSleep() method causes the calling thread to sleep for at
2284 ** least the number of microseconds given. ^The xCurrentTime()
2285 ** method returns a Julian Day Number for the current date and time as
2286 ** a floating point value.
2287 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
2288 ** Day Number multiplied by 86400000 (the number of milliseconds in
2289 ** a 24-hour day).
2290 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
2291 ** date and time if that method is available (if iVersion is 2 or
2292 ** greater and the function pointer is not NULL) and will fall back
2293 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
2295 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
2296 ** are not used by the SQLite core. These optional interfaces are provided
2297 ** by some VFSes to facilitate testing of the VFS code. By overriding
2298 ** system calls with functions under its control, a test program can
2299 ** simulate faults and error conditions that would otherwise be difficult
2300 ** or impossible to induce. The set of system calls that can be overridden
2301 ** varies from one VFS to another, and from one version of the same VFS to the
2302 ** next. Applications that use these interfaces must be prepared for any
2303 ** or all of these interfaces to be NULL or for their behavior to change
2304 ** from one release to the next. Applications must not attempt to access
2305 ** any of these methods if the iVersion of the VFS is less than 3.
2307 typedef struct sqlite3_vfs sqlite3_vfs;
2308 typedef void (*sqlite3_syscall_ptr)(void);
2309 struct sqlite3_vfs {
2310 int iVersion; /* Structure version number (currently 3) */
2311 int szOsFile; /* Size of subclassed sqlite3_file */
2312 int mxPathname; /* Maximum file pathname length */
2313 sqlite3_vfs *pNext; /* Next registered VFS */
2314 const char *zName; /* Name of this virtual file system */
2315 void *pAppData; /* Pointer to application-specific data */
2316 int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
2317 int flags, int *pOutFlags);
2318 int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
2319 int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
2320 int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
2321 void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
2322 void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
2323 void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
2324 void (*xDlClose)(sqlite3_vfs*, void*);
2325 int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
2326 int (*xSleep)(sqlite3_vfs*, int microseconds);
2327 int (*xCurrentTime)(sqlite3_vfs*, double*);
2328 int (*xGetLastError)(sqlite3_vfs*, int, char *);
2330 ** The methods above are in version 1 of the sqlite_vfs object
2331 ** definition. Those that follow are added in version 2 or later
2333 int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
2335 ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
2336 ** Those below are for version 3 and greater.
2338 int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
2339 sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
2340 const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
2342 ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
2343 ** New fields may be appended in future versions. The iVersion
2344 ** value will increment whenever this happens.
2349 ** CAPI3REF: Flags for the xAccess VFS method
2351 ** These integer constants can be used as the third parameter to
2352 ** the xAccess method of an [sqlite3_vfs] object. They determine
2353 ** what kind of permissions the xAccess method is looking for.
2354 ** With SQLITE_ACCESS_EXISTS, the xAccess method
2355 ** simply checks whether the file exists.
2356 ** With SQLITE_ACCESS_READWRITE, the xAccess method
2357 ** checks whether the named directory is both readable and writable
2358 ** (in other words, if files can be added, removed, and renamed within
2359 ** the directory).
2360 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
2361 ** [temp_store_directory pragma], though this could change in a future
2362 ** release of SQLite.
2363 ** With SQLITE_ACCESS_READ, the xAccess method
2364 ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
2365 ** currently unused, though it might be used in a future release of
2366 ** SQLite.
2368 #define SQLITE_ACCESS_EXISTS 0
2369 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
2370 #define SQLITE_ACCESS_READ 2 /* Unused */
2373 ** CAPI3REF: Flags for the xShmLock VFS method
2375 ** These integer constants define the various locking operations
2376 ** allowed by the xShmLock method of [sqlite3_io_methods]. The
2377 ** following are the only legal combinations of flags to the
2378 ** xShmLock method:
2380 ** <ul>
2381 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
2382 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
2383 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
2384 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
2385 ** </ul>
2387 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
2388 ** was given on the corresponding lock.
2390 ** The xShmLock method can transition between unlocked and SHARED or
2391 ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
2392 ** and EXCLUSIVE.
2394 #define SQLITE_SHM_UNLOCK 1
2395 #define SQLITE_SHM_LOCK 2
2396 #define SQLITE_SHM_SHARED 4
2397 #define SQLITE_SHM_EXCLUSIVE 8
2400 ** CAPI3REF: Maximum xShmLock index
2402 ** The xShmLock method on [sqlite3_io_methods] may use values
2403 ** between 0 and this upper bound as its "offset" argument.
2404 ** The SQLite core will never attempt to acquire or release a
2405 ** lock outside of this range
2407 #define SQLITE_SHM_NLOCK 8
2411 ** CAPI3REF: Initialize The SQLite Library
2413 ** ^The sqlite3_initialize() routine initializes the
2414 ** SQLite library. ^The sqlite3_shutdown() routine
2415 ** deallocates any resources that were allocated by sqlite3_initialize().
2416 ** These routines are designed to aid in process initialization and
2417 ** shutdown on embedded systems. Workstation applications using
2418 ** SQLite normally do not need to invoke either of these routines.
2420 ** A call to sqlite3_initialize() is an "effective" call if it is
2421 ** the first time sqlite3_initialize() is invoked during the lifetime of
2422 ** the process, or if it is the first time sqlite3_initialize() is invoked
2423 ** following a call to sqlite3_shutdown(). ^(Only an effective call
2424 ** of sqlite3_initialize() does any initialization. All other calls
2425 ** are harmless no-ops.)^
2427 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
2428 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
2429 ** an effective call to sqlite3_shutdown() does any deinitialization.
2430 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
2432 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
2433 ** is not. The sqlite3_shutdown() interface must only be called from a
2434 ** single thread. All open [database connections] must be closed and all
2435 ** other SQLite resources must be deallocated prior to invoking
2436 ** sqlite3_shutdown().
2438 ** Among other things, ^sqlite3_initialize() will invoke
2439 ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
2440 ** will invoke sqlite3_os_end().
2442 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
2443 ** ^If for some reason, sqlite3_initialize() is unable to initialize
2444 ** the library (perhaps it is unable to allocate a needed resource such
2445 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
2447 ** ^The sqlite3_initialize() routine is called internally by many other
2448 ** SQLite interfaces so that an application usually does not need to
2449 ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
2450 ** calls sqlite3_initialize() so the SQLite library will be automatically
2451 ** initialized when [sqlite3_open()] is called if it has not be initialized
2452 ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
2453 ** compile-time option, then the automatic calls to sqlite3_initialize()
2454 ** are omitted and the application must call sqlite3_initialize() directly
2455 ** prior to using any other SQLite interface. For maximum portability,
2456 ** it is recommended that applications always invoke sqlite3_initialize()
2457 ** directly prior to using any other SQLite interface. Future releases
2458 ** of SQLite may require this. In other words, the behavior exhibited
2459 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
2460 ** default behavior in some future release of SQLite.
2462 ** The sqlite3_os_init() routine does operating-system specific
2463 ** initialization of the SQLite library. The sqlite3_os_end()
2464 ** routine undoes the effect of sqlite3_os_init(). Typical tasks
2465 ** performed by these routines include allocation or deallocation
2466 ** of static resources, initialization of global variables,
2467 ** setting up a default [sqlite3_vfs] module, or setting up
2468 ** a default configuration using [sqlite3_config()].
2470 ** The application should never invoke either sqlite3_os_init()
2471 ** or sqlite3_os_end() directly. The application should only invoke
2472 ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
2473 ** interface is called automatically by sqlite3_initialize() and
2474 ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
2475 ** implementations for sqlite3_os_init() and sqlite3_os_end()
2476 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
2477 ** When [custom builds | built for other platforms]
2478 ** (using the [SQLITE_OS_OTHER=1] compile-time
2479 ** option) the application must supply a suitable implementation for
2480 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
2481 ** implementation of sqlite3_os_init() or sqlite3_os_end()
2482 ** must return [SQLITE_OK] on success and some other [error code] upon
2483 ** failure.
2485 SQLITE_API int sqlite3_initialize(void);
2486 SQLITE_API int sqlite3_shutdown(void);
2487 SQLITE_API int sqlite3_os_init(void);
2488 SQLITE_API int sqlite3_os_end(void);
2491 ** CAPI3REF: Configuring The SQLite Library
2493 ** The sqlite3_config() interface is used to make global configuration
2494 ** changes to SQLite in order to tune SQLite to the specific needs of
2495 ** the application. The default configuration is recommended for most
2496 ** applications and so this routine is usually not necessary. It is
2497 ** provided to support rare applications with unusual needs.
2499 ** <b>The sqlite3_config() interface is not threadsafe. The application
2500 ** must ensure that no other SQLite interfaces are invoked by other
2501 ** threads while sqlite3_config() is running.</b>
2503 ** The sqlite3_config() interface
2504 ** may only be invoked prior to library initialization using
2505 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
2506 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
2507 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
2508 ** Note, however, that ^sqlite3_config() can be called as part of the
2509 ** implementation of an application-defined [sqlite3_os_init()].
2511 ** The first argument to sqlite3_config() is an integer
2512 ** [configuration option] that determines
2513 ** what property of SQLite is to be configured. Subsequent arguments
2514 ** vary depending on the [configuration option]
2515 ** in the first argument.
2517 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
2518 ** ^If the option is unknown or SQLite is unable to set the option
2519 ** then this routine returns a non-zero [error code].
2521 SQLITE_API int sqlite3_config(int, ...);
2524 ** CAPI3REF: Configure database connections
2525 ** METHOD: sqlite3
2527 ** The sqlite3_db_config() interface is used to make configuration
2528 ** changes to a [database connection]. The interface is similar to
2529 ** [sqlite3_config()] except that the changes apply to a single
2530 ** [database connection] (specified in the first argument).
2532 ** The second argument to sqlite3_db_config(D,V,...) is the
2533 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
2534 ** that indicates what aspect of the [database connection] is being configured.
2535 ** Subsequent arguments vary depending on the configuration verb.
2537 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
2538 ** the call is considered successful.
2540 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
2543 ** CAPI3REF: Memory Allocation Routines
2545 ** An instance of this object defines the interface between SQLite
2546 ** and low-level memory allocation routines.
2548 ** This object is used in only one place in the SQLite interface.
2549 ** A pointer to an instance of this object is the argument to
2550 ** [sqlite3_config()] when the configuration option is
2551 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
2552 ** By creating an instance of this object
2553 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
2554 ** during configuration, an application can specify an alternative
2555 ** memory allocation subsystem for SQLite to use for all of its
2556 ** dynamic memory needs.
2558 ** Note that SQLite comes with several [built-in memory allocators]
2559 ** that are perfectly adequate for the overwhelming majority of applications
2560 ** and that this object is only useful to a tiny minority of applications
2561 ** with specialized memory allocation requirements. This object is
2562 ** also used during testing of SQLite in order to specify an alternative
2563 ** memory allocator that simulates memory out-of-memory conditions in
2564 ** order to verify that SQLite recovers gracefully from such
2565 ** conditions.
2567 ** The xMalloc, xRealloc, and xFree methods must work like the
2568 ** malloc(), realloc() and free() functions from the standard C library.
2569 ** ^SQLite guarantees that the second argument to
2570 ** xRealloc is always a value returned by a prior call to xRoundup.
2572 ** xSize should return the allocated size of a memory allocation
2573 ** previously obtained from xMalloc or xRealloc. The allocated size
2574 ** is always at least as big as the requested size but may be larger.
2576 ** The xRoundup method returns what would be the allocated size of
2577 ** a memory allocation given a particular requested size. Most memory
2578 ** allocators round up memory allocations at least to the next multiple
2579 ** of 8. Some allocators round up to a larger multiple or to a power of 2.
2580 ** Every memory allocation request coming in through [sqlite3_malloc()]
2581 ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
2582 ** that causes the corresponding memory allocation to fail.
2584 ** The xInit method initializes the memory allocator. For example,
2585 ** it might allocate any require mutexes or initialize internal data
2586 ** structures. The xShutdown method is invoked (indirectly) by
2587 ** [sqlite3_shutdown()] and should deallocate any resources acquired
2588 ** by xInit. The pAppData pointer is used as the only parameter to
2589 ** xInit and xShutdown.
2591 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
2592 ** the xInit method, so the xInit method need not be threadsafe. The
2593 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
2594 ** not need to be threadsafe either. For all other methods, SQLite
2595 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
2596 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
2597 ** it is by default) and so the methods are automatically serialized.
2598 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
2599 ** methods must be threadsafe or else make their own arrangements for
2600 ** serialization.
2602 ** SQLite will never invoke xInit() more than once without an intervening
2603 ** call to xShutdown().
2605 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
2606 struct sqlite3_mem_methods {
2607 void *(*xMalloc)(int); /* Memory allocation function */
2608 void (*xFree)(void*); /* Free a prior allocation */
2609 void *(*xRealloc)(void*,int); /* Resize an allocation */
2610 int (*xSize)(void*); /* Return the size of an allocation */
2611 int (*xRoundup)(int); /* Round up request size to allocation size */
2612 int (*xInit)(void*); /* Initialize the memory allocator */
2613 void (*xShutdown)(void*); /* Deinitialize the memory allocator */
2614 void *pAppData; /* Argument to xInit() and xShutdown() */
2618 ** CAPI3REF: Configuration Options
2619 ** KEYWORDS: {configuration option}
2621 ** These constants are the available integer configuration options that
2622 ** can be passed as the first argument to the [sqlite3_config()] interface.
2624 ** New configuration options may be added in future releases of SQLite.
2625 ** Existing configuration options might be discontinued. Applications
2626 ** should check the return code from [sqlite3_config()] to make sure that
2627 ** the call worked. The [sqlite3_config()] interface will return a
2628 ** non-zero [error code] if a discontinued or unsupported configuration option
2629 ** is invoked.
2631 ** <dl>
2632 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
2633 ** <dd>There are no arguments to this option. ^This option sets the
2634 ** [threading mode] to Single-thread. In other words, it disables
2635 ** all mutexing and puts SQLite into a mode where it can only be used
2636 ** by a single thread. ^If SQLite is compiled with
2637 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2638 ** it is not possible to change the [threading mode] from its default
2639 ** value of Single-thread and so [sqlite3_config()] will return
2640 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
2641 ** configuration option.</dd>
2643 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
2644 ** <dd>There are no arguments to this option. ^This option sets the
2645 ** [threading mode] to Multi-thread. In other words, it disables
2646 ** mutexing on [database connection] and [prepared statement] objects.
2647 ** The application is responsible for serializing access to
2648 ** [database connections] and [prepared statements]. But other mutexes
2649 ** are enabled so that SQLite will be safe to use in a multi-threaded
2650 ** environment as long as no two threads attempt to use the same
2651 ** [database connection] at the same time. ^If SQLite is compiled with
2652 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2653 ** it is not possible to set the Multi-thread [threading mode] and
2654 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2655 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
2657 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
2658 ** <dd>There are no arguments to this option. ^This option sets the
2659 ** [threading mode] to Serialized. In other words, this option enables
2660 ** all mutexes including the recursive
2661 ** mutexes on [database connection] and [prepared statement] objects.
2662 ** In this mode (which is the default when SQLite is compiled with
2663 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
2664 ** to [database connections] and [prepared statements] so that the
2665 ** application is free to use the same [database connection] or the
2666 ** same [prepared statement] in different threads at the same time.
2667 ** ^If SQLite is compiled with
2668 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2669 ** it is not possible to set the Serialized [threading mode] and
2670 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2671 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
2673 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
2674 ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
2675 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
2676 ** The argument specifies
2677 ** alternative low-level memory allocation routines to be used in place of
2678 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
2679 ** its own private copy of the content of the [sqlite3_mem_methods] structure
2680 ** before the [sqlite3_config()] call returns.</dd>
2682 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
2683 ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
2684 ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
2685 ** The [sqlite3_mem_methods]
2686 ** structure is filled with the currently defined memory allocation routines.)^
2687 ** This option can be used to overload the default memory allocation
2688 ** routines with a wrapper that simulations memory allocation failure or
2689 ** tracks memory usage, for example. </dd>
2691 ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
2692 ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
2693 ** type int, interpreted as a boolean, which if true provides a hint to
2694 ** SQLite that it should avoid large memory allocations if possible.
2695 ** SQLite will run faster if it is free to make large memory allocations,
2696 ** but some application might prefer to run slower in exchange for
2697 ** guarantees about memory fragmentation that are possible if large
2698 ** allocations are avoided. This hint is normally off.
2699 ** </dd>
2701 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
2702 ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
2703 ** interpreted as a boolean, which enables or disables the collection of
2704 ** memory allocation statistics. ^(When memory allocation statistics are
2705 ** disabled, the following SQLite interfaces become non-operational:
2706 ** <ul>
2707 ** <li> [sqlite3_memory_used()]
2708 ** <li> [sqlite3_memory_highwater()]
2709 ** <li> [sqlite3_soft_heap_limit64()]
2710 ** <li> [sqlite3_status64()]
2711 ** </ul>)^
2712 ** ^Memory allocation statistics are enabled by default unless SQLite is
2713 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2714 ** allocation statistics are disabled by default.
2715 ** </dd>
2717 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2718 ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
2719 ** </dd>
2721 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2722 ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
2723 ** that SQLite can use for the database page cache with the default page
2724 ** cache implementation.
2725 ** This configuration option is a no-op if an application-define page
2726 ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
2727 ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
2728 ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
2729 ** and the number of cache lines (N).
2730 ** The sz argument should be the size of the largest database page
2731 ** (a power of two between 512 and 65536) plus some extra bytes for each
2732 ** page header. ^The number of extra bytes needed by the page header
2733 ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
2734 ** ^It is harmless, apart from the wasted memory,
2735 ** for the sz parameter to be larger than necessary. The pMem
2736 ** argument must be either a NULL pointer or a pointer to an 8-byte
2737 ** aligned block of memory of at least sz*N bytes, otherwise
2738 ** subsequent behavior is undefined.
2739 ** ^When pMem is not NULL, SQLite will strive to use the memory provided
2740 ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
2741 ** a page cache line is larger than sz bytes or if all of the pMem buffer
2742 ** is exhausted.
2743 ** ^If pMem is NULL and N is non-zero, then each database connection
2744 ** does an initial bulk allocation for page cache memory
2745 ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
2746 ** of -1024*N bytes if N is negative, . ^If additional
2747 ** page cache memory is needed beyond what is provided by the initial
2748 ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
2749 ** additional cache line. </dd>
2751 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2752 ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
2753 ** that SQLite will use for all of its dynamic memory allocation needs
2754 ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
2755 ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
2756 ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
2757 ** [SQLITE_ERROR] if invoked otherwise.
2758 ** ^There are three arguments to SQLITE_CONFIG_HEAP:
2759 ** An 8-byte aligned pointer to the memory,
2760 ** the number of bytes in the memory buffer, and the minimum allocation size.
2761 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2762 ** to using its default memory allocator (the system malloc() implementation),
2763 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
2764 ** memory pointer is not NULL then the alternative memory
2765 ** allocator is engaged to handle all of SQLites memory allocation needs.
2766 ** The first pointer (the memory pointer) must be aligned to an 8-byte
2767 ** boundary or subsequent behavior of SQLite will be undefined.
2768 ** The minimum allocation size is capped at 2**12. Reasonable values
2769 ** for the minimum allocation size are 2**5 through 2**8.</dd>
2771 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2772 ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
2773 ** pointer to an instance of the [sqlite3_mutex_methods] structure.
2774 ** The argument specifies alternative low-level mutex routines to be used
2775 ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
2776 ** the content of the [sqlite3_mutex_methods] structure before the call to
2777 ** [sqlite3_config()] returns. ^If SQLite is compiled with
2778 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2779 ** the entire mutexing subsystem is omitted from the build and hence calls to
2780 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2781 ** return [SQLITE_ERROR].</dd>
2783 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2784 ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
2785 ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
2786 ** [sqlite3_mutex_methods]
2787 ** structure is filled with the currently defined mutex routines.)^
2788 ** This option can be used to overload the default mutex allocation
2789 ** routines with a wrapper used to track mutex usage for performance
2790 ** profiling or testing, for example. ^If SQLite is compiled with
2791 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2792 ** the entire mutexing subsystem is omitted from the build and hence calls to
2793 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2794 ** return [SQLITE_ERROR].</dd>
2796 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2797 ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
2798 ** the default size of lookaside memory on each [database connection].
2799 ** The first argument is the
2800 ** size of each lookaside buffer slot and the second is the number of
2801 ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
2802 ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2803 ** option to [sqlite3_db_config()] can be used to change the lookaside
2804 ** configuration on individual connections.)^ </dd>
2806 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2807 ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
2808 ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
2809 ** the interface to a custom page cache implementation.)^
2810 ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
2812 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2813 ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
2814 ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
2815 ** the current page cache implementation into that object.)^ </dd>
2817 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2818 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
2819 ** global [error log].
2820 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2821 ** function with a call signature of void(*)(void*,int,const char*),
2822 ** and a pointer to void. ^If the function pointer is not NULL, it is
2823 ** invoked by [sqlite3_log()] to process each logging event. ^If the
2824 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2825 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2826 ** passed through as the first parameter to the application-defined logger
2827 ** function whenever that function is invoked. ^The second parameter to
2828 ** the logger function is a copy of the first parameter to the corresponding
2829 ** [sqlite3_log()] call and is intended to be a [result code] or an
2830 ** [extended result code]. ^The third parameter passed to the logger is
2831 ** log message after formatting via [sqlite3_snprintf()].
2832 ** The SQLite logging interface is not reentrant; the logger function
2833 ** supplied by the application must not invoke any SQLite interface.
2834 ** In a multi-threaded application, the application-defined logger
2835 ** function must be threadsafe. </dd>
2837 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2838 ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
2839 ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2840 ** then URI handling is globally disabled.)^ ^If URI handling is globally
2841 ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
2842 ** [sqlite3_open16()] or
2843 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2844 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2845 ** connection is opened. ^If it is globally disabled, filenames are
2846 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2847 ** database connection is opened. ^(By default, URI handling is globally
2848 ** disabled. The default value may be changed by compiling with the
2849 ** [SQLITE_USE_URI] symbol defined.)^
2851 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2852 ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
2853 ** argument which is interpreted as a boolean in order to enable or disable
2854 ** the use of covering indices for full table scans in the query optimizer.
2855 ** ^The default setting is determined
2856 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2857 ** if that compile-time option is omitted.
2858 ** The ability to disable the use of covering indices for full table scans
2859 ** is because some incorrectly coded legacy applications might malfunction
2860 ** when the optimization is enabled. Providing the ability to
2861 ** disable the optimization allows the older, buggy application code to work
2862 ** without change even with newer versions of SQLite.
2864 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2865 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2866 ** <dd> These options are obsolete and should not be used by new code.
2867 ** They are retained for backwards compatibility but are now no-ops.
2868 ** </dd>
2870 ** [[SQLITE_CONFIG_SQLLOG]]
2871 ** <dt>SQLITE_CONFIG_SQLLOG
2872 ** <dd>This option is only available if sqlite is compiled with the
2873 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2874 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2875 ** The second should be of type (void*). The callback is invoked by the library
2876 ** in three separate circumstances, identified by the value passed as the
2877 ** fourth parameter. If the fourth parameter is 0, then the database connection
2878 ** passed as the second argument has just been opened. The third argument
2879 ** points to a buffer containing the name of the main database file. If the
2880 ** fourth parameter is 1, then the SQL statement that the third parameter
2881 ** points to has just been executed. Or, if the fourth parameter is 2, then
2882 ** the connection being passed as the second parameter is being closed. The
2883 ** third parameter is passed NULL In this case. An example of using this
2884 ** configuration option can be seen in the "test_sqllog.c" source file in
2885 ** the canonical SQLite source tree.</dd>
2887 ** [[SQLITE_CONFIG_MMAP_SIZE]]
2888 ** <dt>SQLITE_CONFIG_MMAP_SIZE
2889 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2890 ** that are the default mmap size limit (the default setting for
2891 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2892 ** ^The default setting can be overridden by each database connection using
2893 ** either the [PRAGMA mmap_size] command, or by using the
2894 ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
2895 ** will be silently truncated if necessary so that it does not exceed the
2896 ** compile-time maximum mmap size set by the
2897 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2898 ** ^If either argument to this option is negative, then that argument is
2899 ** changed to its compile-time default.
2901 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2902 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2903 ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2904 ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2905 ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2906 ** that specifies the maximum size of the created heap.
2908 ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2909 ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2910 ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2911 ** is a pointer to an integer and writes into that integer the number of extra
2912 ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2913 ** The amount of extra space required can change depending on the compiler,
2914 ** target platform, and SQLite version.
2916 ** [[SQLITE_CONFIG_PMASZ]]
2917 ** <dt>SQLITE_CONFIG_PMASZ
2918 ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2919 ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2920 ** sorter to that integer. The default minimum PMA Size is set by the
2921 ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
2922 ** to help with sort operations when multithreaded sorting
2923 ** is enabled (using the [PRAGMA threads] command) and the amount of content
2924 ** to be sorted exceeds the page size times the minimum of the
2925 ** [PRAGMA cache_size] setting and this value.
2927 ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
2928 ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
2929 ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
2930 ** becomes the [statement journal] spill-to-disk threshold.
2931 ** [Statement journals] are held in memory until their size (in bytes)
2932 ** exceeds this threshold, at which point they are written to disk.
2933 ** Or if the threshold is -1, statement journals are always held
2934 ** exclusively in memory.
2935 ** Since many statement journals never become large, setting the spill
2936 ** threshold to a value such as 64KiB can greatly reduce the amount of
2937 ** I/O required to support statement rollback.
2938 ** The default value for this setting is controlled by the
2939 ** [SQLITE_STMTJRNL_SPILL] compile-time option.
2940 ** </dl>
2942 #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
2943 #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
2944 #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
2945 #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
2946 #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
2947 #define SQLITE_CONFIG_SCRATCH 6 /* No longer used */
2948 #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
2949 #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
2950 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
2951 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
2952 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
2953 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2954 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
2955 #define SQLITE_CONFIG_PCACHE 14 /* no-op */
2956 #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
2957 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
2958 #define SQLITE_CONFIG_URI 17 /* int */
2959 #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
2960 #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
2961 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
2962 #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
2963 #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
2964 #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
2965 #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
2966 #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
2967 #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
2968 #define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
2971 ** CAPI3REF: Database Connection Configuration Options
2973 ** These constants are the available integer configuration options that
2974 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2976 ** New configuration options may be added in future releases of SQLite.
2977 ** Existing configuration options might be discontinued. Applications
2978 ** should check the return code from [sqlite3_db_config()] to make sure that
2979 ** the call worked. ^The [sqlite3_db_config()] interface will return a
2980 ** non-zero [error code] if a discontinued or unsupported configuration option
2981 ** is invoked.
2983 ** <dl>
2984 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2985 ** <dd> ^This option takes three additional arguments that determine the
2986 ** [lookaside memory allocator] configuration for the [database connection].
2987 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2988 ** pointer to a memory buffer to use for lookaside memory.
2989 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2990 ** may be NULL in which case SQLite will allocate the
2991 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2992 ** size of each lookaside buffer slot. ^The third argument is the number of
2993 ** slots. The size of the buffer in the first argument must be greater than
2994 ** or equal to the product of the second and third arguments. The buffer
2995 ** must be aligned to an 8-byte boundary. ^If the second argument to
2996 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2997 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
2998 ** configuration for a database connection can only be changed when that
2999 ** connection is not currently using lookaside memory, or in other words
3000 ** when the "current value" returned by
3001 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
3002 ** Any attempt to change the lookaside memory configuration when lookaside
3003 ** memory is in use leaves the configuration unchanged and returns
3004 ** [SQLITE_BUSY].)^</dd>
3006 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
3007 ** <dd> ^This option is used to enable or disable the enforcement of
3008 ** [foreign key constraints]. There should be two additional arguments.
3009 ** The first argument is an integer which is 0 to disable FK enforcement,
3010 ** positive to enable FK enforcement or negative to leave FK enforcement
3011 ** unchanged. The second parameter is a pointer to an integer into which
3012 ** is written 0 or 1 to indicate whether FK enforcement is off or on
3013 ** following this call. The second parameter may be a NULL pointer, in
3014 ** which case the FK enforcement setting is not reported back. </dd>
3016 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
3017 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
3018 ** There should be two additional arguments.
3019 ** The first argument is an integer which is 0 to disable triggers,
3020 ** positive to enable triggers or negative to leave the setting unchanged.
3021 ** The second parameter is a pointer to an integer into which
3022 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
3023 ** following this call. The second parameter may be a NULL pointer, in
3024 ** which case the trigger setting is not reported back. </dd>
3026 ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
3027 ** <dd> ^This option is used to enable or disable the two-argument
3028 ** version of the [fts3_tokenizer()] function which is part of the
3029 ** [FTS3] full-text search engine extension.
3030 ** There should be two additional arguments.
3031 ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
3032 ** positive to enable fts3_tokenizer() or negative to leave the setting
3033 ** unchanged.
3034 ** The second parameter is a pointer to an integer into which
3035 ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
3036 ** following this call. The second parameter may be a NULL pointer, in
3037 ** which case the new setting is not reported back. </dd>
3039 ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
3040 ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
3041 ** interface independently of the [load_extension()] SQL function.
3042 ** The [sqlite3_enable_load_extension()] API enables or disables both the
3043 ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
3044 ** There should be two additional arguments.
3045 ** When the first argument to this interface is 1, then only the C-API is
3046 ** enabled and the SQL function remains disabled. If the first argument to
3047 ** this interface is 0, then both the C-API and the SQL function are disabled.
3048 ** If the first argument is -1, then no changes are made to state of either the
3049 ** C-API or the SQL function.
3050 ** The second parameter is a pointer to an integer into which
3051 ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
3052 ** is disabled or enabled following this call. The second parameter may
3053 ** be a NULL pointer, in which case the new setting is not reported back.
3054 ** </dd>
3056 ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
3057 ** <dd> ^This option is used to change the name of the "main" database
3058 ** schema. ^The sole argument is a pointer to a constant UTF8 string
3059 ** which will become the new schema name in place of "main". ^SQLite
3060 ** does not make a copy of the new main schema name string, so the application
3061 ** must ensure that the argument passed into this DBCONFIG option is unchanged
3062 ** until after the database connection closes.
3063 ** </dd>
3065 ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
3066 ** <dd> Usually, when a database in wal mode is closed or detached from a
3067 ** database handle, SQLite checks if this will mean that there are now no
3068 ** connections at all to the database. If so, it performs a checkpoint
3069 ** operation before closing the connection. This option may be used to
3070 ** override this behaviour. The first parameter passed to this operation
3071 ** is an integer - non-zero to disable checkpoints-on-close, or zero (the
3072 ** default) to enable them. The second parameter is a pointer to an integer
3073 ** into which is written 0 or 1 to indicate whether checkpoints-on-close
3074 ** have been disabled - 0 if they are not disabled, 1 if they are.
3075 ** </dd>
3077 ** <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
3078 ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
3079 ** the [query planner stability guarantee] (QPSG). When the QPSG is active,
3080 ** a single SQL query statement will always use the same algorithm regardless
3081 ** of values of [bound parameters].)^ The QPSG disables some query optimizations
3082 ** that look at the values of bound parameters, which can make some queries
3083 ** slower. But the QPSG has the advantage of more predictable behavior. With
3084 ** the QPSG active, SQLite will always use the same query plan in the field as
3085 ** was used during testing in the lab.
3086 ** </dd>
3088 ** </dl>
3090 #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
3091 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
3092 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
3093 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
3094 #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
3095 #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
3096 #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
3097 #define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
3101 ** CAPI3REF: Enable Or Disable Extended Result Codes
3102 ** METHOD: sqlite3
3104 ** ^The sqlite3_extended_result_codes() routine enables or disables the
3105 ** [extended result codes] feature of SQLite. ^The extended result
3106 ** codes are disabled by default for historical compatibility.
3108 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
3111 ** CAPI3REF: Last Insert Rowid
3112 ** METHOD: sqlite3
3114 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
3115 ** has a unique 64-bit signed
3116 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
3117 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
3118 ** names are not also used by explicitly declared columns. ^If
3119 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
3120 ** is another alias for the rowid.
3122 ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
3123 ** the most recent successful [INSERT] into a rowid table or [virtual table]
3124 ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
3125 ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
3126 ** on the database connection D, then sqlite3_last_insert_rowid(D) returns
3127 ** zero.
3129 ** As well as being set automatically as rows are inserted into database
3130 ** tables, the value returned by this function may be set explicitly by
3131 ** [sqlite3_set_last_insert_rowid()]
3133 ** Some virtual table implementations may INSERT rows into rowid tables as
3134 ** part of committing a transaction (e.g. to flush data accumulated in memory
3135 ** to disk). In this case subsequent calls to this function return the rowid
3136 ** associated with these internal INSERT operations, which leads to
3137 ** unintuitive results. Virtual table implementations that do write to rowid
3138 ** tables in this way can avoid this problem by restoring the original
3139 ** rowid value using [sqlite3_set_last_insert_rowid()] before returning
3140 ** control to the user.
3142 ** ^(If an [INSERT] occurs within a trigger then this routine will
3143 ** return the [rowid] of the inserted row as long as the trigger is
3144 ** running. Once the trigger program ends, the value returned
3145 ** by this routine reverts to what it was before the trigger was fired.)^
3147 ** ^An [INSERT] that fails due to a constraint violation is not a
3148 ** successful [INSERT] and does not change the value returned by this
3149 ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
3150 ** and INSERT OR ABORT make no changes to the return value of this
3151 ** routine when their insertion fails. ^(When INSERT OR REPLACE
3152 ** encounters a constraint violation, it does not fail. The
3153 ** INSERT continues to completion after deleting rows that caused
3154 ** the constraint problem so INSERT OR REPLACE will always change
3155 ** the return value of this interface.)^
3157 ** ^For the purposes of this routine, an [INSERT] is considered to
3158 ** be successful even if it is subsequently rolled back.
3160 ** This function is accessible to SQL statements via the
3161 ** [last_insert_rowid() SQL function].
3163 ** If a separate thread performs a new [INSERT] on the same
3164 ** database connection while the [sqlite3_last_insert_rowid()]
3165 ** function is running and thus changes the last insert [rowid],
3166 ** then the value returned by [sqlite3_last_insert_rowid()] is
3167 ** unpredictable and might not equal either the old or the new
3168 ** last insert [rowid].
3170 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
3173 ** CAPI3REF: Set the Last Insert Rowid value.
3174 ** METHOD: sqlite3
3176 ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
3177 ** set the value returned by calling sqlite3_last_insert_rowid(D) to R
3178 ** without inserting a row into the database.
3180 SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
3183 ** CAPI3REF: Count The Number Of Rows Modified
3184 ** METHOD: sqlite3
3186 ** ^This function returns the number of rows modified, inserted or
3187 ** deleted by the most recently completed INSERT, UPDATE or DELETE
3188 ** statement on the database connection specified by the only parameter.
3189 ** ^Executing any other type of SQL statement does not modify the value
3190 ** returned by this function.
3192 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
3193 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
3194 ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
3196 ** Changes to a view that are intercepted by
3197 ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
3198 ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
3199 ** DELETE statement run on a view is always zero. Only changes made to real
3200 ** tables are counted.
3202 ** Things are more complicated if the sqlite3_changes() function is
3203 ** executed while a trigger program is running. This may happen if the
3204 ** program uses the [changes() SQL function], or if some other callback
3205 ** function invokes sqlite3_changes() directly. Essentially:
3207 ** <ul>
3208 ** <li> ^(Before entering a trigger program the value returned by
3209 ** sqlite3_changes() function is saved. After the trigger program
3210 ** has finished, the original value is restored.)^
3212 ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
3213 ** statement sets the value returned by sqlite3_changes()
3214 ** upon completion as normal. Of course, this value will not include
3215 ** any changes performed by sub-triggers, as the sqlite3_changes()
3216 ** value will be saved and restored after each sub-trigger has run.)^
3217 ** </ul>
3219 ** ^This means that if the changes() SQL function (or similar) is used
3220 ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
3221 ** returns the value as set when the calling statement began executing.
3222 ** ^If it is used by the second or subsequent such statement within a trigger
3223 ** program, the value returned reflects the number of rows modified by the
3224 ** previous INSERT, UPDATE or DELETE statement within the same trigger.
3226 ** See also the [sqlite3_total_changes()] interface, the
3227 ** [count_changes pragma], and the [changes() SQL function].
3229 ** If a separate thread makes changes on the same database connection
3230 ** while [sqlite3_changes()] is running then the value returned
3231 ** is unpredictable and not meaningful.
3233 SQLITE_API int sqlite3_changes(sqlite3*);
3236 ** CAPI3REF: Total Number Of Rows Modified
3237 ** METHOD: sqlite3
3239 ** ^This function returns the total number of rows inserted, modified or
3240 ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
3241 ** since the database connection was opened, including those executed as
3242 ** part of trigger programs. ^Executing any other type of SQL statement
3243 ** does not affect the value returned by sqlite3_total_changes().
3245 ** ^Changes made as part of [foreign key actions] are included in the
3246 ** count, but those made as part of REPLACE constraint resolution are
3247 ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
3248 ** are not counted.
3250 ** See also the [sqlite3_changes()] interface, the
3251 ** [count_changes pragma], and the [total_changes() SQL function].
3253 ** If a separate thread makes changes on the same database connection
3254 ** while [sqlite3_total_changes()] is running then the value
3255 ** returned is unpredictable and not meaningful.
3257 SQLITE_API int sqlite3_total_changes(sqlite3*);
3260 ** CAPI3REF: Interrupt A Long-Running Query
3261 ** METHOD: sqlite3
3263 ** ^This function causes any pending database operation to abort and
3264 ** return at its earliest opportunity. This routine is typically
3265 ** called in response to a user action such as pressing "Cancel"
3266 ** or Ctrl-C where the user wants a long query operation to halt
3267 ** immediately.
3269 ** ^It is safe to call this routine from a thread different from the
3270 ** thread that is currently running the database operation. But it
3271 ** is not safe to call this routine with a [database connection] that
3272 ** is closed or might close before sqlite3_interrupt() returns.
3274 ** ^If an SQL operation is very nearly finished at the time when
3275 ** sqlite3_interrupt() is called, then it might not have an opportunity
3276 ** to be interrupted and might continue to completion.
3278 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
3279 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
3280 ** that is inside an explicit transaction, then the entire transaction
3281 ** will be rolled back automatically.
3283 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
3284 ** SQL statements on [database connection] D complete. ^Any new SQL statements
3285 ** that are started after the sqlite3_interrupt() call and before the
3286 ** running statements reaches zero are interrupted as if they had been
3287 ** running prior to the sqlite3_interrupt() call. ^New SQL statements
3288 ** that are started after the running statement count reaches zero are
3289 ** not effected by the sqlite3_interrupt().
3290 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
3291 ** SQL statements is a no-op and has no effect on SQL statements
3292 ** that are started after the sqlite3_interrupt() call returns.
3294 SQLITE_API void sqlite3_interrupt(sqlite3*);
3297 ** CAPI3REF: Determine If An SQL Statement Is Complete
3299 ** These routines are useful during command-line input to determine if the
3300 ** currently entered text seems to form a complete SQL statement or
3301 ** if additional input is needed before sending the text into
3302 ** SQLite for parsing. ^These routines return 1 if the input string
3303 ** appears to be a complete SQL statement. ^A statement is judged to be
3304 ** complete if it ends with a semicolon token and is not a prefix of a
3305 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
3306 ** string literals or quoted identifier names or comments are not
3307 ** independent tokens (they are part of the token in which they are
3308 ** embedded) and thus do not count as a statement terminator. ^Whitespace
3309 ** and comments that follow the final semicolon are ignored.
3311 ** ^These routines return 0 if the statement is incomplete. ^If a
3312 ** memory allocation fails, then SQLITE_NOMEM is returned.
3314 ** ^These routines do not parse the SQL statements thus
3315 ** will not detect syntactically incorrect SQL.
3317 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
3318 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
3319 ** automatically by sqlite3_complete16(). If that initialization fails,
3320 ** then the return value from sqlite3_complete16() will be non-zero
3321 ** regardless of whether or not the input SQL is complete.)^
3323 ** The input to [sqlite3_complete()] must be a zero-terminated
3324 ** UTF-8 string.
3326 ** The input to [sqlite3_complete16()] must be a zero-terminated
3327 ** UTF-16 string in native byte order.
3329 SQLITE_API int sqlite3_complete(const char *sql);
3330 SQLITE_API int sqlite3_complete16(const void *sql);
3333 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
3334 ** KEYWORDS: {busy-handler callback} {busy handler}
3335 ** METHOD: sqlite3
3337 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
3338 ** that might be invoked with argument P whenever
3339 ** an attempt is made to access a database table associated with
3340 ** [database connection] D when another thread
3341 ** or process has the table locked.
3342 ** The sqlite3_busy_handler() interface is used to implement
3343 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
3345 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
3346 ** is returned immediately upon encountering the lock. ^If the busy callback
3347 ** is not NULL, then the callback might be invoked with two arguments.
3349 ** ^The first argument to the busy handler is a copy of the void* pointer which
3350 ** is the third argument to sqlite3_busy_handler(). ^The second argument to
3351 ** the busy handler callback is the number of times that the busy handler has
3352 ** been invoked previously for the same locking event. ^If the
3353 ** busy callback returns 0, then no additional attempts are made to
3354 ** access the database and [SQLITE_BUSY] is returned
3355 ** to the application.
3356 ** ^If the callback returns non-zero, then another attempt
3357 ** is made to access the database and the cycle repeats.
3359 ** The presence of a busy handler does not guarantee that it will be invoked
3360 ** when there is lock contention. ^If SQLite determines that invoking the busy
3361 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
3362 ** to the application instead of invoking the
3363 ** busy handler.
3364 ** Consider a scenario where one process is holding a read lock that
3365 ** it is trying to promote to a reserved lock and
3366 ** a second process is holding a reserved lock that it is trying
3367 ** to promote to an exclusive lock. The first process cannot proceed
3368 ** because it is blocked by the second and the second process cannot
3369 ** proceed because it is blocked by the first. If both processes
3370 ** invoke the busy handlers, neither will make any progress. Therefore,
3371 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
3372 ** will induce the first process to release its read lock and allow
3373 ** the second process to proceed.
3375 ** ^The default busy callback is NULL.
3377 ** ^(There can only be a single busy handler defined for each
3378 ** [database connection]. Setting a new busy handler clears any
3379 ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
3380 ** or evaluating [PRAGMA busy_timeout=N] will change the
3381 ** busy handler and thus clear any previously set busy handler.
3383 ** The busy callback should not take any actions which modify the
3384 ** database connection that invoked the busy handler. In other words,
3385 ** the busy handler is not reentrant. Any such actions
3386 ** result in undefined behavior.
3388 ** A busy handler must not close the database connection
3389 ** or [prepared statement] that invoked the busy handler.
3391 SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
3394 ** CAPI3REF: Set A Busy Timeout
3395 ** METHOD: sqlite3
3397 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
3398 ** for a specified amount of time when a table is locked. ^The handler
3399 ** will sleep multiple times until at least "ms" milliseconds of sleeping
3400 ** have accumulated. ^After at least "ms" milliseconds of sleeping,
3401 ** the handler returns 0 which causes [sqlite3_step()] to return
3402 ** [SQLITE_BUSY].
3404 ** ^Calling this routine with an argument less than or equal to zero
3405 ** turns off all busy handlers.
3407 ** ^(There can only be a single busy handler for a particular
3408 ** [database connection] at any given moment. If another busy handler
3409 ** was defined (using [sqlite3_busy_handler()]) prior to calling
3410 ** this routine, that other busy handler is cleared.)^
3412 ** See also: [PRAGMA busy_timeout]
3414 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
3417 ** CAPI3REF: Convenience Routines For Running Queries
3418 ** METHOD: sqlite3
3420 ** This is a legacy interface that is preserved for backwards compatibility.
3421 ** Use of this interface is not recommended.
3423 ** Definition: A <b>result table</b> is memory data structure created by the
3424 ** [sqlite3_get_table()] interface. A result table records the
3425 ** complete query results from one or more queries.
3427 ** The table conceptually has a number of rows and columns. But
3428 ** these numbers are not part of the result table itself. These
3429 ** numbers are obtained separately. Let N be the number of rows
3430 ** and M be the number of columns.
3432 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
3433 ** There are (N+1)*M elements in the array. The first M pointers point
3434 ** to zero-terminated strings that contain the names of the columns.
3435 ** The remaining entries all point to query results. NULL values result
3436 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
3437 ** string representation as returned by [sqlite3_column_text()].
3439 ** A result table might consist of one or more memory allocations.
3440 ** It is not safe to pass a result table directly to [sqlite3_free()].
3441 ** A result table should be deallocated using [sqlite3_free_table()].
3443 ** ^(As an example of the result table format, suppose a query result
3444 ** is as follows:
3446 ** <blockquote><pre>
3447 ** Name | Age
3448 ** -----------------------
3449 ** Alice | 43
3450 ** Bob | 28
3451 ** Cindy | 21
3452 ** </pre></blockquote>
3454 ** There are two column (M==2) and three rows (N==3). Thus the
3455 ** result table has 8 entries. Suppose the result table is stored
3456 ** in an array names azResult. Then azResult holds this content:
3458 ** <blockquote><pre>
3459 ** azResult&#91;0] = "Name";
3460 ** azResult&#91;1] = "Age";
3461 ** azResult&#91;2] = "Alice";
3462 ** azResult&#91;3] = "43";
3463 ** azResult&#91;4] = "Bob";
3464 ** azResult&#91;5] = "28";
3465 ** azResult&#91;6] = "Cindy";
3466 ** azResult&#91;7] = "21";
3467 ** </pre></blockquote>)^
3469 ** ^The sqlite3_get_table() function evaluates one or more
3470 ** semicolon-separated SQL statements in the zero-terminated UTF-8
3471 ** string of its 2nd parameter and returns a result table to the
3472 ** pointer given in its 3rd parameter.
3474 ** After the application has finished with the result from sqlite3_get_table(),
3475 ** it must pass the result table pointer to sqlite3_free_table() in order to
3476 ** release the memory that was malloced. Because of the way the
3477 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
3478 ** function must not try to call [sqlite3_free()] directly. Only
3479 ** [sqlite3_free_table()] is able to release the memory properly and safely.
3481 ** The sqlite3_get_table() interface is implemented as a wrapper around
3482 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
3483 ** to any internal data structures of SQLite. It uses only the public
3484 ** interface defined here. As a consequence, errors that occur in the
3485 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
3486 ** reflected in subsequent calls to [sqlite3_errcode()] or
3487 ** [sqlite3_errmsg()].
3489 SQLITE_API int sqlite3_get_table(
3490 sqlite3 *db, /* An open database */
3491 const char *zSql, /* SQL to be evaluated */
3492 char ***pazResult, /* Results of the query */
3493 int *pnRow, /* Number of result rows written here */
3494 int *pnColumn, /* Number of result columns written here */
3495 char **pzErrmsg /* Error msg written here */
3497 SQLITE_API void sqlite3_free_table(char **result);
3500 ** CAPI3REF: Formatted String Printing Functions
3502 ** These routines are work-alikes of the "printf()" family of functions
3503 ** from the standard C library.
3504 ** These routines understand most of the common K&R formatting options,
3505 ** plus some additional non-standard formats, detailed below.
3506 ** Note that some of the more obscure formatting options from recent
3507 ** C-library standards are omitted from this implementation.
3509 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
3510 ** results into memory obtained from [sqlite3_malloc()].
3511 ** The strings returned by these two routines should be
3512 ** released by [sqlite3_free()]. ^Both routines return a
3513 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
3514 ** memory to hold the resulting string.
3516 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
3517 ** the standard C library. The result is written into the
3518 ** buffer supplied as the second parameter whose size is given by
3519 ** the first parameter. Note that the order of the
3520 ** first two parameters is reversed from snprintf().)^ This is an
3521 ** historical accident that cannot be fixed without breaking
3522 ** backwards compatibility. ^(Note also that sqlite3_snprintf()
3523 ** returns a pointer to its buffer instead of the number of
3524 ** characters actually written into the buffer.)^ We admit that
3525 ** the number of characters written would be a more useful return
3526 ** value but we cannot change the implementation of sqlite3_snprintf()
3527 ** now without breaking compatibility.
3529 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
3530 ** guarantees that the buffer is always zero-terminated. ^The first
3531 ** parameter "n" is the total size of the buffer, including space for
3532 ** the zero terminator. So the longest string that can be completely
3533 ** written will be n-1 characters.
3535 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
3537 ** These routines all implement some additional formatting
3538 ** options that are useful for constructing SQL statements.
3539 ** All of the usual printf() formatting options apply. In addition, there
3540 ** is are "%q", "%Q", "%w" and "%z" options.
3542 ** ^(The %q option works like %s in that it substitutes a nul-terminated
3543 ** string from the argument list. But %q also doubles every '\'' character.
3544 ** %q is designed for use inside a string literal.)^ By doubling each '\''
3545 ** character it escapes that character and allows it to be inserted into
3546 ** the string.
3548 ** For example, assume the string variable zText contains text as follows:
3550 ** <blockquote><pre>
3551 ** char *zText = "It's a happy day!";
3552 ** </pre></blockquote>
3554 ** One can use this text in an SQL statement as follows:
3556 ** <blockquote><pre>
3557 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
3558 ** sqlite3_exec(db, zSQL, 0, 0, 0);
3559 ** sqlite3_free(zSQL);
3560 ** </pre></blockquote>
3562 ** Because the %q format string is used, the '\'' character in zText
3563 ** is escaped and the SQL generated is as follows:
3565 ** <blockquote><pre>
3566 ** INSERT INTO table1 VALUES('It''s a happy day!')
3567 ** </pre></blockquote>
3569 ** This is correct. Had we used %s instead of %q, the generated SQL
3570 ** would have looked like this:
3572 ** <blockquote><pre>
3573 ** INSERT INTO table1 VALUES('It's a happy day!');
3574 ** </pre></blockquote>
3576 ** This second example is an SQL syntax error. As a general rule you should
3577 ** always use %q instead of %s when inserting text into a string literal.
3579 ** ^(The %Q option works like %q except it also adds single quotes around
3580 ** the outside of the total string. Additionally, if the parameter in the
3581 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
3582 ** single quotes).)^ So, for example, one could say:
3584 ** <blockquote><pre>
3585 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
3586 ** sqlite3_exec(db, zSQL, 0, 0, 0);
3587 ** sqlite3_free(zSQL);
3588 ** </pre></blockquote>
3590 ** The code above will render a correct SQL statement in the zSQL
3591 ** variable even if the zText variable is a NULL pointer.
3593 ** ^(The "%w" formatting option is like "%q" except that it expects to
3594 ** be contained within double-quotes instead of single quotes, and it
3595 ** escapes the double-quote character instead of the single-quote
3596 ** character.)^ The "%w" formatting option is intended for safely inserting
3597 ** table and column names into a constructed SQL statement.
3599 ** ^(The "%z" formatting option works like "%s" but with the
3600 ** addition that after the string has been read and copied into
3601 ** the result, [sqlite3_free()] is called on the input string.)^
3603 SQLITE_API char *sqlite3_mprintf(const char*,...);
3604 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
3605 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
3606 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
3609 ** CAPI3REF: Memory Allocation Subsystem
3611 ** The SQLite core uses these three routines for all of its own
3612 ** internal memory allocation needs. "Core" in the previous sentence
3613 ** does not include operating-system specific VFS implementation. The
3614 ** Windows VFS uses native malloc() and free() for some operations.
3616 ** ^The sqlite3_malloc() routine returns a pointer to a block
3617 ** of memory at least N bytes in length, where N is the parameter.
3618 ** ^If sqlite3_malloc() is unable to obtain sufficient free
3619 ** memory, it returns a NULL pointer. ^If the parameter N to
3620 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
3621 ** a NULL pointer.
3623 ** ^The sqlite3_malloc64(N) routine works just like
3624 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
3625 ** of a signed 32-bit integer.
3627 ** ^Calling sqlite3_free() with a pointer previously returned
3628 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
3629 ** that it might be reused. ^The sqlite3_free() routine is
3630 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
3631 ** to sqlite3_free() is harmless. After being freed, memory
3632 ** should neither be read nor written. Even reading previously freed
3633 ** memory might result in a segmentation fault or other severe error.
3634 ** Memory corruption, a segmentation fault, or other severe error
3635 ** might result if sqlite3_free() is called with a non-NULL pointer that
3636 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
3638 ** ^The sqlite3_realloc(X,N) interface attempts to resize a
3639 ** prior memory allocation X to be at least N bytes.
3640 ** ^If the X parameter to sqlite3_realloc(X,N)
3641 ** is a NULL pointer then its behavior is identical to calling
3642 ** sqlite3_malloc(N).
3643 ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
3644 ** negative then the behavior is exactly the same as calling
3645 ** sqlite3_free(X).
3646 ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
3647 ** of at least N bytes in size or NULL if insufficient memory is available.
3648 ** ^If M is the size of the prior allocation, then min(N,M) bytes
3649 ** of the prior allocation are copied into the beginning of buffer returned
3650 ** by sqlite3_realloc(X,N) and the prior allocation is freed.
3651 ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
3652 ** prior allocation is not freed.
3654 ** ^The sqlite3_realloc64(X,N) interfaces works the same as
3655 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
3656 ** of a 32-bit signed integer.
3658 ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
3659 ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
3660 ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
3661 ** ^The value returned by sqlite3_msize(X) might be larger than the number
3662 ** of bytes requested when X was allocated. ^If X is a NULL pointer then
3663 ** sqlite3_msize(X) returns zero. If X points to something that is not
3664 ** the beginning of memory allocation, or if it points to a formerly
3665 ** valid memory allocation that has now been freed, then the behavior
3666 ** of sqlite3_msize(X) is undefined and possibly harmful.
3668 ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
3669 ** sqlite3_malloc64(), and sqlite3_realloc64()
3670 ** is always aligned to at least an 8 byte boundary, or to a
3671 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
3672 ** option is used.
3674 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
3675 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
3676 ** implementation of these routines to be omitted. That capability
3677 ** is no longer provided. Only built-in memory allocators can be used.
3679 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
3680 ** the system malloc() and free() directly when converting
3681 ** filenames between the UTF-8 encoding used by SQLite
3682 ** and whatever filename encoding is used by the particular Windows
3683 ** installation. Memory allocation errors were detected, but
3684 ** they were reported back as [SQLITE_CANTOPEN] or
3685 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
3687 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
3688 ** must be either NULL or else pointers obtained from a prior
3689 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
3690 ** not yet been released.
3692 ** The application must not read or write any part of
3693 ** a block of memory after it has been released using
3694 ** [sqlite3_free()] or [sqlite3_realloc()].
3696 SQLITE_API void *sqlite3_malloc(int);
3697 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
3698 SQLITE_API void *sqlite3_realloc(void*, int);
3699 SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
3700 SQLITE_API void sqlite3_free(void*);
3701 SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
3704 ** CAPI3REF: Memory Allocator Statistics
3706 ** SQLite provides these two interfaces for reporting on the status
3707 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
3708 ** routines, which form the built-in memory allocation subsystem.
3710 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
3711 ** of memory currently outstanding (malloced but not freed).
3712 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
3713 ** value of [sqlite3_memory_used()] since the high-water mark
3714 ** was last reset. ^The values returned by [sqlite3_memory_used()] and
3715 ** [sqlite3_memory_highwater()] include any overhead
3716 ** added by SQLite in its implementation of [sqlite3_malloc()],
3717 ** but not overhead added by the any underlying system library
3718 ** routines that [sqlite3_malloc()] may call.
3720 ** ^The memory high-water mark is reset to the current value of
3721 ** [sqlite3_memory_used()] if and only if the parameter to
3722 ** [sqlite3_memory_highwater()] is true. ^The value returned
3723 ** by [sqlite3_memory_highwater(1)] is the high-water mark
3724 ** prior to the reset.
3726 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
3727 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
3730 ** CAPI3REF: Pseudo-Random Number Generator
3732 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
3733 ** select random [ROWID | ROWIDs] when inserting new records into a table that
3734 ** already uses the largest possible [ROWID]. The PRNG is also used for
3735 ** the build-in random() and randomblob() SQL functions. This interface allows
3736 ** applications to access the same PRNG for other purposes.
3738 ** ^A call to this routine stores N bytes of randomness into buffer P.
3739 ** ^The P parameter can be a NULL pointer.
3741 ** ^If this routine has not been previously called or if the previous
3742 ** call had N less than one or a NULL pointer for P, then the PRNG is
3743 ** seeded using randomness obtained from the xRandomness method of
3744 ** the default [sqlite3_vfs] object.
3745 ** ^If the previous call to this routine had an N of 1 or more and a
3746 ** non-NULL P then the pseudo-randomness is generated
3747 ** internally and without recourse to the [sqlite3_vfs] xRandomness
3748 ** method.
3750 SQLITE_API void sqlite3_randomness(int N, void *P);
3753 ** CAPI3REF: Compile-Time Authorization Callbacks
3754 ** METHOD: sqlite3
3755 ** KEYWORDS: {authorizer callback}
3757 ** ^This routine registers an authorizer callback with a particular
3758 ** [database connection], supplied in the first argument.
3759 ** ^The authorizer callback is invoked as SQL statements are being compiled
3760 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
3761 ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
3762 ** and [sqlite3_prepare16_v3()]. ^At various
3763 ** points during the compilation process, as logic is being created
3764 ** to perform various actions, the authorizer callback is invoked to
3765 ** see if those actions are allowed. ^The authorizer callback should
3766 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
3767 ** specific action but allow the SQL statement to continue to be
3768 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
3769 ** rejected with an error. ^If the authorizer callback returns
3770 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
3771 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
3772 ** the authorizer will fail with an error message.
3774 ** When the callback returns [SQLITE_OK], that means the operation
3775 ** requested is ok. ^When the callback returns [SQLITE_DENY], the
3776 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
3777 ** authorizer will fail with an error message explaining that
3778 ** access is denied.
3780 ** ^The first parameter to the authorizer callback is a copy of the third
3781 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
3782 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
3783 ** the particular action to be authorized. ^The third through sixth parameters
3784 ** to the callback are either NULL pointers or zero-terminated strings
3785 ** that contain additional details about the action to be authorized.
3786 ** Applications must always be prepared to encounter a NULL pointer in any
3787 ** of the third through the sixth parameters of the authorization callback.
3789 ** ^If the action code is [SQLITE_READ]
3790 ** and the callback returns [SQLITE_IGNORE] then the
3791 ** [prepared statement] statement is constructed to substitute
3792 ** a NULL value in place of the table column that would have
3793 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
3794 ** return can be used to deny an untrusted user access to individual
3795 ** columns of a table.
3796 ** ^When a table is referenced by a [SELECT] but no column values are
3797 ** extracted from that table (for example in a query like
3798 ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
3799 ** is invoked once for that table with a column name that is an empty string.
3800 ** ^If the action code is [SQLITE_DELETE] and the callback returns
3801 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
3802 ** [truncate optimization] is disabled and all rows are deleted individually.
3804 ** An authorizer is used when [sqlite3_prepare | preparing]
3805 ** SQL statements from an untrusted source, to ensure that the SQL statements
3806 ** do not try to access data they are not allowed to see, or that they do not
3807 ** try to execute malicious statements that damage the database. For
3808 ** example, an application may allow a user to enter arbitrary
3809 ** SQL queries for evaluation by a database. But the application does
3810 ** not want the user to be able to make arbitrary changes to the
3811 ** database. An authorizer could then be put in place while the
3812 ** user-entered SQL is being [sqlite3_prepare | prepared] that
3813 ** disallows everything except [SELECT] statements.
3815 ** Applications that need to process SQL from untrusted sources
3816 ** might also consider lowering resource limits using [sqlite3_limit()]
3817 ** and limiting database size using the [max_page_count] [PRAGMA]
3818 ** in addition to using an authorizer.
3820 ** ^(Only a single authorizer can be in place on a database connection
3821 ** at a time. Each call to sqlite3_set_authorizer overrides the
3822 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
3823 ** The authorizer is disabled by default.
3825 ** The authorizer callback must not do anything that will modify
3826 ** the database connection that invoked the authorizer callback.
3827 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3828 ** database connections for the meaning of "modify" in this paragraph.
3830 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3831 ** statement might be re-prepared during [sqlite3_step()] due to a
3832 ** schema change. Hence, the application should ensure that the
3833 ** correct authorizer callback remains in place during the [sqlite3_step()].
3835 ** ^Note that the authorizer callback is invoked only during
3836 ** [sqlite3_prepare()] or its variants. Authorization is not
3837 ** performed during statement evaluation in [sqlite3_step()], unless
3838 ** as stated in the previous paragraph, sqlite3_step() invokes
3839 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3841 SQLITE_API int sqlite3_set_authorizer(
3842 sqlite3*,
3843 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3844 void *pUserData
3848 ** CAPI3REF: Authorizer Return Codes
3850 ** The [sqlite3_set_authorizer | authorizer callback function] must
3851 ** return either [SQLITE_OK] or one of these two constants in order
3852 ** to signal SQLite whether or not the action is permitted. See the
3853 ** [sqlite3_set_authorizer | authorizer documentation] for additional
3854 ** information.
3856 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
3857 ** returned from the [sqlite3_vtab_on_conflict()] interface.
3859 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
3860 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
3863 ** CAPI3REF: Authorizer Action Codes
3865 ** The [sqlite3_set_authorizer()] interface registers a callback function
3866 ** that is invoked to authorize certain SQL statement actions. The
3867 ** second parameter to the callback is an integer code that specifies
3868 ** what action is being authorized. These are the integer action codes that
3869 ** the authorizer callback may be passed.
3871 ** These action code values signify what kind of operation is to be
3872 ** authorized. The 3rd and 4th parameters to the authorization
3873 ** callback function will be parameters or NULL depending on which of these
3874 ** codes is used as the second parameter. ^(The 5th parameter to the
3875 ** authorizer callback is the name of the database ("main", "temp",
3876 ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
3877 ** is the name of the inner-most trigger or view that is responsible for
3878 ** the access attempt or NULL if this access attempt is directly from
3879 ** top-level SQL code.
3881 /******************************************* 3rd ************ 4th ***********/
3882 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
3883 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
3884 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
3885 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
3886 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
3887 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
3888 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
3889 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
3890 #define SQLITE_DELETE 9 /* Table Name NULL */
3891 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
3892 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
3893 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
3894 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
3895 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
3896 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
3897 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
3898 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
3899 #define SQLITE_INSERT 18 /* Table Name NULL */
3900 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
3901 #define SQLITE_READ 20 /* Table Name Column Name */
3902 #define SQLITE_SELECT 21 /* NULL NULL */
3903 #define SQLITE_TRANSACTION 22 /* Operation NULL */
3904 #define SQLITE_UPDATE 23 /* Table Name Column Name */
3905 #define SQLITE_ATTACH 24 /* Filename NULL */
3906 #define SQLITE_DETACH 25 /* Database Name NULL */
3907 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
3908 #define SQLITE_REINDEX 27 /* Index Name NULL */
3909 #define SQLITE_ANALYZE 28 /* Table Name NULL */
3910 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
3911 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
3912 #define SQLITE_FUNCTION 31 /* NULL Function Name */
3913 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
3914 #define SQLITE_COPY 0 /* No longer used */
3915 #define SQLITE_RECURSIVE 33 /* NULL NULL */
3918 ** CAPI3REF: Tracing And Profiling Functions
3919 ** METHOD: sqlite3
3921 ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
3922 ** instead of the routines described here.
3924 ** These routines register callback functions that can be used for
3925 ** tracing and profiling the execution of SQL statements.
3927 ** ^The callback function registered by sqlite3_trace() is invoked at
3928 ** various times when an SQL statement is being run by [sqlite3_step()].
3929 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3930 ** SQL statement text as the statement first begins executing.
3931 ** ^(Additional sqlite3_trace() callbacks might occur
3932 ** as each triggered subprogram is entered. The callbacks for triggers
3933 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3935 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3936 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
3938 ** ^The callback function registered by sqlite3_profile() is invoked
3939 ** as each SQL statement finishes. ^The profile callback contains
3940 ** the original statement text and an estimate of wall-clock time
3941 ** of how long that statement took to run. ^The profile callback
3942 ** time is in units of nanoseconds, however the current implementation
3943 ** is only capable of millisecond resolution so the six least significant
3944 ** digits in the time are meaningless. Future versions of SQLite
3945 ** might provide greater resolution on the profiler callback. The
3946 ** sqlite3_profile() function is considered experimental and is
3947 ** subject to change in future versions of SQLite.
3949 SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
3950 void(*xTrace)(void*,const char*), void*);
3951 SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
3952 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3955 ** CAPI3REF: SQL Trace Event Codes
3956 ** KEYWORDS: SQLITE_TRACE
3958 ** These constants identify classes of events that can be monitored
3959 ** using the [sqlite3_trace_v2()] tracing logic. The third argument
3960 ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
3961 ** the following constants. ^The first argument to the trace callback
3962 ** is one of the following constants.
3964 ** New tracing constants may be added in future releases.
3966 ** ^A trace callback has four arguments: xCallback(T,C,P,X).
3967 ** ^The T argument is one of the integer type codes above.
3968 ** ^The C argument is a copy of the context pointer passed in as the
3969 ** fourth argument to [sqlite3_trace_v2()].
3970 ** The P and X arguments are pointers whose meanings depend on T.
3972 ** <dl>
3973 ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
3974 ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
3975 ** first begins running and possibly at other times during the
3976 ** execution of the prepared statement, such as at the start of each
3977 ** trigger subprogram. ^The P argument is a pointer to the
3978 ** [prepared statement]. ^The X argument is a pointer to a string which
3979 ** is the unexpanded SQL text of the prepared statement or an SQL comment
3980 ** that indicates the invocation of a trigger. ^The callback can compute
3981 ** the same text that would have been returned by the legacy [sqlite3_trace()]
3982 ** interface by using the X argument when X begins with "--" and invoking
3983 ** [sqlite3_expanded_sql(P)] otherwise.
3985 ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
3986 ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
3987 ** information as is provided by the [sqlite3_profile()] callback.
3988 ** ^The P argument is a pointer to the [prepared statement] and the
3989 ** X argument points to a 64-bit integer which is the estimated of
3990 ** the number of nanosecond that the prepared statement took to run.
3991 ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
3993 ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
3994 ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
3995 ** statement generates a single row of result.
3996 ** ^The P argument is a pointer to the [prepared statement] and the
3997 ** X argument is unused.
3999 ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
4000 ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
4001 ** connection closes.
4002 ** ^The P argument is a pointer to the [database connection] object
4003 ** and the X argument is unused.
4004 ** </dl>
4006 #define SQLITE_TRACE_STMT 0x01
4007 #define SQLITE_TRACE_PROFILE 0x02
4008 #define SQLITE_TRACE_ROW 0x04
4009 #define SQLITE_TRACE_CLOSE 0x08
4012 ** CAPI3REF: SQL Trace Hook
4013 ** METHOD: sqlite3
4015 ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
4016 ** function X against [database connection] D, using property mask M
4017 ** and context pointer P. ^If the X callback is
4018 ** NULL or if the M mask is zero, then tracing is disabled. The
4019 ** M argument should be the bitwise OR-ed combination of
4020 ** zero or more [SQLITE_TRACE] constants.
4022 ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
4023 ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
4025 ** ^The X callback is invoked whenever any of the events identified by
4026 ** mask M occur. ^The integer return value from the callback is currently
4027 ** ignored, though this may change in future releases. Callback
4028 ** implementations should return zero to ensure future compatibility.
4030 ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
4031 ** ^The T argument is one of the [SQLITE_TRACE]
4032 ** constants to indicate why the callback was invoked.
4033 ** ^The C argument is a copy of the context pointer.
4034 ** The P and X arguments are pointers whose meanings depend on T.
4036 ** The sqlite3_trace_v2() interface is intended to replace the legacy
4037 ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
4038 ** are deprecated.
4040 SQLITE_API int sqlite3_trace_v2(
4041 sqlite3*,
4042 unsigned uMask,
4043 int(*xCallback)(unsigned,void*,void*,void*),
4044 void *pCtx
4048 ** CAPI3REF: Query Progress Callbacks
4049 ** METHOD: sqlite3
4051 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
4052 ** function X to be invoked periodically during long running calls to
4053 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
4054 ** database connection D. An example use for this
4055 ** interface is to keep a GUI updated during a large query.
4057 ** ^The parameter P is passed through as the only parameter to the
4058 ** callback function X. ^The parameter N is the approximate number of
4059 ** [virtual machine instructions] that are evaluated between successive
4060 ** invocations of the callback X. ^If N is less than one then the progress
4061 ** handler is disabled.
4063 ** ^Only a single progress handler may be defined at one time per
4064 ** [database connection]; setting a new progress handler cancels the
4065 ** old one. ^Setting parameter X to NULL disables the progress handler.
4066 ** ^The progress handler is also disabled by setting N to a value less
4067 ** than 1.
4069 ** ^If the progress callback returns non-zero, the operation is
4070 ** interrupted. This feature can be used to implement a
4071 ** "Cancel" button on a GUI progress dialog box.
4073 ** The progress handler callback must not do anything that will modify
4074 ** the database connection that invoked the progress handler.
4075 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4076 ** database connections for the meaning of "modify" in this paragraph.
4079 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
4082 ** CAPI3REF: Opening A New Database Connection
4083 ** CONSTRUCTOR: sqlite3
4085 ** ^These routines open an SQLite database file as specified by the
4086 ** filename argument. ^The filename argument is interpreted as UTF-8 for
4087 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
4088 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
4089 ** returned in *ppDb, even if an error occurs. The only exception is that
4090 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
4091 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
4092 ** object.)^ ^(If the database is opened (and/or created) successfully, then
4093 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
4094 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
4095 ** an English language description of the error following a failure of any
4096 ** of the sqlite3_open() routines.
4098 ** ^The default encoding will be UTF-8 for databases created using
4099 ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
4100 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
4102 ** Whether or not an error occurs when it is opened, resources
4103 ** associated with the [database connection] handle should be released by
4104 ** passing it to [sqlite3_close()] when it is no longer required.
4106 ** The sqlite3_open_v2() interface works like sqlite3_open()
4107 ** except that it accepts two additional parameters for additional control
4108 ** over the new database connection. ^(The flags parameter to
4109 ** sqlite3_open_v2() can take one of
4110 ** the following three values, optionally combined with the
4111 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
4112 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
4114 ** <dl>
4115 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
4116 ** <dd>The database is opened in read-only mode. If the database does not
4117 ** already exist, an error is returned.</dd>)^
4119 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
4120 ** <dd>The database is opened for reading and writing if possible, or reading
4121 ** only if the file is write protected by the operating system. In either
4122 ** case the database must already exist, otherwise an error is returned.</dd>)^
4124 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
4125 ** <dd>The database is opened for reading and writing, and is created if
4126 ** it does not already exist. This is the behavior that is always used for
4127 ** sqlite3_open() and sqlite3_open16().</dd>)^
4128 ** </dl>
4130 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
4131 ** combinations shown above optionally combined with other
4132 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
4133 ** then the behavior is undefined.
4135 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
4136 ** opens in the multi-thread [threading mode] as long as the single-thread
4137 ** mode has not been set at compile-time or start-time. ^If the
4138 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
4139 ** in the serialized [threading mode] unless single-thread was
4140 ** previously selected at compile-time or start-time.
4141 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
4142 ** eligible to use [shared cache mode], regardless of whether or not shared
4143 ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
4144 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
4145 ** participate in [shared cache mode] even if it is enabled.
4147 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
4148 ** [sqlite3_vfs] object that defines the operating system interface that
4149 ** the new database connection should use. ^If the fourth parameter is
4150 ** a NULL pointer then the default [sqlite3_vfs] object is used.
4152 ** ^If the filename is ":memory:", then a private, temporary in-memory database
4153 ** is created for the connection. ^This in-memory database will vanish when
4154 ** the database connection is closed. Future versions of SQLite might
4155 ** make use of additional special filenames that begin with the ":" character.
4156 ** It is recommended that when a database filename actually does begin with
4157 ** a ":" character you should prefix the filename with a pathname such as
4158 ** "./" to avoid ambiguity.
4160 ** ^If the filename is an empty string, then a private, temporary
4161 ** on-disk database will be created. ^This private database will be
4162 ** automatically deleted as soon as the database connection is closed.
4164 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
4166 ** ^If [URI filename] interpretation is enabled, and the filename argument
4167 ** begins with "file:", then the filename is interpreted as a URI. ^URI
4168 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
4169 ** set in the third argument to sqlite3_open_v2(), or if it has
4170 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
4171 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
4172 ** URI filename interpretation is turned off
4173 ** by default, but future releases of SQLite might enable URI filename
4174 ** interpretation by default. See "[URI filenames]" for additional
4175 ** information.
4177 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
4178 ** authority, then it must be either an empty string or the string
4179 ** "localhost". ^If the authority is not an empty string or "localhost", an
4180 ** error is returned to the caller. ^The fragment component of a URI, if
4181 ** present, is ignored.
4183 ** ^SQLite uses the path component of the URI as the name of the disk file
4184 ** which contains the database. ^If the path begins with a '/' character,
4185 ** then it is interpreted as an absolute path. ^If the path does not begin
4186 ** with a '/' (meaning that the authority section is omitted from the URI)
4187 ** then the path is interpreted as a relative path.
4188 ** ^(On windows, the first component of an absolute path
4189 ** is a drive specification (e.g. "C:").)^
4191 ** [[core URI query parameters]]
4192 ** The query component of a URI may contain parameters that are interpreted
4193 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
4194 ** SQLite and its built-in [VFSes] interpret the
4195 ** following query parameters:
4197 ** <ul>
4198 ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
4199 ** a VFS object that provides the operating system interface that should
4200 ** be used to access the database file on disk. ^If this option is set to
4201 ** an empty string the default VFS object is used. ^Specifying an unknown
4202 ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
4203 ** present, then the VFS specified by the option takes precedence over
4204 ** the value passed as the fourth parameter to sqlite3_open_v2().
4206 ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
4207 ** "rwc", or "memory". Attempting to set it to any other value is
4208 ** an error)^.
4209 ** ^If "ro" is specified, then the database is opened for read-only
4210 ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
4211 ** third argument to sqlite3_open_v2(). ^If the mode option is set to
4212 ** "rw", then the database is opened for read-write (but not create)
4213 ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
4214 ** been set. ^Value "rwc" is equivalent to setting both
4215 ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
4216 ** set to "memory" then a pure [in-memory database] that never reads
4217 ** or writes from disk is used. ^It is an error to specify a value for
4218 ** the mode parameter that is less restrictive than that specified by
4219 ** the flags passed in the third parameter to sqlite3_open_v2().
4221 ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
4222 ** "private". ^Setting it to "shared" is equivalent to setting the
4223 ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
4224 ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
4225 ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
4226 ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
4227 ** a URI filename, its value overrides any behavior requested by setting
4228 ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
4230 ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
4231 ** [powersafe overwrite] property does or does not apply to the
4232 ** storage media on which the database file resides.
4234 ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
4235 ** which if set disables file locking in rollback journal modes. This
4236 ** is useful for accessing a database on a filesystem that does not
4237 ** support locking. Caution: Database corruption might result if two
4238 ** or more processes write to the same database and any one of those
4239 ** processes uses nolock=1.
4241 ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
4242 ** parameter that indicates that the database file is stored on
4243 ** read-only media. ^When immutable is set, SQLite assumes that the
4244 ** database file cannot be changed, even by a process with higher
4245 ** privilege, and so the database is opened read-only and all locking
4246 ** and change detection is disabled. Caution: Setting the immutable
4247 ** property on a database file that does in fact change can result
4248 ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
4249 ** See also: [SQLITE_IOCAP_IMMUTABLE].
4251 ** </ul>
4253 ** ^Specifying an unknown parameter in the query component of a URI is not an
4254 ** error. Future versions of SQLite might understand additional query
4255 ** parameters. See "[query parameters with special meaning to SQLite]" for
4256 ** additional information.
4258 ** [[URI filename examples]] <h3>URI filename examples</h3>
4260 ** <table border="1" align=center cellpadding=5>
4261 ** <tr><th> URI filenames <th> Results
4262 ** <tr><td> file:data.db <td>
4263 ** Open the file "data.db" in the current directory.
4264 ** <tr><td> file:/home/fred/data.db<br>
4265 ** file:///home/fred/data.db <br>
4266 ** file://localhost/home/fred/data.db <br> <td>
4267 ** Open the database file "/home/fred/data.db".
4268 ** <tr><td> file://darkstar/home/fred/data.db <td>
4269 ** An error. "darkstar" is not a recognized authority.
4270 ** <tr><td style="white-space:nowrap">
4271 ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
4272 ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
4273 ** C:. Note that the %20 escaping in this example is not strictly
4274 ** necessary - space characters can be used literally
4275 ** in URI filenames.
4276 ** <tr><td> file:data.db?mode=ro&cache=private <td>
4277 ** Open file "data.db" in the current directory for read-only access.
4278 ** Regardless of whether or not shared-cache mode is enabled by
4279 ** default, use a private cache.
4280 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
4281 ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
4282 ** that uses dot-files in place of posix advisory locking.
4283 ** <tr><td> file:data.db?mode=readonly <td>
4284 ** An error. "readonly" is not a valid option for the "mode" parameter.
4285 ** </table>
4287 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
4288 ** query components of a URI. A hexadecimal escape sequence consists of a
4289 ** percent sign - "%" - followed by exactly two hexadecimal digits
4290 ** specifying an octet value. ^Before the path or query components of a
4291 ** URI filename are interpreted, they are encoded using UTF-8 and all
4292 ** hexadecimal escape sequences replaced by a single byte containing the
4293 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
4294 ** the results are undefined.
4296 ** <b>Note to Windows users:</b> The encoding used for the filename argument
4297 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
4298 ** codepage is currently defined. Filenames containing international
4299 ** characters must be converted to UTF-8 prior to passing them into
4300 ** sqlite3_open() or sqlite3_open_v2().
4302 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
4303 ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
4304 ** features that require the use of temporary files may fail.
4306 ** See also: [sqlite3_temp_directory]
4308 SQLITE_API int sqlite3_open(
4309 const char *filename, /* Database filename (UTF-8) */
4310 sqlite3 **ppDb /* OUT: SQLite db handle */
4312 SQLITE_API int sqlite3_open16(
4313 const void *filename, /* Database filename (UTF-16) */
4314 sqlite3 **ppDb /* OUT: SQLite db handle */
4316 SQLITE_API int sqlite3_open_v2(
4317 const char *filename, /* Database filename (UTF-8) */
4318 sqlite3 **ppDb, /* OUT: SQLite db handle */
4319 int flags, /* Flags */
4320 const char *zVfs /* Name of VFS module to use */
4324 ** CAPI3REF: Obtain Values For URI Parameters
4326 ** These are utility routines, useful to VFS implementations, that check
4327 ** to see if a database file was a URI that contained a specific query
4328 ** parameter, and if so obtains the value of that query parameter.
4330 ** If F is the database filename pointer passed into the xOpen() method of
4331 ** a VFS implementation when the flags parameter to xOpen() has one or
4332 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
4333 ** P is the name of the query parameter, then
4334 ** sqlite3_uri_parameter(F,P) returns the value of the P
4335 ** parameter if it exists or a NULL pointer if P does not appear as a
4336 ** query parameter on F. If P is a query parameter of F
4337 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
4338 ** a pointer to an empty string.
4340 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
4341 ** parameter and returns true (1) or false (0) according to the value
4342 ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
4343 ** value of query parameter P is one of "yes", "true", or "on" in any
4344 ** case or if the value begins with a non-zero number. The
4345 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
4346 ** query parameter P is one of "no", "false", or "off" in any case or
4347 ** if the value begins with a numeric zero. If P is not a query
4348 ** parameter on F or if the value of P is does not match any of the
4349 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
4351 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
4352 ** 64-bit signed integer and returns that integer, or D if P does not
4353 ** exist. If the value of P is something other than an integer, then
4354 ** zero is returned.
4356 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
4357 ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
4358 ** is not a database file pathname pointer that SQLite passed into the xOpen
4359 ** VFS method, then the behavior of this routine is undefined and probably
4360 ** undesirable.
4362 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
4363 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
4364 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
4368 ** CAPI3REF: Error Codes And Messages
4369 ** METHOD: sqlite3
4371 ** ^If the most recent sqlite3_* API call associated with
4372 ** [database connection] D failed, then the sqlite3_errcode(D) interface
4373 ** returns the numeric [result code] or [extended result code] for that
4374 ** API call.
4375 ** If the most recent API call was successful,
4376 ** then the return value from sqlite3_errcode() is undefined.
4377 ** ^The sqlite3_extended_errcode()
4378 ** interface is the same except that it always returns the
4379 ** [extended result code] even when extended result codes are
4380 ** disabled.
4382 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
4383 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
4384 ** ^(Memory to hold the error message string is managed internally.
4385 ** The application does not need to worry about freeing the result.
4386 ** However, the error string might be overwritten or deallocated by
4387 ** subsequent calls to other SQLite interface functions.)^
4389 ** ^The sqlite3_errstr() interface returns the English-language text
4390 ** that describes the [result code], as UTF-8.
4391 ** ^(Memory to hold the error message string is managed internally
4392 ** and must not be freed by the application)^.
4394 ** When the serialized [threading mode] is in use, it might be the
4395 ** case that a second error occurs on a separate thread in between
4396 ** the time of the first error and the call to these interfaces.
4397 ** When that happens, the second error will be reported since these
4398 ** interfaces always report the most recent result. To avoid
4399 ** this, each thread can obtain exclusive use of the [database connection] D
4400 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
4401 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
4402 ** all calls to the interfaces listed here are completed.
4404 ** If an interface fails with SQLITE_MISUSE, that means the interface
4405 ** was invoked incorrectly by the application. In that case, the
4406 ** error code and message may or may not be set.
4408 SQLITE_API int sqlite3_errcode(sqlite3 *db);
4409 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
4410 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
4411 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
4412 SQLITE_API const char *sqlite3_errstr(int);
4415 ** CAPI3REF: Prepared Statement Object
4416 ** KEYWORDS: {prepared statement} {prepared statements}
4418 ** An instance of this object represents a single SQL statement that
4419 ** has been compiled into binary form and is ready to be evaluated.
4421 ** Think of each SQL statement as a separate computer program. The
4422 ** original SQL text is source code. A prepared statement object
4423 ** is the compiled object code. All SQL must be converted into a
4424 ** prepared statement before it can be run.
4426 ** The life-cycle of a prepared statement object usually goes like this:
4428 ** <ol>
4429 ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
4430 ** <li> Bind values to [parameters] using the sqlite3_bind_*()
4431 ** interfaces.
4432 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
4433 ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
4434 ** to step 2. Do this zero or more times.
4435 ** <li> Destroy the object using [sqlite3_finalize()].
4436 ** </ol>
4438 typedef struct sqlite3_stmt sqlite3_stmt;
4441 ** CAPI3REF: Run-time Limits
4442 ** METHOD: sqlite3
4444 ** ^(This interface allows the size of various constructs to be limited
4445 ** on a connection by connection basis. The first parameter is the
4446 ** [database connection] whose limit is to be set or queried. The
4447 ** second parameter is one of the [limit categories] that define a
4448 ** class of constructs to be size limited. The third parameter is the
4449 ** new limit for that construct.)^
4451 ** ^If the new limit is a negative number, the limit is unchanged.
4452 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
4453 ** [limits | hard upper bound]
4454 ** set at compile-time by a C preprocessor macro called
4455 ** [limits | SQLITE_MAX_<i>NAME</i>].
4456 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
4457 ** ^Attempts to increase a limit above its hard upper bound are
4458 ** silently truncated to the hard upper bound.
4460 ** ^Regardless of whether or not the limit was changed, the
4461 ** [sqlite3_limit()] interface returns the prior value of the limit.
4462 ** ^Hence, to find the current value of a limit without changing it,
4463 ** simply invoke this interface with the third parameter set to -1.
4465 ** Run-time limits are intended for use in applications that manage
4466 ** both their own internal database and also databases that are controlled
4467 ** by untrusted external sources. An example application might be a
4468 ** web browser that has its own databases for storing history and
4469 ** separate databases controlled by JavaScript applications downloaded
4470 ** off the Internet. The internal databases can be given the
4471 ** large, default limits. Databases managed by external sources can
4472 ** be given much smaller limits designed to prevent a denial of service
4473 ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
4474 ** interface to further control untrusted SQL. The size of the database
4475 ** created by an untrusted script can be contained using the
4476 ** [max_page_count] [PRAGMA].
4478 ** New run-time limit categories may be added in future releases.
4480 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
4483 ** CAPI3REF: Run-Time Limit Categories
4484 ** KEYWORDS: {limit category} {*limit categories}
4486 ** These constants define various performance limits
4487 ** that can be lowered at run-time using [sqlite3_limit()].
4488 ** The synopsis of the meanings of the various limits is shown below.
4489 ** Additional information is available at [limits | Limits in SQLite].
4491 ** <dl>
4492 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
4493 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
4495 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
4496 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
4498 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
4499 ** <dd>The maximum number of columns in a table definition or in the
4500 ** result set of a [SELECT] or the maximum number of columns in an index
4501 ** or in an ORDER BY or GROUP BY clause.</dd>)^
4503 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
4504 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
4506 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
4507 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
4509 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
4510 ** <dd>The maximum number of instructions in a virtual machine program
4511 ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
4512 ** the equivalent tries to allocate space for more than this many opcodes
4513 ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
4515 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
4516 ** <dd>The maximum number of arguments on a function.</dd>)^
4518 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
4519 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
4521 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
4522 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
4523 ** <dd>The maximum length of the pattern argument to the [LIKE] or
4524 ** [GLOB] operators.</dd>)^
4526 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
4527 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
4528 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
4530 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
4531 ** <dd>The maximum depth of recursion for triggers.</dd>)^
4533 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4534 ** <dd>The maximum number of auxiliary worker threads that a single
4535 ** [prepared statement] may start.</dd>)^
4536 ** </dl>
4538 #define SQLITE_LIMIT_LENGTH 0
4539 #define SQLITE_LIMIT_SQL_LENGTH 1
4540 #define SQLITE_LIMIT_COLUMN 2
4541 #define SQLITE_LIMIT_EXPR_DEPTH 3
4542 #define SQLITE_LIMIT_COMPOUND_SELECT 4
4543 #define SQLITE_LIMIT_VDBE_OP 5
4544 #define SQLITE_LIMIT_FUNCTION_ARG 6
4545 #define SQLITE_LIMIT_ATTACHED 7
4546 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
4547 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
4548 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
4549 #define SQLITE_LIMIT_WORKER_THREADS 11
4552 ** CAPI3REF: Prepare Flags
4554 ** These constants define various flags that can be passed into
4555 ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
4556 ** [sqlite3_prepare16_v3()] interfaces.
4558 ** New flags may be added in future releases of SQLite.
4560 ** <dl>
4561 ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
4562 ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
4563 ** that the prepared statement will be retained for a long time and
4564 ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
4565 ** and [sqlite3_prepare16_v3()] assume that the prepared statement will
4566 ** be used just once or at most a few times and then destroyed using
4567 ** [sqlite3_finalize()] relatively soon. The current implementation acts
4568 ** on this hint by avoiding the use of [lookaside memory] so as not to
4569 ** deplete the limited store of lookaside memory. Future versions of
4570 ** SQLite may act on this hint differently.
4571 ** </dl>
4573 #define SQLITE_PREPARE_PERSISTENT 0x01
4576 ** CAPI3REF: Compiling An SQL Statement
4577 ** KEYWORDS: {SQL statement compiler}
4578 ** METHOD: sqlite3
4579 ** CONSTRUCTOR: sqlite3_stmt
4581 ** To execute an SQL statement, it must first be compiled into a byte-code
4582 ** program using one of these routines. Or, in other words, these routines
4583 ** are constructors for the [prepared statement] object.
4585 ** The preferred routine to use is [sqlite3_prepare_v2()]. The
4586 ** [sqlite3_prepare()] interface is legacy and should be avoided.
4587 ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
4588 ** for special purposes.
4590 ** The use of the UTF-8 interfaces is preferred, as SQLite currently
4591 ** does all parsing using UTF-8. The UTF-16 interfaces are provided
4592 ** as a convenience. The UTF-16 interfaces work by converting the
4593 ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
4595 ** The first argument, "db", is a [database connection] obtained from a
4596 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
4597 ** [sqlite3_open16()]. The database connection must not have been closed.
4599 ** The second argument, "zSql", is the statement to be compiled, encoded
4600 ** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
4601 ** and sqlite3_prepare_v3()
4602 ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
4603 ** and sqlite3_prepare16_v3() use UTF-16.
4605 ** ^If the nByte argument is negative, then zSql is read up to the
4606 ** first zero terminator. ^If nByte is positive, then it is the
4607 ** number of bytes read from zSql. ^If nByte is zero, then no prepared
4608 ** statement is generated.
4609 ** If the caller knows that the supplied string is nul-terminated, then
4610 ** there is a small performance advantage to passing an nByte parameter that
4611 ** is the number of bytes in the input string <i>including</i>
4612 ** the nul-terminator.
4614 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
4615 ** past the end of the first SQL statement in zSql. These routines only
4616 ** compile the first statement in zSql, so *pzTail is left pointing to
4617 ** what remains uncompiled.
4619 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
4620 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
4621 ** to NULL. ^If the input text contains no SQL (if the input is an empty
4622 ** string or a comment) then *ppStmt is set to NULL.
4623 ** The calling procedure is responsible for deleting the compiled
4624 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
4625 ** ppStmt may not be NULL.
4627 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
4628 ** otherwise an [error code] is returned.
4630 ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
4631 ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
4632 ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
4633 ** are retained for backwards compatibility, but their use is discouraged.
4634 ** ^In the "vX" interfaces, the prepared statement
4635 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
4636 ** original SQL text. This causes the [sqlite3_step()] interface to
4637 ** behave differently in three ways:
4639 ** <ol>
4640 ** <li>
4641 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
4642 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
4643 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
4644 ** retries will occur before sqlite3_step() gives up and returns an error.
4645 ** </li>
4647 ** <li>
4648 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
4649 ** [error codes] or [extended error codes]. ^The legacy behavior was that
4650 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
4651 ** and the application would have to make a second call to [sqlite3_reset()]
4652 ** in order to find the underlying cause of the problem. With the "v2" prepare
4653 ** interfaces, the underlying reason for the error is returned immediately.
4654 ** </li>
4656 ** <li>
4657 ** ^If the specific value bound to [parameter | host parameter] in the
4658 ** WHERE clause might influence the choice of query plan for a statement,
4659 ** then the statement will be automatically recompiled, as if there had been
4660 ** a schema change, on the first [sqlite3_step()] call following any change
4661 ** to the [sqlite3_bind_text | bindings] of that [parameter].
4662 ** ^The specific value of WHERE-clause [parameter] might influence the
4663 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
4664 ** or [GLOB] operator or if the parameter is compared to an indexed column
4665 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
4666 ** </li>
4668 ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
4669 ** the extra prepFlags parameter, which is a bit array consisting of zero or
4670 ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
4671 ** sqlite3_prepare_v2() interface works exactly the same as
4672 ** sqlite3_prepare_v3() with a zero prepFlags parameter.
4673 ** </ol>
4675 SQLITE_API int sqlite3_prepare(
4676 sqlite3 *db, /* Database handle */
4677 const char *zSql, /* SQL statement, UTF-8 encoded */
4678 int nByte, /* Maximum length of zSql in bytes. */
4679 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4680 const char **pzTail /* OUT: Pointer to unused portion of zSql */
4682 SQLITE_API int sqlite3_prepare_v2(
4683 sqlite3 *db, /* Database handle */
4684 const char *zSql, /* SQL statement, UTF-8 encoded */
4685 int nByte, /* Maximum length of zSql in bytes. */
4686 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4687 const char **pzTail /* OUT: Pointer to unused portion of zSql */
4689 SQLITE_API int sqlite3_prepare_v3(
4690 sqlite3 *db, /* Database handle */
4691 const char *zSql, /* SQL statement, UTF-8 encoded */
4692 int nByte, /* Maximum length of zSql in bytes. */
4693 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
4694 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4695 const char **pzTail /* OUT: Pointer to unused portion of zSql */
4697 SQLITE_API int sqlite3_prepare16(
4698 sqlite3 *db, /* Database handle */
4699 const void *zSql, /* SQL statement, UTF-16 encoded */
4700 int nByte, /* Maximum length of zSql in bytes. */
4701 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4702 const void **pzTail /* OUT: Pointer to unused portion of zSql */
4704 SQLITE_API int sqlite3_prepare16_v2(
4705 sqlite3 *db, /* Database handle */
4706 const void *zSql, /* SQL statement, UTF-16 encoded */
4707 int nByte, /* Maximum length of zSql in bytes. */
4708 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4709 const void **pzTail /* OUT: Pointer to unused portion of zSql */
4711 SQLITE_API int sqlite3_prepare16_v3(
4712 sqlite3 *db, /* Database handle */
4713 const void *zSql, /* SQL statement, UTF-16 encoded */
4714 int nByte, /* Maximum length of zSql in bytes. */
4715 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
4716 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
4717 const void **pzTail /* OUT: Pointer to unused portion of zSql */
4721 ** CAPI3REF: Retrieving Statement SQL
4722 ** METHOD: sqlite3_stmt
4724 ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
4725 ** SQL text used to create [prepared statement] P if P was
4726 ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
4727 ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
4728 ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
4729 ** string containing the SQL text of prepared statement P with
4730 ** [bound parameters] expanded.
4732 ** ^(For example, if a prepared statement is created using the SQL
4733 ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
4734 ** and parameter :xyz is unbound, then sqlite3_sql() will return
4735 ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
4736 ** will return "SELECT 2345,NULL".)^
4738 ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
4739 ** is available to hold the result, or if the result would exceed the
4740 ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
4742 ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
4743 ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
4744 ** option causes sqlite3_expanded_sql() to always return NULL.
4746 ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
4747 ** automatically freed when the prepared statement is finalized.
4748 ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
4749 ** is obtained from [sqlite3_malloc()] and must be free by the application
4750 ** by passing it to [sqlite3_free()].
4752 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
4753 SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
4756 ** CAPI3REF: Determine If An SQL Statement Writes The Database
4757 ** METHOD: sqlite3_stmt
4759 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
4760 ** and only if the [prepared statement] X makes no direct changes to
4761 ** the content of the database file.
4763 ** Note that [application-defined SQL functions] or
4764 ** [virtual tables] might change the database indirectly as a side effect.
4765 ** ^(For example, if an application defines a function "eval()" that
4766 ** calls [sqlite3_exec()], then the following SQL statement would
4767 ** change the database file through side-effects:
4769 ** <blockquote><pre>
4770 ** SELECT eval('DELETE FROM t1') FROM t2;
4771 ** </pre></blockquote>
4773 ** But because the [SELECT] statement does not change the database file
4774 ** directly, sqlite3_stmt_readonly() would still return true.)^
4776 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
4777 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
4778 ** since the statements themselves do not actually modify the database but
4779 ** rather they control the timing of when other statements modify the
4780 ** database. ^The [ATTACH] and [DETACH] statements also cause
4781 ** sqlite3_stmt_readonly() to return true since, while those statements
4782 ** change the configuration of a database connection, they do not make
4783 ** changes to the content of the database files on disk.
4784 ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
4785 ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
4786 ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
4787 ** sqlite3_stmt_readonly() returns false for those commands.
4789 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
4792 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
4793 ** METHOD: sqlite3_stmt
4795 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
4796 ** [prepared statement] S has been stepped at least once using
4797 ** [sqlite3_step(S)] but has neither run to completion (returned
4798 ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
4799 ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
4800 ** interface returns false if S is a NULL pointer. If S is not a
4801 ** NULL pointer and is not a pointer to a valid [prepared statement]
4802 ** object, then the behavior is undefined and probably undesirable.
4804 ** This interface can be used in combination [sqlite3_next_stmt()]
4805 ** to locate all prepared statements associated with a database
4806 ** connection that are in need of being reset. This can be used,
4807 ** for example, in diagnostic routines to search for prepared
4808 ** statements that are holding a transaction open.
4810 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
4813 ** CAPI3REF: Dynamically Typed Value Object
4814 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
4816 ** SQLite uses the sqlite3_value object to represent all values
4817 ** that can be stored in a database table. SQLite uses dynamic typing
4818 ** for the values it stores. ^Values stored in sqlite3_value objects
4819 ** can be integers, floating point values, strings, BLOBs, or NULL.
4821 ** An sqlite3_value object may be either "protected" or "unprotected".
4822 ** Some interfaces require a protected sqlite3_value. Other interfaces
4823 ** will accept either a protected or an unprotected sqlite3_value.
4824 ** Every interface that accepts sqlite3_value arguments specifies
4825 ** whether or not it requires a protected sqlite3_value. The
4826 ** [sqlite3_value_dup()] interface can be used to construct a new
4827 ** protected sqlite3_value from an unprotected sqlite3_value.
4829 ** The terms "protected" and "unprotected" refer to whether or not
4830 ** a mutex is held. An internal mutex is held for a protected
4831 ** sqlite3_value object but no mutex is held for an unprotected
4832 ** sqlite3_value object. If SQLite is compiled to be single-threaded
4833 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
4834 ** or if SQLite is run in one of reduced mutex modes
4835 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
4836 ** then there is no distinction between protected and unprotected
4837 ** sqlite3_value objects and they can be used interchangeably. However,
4838 ** for maximum code portability it is recommended that applications
4839 ** still make the distinction between protected and unprotected
4840 ** sqlite3_value objects even when not strictly required.
4842 ** ^The sqlite3_value objects that are passed as parameters into the
4843 ** implementation of [application-defined SQL functions] are protected.
4844 ** ^The sqlite3_value object returned by
4845 ** [sqlite3_column_value()] is unprotected.
4846 ** Unprotected sqlite3_value objects may only be used as arguments
4847 ** to [sqlite3_result_value()], [sqlite3_bind_value()], and
4848 ** [sqlite3_value_dup()].
4849 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
4850 ** interfaces require protected sqlite3_value objects.
4852 typedef struct sqlite3_value sqlite3_value;
4855 ** CAPI3REF: SQL Function Context Object
4857 ** The context in which an SQL function executes is stored in an
4858 ** sqlite3_context object. ^A pointer to an sqlite3_context object
4859 ** is always first parameter to [application-defined SQL functions].
4860 ** The application-defined SQL function implementation will pass this
4861 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
4862 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
4863 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
4864 ** and/or [sqlite3_set_auxdata()].
4866 typedef struct sqlite3_context sqlite3_context;
4869 ** CAPI3REF: Binding Values To Prepared Statements
4870 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
4871 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
4872 ** METHOD: sqlite3_stmt
4874 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
4875 ** literals may be replaced by a [parameter] that matches one of following
4876 ** templates:
4878 ** <ul>
4879 ** <li> ?
4880 ** <li> ?NNN
4881 ** <li> :VVV
4882 ** <li> @VVV
4883 ** <li> $VVV
4884 ** </ul>
4886 ** In the templates above, NNN represents an integer literal,
4887 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
4888 ** parameters (also called "host parameter names" or "SQL parameters")
4889 ** can be set using the sqlite3_bind_*() routines defined here.
4891 ** ^The first argument to the sqlite3_bind_*() routines is always
4892 ** a pointer to the [sqlite3_stmt] object returned from
4893 ** [sqlite3_prepare_v2()] or its variants.
4895 ** ^The second argument is the index of the SQL parameter to be set.
4896 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
4897 ** SQL parameter is used more than once, second and subsequent
4898 ** occurrences have the same index as the first occurrence.
4899 ** ^The index for named parameters can be looked up using the
4900 ** [sqlite3_bind_parameter_index()] API if desired. ^The index
4901 ** for "?NNN" parameters is the value of NNN.
4902 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
4903 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
4905 ** ^The third argument is the value to bind to the parameter.
4906 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
4907 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
4908 ** is ignored and the end result is the same as sqlite3_bind_null().
4910 ** ^(In those routines that have a fourth argument, its value is the
4911 ** number of bytes in the parameter. To be clear: the value is the
4912 ** number of <u>bytes</u> in the value, not the number of characters.)^
4913 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
4914 ** is negative, then the length of the string is
4915 ** the number of bytes up to the first zero terminator.
4916 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
4917 ** the behavior is undefined.
4918 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
4919 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
4920 ** that parameter must be the byte offset
4921 ** where the NUL terminator would occur assuming the string were NUL
4922 ** terminated. If any NUL characters occur at byte offsets less than
4923 ** the value of the fourth parameter then the resulting string value will
4924 ** contain embedded NULs. The result of expressions involving strings
4925 ** with embedded NULs is undefined.
4927 ** ^The fifth argument to the BLOB and string binding interfaces
4928 ** is a destructor used to dispose of the BLOB or
4929 ** string after SQLite has finished with it. ^The destructor is called
4930 ** to dispose of the BLOB or string even if the call to bind API fails.
4931 ** ^If the fifth argument is
4932 ** the special value [SQLITE_STATIC], then SQLite assumes that the
4933 ** information is in static, unmanaged space and does not need to be freed.
4934 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
4935 ** SQLite makes its own private copy of the data immediately, before
4936 ** the sqlite3_bind_*() routine returns.
4938 ** ^The sixth argument to sqlite3_bind_text64() must be one of
4939 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
4940 ** to specify the encoding of the text in the third parameter. If
4941 ** the sixth argument to sqlite3_bind_text64() is not one of the
4942 ** allowed values shown above, or if the text encoding is different
4943 ** from the encoding specified by the sixth parameter, then the behavior
4944 ** is undefined.
4946 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
4947 ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
4948 ** (just an integer to hold its size) while it is being processed.
4949 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
4950 ** content is later written using
4951 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
4952 ** ^A negative value for the zeroblob results in a zero-length BLOB.
4954 ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
4955 ** [prepared statement] S to have an SQL value of NULL, but to also be
4956 ** associated with the pointer P of type T. ^D is either a NULL pointer or
4957 ** a pointer to a destructor function for P. ^SQLite will invoke the
4958 ** destructor D with a single argument of P when it is finished using
4959 ** P. The T parameter should be a static string, preferably a string
4960 ** literal. The sqlite3_bind_pointer() routine is part of the
4961 ** [pointer passing interface] added for SQLite 3.20.0.
4963 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
4964 ** for the [prepared statement] or with a prepared statement for which
4965 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
4966 ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
4967 ** routine is passed a [prepared statement] that has been finalized, the
4968 ** result is undefined and probably harmful.
4970 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
4971 ** ^Unbound parameters are interpreted as NULL.
4973 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
4974 ** [error code] if anything goes wrong.
4975 ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
4976 ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
4977 ** [SQLITE_MAX_LENGTH].
4978 ** ^[SQLITE_RANGE] is returned if the parameter
4979 ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
4981 ** See also: [sqlite3_bind_parameter_count()],
4982 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
4984 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
4985 SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
4986 void(*)(void*));
4987 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
4988 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
4989 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
4990 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
4991 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
4992 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
4993 SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
4994 void(*)(void*), unsigned char encoding);
4995 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
4996 SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
4997 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
4998 SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
5001 ** CAPI3REF: Number Of SQL Parameters
5002 ** METHOD: sqlite3_stmt
5004 ** ^This routine can be used to find the number of [SQL parameters]
5005 ** in a [prepared statement]. SQL parameters are tokens of the
5006 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
5007 ** placeholders for values that are [sqlite3_bind_blob | bound]
5008 ** to the parameters at a later time.
5010 ** ^(This routine actually returns the index of the largest (rightmost)
5011 ** parameter. For all forms except ?NNN, this will correspond to the
5012 ** number of unique parameters. If parameters of the ?NNN form are used,
5013 ** there may be gaps in the list.)^
5015 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
5016 ** [sqlite3_bind_parameter_name()], and
5017 ** [sqlite3_bind_parameter_index()].
5019 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
5022 ** CAPI3REF: Name Of A Host Parameter
5023 ** METHOD: sqlite3_stmt
5025 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
5026 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
5027 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
5028 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
5029 ** respectively.
5030 ** In other words, the initial ":" or "$" or "@" or "?"
5031 ** is included as part of the name.)^
5032 ** ^Parameters of the form "?" without a following integer have no name
5033 ** and are referred to as "nameless" or "anonymous parameters".
5035 ** ^The first host parameter has an index of 1, not 0.
5037 ** ^If the value N is out of range or if the N-th parameter is
5038 ** nameless, then NULL is returned. ^The returned string is
5039 ** always in UTF-8 encoding even if the named parameter was
5040 ** originally specified as UTF-16 in [sqlite3_prepare16()],
5041 ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
5043 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
5044 ** [sqlite3_bind_parameter_count()], and
5045 ** [sqlite3_bind_parameter_index()].
5047 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
5050 ** CAPI3REF: Index Of A Parameter With A Given Name
5051 ** METHOD: sqlite3_stmt
5053 ** ^Return the index of an SQL parameter given its name. ^The
5054 ** index value returned is suitable for use as the second
5055 ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
5056 ** is returned if no matching parameter is found. ^The parameter
5057 ** name must be given in UTF-8 even if the original statement
5058 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
5059 ** [sqlite3_prepare16_v3()].
5061 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
5062 ** [sqlite3_bind_parameter_count()], and
5063 ** [sqlite3_bind_parameter_name()].
5065 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
5068 ** CAPI3REF: Reset All Bindings On A Prepared Statement
5069 ** METHOD: sqlite3_stmt
5071 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
5072 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
5073 ** ^Use this routine to reset all host parameters to NULL.
5075 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
5078 ** CAPI3REF: Number Of Columns In A Result Set
5079 ** METHOD: sqlite3_stmt
5081 ** ^Return the number of columns in the result set returned by the
5082 ** [prepared statement]. ^If this routine returns 0, that means the
5083 ** [prepared statement] returns no data (for example an [UPDATE]).
5084 ** ^However, just because this routine returns a positive number does not
5085 ** mean that one or more rows of data will be returned. ^A SELECT statement
5086 ** will always have a positive sqlite3_column_count() but depending on the
5087 ** WHERE clause constraints and the table content, it might return no rows.
5089 ** See also: [sqlite3_data_count()]
5091 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
5094 ** CAPI3REF: Column Names In A Result Set
5095 ** METHOD: sqlite3_stmt
5097 ** ^These routines return the name assigned to a particular column
5098 ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
5099 ** interface returns a pointer to a zero-terminated UTF-8 string
5100 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
5101 ** UTF-16 string. ^The first parameter is the [prepared statement]
5102 ** that implements the [SELECT] statement. ^The second parameter is the
5103 ** column number. ^The leftmost column is number 0.
5105 ** ^The returned string pointer is valid until either the [prepared statement]
5106 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
5107 ** reprepared by the first call to [sqlite3_step()] for a particular run
5108 ** or until the next call to
5109 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
5111 ** ^If sqlite3_malloc() fails during the processing of either routine
5112 ** (for example during a conversion from UTF-8 to UTF-16) then a
5113 ** NULL pointer is returned.
5115 ** ^The name of a result column is the value of the "AS" clause for
5116 ** that column, if there is an AS clause. If there is no AS clause
5117 ** then the name of the column is unspecified and may change from
5118 ** one release of SQLite to the next.
5120 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
5121 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
5124 ** CAPI3REF: Source Of Data In A Query Result
5125 ** METHOD: sqlite3_stmt
5127 ** ^These routines provide a means to determine the database, table, and
5128 ** table column that is the origin of a particular result column in
5129 ** [SELECT] statement.
5130 ** ^The name of the database or table or column can be returned as
5131 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
5132 ** the database name, the _table_ routines return the table name, and
5133 ** the origin_ routines return the column name.
5134 ** ^The returned string is valid until the [prepared statement] is destroyed
5135 ** using [sqlite3_finalize()] or until the statement is automatically
5136 ** reprepared by the first call to [sqlite3_step()] for a particular run
5137 ** or until the same information is requested
5138 ** again in a different encoding.
5140 ** ^The names returned are the original un-aliased names of the
5141 ** database, table, and column.
5143 ** ^The first argument to these interfaces is a [prepared statement].
5144 ** ^These functions return information about the Nth result column returned by
5145 ** the statement, where N is the second function argument.
5146 ** ^The left-most column is column 0 for these routines.
5148 ** ^If the Nth column returned by the statement is an expression or
5149 ** subquery and is not a column value, then all of these functions return
5150 ** NULL. ^These routine might also return NULL if a memory allocation error
5151 ** occurs. ^Otherwise, they return the name of the attached database, table,
5152 ** or column that query result column was extracted from.
5154 ** ^As with all other SQLite APIs, those whose names end with "16" return
5155 ** UTF-16 encoded strings and the other functions return UTF-8.
5157 ** ^These APIs are only available if the library was compiled with the
5158 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
5160 ** If two or more threads call one or more of these routines against the same
5161 ** prepared statement and column at the same time then the results are
5162 ** undefined.
5164 ** If two or more threads call one or more
5165 ** [sqlite3_column_database_name | column metadata interfaces]
5166 ** for the same [prepared statement] and result column
5167 ** at the same time then the results are undefined.
5169 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
5170 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
5171 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
5172 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
5173 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
5174 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
5177 ** CAPI3REF: Declared Datatype Of A Query Result
5178 ** METHOD: sqlite3_stmt
5180 ** ^(The first parameter is a [prepared statement].
5181 ** If this statement is a [SELECT] statement and the Nth column of the
5182 ** returned result set of that [SELECT] is a table column (not an
5183 ** expression or subquery) then the declared type of the table
5184 ** column is returned.)^ ^If the Nth column of the result set is an
5185 ** expression or subquery, then a NULL pointer is returned.
5186 ** ^The returned string is always UTF-8 encoded.
5188 ** ^(For example, given the database schema:
5190 ** CREATE TABLE t1(c1 VARIANT);
5192 ** and the following statement to be compiled:
5194 ** SELECT c1 + 1, c1 FROM t1;
5196 ** this routine would return the string "VARIANT" for the second result
5197 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
5199 ** ^SQLite uses dynamic run-time typing. ^So just because a column
5200 ** is declared to contain a particular type does not mean that the
5201 ** data stored in that column is of the declared type. SQLite is
5202 ** strongly typed, but the typing is dynamic not static. ^Type
5203 ** is associated with individual values, not with the containers
5204 ** used to hold those values.
5206 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
5207 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
5210 ** CAPI3REF: Evaluate An SQL Statement
5211 ** METHOD: sqlite3_stmt
5213 ** After a [prepared statement] has been prepared using any of
5214 ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
5215 ** or [sqlite3_prepare16_v3()] or one of the legacy
5216 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
5217 ** must be called one or more times to evaluate the statement.
5219 ** The details of the behavior of the sqlite3_step() interface depend
5220 ** on whether the statement was prepared using the newer "vX" interfaces
5221 ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
5222 ** [sqlite3_prepare16_v2()] or the older legacy
5223 ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
5224 ** new "vX" interface is recommended for new applications but the legacy
5225 ** interface will continue to be supported.
5227 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
5228 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
5229 ** ^With the "v2" interface, any of the other [result codes] or
5230 ** [extended result codes] might be returned as well.
5232 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
5233 ** database locks it needs to do its job. ^If the statement is a [COMMIT]
5234 ** or occurs outside of an explicit transaction, then you can retry the
5235 ** statement. If the statement is not a [COMMIT] and occurs within an
5236 ** explicit transaction then you should rollback the transaction before
5237 ** continuing.
5239 ** ^[SQLITE_DONE] means that the statement has finished executing
5240 ** successfully. sqlite3_step() should not be called again on this virtual
5241 ** machine without first calling [sqlite3_reset()] to reset the virtual
5242 ** machine back to its initial state.
5244 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
5245 ** is returned each time a new row of data is ready for processing by the
5246 ** caller. The values may be accessed using the [column access functions].
5247 ** sqlite3_step() is called again to retrieve the next row of data.
5249 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
5250 ** violation) has occurred. sqlite3_step() should not be called again on
5251 ** the VM. More information may be found by calling [sqlite3_errmsg()].
5252 ** ^With the legacy interface, a more specific error code (for example,
5253 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
5254 ** can be obtained by calling [sqlite3_reset()] on the
5255 ** [prepared statement]. ^In the "v2" interface,
5256 ** the more specific error code is returned directly by sqlite3_step().
5258 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
5259 ** Perhaps it was called on a [prepared statement] that has
5260 ** already been [sqlite3_finalize | finalized] or on one that had
5261 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
5262 ** be the case that the same database connection is being used by two or
5263 ** more threads at the same moment in time.
5265 ** For all versions of SQLite up to and including 3.6.23.1, a call to
5266 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
5267 ** other than [SQLITE_ROW] before any subsequent invocation of
5268 ** sqlite3_step(). Failure to reset the prepared statement using
5269 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
5270 ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
5271 ** sqlite3_step() began
5272 ** calling [sqlite3_reset()] automatically in this circumstance rather
5273 ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
5274 ** break because any application that ever receives an SQLITE_MISUSE error
5275 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
5276 ** can be used to restore the legacy behavior.
5278 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
5279 ** API always returns a generic error code, [SQLITE_ERROR], following any
5280 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
5281 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
5282 ** specific [error codes] that better describes the error.
5283 ** We admit that this is a goofy design. The problem has been fixed
5284 ** with the "v2" interface. If you prepare all of your SQL statements
5285 ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
5286 ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
5287 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
5288 ** then the more specific [error codes] are returned directly
5289 ** by sqlite3_step(). The use of the "vX" interfaces is recommended.
5291 SQLITE_API int sqlite3_step(sqlite3_stmt*);
5294 ** CAPI3REF: Number of columns in a result set
5295 ** METHOD: sqlite3_stmt
5297 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
5298 ** current row of the result set of [prepared statement] P.
5299 ** ^If prepared statement P does not have results ready to return
5300 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
5301 ** interfaces) then sqlite3_data_count(P) returns 0.
5302 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
5303 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
5304 ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
5305 ** will return non-zero if previous call to [sqlite3_step](P) returned
5306 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
5307 ** where it always returns zero since each step of that multi-step
5308 ** pragma returns 0 columns of data.
5310 ** See also: [sqlite3_column_count()]
5312 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
5315 ** CAPI3REF: Fundamental Datatypes
5316 ** KEYWORDS: SQLITE_TEXT
5318 ** ^(Every value in SQLite has one of five fundamental datatypes:
5320 ** <ul>
5321 ** <li> 64-bit signed integer
5322 ** <li> 64-bit IEEE floating point number
5323 ** <li> string
5324 ** <li> BLOB
5325 ** <li> NULL
5326 ** </ul>)^
5328 ** These constants are codes for each of those types.
5330 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
5331 ** for a completely different meaning. Software that links against both
5332 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
5333 ** SQLITE_TEXT.
5335 #define SQLITE_INTEGER 1
5336 #define SQLITE_FLOAT 2
5337 #define SQLITE_BLOB 4
5338 #define SQLITE_NULL 5
5339 #ifdef SQLITE_TEXT
5340 # undef SQLITE_TEXT
5341 #else
5342 # define SQLITE_TEXT 3
5343 #endif
5344 #define SQLITE3_TEXT 3
5347 ** CAPI3REF: Result Values From A Query
5348 ** KEYWORDS: {column access functions}
5349 ** METHOD: sqlite3_stmt
5351 ** <b>Summary:</b>
5352 ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
5353 ** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
5354 ** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
5355 ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
5356 ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
5357 ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
5358 ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
5359 ** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
5360 ** [sqlite3_value|unprotected sqlite3_value] object.
5361 ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
5362 ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
5363 ** or a UTF-8 TEXT result in bytes
5364 ** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
5365 ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
5366 ** TEXT in bytes
5367 ** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
5368 ** datatype of the result
5369 ** </table></blockquote>
5371 ** <b>Details:</b>
5373 ** ^These routines return information about a single column of the current
5374 ** result row of a query. ^In every case the first argument is a pointer
5375 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
5376 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
5377 ** and the second argument is the index of the column for which information
5378 ** should be returned. ^The leftmost column of the result set has the index 0.
5379 ** ^The number of columns in the result can be determined using
5380 ** [sqlite3_column_count()].
5382 ** If the SQL statement does not currently point to a valid row, or if the
5383 ** column index is out of range, the result is undefined.
5384 ** These routines may only be called when the most recent call to
5385 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
5386 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
5387 ** If any of these routines are called after [sqlite3_reset()] or
5388 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
5389 ** something other than [SQLITE_ROW], the results are undefined.
5390 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
5391 ** are called from a different thread while any of these routines
5392 ** are pending, then the results are undefined.
5394 ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
5395 ** each return the value of a result column in a specific data format. If
5396 ** the result column is not initially in the requested format (for example,
5397 ** if the query returns an integer but the sqlite3_column_text() interface
5398 ** is used to extract the value) then an automatic type conversion is performed.
5400 ** ^The sqlite3_column_type() routine returns the
5401 ** [SQLITE_INTEGER | datatype code] for the initial data type
5402 ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
5403 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
5404 ** The return value of sqlite3_column_type() can be used to decide which
5405 ** of the first six interface should be used to extract the column value.
5406 ** The value returned by sqlite3_column_type() is only meaningful if no
5407 ** automatic type conversions have occurred for the value in question.
5408 ** After a type conversion, the result of calling sqlite3_column_type()
5409 ** is undefined, though harmless. Future
5410 ** versions of SQLite may change the behavior of sqlite3_column_type()
5411 ** following a type conversion.
5413 ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
5414 ** or sqlite3_column_bytes16() interfaces can be used to determine the size
5415 ** of that BLOB or string.
5417 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
5418 ** routine returns the number of bytes in that BLOB or string.
5419 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
5420 ** the string to UTF-8 and then returns the number of bytes.
5421 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
5422 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
5423 ** the number of bytes in that string.
5424 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
5426 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
5427 ** routine returns the number of bytes in that BLOB or string.
5428 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
5429 ** the string to UTF-16 and then returns the number of bytes.
5430 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
5431 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
5432 ** the number of bytes in that string.
5433 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
5435 ** ^The values returned by [sqlite3_column_bytes()] and
5436 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
5437 ** of the string. ^For clarity: the values returned by
5438 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
5439 ** bytes in the string, not the number of characters.
5441 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
5442 ** even empty strings, are always zero-terminated. ^The return
5443 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
5445 ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
5446 ** [unprotected sqlite3_value] object. In a multithreaded environment,
5447 ** an unprotected sqlite3_value object may only be used safely with
5448 ** [sqlite3_bind_value()] and [sqlite3_result_value()].
5449 ** If the [unprotected sqlite3_value] object returned by
5450 ** [sqlite3_column_value()] is used in any other way, including calls
5451 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
5452 ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
5453 ** Hence, the sqlite3_column_value() interface
5454 ** is normally only useful within the implementation of
5455 ** [application-defined SQL functions] or [virtual tables], not within
5456 ** top-level application code.
5458 ** The these routines may attempt to convert the datatype of the result.
5459 ** ^For example, if the internal representation is FLOAT and a text result
5460 ** is requested, [sqlite3_snprintf()] is used internally to perform the
5461 ** conversion automatically. ^(The following table details the conversions
5462 ** that are applied:
5464 ** <blockquote>
5465 ** <table border="1">
5466 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
5468 ** <tr><td> NULL <td> INTEGER <td> Result is 0
5469 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
5470 ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
5471 ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
5472 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
5473 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
5474 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
5475 ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
5476 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
5477 ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
5478 ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
5479 ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
5480 ** <tr><td> TEXT <td> BLOB <td> No change
5481 ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
5482 ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
5483 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
5484 ** </table>
5485 ** </blockquote>)^
5487 ** Note that when type conversions occur, pointers returned by prior
5488 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
5489 ** sqlite3_column_text16() may be invalidated.
5490 ** Type conversions and pointer invalidations might occur
5491 ** in the following cases:
5493 ** <ul>
5494 ** <li> The initial content is a BLOB and sqlite3_column_text() or
5495 ** sqlite3_column_text16() is called. A zero-terminator might
5496 ** need to be added to the string.</li>
5497 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
5498 ** sqlite3_column_text16() is called. The content must be converted
5499 ** to UTF-16.</li>
5500 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
5501 ** sqlite3_column_text() is called. The content must be converted
5502 ** to UTF-8.</li>
5503 ** </ul>
5505 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
5506 ** not invalidate a prior pointer, though of course the content of the buffer
5507 ** that the prior pointer references will have been modified. Other kinds
5508 ** of conversion are done in place when it is possible, but sometimes they
5509 ** are not possible and in those cases prior pointers are invalidated.
5511 ** The safest policy is to invoke these routines
5512 ** in one of the following ways:
5514 ** <ul>
5515 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
5516 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
5517 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
5518 ** </ul>
5520 ** In other words, you should call sqlite3_column_text(),
5521 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
5522 ** into the desired format, then invoke sqlite3_column_bytes() or
5523 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
5524 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
5525 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
5526 ** with calls to sqlite3_column_bytes().
5528 ** ^The pointers returned are valid until a type conversion occurs as
5529 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
5530 ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
5531 ** and BLOBs is freed automatically. Do not pass the pointers returned
5532 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
5533 ** [sqlite3_free()].
5535 ** ^(If a memory allocation error occurs during the evaluation of any
5536 ** of these routines, a default value is returned. The default value
5537 ** is either the integer 0, the floating point number 0.0, or a NULL
5538 ** pointer. Subsequent calls to [sqlite3_errcode()] will return
5539 ** [SQLITE_NOMEM].)^
5541 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
5542 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
5543 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
5544 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
5545 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
5546 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
5547 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
5548 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
5549 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
5550 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
5553 ** CAPI3REF: Destroy A Prepared Statement Object
5554 ** DESTRUCTOR: sqlite3_stmt
5556 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
5557 ** ^If the most recent evaluation of the statement encountered no errors
5558 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
5559 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
5560 ** sqlite3_finalize(S) returns the appropriate [error code] or
5561 ** [extended error code].
5563 ** ^The sqlite3_finalize(S) routine can be called at any point during
5564 ** the life cycle of [prepared statement] S:
5565 ** before statement S is ever evaluated, after
5566 ** one or more calls to [sqlite3_reset()], or after any call
5567 ** to [sqlite3_step()] regardless of whether or not the statement has
5568 ** completed execution.
5570 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
5572 ** The application must finalize every [prepared statement] in order to avoid
5573 ** resource leaks. It is a grievous error for the application to try to use
5574 ** a prepared statement after it has been finalized. Any use of a prepared
5575 ** statement after it has been finalized can result in undefined and
5576 ** undesirable behavior such as segfaults and heap corruption.
5578 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
5581 ** CAPI3REF: Reset A Prepared Statement Object
5582 ** METHOD: sqlite3_stmt
5584 ** The sqlite3_reset() function is called to reset a [prepared statement]
5585 ** object back to its initial state, ready to be re-executed.
5586 ** ^Any SQL statement variables that had values bound to them using
5587 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
5588 ** Use [sqlite3_clear_bindings()] to reset the bindings.
5590 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
5591 ** back to the beginning of its program.
5593 ** ^If the most recent call to [sqlite3_step(S)] for the
5594 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
5595 ** or if [sqlite3_step(S)] has never before been called on S,
5596 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
5598 ** ^If the most recent call to [sqlite3_step(S)] for the
5599 ** [prepared statement] S indicated an error, then
5600 ** [sqlite3_reset(S)] returns an appropriate [error code].
5602 ** ^The [sqlite3_reset(S)] interface does not change the values
5603 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
5605 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
5608 ** CAPI3REF: Create Or Redefine SQL Functions
5609 ** KEYWORDS: {function creation routines}
5610 ** KEYWORDS: {application-defined SQL function}
5611 ** KEYWORDS: {application-defined SQL functions}
5612 ** METHOD: sqlite3
5614 ** ^These functions (collectively known as "function creation routines")
5615 ** are used to add SQL functions or aggregates or to redefine the behavior
5616 ** of existing SQL functions or aggregates. The only differences between
5617 ** these routines are the text encoding expected for
5618 ** the second parameter (the name of the function being created)
5619 ** and the presence or absence of a destructor callback for
5620 ** the application data pointer.
5622 ** ^The first parameter is the [database connection] to which the SQL
5623 ** function is to be added. ^If an application uses more than one database
5624 ** connection then application-defined SQL functions must be added
5625 ** to each database connection separately.
5627 ** ^The second parameter is the name of the SQL function to be created or
5628 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
5629 ** representation, exclusive of the zero-terminator. ^Note that the name
5630 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
5631 ** ^Any attempt to create a function with a longer name
5632 ** will result in [SQLITE_MISUSE] being returned.
5634 ** ^The third parameter (nArg)
5635 ** is the number of arguments that the SQL function or
5636 ** aggregate takes. ^If this parameter is -1, then the SQL function or
5637 ** aggregate may take any number of arguments between 0 and the limit
5638 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
5639 ** parameter is less than -1 or greater than 127 then the behavior is
5640 ** undefined.
5642 ** ^The fourth parameter, eTextRep, specifies what
5643 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
5644 ** its parameters. The application should set this parameter to
5645 ** [SQLITE_UTF16LE] if the function implementation invokes
5646 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
5647 ** implementation invokes [sqlite3_value_text16be()] on an input, or
5648 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
5649 ** otherwise. ^The same SQL function may be registered multiple times using
5650 ** different preferred text encodings, with different implementations for
5651 ** each encoding.
5652 ** ^When multiple implementations of the same function are available, SQLite
5653 ** will pick the one that involves the least amount of data conversion.
5655 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
5656 ** to signal that the function will always return the same result given
5657 ** the same inputs within a single SQL statement. Most SQL functions are
5658 ** deterministic. The built-in [random()] SQL function is an example of a
5659 ** function that is not deterministic. The SQLite query planner is able to
5660 ** perform additional optimizations on deterministic functions, so use
5661 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
5663 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
5664 ** function can gain access to this pointer using [sqlite3_user_data()].)^
5666 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
5667 ** pointers to C-language functions that implement the SQL function or
5668 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
5669 ** callback only; NULL pointers must be passed as the xStep and xFinal
5670 ** parameters. ^An aggregate SQL function requires an implementation of xStep
5671 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
5672 ** SQL function or aggregate, pass NULL pointers for all three function
5673 ** callbacks.
5675 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
5676 ** then it is destructor for the application data pointer.
5677 ** The destructor is invoked when the function is deleted, either by being
5678 ** overloaded or when the database connection closes.)^
5679 ** ^The destructor is also invoked if the call to
5680 ** sqlite3_create_function_v2() fails.
5681 ** ^When the destructor callback of the tenth parameter is invoked, it
5682 ** is passed a single argument which is a copy of the application data
5683 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
5685 ** ^It is permitted to register multiple implementations of the same
5686 ** functions with the same name but with either differing numbers of
5687 ** arguments or differing preferred text encodings. ^SQLite will use
5688 ** the implementation that most closely matches the way in which the
5689 ** SQL function is used. ^A function implementation with a non-negative
5690 ** nArg parameter is a better match than a function implementation with
5691 ** a negative nArg. ^A function where the preferred text encoding
5692 ** matches the database encoding is a better
5693 ** match than a function where the encoding is different.
5694 ** ^A function where the encoding difference is between UTF16le and UTF16be
5695 ** is a closer match than a function where the encoding difference is
5696 ** between UTF8 and UTF16.
5698 ** ^Built-in functions may be overloaded by new application-defined functions.
5700 ** ^An application-defined function is permitted to call other
5701 ** SQLite interfaces. However, such calls must not
5702 ** close the database connection nor finalize or reset the prepared
5703 ** statement in which the function is running.
5705 SQLITE_API int sqlite3_create_function(
5706 sqlite3 *db,
5707 const char *zFunctionName,
5708 int nArg,
5709 int eTextRep,
5710 void *pApp,
5711 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5712 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5713 void (*xFinal)(sqlite3_context*)
5715 SQLITE_API int sqlite3_create_function16(
5716 sqlite3 *db,
5717 const void *zFunctionName,
5718 int nArg,
5719 int eTextRep,
5720 void *pApp,
5721 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5722 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5723 void (*xFinal)(sqlite3_context*)
5725 SQLITE_API int sqlite3_create_function_v2(
5726 sqlite3 *db,
5727 const char *zFunctionName,
5728 int nArg,
5729 int eTextRep,
5730 void *pApp,
5731 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5732 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5733 void (*xFinal)(sqlite3_context*),
5734 void(*xDestroy)(void*)
5738 ** CAPI3REF: Text Encodings
5740 ** These constant define integer codes that represent the various
5741 ** text encodings supported by SQLite.
5743 #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
5744 #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
5745 #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
5746 #define SQLITE_UTF16 4 /* Use native byte order */
5747 #define SQLITE_ANY 5 /* Deprecated */
5748 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
5751 ** CAPI3REF: Function Flags
5753 ** These constants may be ORed together with the
5754 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
5755 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
5756 ** [sqlite3_create_function_v2()].
5758 #define SQLITE_DETERMINISTIC 0x800
5761 ** CAPI3REF: Deprecated Functions
5762 ** DEPRECATED
5764 ** These functions are [deprecated]. In order to maintain
5765 ** backwards compatibility with older code, these functions continue
5766 ** to be supported. However, new applications should avoid
5767 ** the use of these functions. To encourage programmers to avoid
5768 ** these functions, we will not explain what they do.
5770 #ifndef SQLITE_OMIT_DEPRECATED
5771 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
5772 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
5773 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
5774 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
5775 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
5776 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
5777 void*,sqlite3_int64);
5778 #endif
5781 ** CAPI3REF: Obtaining SQL Values
5782 ** METHOD: sqlite3_value
5784 ** <b>Summary:</b>
5785 ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
5786 ** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
5787 ** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
5788 ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
5789 ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
5790 ** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
5791 ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
5792 ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
5793 ** the native byteorder
5794 ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
5795 ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
5796 ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
5797 ** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
5798 ** or a UTF-8 TEXT in bytes
5799 ** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
5800 ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
5801 ** TEXT in bytes
5802 ** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
5803 ** datatype of the value
5804 ** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
5805 ** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
5806 ** </table></blockquote>
5808 ** <b>Details:</b>
5810 ** These routines extract type, size, and content information from
5811 ** [protected sqlite3_value] objects. Protected sqlite3_value objects
5812 ** are used to pass parameter information into implementation of
5813 ** [application-defined SQL functions] and [virtual tables].
5815 ** These routines work only with [protected sqlite3_value] objects.
5816 ** Any attempt to use these routines on an [unprotected sqlite3_value]
5817 ** is not threadsafe.
5819 ** ^These routines work just like the corresponding [column access functions]
5820 ** except that these routines take a single [protected sqlite3_value] object
5821 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
5823 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
5824 ** in the native byte-order of the host machine. ^The
5825 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
5826 ** extract UTF-16 strings as big-endian and little-endian respectively.
5828 ** ^If [sqlite3_value] object V was initialized
5829 ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
5830 ** and if X and Y are strings that compare equal according to strcmp(X,Y),
5831 ** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
5832 ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
5833 ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
5835 ** ^(The sqlite3_value_type(V) interface returns the
5836 ** [SQLITE_INTEGER | datatype code] for the initial datatype of the
5837 ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
5838 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
5839 ** Other interfaces might change the datatype for an sqlite3_value object.
5840 ** For example, if the datatype is initially SQLITE_INTEGER and
5841 ** sqlite3_value_text(V) is called to extract a text value for that
5842 ** integer, then subsequent calls to sqlite3_value_type(V) might return
5843 ** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
5844 ** occurs is undefined and may change from one release of SQLite to the next.
5846 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
5847 ** numeric affinity to the value. This means that an attempt is
5848 ** made to convert the value to an integer or floating point. If
5849 ** such a conversion is possible without loss of information (in other
5850 ** words, if the value is a string that looks like a number)
5851 ** then the conversion is performed. Otherwise no conversion occurs.
5852 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
5854 ** Please pay particular attention to the fact that the pointer returned
5855 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
5856 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
5857 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
5858 ** or [sqlite3_value_text16()].
5860 ** These routines must be called from the same thread as
5861 ** the SQL function that supplied the [sqlite3_value*] parameters.
5863 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
5864 SQLITE_API double sqlite3_value_double(sqlite3_value*);
5865 SQLITE_API int sqlite3_value_int(sqlite3_value*);
5866 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
5867 SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
5868 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
5869 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
5870 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
5871 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
5872 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
5873 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
5874 SQLITE_API int sqlite3_value_type(sqlite3_value*);
5875 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
5878 ** CAPI3REF: Finding The Subtype Of SQL Values
5879 ** METHOD: sqlite3_value
5881 ** The sqlite3_value_subtype(V) function returns the subtype for
5882 ** an [application-defined SQL function] argument V. The subtype
5883 ** information can be used to pass a limited amount of context from
5884 ** one SQL function to another. Use the [sqlite3_result_subtype()]
5885 ** routine to set the subtype for the return value of an SQL function.
5887 SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
5890 ** CAPI3REF: Copy And Free SQL Values
5891 ** METHOD: sqlite3_value
5893 ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
5894 ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
5895 ** is a [protected sqlite3_value] object even if the input is not.
5896 ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
5897 ** memory allocation fails.
5899 ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
5900 ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
5901 ** then sqlite3_value_free(V) is a harmless no-op.
5903 SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
5904 SQLITE_API void sqlite3_value_free(sqlite3_value*);
5907 ** CAPI3REF: Obtain Aggregate Function Context
5908 ** METHOD: sqlite3_context
5910 ** Implementations of aggregate SQL functions use this
5911 ** routine to allocate memory for storing their state.
5913 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
5914 ** for a particular aggregate function, SQLite
5915 ** allocates N of memory, zeroes out that memory, and returns a pointer
5916 ** to the new memory. ^On second and subsequent calls to
5917 ** sqlite3_aggregate_context() for the same aggregate function instance,
5918 ** the same buffer is returned. Sqlite3_aggregate_context() is normally
5919 ** called once for each invocation of the xStep callback and then one
5920 ** last time when the xFinal callback is invoked. ^(When no rows match
5921 ** an aggregate query, the xStep() callback of the aggregate function
5922 ** implementation is never called and xFinal() is called exactly once.
5923 ** In those cases, sqlite3_aggregate_context() might be called for the
5924 ** first time from within xFinal().)^
5926 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
5927 ** when first called if N is less than or equal to zero or if a memory
5928 ** allocate error occurs.
5930 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
5931 ** determined by the N parameter on first successful call. Changing the
5932 ** value of N in subsequent call to sqlite3_aggregate_context() within
5933 ** the same aggregate function instance will not resize the memory
5934 ** allocation.)^ Within the xFinal callback, it is customary to set
5935 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
5936 ** pointless memory allocations occur.
5938 ** ^SQLite automatically frees the memory allocated by
5939 ** sqlite3_aggregate_context() when the aggregate query concludes.
5941 ** The first parameter must be a copy of the
5942 ** [sqlite3_context | SQL function context] that is the first parameter
5943 ** to the xStep or xFinal callback routine that implements the aggregate
5944 ** function.
5946 ** This routine must be called from the same thread in which
5947 ** the aggregate SQL function is running.
5949 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
5952 ** CAPI3REF: User Data For Functions
5953 ** METHOD: sqlite3_context
5955 ** ^The sqlite3_user_data() interface returns a copy of
5956 ** the pointer that was the pUserData parameter (the 5th parameter)
5957 ** of the [sqlite3_create_function()]
5958 ** and [sqlite3_create_function16()] routines that originally
5959 ** registered the application defined function.
5961 ** This routine must be called from the same thread in which
5962 ** the application-defined function is running.
5964 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
5967 ** CAPI3REF: Database Connection For Functions
5968 ** METHOD: sqlite3_context
5970 ** ^The sqlite3_context_db_handle() interface returns a copy of
5971 ** the pointer to the [database connection] (the 1st parameter)
5972 ** of the [sqlite3_create_function()]
5973 ** and [sqlite3_create_function16()] routines that originally
5974 ** registered the application defined function.
5976 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
5979 ** CAPI3REF: Function Auxiliary Data
5980 ** METHOD: sqlite3_context
5982 ** These functions may be used by (non-aggregate) SQL functions to
5983 ** associate metadata with argument values. If the same value is passed to
5984 ** multiple invocations of the same SQL function during query execution, under
5985 ** some circumstances the associated metadata may be preserved. An example
5986 ** of where this might be useful is in a regular-expression matching
5987 ** function. The compiled version of the regular expression can be stored as
5988 ** metadata associated with the pattern string.
5989 ** Then as long as the pattern string remains the same,
5990 ** the compiled regular expression can be reused on multiple
5991 ** invocations of the same function.
5993 ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
5994 ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
5995 ** value to the application-defined function. ^N is zero for the left-most
5996 ** function argument. ^If there is no metadata
5997 ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
5998 ** returns a NULL pointer.
6000 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
6001 ** argument of the application-defined function. ^Subsequent
6002 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
6003 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
6004 ** NULL if the metadata has been discarded.
6005 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
6006 ** SQLite will invoke the destructor function X with parameter P exactly
6007 ** once, when the metadata is discarded.
6008 ** SQLite is free to discard the metadata at any time, including: <ul>
6009 ** <li> ^(when the corresponding function parameter changes)^, or
6010 ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
6011 ** SQL statement)^, or
6012 ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
6013 ** parameter)^, or
6014 ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
6015 ** allocation error occurs.)^ </ul>
6017 ** Note the last bullet in particular. The destructor X in
6018 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
6019 ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
6020 ** should be called near the end of the function implementation and the
6021 ** function implementation should not make any use of P after
6022 ** sqlite3_set_auxdata() has been called.
6024 ** ^(In practice, metadata is preserved between function calls for
6025 ** function parameters that are compile-time constants, including literal
6026 ** values and [parameters] and expressions composed from the same.)^
6028 ** The value of the N parameter to these interfaces should be non-negative.
6029 ** Future enhancements may make use of negative N values to define new
6030 ** kinds of function caching behavior.
6032 ** These routines must be called from the same thread in which
6033 ** the SQL function is running.
6035 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
6036 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
6040 ** CAPI3REF: Constants Defining Special Destructor Behavior
6042 ** These are special values for the destructor that is passed in as the
6043 ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
6044 ** argument is SQLITE_STATIC, it means that the content pointer is constant
6045 ** and will never change. It does not need to be destroyed. ^The
6046 ** SQLITE_TRANSIENT value means that the content will likely change in
6047 ** the near future and that SQLite should make its own private copy of
6048 ** the content before returning.
6050 ** The typedef is necessary to work around problems in certain
6051 ** C++ compilers.
6053 typedef void (*sqlite3_destructor_type)(void*);
6054 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
6055 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
6058 ** CAPI3REF: Setting The Result Of An SQL Function
6059 ** METHOD: sqlite3_context
6061 ** These routines are used by the xFunc or xFinal callbacks that
6062 ** implement SQL functions and aggregates. See
6063 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
6064 ** for additional information.
6066 ** These functions work very much like the [parameter binding] family of
6067 ** functions used to bind values to host parameters in prepared statements.
6068 ** Refer to the [SQL parameter] documentation for additional information.
6070 ** ^The sqlite3_result_blob() interface sets the result from
6071 ** an application-defined function to be the BLOB whose content is pointed
6072 ** to by the second parameter and which is N bytes long where N is the
6073 ** third parameter.
6075 ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
6076 ** interfaces set the result of the application-defined function to be
6077 ** a BLOB containing all zero bytes and N bytes in size.
6079 ** ^The sqlite3_result_double() interface sets the result from
6080 ** an application-defined function to be a floating point value specified
6081 ** by its 2nd argument.
6083 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
6084 ** cause the implemented SQL function to throw an exception.
6085 ** ^SQLite uses the string pointed to by the
6086 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
6087 ** as the text of an error message. ^SQLite interprets the error
6088 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
6089 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
6090 ** byte order. ^If the third parameter to sqlite3_result_error()
6091 ** or sqlite3_result_error16() is negative then SQLite takes as the error
6092 ** message all text up through the first zero character.
6093 ** ^If the third parameter to sqlite3_result_error() or
6094 ** sqlite3_result_error16() is non-negative then SQLite takes that many
6095 ** bytes (not characters) from the 2nd parameter as the error message.
6096 ** ^The sqlite3_result_error() and sqlite3_result_error16()
6097 ** routines make a private copy of the error message text before
6098 ** they return. Hence, the calling function can deallocate or
6099 ** modify the text after they return without harm.
6100 ** ^The sqlite3_result_error_code() function changes the error code
6101 ** returned by SQLite as a result of an error in a function. ^By default,
6102 ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
6103 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
6105 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
6106 ** error indicating that a string or BLOB is too long to represent.
6108 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
6109 ** error indicating that a memory allocation failed.
6111 ** ^The sqlite3_result_int() interface sets the return value
6112 ** of the application-defined function to be the 32-bit signed integer
6113 ** value given in the 2nd argument.
6114 ** ^The sqlite3_result_int64() interface sets the return value
6115 ** of the application-defined function to be the 64-bit signed integer
6116 ** value given in the 2nd argument.
6118 ** ^The sqlite3_result_null() interface sets the return value
6119 ** of the application-defined function to be NULL.
6121 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
6122 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
6123 ** set the return value of the application-defined function to be
6124 ** a text string which is represented as UTF-8, UTF-16 native byte order,
6125 ** UTF-16 little endian, or UTF-16 big endian, respectively.
6126 ** ^The sqlite3_result_text64() interface sets the return value of an
6127 ** application-defined function to be a text string in an encoding
6128 ** specified by the fifth (and last) parameter, which must be one
6129 ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
6130 ** ^SQLite takes the text result from the application from
6131 ** the 2nd parameter of the sqlite3_result_text* interfaces.
6132 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
6133 ** is negative, then SQLite takes result text from the 2nd parameter
6134 ** through the first zero character.
6135 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
6136 ** is non-negative, then as many bytes (not characters) of the text
6137 ** pointed to by the 2nd parameter are taken as the application-defined
6138 ** function result. If the 3rd parameter is non-negative, then it
6139 ** must be the byte offset into the string where the NUL terminator would
6140 ** appear if the string where NUL terminated. If any NUL characters occur
6141 ** in the string at a byte offset that is less than the value of the 3rd
6142 ** parameter, then the resulting string will contain embedded NULs and the
6143 ** result of expressions operating on strings with embedded NULs is undefined.
6144 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
6145 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
6146 ** function as the destructor on the text or BLOB result when it has
6147 ** finished using that result.
6148 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
6149 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
6150 ** assumes that the text or BLOB result is in constant space and does not
6151 ** copy the content of the parameter nor call a destructor on the content
6152 ** when it has finished using that result.
6153 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
6154 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
6155 ** then SQLite makes a copy of the result into space obtained
6156 ** from [sqlite3_malloc()] before it returns.
6158 ** ^The sqlite3_result_value() interface sets the result of
6159 ** the application-defined function to be a copy of the
6160 ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
6161 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
6162 ** so that the [sqlite3_value] specified in the parameter may change or
6163 ** be deallocated after sqlite3_result_value() returns without harm.
6164 ** ^A [protected sqlite3_value] object may always be used where an
6165 ** [unprotected sqlite3_value] object is required, so either
6166 ** kind of [sqlite3_value] object can be used with this interface.
6168 ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
6169 ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
6170 ** also associates the host-language pointer P or type T with that
6171 ** NULL value such that the pointer can be retrieved within an
6172 ** [application-defined SQL function] using [sqlite3_value_pointer()].
6173 ** ^If the D parameter is not NULL, then it is a pointer to a destructor
6174 ** for the P parameter. ^SQLite invokes D with P as its only argument
6175 ** when SQLite is finished with P. The T parameter should be a static
6176 ** string and preferably a string literal. The sqlite3_result_pointer()
6177 ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
6179 ** If these routines are called from within the different thread
6180 ** than the one containing the application-defined function that received
6181 ** the [sqlite3_context] pointer, the results are undefined.
6183 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
6184 SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
6185 sqlite3_uint64,void(*)(void*));
6186 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
6187 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
6188 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
6189 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
6190 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
6191 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
6192 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
6193 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
6194 SQLITE_API void sqlite3_result_null(sqlite3_context*);
6195 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
6196 SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
6197 void(*)(void*), unsigned char encoding);
6198 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
6199 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
6200 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
6201 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
6202 SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
6203 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
6204 SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
6208 ** CAPI3REF: Setting The Subtype Of An SQL Function
6209 ** METHOD: sqlite3_context
6211 ** The sqlite3_result_subtype(C,T) function causes the subtype of
6212 ** the result from the [application-defined SQL function] with
6213 ** [sqlite3_context] C to be the value T. Only the lower 8 bits
6214 ** of the subtype T are preserved in current versions of SQLite;
6215 ** higher order bits are discarded.
6216 ** The number of subtype bytes preserved by SQLite might increase
6217 ** in future releases of SQLite.
6219 SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
6222 ** CAPI3REF: Define New Collating Sequences
6223 ** METHOD: sqlite3
6225 ** ^These functions add, remove, or modify a [collation] associated
6226 ** with the [database connection] specified as the first argument.
6228 ** ^The name of the collation is a UTF-8 string
6229 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
6230 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
6231 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
6232 ** considered to be the same name.
6234 ** ^(The third argument (eTextRep) must be one of the constants:
6235 ** <ul>
6236 ** <li> [SQLITE_UTF8],
6237 ** <li> [SQLITE_UTF16LE],
6238 ** <li> [SQLITE_UTF16BE],
6239 ** <li> [SQLITE_UTF16], or
6240 ** <li> [SQLITE_UTF16_ALIGNED].
6241 ** </ul>)^
6242 ** ^The eTextRep argument determines the encoding of strings passed
6243 ** to the collating function callback, xCallback.
6244 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
6245 ** force strings to be UTF16 with native byte order.
6246 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
6247 ** on an even byte address.
6249 ** ^The fourth argument, pArg, is an application data pointer that is passed
6250 ** through as the first argument to the collating function callback.
6252 ** ^The fifth argument, xCallback, is a pointer to the collating function.
6253 ** ^Multiple collating functions can be registered using the same name but
6254 ** with different eTextRep parameters and SQLite will use whichever
6255 ** function requires the least amount of data transformation.
6256 ** ^If the xCallback argument is NULL then the collating function is
6257 ** deleted. ^When all collating functions having the same name are deleted,
6258 ** that collation is no longer usable.
6260 ** ^The collating function callback is invoked with a copy of the pArg
6261 ** application data pointer and with two strings in the encoding specified
6262 ** by the eTextRep argument. The collating function must return an
6263 ** integer that is negative, zero, or positive
6264 ** if the first string is less than, equal to, or greater than the second,
6265 ** respectively. A collating function must always return the same answer
6266 ** given the same inputs. If two or more collating functions are registered
6267 ** to the same collation name (using different eTextRep values) then all
6268 ** must give an equivalent answer when invoked with equivalent strings.
6269 ** The collating function must obey the following properties for all
6270 ** strings A, B, and C:
6272 ** <ol>
6273 ** <li> If A==B then B==A.
6274 ** <li> If A==B and B==C then A==C.
6275 ** <li> If A&lt;B THEN B&gt;A.
6276 ** <li> If A&lt;B and B&lt;C then A&lt;C.
6277 ** </ol>
6279 ** If a collating function fails any of the above constraints and that
6280 ** collating function is registered and used, then the behavior of SQLite
6281 ** is undefined.
6283 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
6284 ** with the addition that the xDestroy callback is invoked on pArg when
6285 ** the collating function is deleted.
6286 ** ^Collating functions are deleted when they are overridden by later
6287 ** calls to the collation creation functions or when the
6288 ** [database connection] is closed using [sqlite3_close()].
6290 ** ^The xDestroy callback is <u>not</u> called if the
6291 ** sqlite3_create_collation_v2() function fails. Applications that invoke
6292 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
6293 ** check the return code and dispose of the application data pointer
6294 ** themselves rather than expecting SQLite to deal with it for them.
6295 ** This is different from every other SQLite interface. The inconsistency
6296 ** is unfortunate but cannot be changed without breaking backwards
6297 ** compatibility.
6299 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
6301 SQLITE_API int sqlite3_create_collation(
6302 sqlite3*,
6303 const char *zName,
6304 int eTextRep,
6305 void *pArg,
6306 int(*xCompare)(void*,int,const void*,int,const void*)
6308 SQLITE_API int sqlite3_create_collation_v2(
6309 sqlite3*,
6310 const char *zName,
6311 int eTextRep,
6312 void *pArg,
6313 int(*xCompare)(void*,int,const void*,int,const void*),
6314 void(*xDestroy)(void*)
6316 SQLITE_API int sqlite3_create_collation16(
6317 sqlite3*,
6318 const void *zName,
6319 int eTextRep,
6320 void *pArg,
6321 int(*xCompare)(void*,int,const void*,int,const void*)
6325 ** CAPI3REF: Collation Needed Callbacks
6326 ** METHOD: sqlite3
6328 ** ^To avoid having to register all collation sequences before a database
6329 ** can be used, a single callback function may be registered with the
6330 ** [database connection] to be invoked whenever an undefined collation
6331 ** sequence is required.
6333 ** ^If the function is registered using the sqlite3_collation_needed() API,
6334 ** then it is passed the names of undefined collation sequences as strings
6335 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
6336 ** the names are passed as UTF-16 in machine native byte order.
6337 ** ^A call to either function replaces the existing collation-needed callback.
6339 ** ^(When the callback is invoked, the first argument passed is a copy
6340 ** of the second argument to sqlite3_collation_needed() or
6341 ** sqlite3_collation_needed16(). The second argument is the database
6342 ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
6343 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
6344 ** sequence function required. The fourth parameter is the name of the
6345 ** required collation sequence.)^
6347 ** The callback function should register the desired collation using
6348 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
6349 ** [sqlite3_create_collation_v2()].
6351 SQLITE_API int sqlite3_collation_needed(
6352 sqlite3*,
6353 void*,
6354 void(*)(void*,sqlite3*,int eTextRep,const char*)
6356 SQLITE_API int sqlite3_collation_needed16(
6357 sqlite3*,
6358 void*,
6359 void(*)(void*,sqlite3*,int eTextRep,const void*)
6362 #ifdef SQLITE_HAS_CODEC
6364 ** Specify the key for an encrypted database. This routine should be
6365 ** called right after sqlite3_open().
6367 ** The code to implement this API is not available in the public release
6368 ** of SQLite.
6370 SQLITE_API int sqlite3_key(
6371 sqlite3 *db, /* Database to be rekeyed */
6372 const void *pKey, int nKey /* The key */
6374 SQLITE_API int sqlite3_key_v2(
6375 sqlite3 *db, /* Database to be rekeyed */
6376 const char *zDbName, /* Name of the database */
6377 const void *pKey, int nKey /* The key */
6381 ** Change the key on an open database. If the current database is not
6382 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
6383 ** database is decrypted.
6385 ** The code to implement this API is not available in the public release
6386 ** of SQLite.
6388 SQLITE_API int sqlite3_rekey(
6389 sqlite3 *db, /* Database to be rekeyed */
6390 const void *pKey, int nKey /* The new key */
6392 SQLITE_API int sqlite3_rekey_v2(
6393 sqlite3 *db, /* Database to be rekeyed */
6394 const char *zDbName, /* Name of the database */
6395 const void *pKey, int nKey /* The new key */
6399 ** Specify the activation key for a SEE database. Unless
6400 ** activated, none of the SEE routines will work.
6402 SQLITE_API void sqlite3_activate_see(
6403 const char *zPassPhrase /* Activation phrase */
6405 #endif
6407 #ifdef SQLITE_ENABLE_CEROD
6409 ** Specify the activation key for a CEROD database. Unless
6410 ** activated, none of the CEROD routines will work.
6412 SQLITE_API void sqlite3_activate_cerod(
6413 const char *zPassPhrase /* Activation phrase */
6415 #endif
6418 ** CAPI3REF: Suspend Execution For A Short Time
6420 ** The sqlite3_sleep() function causes the current thread to suspend execution
6421 ** for at least a number of milliseconds specified in its parameter.
6423 ** If the operating system does not support sleep requests with
6424 ** millisecond time resolution, then the time will be rounded up to
6425 ** the nearest second. The number of milliseconds of sleep actually
6426 ** requested from the operating system is returned.
6428 ** ^SQLite implements this interface by calling the xSleep()
6429 ** method of the default [sqlite3_vfs] object. If the xSleep() method
6430 ** of the default VFS is not implemented correctly, or not implemented at
6431 ** all, then the behavior of sqlite3_sleep() may deviate from the description
6432 ** in the previous paragraphs.
6434 SQLITE_API int sqlite3_sleep(int);
6437 ** CAPI3REF: Name Of The Folder Holding Temporary Files
6439 ** ^(If this global variable is made to point to a string which is
6440 ** the name of a folder (a.k.a. directory), then all temporary files
6441 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
6442 ** will be placed in that directory.)^ ^If this variable
6443 ** is a NULL pointer, then SQLite performs a search for an appropriate
6444 ** temporary file directory.
6446 ** Applications are strongly discouraged from using this global variable.
6447 ** It is required to set a temporary folder on Windows Runtime (WinRT).
6448 ** But for all other platforms, it is highly recommended that applications
6449 ** neither read nor write this variable. This global variable is a relic
6450 ** that exists for backwards compatibility of legacy applications and should
6451 ** be avoided in new projects.
6453 ** It is not safe to read or modify this variable in more than one
6454 ** thread at a time. It is not safe to read or modify this variable
6455 ** if a [database connection] is being used at the same time in a separate
6456 ** thread.
6457 ** It is intended that this variable be set once
6458 ** as part of process initialization and before any SQLite interface
6459 ** routines have been called and that this variable remain unchanged
6460 ** thereafter.
6462 ** ^The [temp_store_directory pragma] may modify this variable and cause
6463 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
6464 ** the [temp_store_directory pragma] always assumes that any string
6465 ** that this variable points to is held in memory obtained from
6466 ** [sqlite3_malloc] and the pragma may attempt to free that memory
6467 ** using [sqlite3_free].
6468 ** Hence, if this variable is modified directly, either it should be
6469 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
6470 ** or else the use of the [temp_store_directory pragma] should be avoided.
6471 ** Except when requested by the [temp_store_directory pragma], SQLite
6472 ** does not free the memory that sqlite3_temp_directory points to. If
6473 ** the application wants that memory to be freed, it must do
6474 ** so itself, taking care to only do so after all [database connection]
6475 ** objects have been destroyed.
6477 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
6478 ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
6479 ** features that require the use of temporary files may fail. Here is an
6480 ** example of how to do this using C++ with the Windows Runtime:
6482 ** <blockquote><pre>
6483 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
6484 ** &nbsp; TemporaryFolder->Path->Data();
6485 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
6486 ** memset(zPathBuf, 0, sizeof(zPathBuf));
6487 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
6488 ** &nbsp; NULL, NULL);
6489 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
6490 ** </pre></blockquote>
6492 SQLITE_API char *sqlite3_temp_directory;
6495 ** CAPI3REF: Name Of The Folder Holding Database Files
6497 ** ^(If this global variable is made to point to a string which is
6498 ** the name of a folder (a.k.a. directory), then all database files
6499 ** specified with a relative pathname and created or accessed by
6500 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
6501 ** to be relative to that directory.)^ ^If this variable is a NULL
6502 ** pointer, then SQLite assumes that all database files specified
6503 ** with a relative pathname are relative to the current directory
6504 ** for the process. Only the windows VFS makes use of this global
6505 ** variable; it is ignored by the unix VFS.
6507 ** Changing the value of this variable while a database connection is
6508 ** open can result in a corrupt database.
6510 ** It is not safe to read or modify this variable in more than one
6511 ** thread at a time. It is not safe to read or modify this variable
6512 ** if a [database connection] is being used at the same time in a separate
6513 ** thread.
6514 ** It is intended that this variable be set once
6515 ** as part of process initialization and before any SQLite interface
6516 ** routines have been called and that this variable remain unchanged
6517 ** thereafter.
6519 ** ^The [data_store_directory pragma] may modify this variable and cause
6520 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
6521 ** the [data_store_directory pragma] always assumes that any string
6522 ** that this variable points to is held in memory obtained from
6523 ** [sqlite3_malloc] and the pragma may attempt to free that memory
6524 ** using [sqlite3_free].
6525 ** Hence, if this variable is modified directly, either it should be
6526 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
6527 ** or else the use of the [data_store_directory pragma] should be avoided.
6529 SQLITE_API char *sqlite3_data_directory;
6532 ** CAPI3REF: Test For Auto-Commit Mode
6533 ** KEYWORDS: {autocommit mode}
6534 ** METHOD: sqlite3
6536 ** ^The sqlite3_get_autocommit() interface returns non-zero or
6537 ** zero if the given database connection is or is not in autocommit mode,
6538 ** respectively. ^Autocommit mode is on by default.
6539 ** ^Autocommit mode is disabled by a [BEGIN] statement.
6540 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
6542 ** If certain kinds of errors occur on a statement within a multi-statement
6543 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
6544 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
6545 ** transaction might be rolled back automatically. The only way to
6546 ** find out whether SQLite automatically rolled back the transaction after
6547 ** an error is to use this function.
6549 ** If another thread changes the autocommit status of the database
6550 ** connection while this routine is running, then the return value
6551 ** is undefined.
6553 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
6556 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
6557 ** METHOD: sqlite3_stmt
6559 ** ^The sqlite3_db_handle interface returns the [database connection] handle
6560 ** to which a [prepared statement] belongs. ^The [database connection]
6561 ** returned by sqlite3_db_handle is the same [database connection]
6562 ** that was the first argument
6563 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
6564 ** create the statement in the first place.
6566 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
6569 ** CAPI3REF: Return The Filename For A Database Connection
6570 ** METHOD: sqlite3
6572 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
6573 ** associated with database N of connection D. ^The main database file
6574 ** has the name "main". If there is no attached database N on the database
6575 ** connection D, or if database N is a temporary or in-memory database, then
6576 ** a NULL pointer is returned.
6578 ** ^The filename returned by this function is the output of the
6579 ** xFullPathname method of the [VFS]. ^In other words, the filename
6580 ** will be an absolute pathname, even if the filename used
6581 ** to open the database originally was a URI or relative pathname.
6583 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
6586 ** CAPI3REF: Determine if a database is read-only
6587 ** METHOD: sqlite3
6589 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
6590 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
6591 ** the name of a database on connection D.
6593 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
6596 ** CAPI3REF: Find the next prepared statement
6597 ** METHOD: sqlite3
6599 ** ^This interface returns a pointer to the next [prepared statement] after
6600 ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
6601 ** then this interface returns a pointer to the first prepared statement
6602 ** associated with the database connection pDb. ^If no prepared statement
6603 ** satisfies the conditions of this routine, it returns NULL.
6605 ** The [database connection] pointer D in a call to
6606 ** [sqlite3_next_stmt(D,S)] must refer to an open database
6607 ** connection and in particular must not be a NULL pointer.
6609 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
6612 ** CAPI3REF: Commit And Rollback Notification Callbacks
6613 ** METHOD: sqlite3
6615 ** ^The sqlite3_commit_hook() interface registers a callback
6616 ** function to be invoked whenever a transaction is [COMMIT | committed].
6617 ** ^Any callback set by a previous call to sqlite3_commit_hook()
6618 ** for the same database connection is overridden.
6619 ** ^The sqlite3_rollback_hook() interface registers a callback
6620 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
6621 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
6622 ** for the same database connection is overridden.
6623 ** ^The pArg argument is passed through to the callback.
6624 ** ^If the callback on a commit hook function returns non-zero,
6625 ** then the commit is converted into a rollback.
6627 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
6628 ** return the P argument from the previous call of the same function
6629 ** on the same [database connection] D, or NULL for
6630 ** the first call for each function on D.
6632 ** The commit and rollback hook callbacks are not reentrant.
6633 ** The callback implementation must not do anything that will modify
6634 ** the database connection that invoked the callback. Any actions
6635 ** to modify the database connection must be deferred until after the
6636 ** completion of the [sqlite3_step()] call that triggered the commit
6637 ** or rollback hook in the first place.
6638 ** Note that running any other SQL statements, including SELECT statements,
6639 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
6640 ** the database connections for the meaning of "modify" in this paragraph.
6642 ** ^Registering a NULL function disables the callback.
6644 ** ^When the commit hook callback routine returns zero, the [COMMIT]
6645 ** operation is allowed to continue normally. ^If the commit hook
6646 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
6647 ** ^The rollback hook is invoked on a rollback that results from a commit
6648 ** hook returning non-zero, just as it would be with any other rollback.
6650 ** ^For the purposes of this API, a transaction is said to have been
6651 ** rolled back if an explicit "ROLLBACK" statement is executed, or
6652 ** an error or constraint causes an implicit rollback to occur.
6653 ** ^The rollback callback is not invoked if a transaction is
6654 ** automatically rolled back because the database connection is closed.
6656 ** See also the [sqlite3_update_hook()] interface.
6658 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
6659 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
6662 ** CAPI3REF: Data Change Notification Callbacks
6663 ** METHOD: sqlite3
6665 ** ^The sqlite3_update_hook() interface registers a callback function
6666 ** with the [database connection] identified by the first argument
6667 ** to be invoked whenever a row is updated, inserted or deleted in
6668 ** a [rowid table].
6669 ** ^Any callback set by a previous call to this function
6670 ** for the same database connection is overridden.
6672 ** ^The second argument is a pointer to the function to invoke when a
6673 ** row is updated, inserted or deleted in a rowid table.
6674 ** ^The first argument to the callback is a copy of the third argument
6675 ** to sqlite3_update_hook().
6676 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
6677 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
6678 ** to be invoked.
6679 ** ^The third and fourth arguments to the callback contain pointers to the
6680 ** database and table name containing the affected row.
6681 ** ^The final callback parameter is the [rowid] of the row.
6682 ** ^In the case of an update, this is the [rowid] after the update takes place.
6684 ** ^(The update hook is not invoked when internal system tables are
6685 ** modified (i.e. sqlite_master and sqlite_sequence).)^
6686 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
6688 ** ^In the current implementation, the update hook
6689 ** is not invoked when conflicting rows are deleted because of an
6690 ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
6691 ** invoked when rows are deleted using the [truncate optimization].
6692 ** The exceptions defined in this paragraph might change in a future
6693 ** release of SQLite.
6695 ** The update hook implementation must not do anything that will modify
6696 ** the database connection that invoked the update hook. Any actions
6697 ** to modify the database connection must be deferred until after the
6698 ** completion of the [sqlite3_step()] call that triggered the update hook.
6699 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
6700 ** database connections for the meaning of "modify" in this paragraph.
6702 ** ^The sqlite3_update_hook(D,C,P) function
6703 ** returns the P argument from the previous call
6704 ** on the same [database connection] D, or NULL for
6705 ** the first call on D.
6707 ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
6708 ** and [sqlite3_preupdate_hook()] interfaces.
6710 SQLITE_API void *sqlite3_update_hook(
6711 sqlite3*,
6712 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
6713 void*
6717 ** CAPI3REF: Enable Or Disable Shared Pager Cache
6719 ** ^(This routine enables or disables the sharing of the database cache
6720 ** and schema data structures between [database connection | connections]
6721 ** to the same database. Sharing is enabled if the argument is true
6722 ** and disabled if the argument is false.)^
6724 ** ^Cache sharing is enabled and disabled for an entire process.
6725 ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
6726 ** In prior versions of SQLite,
6727 ** sharing was enabled or disabled for each thread separately.
6729 ** ^(The cache sharing mode set by this interface effects all subsequent
6730 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
6731 ** Existing database connections continue use the sharing mode
6732 ** that was in effect at the time they were opened.)^
6734 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
6735 ** successfully. An [error code] is returned otherwise.)^
6737 ** ^Shared cache is disabled by default. But this might change in
6738 ** future releases of SQLite. Applications that care about shared
6739 ** cache setting should set it explicitly.
6741 ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
6742 ** and will always return SQLITE_MISUSE. On those systems,
6743 ** shared cache mode should be enabled per-database connection via
6744 ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
6746 ** This interface is threadsafe on processors where writing a
6747 ** 32-bit integer is atomic.
6749 ** See Also: [SQLite Shared-Cache Mode]
6751 SQLITE_API int sqlite3_enable_shared_cache(int);
6754 ** CAPI3REF: Attempt To Free Heap Memory
6756 ** ^The sqlite3_release_memory() interface attempts to free N bytes
6757 ** of heap memory by deallocating non-essential memory allocations
6758 ** held by the database library. Memory used to cache database
6759 ** pages to improve performance is an example of non-essential memory.
6760 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
6761 ** which might be more or less than the amount requested.
6762 ** ^The sqlite3_release_memory() routine is a no-op returning zero
6763 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
6765 ** See also: [sqlite3_db_release_memory()]
6767 SQLITE_API int sqlite3_release_memory(int);
6770 ** CAPI3REF: Free Memory Used By A Database Connection
6771 ** METHOD: sqlite3
6773 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
6774 ** memory as possible from database connection D. Unlike the
6775 ** [sqlite3_release_memory()] interface, this interface is in effect even
6776 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
6777 ** omitted.
6779 ** See also: [sqlite3_release_memory()]
6781 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
6784 ** CAPI3REF: Impose A Limit On Heap Size
6786 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
6787 ** soft limit on the amount of heap memory that may be allocated by SQLite.
6788 ** ^SQLite strives to keep heap memory utilization below the soft heap
6789 ** limit by reducing the number of pages held in the page cache
6790 ** as heap memory usages approaches the limit.
6791 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
6792 ** below the limit, it will exceed the limit rather than generate
6793 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
6794 ** is advisory only.
6796 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
6797 ** the soft heap limit prior to the call, or negative in the case of an
6798 ** error. ^If the argument N is negative
6799 ** then no change is made to the soft heap limit. Hence, the current
6800 ** size of the soft heap limit can be determined by invoking
6801 ** sqlite3_soft_heap_limit64() with a negative argument.
6803 ** ^If the argument N is zero then the soft heap limit is disabled.
6805 ** ^(The soft heap limit is not enforced in the current implementation
6806 ** if one or more of following conditions are true:
6808 ** <ul>
6809 ** <li> The soft heap limit is set to zero.
6810 ** <li> Memory accounting is disabled using a combination of the
6811 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
6812 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
6813 ** <li> An alternative page cache implementation is specified using
6814 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
6815 ** <li> The page cache allocates from its own memory pool supplied
6816 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
6817 ** from the heap.
6818 ** </ul>)^
6820 ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
6821 ** the soft heap limit is enforced
6822 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
6823 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
6824 ** the soft heap limit is enforced on every memory allocation. Without
6825 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
6826 ** when memory is allocated by the page cache. Testing suggests that because
6827 ** the page cache is the predominate memory user in SQLite, most
6828 ** applications will achieve adequate soft heap limit enforcement without
6829 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
6831 ** The circumstances under which SQLite will enforce the soft heap limit may
6832 ** changes in future releases of SQLite.
6834 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
6837 ** CAPI3REF: Deprecated Soft Heap Limit Interface
6838 ** DEPRECATED
6840 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
6841 ** interface. This routine is provided for historical compatibility
6842 ** only. All new applications should use the
6843 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
6845 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
6849 ** CAPI3REF: Extract Metadata About A Column Of A Table
6850 ** METHOD: sqlite3
6852 ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
6853 ** information about column C of table T in database D
6854 ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
6855 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
6856 ** the final five arguments with appropriate values if the specified
6857 ** column exists. ^The sqlite3_table_column_metadata() interface returns
6858 ** SQLITE_ERROR and if the specified column does not exist.
6859 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
6860 ** NULL pointer, then this routine simply checks for the existence of the
6861 ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
6862 ** does not. If the table name parameter T in a call to
6863 ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
6864 ** undefined behavior.
6866 ** ^The column is identified by the second, third and fourth parameters to
6867 ** this function. ^(The second parameter is either the name of the database
6868 ** (i.e. "main", "temp", or an attached database) containing the specified
6869 ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
6870 ** for the table using the same algorithm used by the database engine to
6871 ** resolve unqualified table references.
6873 ** ^The third and fourth parameters to this function are the table and column
6874 ** name of the desired column, respectively.
6876 ** ^Metadata is returned by writing to the memory locations passed as the 5th
6877 ** and subsequent parameters to this function. ^Any of these arguments may be
6878 ** NULL, in which case the corresponding element of metadata is omitted.
6880 ** ^(<blockquote>
6881 ** <table border="1">
6882 ** <tr><th> Parameter <th> Output<br>Type <th> Description
6884 ** <tr><td> 5th <td> const char* <td> Data type
6885 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
6886 ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
6887 ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
6888 ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
6889 ** </table>
6890 ** </blockquote>)^
6892 ** ^The memory pointed to by the character pointers returned for the
6893 ** declaration type and collation sequence is valid until the next
6894 ** call to any SQLite API function.
6896 ** ^If the specified table is actually a view, an [error code] is returned.
6898 ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
6899 ** is not a [WITHOUT ROWID] table and an
6900 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
6901 ** parameters are set for the explicitly declared column. ^(If there is no
6902 ** [INTEGER PRIMARY KEY] column, then the outputs
6903 ** for the [rowid] are set as follows:
6905 ** <pre>
6906 ** data type: "INTEGER"
6907 ** collation sequence: "BINARY"
6908 ** not null: 0
6909 ** primary key: 1
6910 ** auto increment: 0
6911 ** </pre>)^
6913 ** ^This function causes all database schemas to be read from disk and
6914 ** parsed, if that has not already been done, and returns an error if
6915 ** any errors are encountered while loading the schema.
6917 SQLITE_API int sqlite3_table_column_metadata(
6918 sqlite3 *db, /* Connection handle */
6919 const char *zDbName, /* Database name or NULL */
6920 const char *zTableName, /* Table name */
6921 const char *zColumnName, /* Column name */
6922 char const **pzDataType, /* OUTPUT: Declared data type */
6923 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
6924 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
6925 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
6926 int *pAutoinc /* OUTPUT: True if column is auto-increment */
6930 ** CAPI3REF: Load An Extension
6931 ** METHOD: sqlite3
6933 ** ^This interface loads an SQLite extension library from the named file.
6935 ** ^The sqlite3_load_extension() interface attempts to load an
6936 ** [SQLite extension] library contained in the file zFile. If
6937 ** the file cannot be loaded directly, attempts are made to load
6938 ** with various operating-system specific extensions added.
6939 ** So for example, if "samplelib" cannot be loaded, then names like
6940 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
6941 ** be tried also.
6943 ** ^The entry point is zProc.
6944 ** ^(zProc may be 0, in which case SQLite will try to come up with an
6945 ** entry point name on its own. It first tries "sqlite3_extension_init".
6946 ** If that does not work, it constructs a name "sqlite3_X_init" where the
6947 ** X is consists of the lower-case equivalent of all ASCII alphabetic
6948 ** characters in the filename from the last "/" to the first following
6949 ** "." and omitting any initial "lib".)^
6950 ** ^The sqlite3_load_extension() interface returns
6951 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
6952 ** ^If an error occurs and pzErrMsg is not 0, then the
6953 ** [sqlite3_load_extension()] interface shall attempt to
6954 ** fill *pzErrMsg with error message text stored in memory
6955 ** obtained from [sqlite3_malloc()]. The calling function
6956 ** should free this memory by calling [sqlite3_free()].
6958 ** ^Extension loading must be enabled using
6959 ** [sqlite3_enable_load_extension()] or
6960 ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
6961 ** prior to calling this API,
6962 ** otherwise an error will be returned.
6964 ** <b>Security warning:</b> It is recommended that the
6965 ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
6966 ** interface. The use of the [sqlite3_enable_load_extension()] interface
6967 ** should be avoided. This will keep the SQL function [load_extension()]
6968 ** disabled and prevent SQL injections from giving attackers
6969 ** access to extension loading capabilities.
6971 ** See also the [load_extension() SQL function].
6973 SQLITE_API int sqlite3_load_extension(
6974 sqlite3 *db, /* Load the extension into this database connection */
6975 const char *zFile, /* Name of the shared library containing extension */
6976 const char *zProc, /* Entry point. Derived from zFile if 0 */
6977 char **pzErrMsg /* Put error message here if not 0 */
6981 ** CAPI3REF: Enable Or Disable Extension Loading
6982 ** METHOD: sqlite3
6984 ** ^So as not to open security holes in older applications that are
6985 ** unprepared to deal with [extension loading], and as a means of disabling
6986 ** [extension loading] while evaluating user-entered SQL, the following API
6987 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
6989 ** ^Extension loading is off by default.
6990 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
6991 ** to turn extension loading on and call it with onoff==0 to turn
6992 ** it back off again.
6994 ** ^This interface enables or disables both the C-API
6995 ** [sqlite3_load_extension()] and the SQL function [load_extension()].
6996 ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
6997 ** to enable or disable only the C-API.)^
6999 ** <b>Security warning:</b> It is recommended that extension loading
7000 ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
7001 ** rather than this interface, so the [load_extension()] SQL function
7002 ** remains disabled. This will prevent SQL injections from giving attackers
7003 ** access to extension loading capabilities.
7005 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
7008 ** CAPI3REF: Automatically Load Statically Linked Extensions
7010 ** ^This interface causes the xEntryPoint() function to be invoked for
7011 ** each new [database connection] that is created. The idea here is that
7012 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
7013 ** that is to be automatically loaded into all new database connections.
7015 ** ^(Even though the function prototype shows that xEntryPoint() takes
7016 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
7017 ** arguments and expects an integer result as if the signature of the
7018 ** entry point where as follows:
7020 ** <blockquote><pre>
7021 ** &nbsp; int xEntryPoint(
7022 ** &nbsp; sqlite3 *db,
7023 ** &nbsp; const char **pzErrMsg,
7024 ** &nbsp; const struct sqlite3_api_routines *pThunk
7025 ** &nbsp; );
7026 ** </pre></blockquote>)^
7028 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
7029 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
7030 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
7031 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
7032 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
7033 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
7034 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
7036 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
7037 ** on the list of automatic extensions is a harmless no-op. ^No entry point
7038 ** will be called more than once for each database connection that is opened.
7040 ** See also: [sqlite3_reset_auto_extension()]
7041 ** and [sqlite3_cancel_auto_extension()]
7043 SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
7046 ** CAPI3REF: Cancel Automatic Extension Loading
7048 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
7049 ** initialization routine X that was registered using a prior call to
7050 ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
7051 ** routine returns 1 if initialization routine X was successfully
7052 ** unregistered and it returns 0 if X was not on the list of initialization
7053 ** routines.
7055 SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
7058 ** CAPI3REF: Reset Automatic Extension Loading
7060 ** ^This interface disables all automatic extensions previously
7061 ** registered using [sqlite3_auto_extension()].
7063 SQLITE_API void sqlite3_reset_auto_extension(void);
7066 ** The interface to the virtual-table mechanism is currently considered
7067 ** to be experimental. The interface might change in incompatible ways.
7068 ** If this is a problem for you, do not use the interface at this time.
7070 ** When the virtual-table mechanism stabilizes, we will declare the
7071 ** interface fixed, support it indefinitely, and remove this comment.
7075 ** Structures used by the virtual table interface
7077 typedef struct sqlite3_vtab sqlite3_vtab;
7078 typedef struct sqlite3_index_info sqlite3_index_info;
7079 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
7080 typedef struct sqlite3_module sqlite3_module;
7083 ** CAPI3REF: Virtual Table Object
7084 ** KEYWORDS: sqlite3_module {virtual table module}
7086 ** This structure, sometimes called a "virtual table module",
7087 ** defines the implementation of a [virtual tables].
7088 ** This structure consists mostly of methods for the module.
7090 ** ^A virtual table module is created by filling in a persistent
7091 ** instance of this structure and passing a pointer to that instance
7092 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
7093 ** ^The registration remains valid until it is replaced by a different
7094 ** module or until the [database connection] closes. The content
7095 ** of this structure must not change while it is registered with
7096 ** any database connection.
7098 struct sqlite3_module {
7099 int iVersion;
7100 int (*xCreate)(sqlite3*, void *pAux,
7101 int argc, const char *const*argv,
7102 sqlite3_vtab **ppVTab, char**);
7103 int (*xConnect)(sqlite3*, void *pAux,
7104 int argc, const char *const*argv,
7105 sqlite3_vtab **ppVTab, char**);
7106 int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
7107 int (*xDisconnect)(sqlite3_vtab *pVTab);
7108 int (*xDestroy)(sqlite3_vtab *pVTab);
7109 int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
7110 int (*xClose)(sqlite3_vtab_cursor*);
7111 int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
7112 int argc, sqlite3_value **argv);
7113 int (*xNext)(sqlite3_vtab_cursor*);
7114 int (*xEof)(sqlite3_vtab_cursor*);
7115 int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
7116 int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
7117 int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
7118 int (*xBegin)(sqlite3_vtab *pVTab);
7119 int (*xSync)(sqlite3_vtab *pVTab);
7120 int (*xCommit)(sqlite3_vtab *pVTab);
7121 int (*xRollback)(sqlite3_vtab *pVTab);
7122 int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
7123 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
7124 void **ppArg);
7125 int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
7126 /* The methods above are in version 1 of the sqlite_module object. Those
7127 ** below are for version 2 and greater. */
7128 int (*xSavepoint)(sqlite3_vtab *pVTab, int);
7129 int (*xRelease)(sqlite3_vtab *pVTab, int);
7130 int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
7134 ** CAPI3REF: Virtual Table Indexing Information
7135 ** KEYWORDS: sqlite3_index_info
7137 ** The sqlite3_index_info structure and its substructures is used as part
7138 ** of the [virtual table] interface to
7139 ** pass information into and receive the reply from the [xBestIndex]
7140 ** method of a [virtual table module]. The fields under **Inputs** are the
7141 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
7142 ** results into the **Outputs** fields.
7144 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
7146 ** <blockquote>column OP expr</blockquote>
7148 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
7149 ** stored in aConstraint[].op using one of the
7150 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
7151 ** ^(The index of the column is stored in
7152 ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
7153 ** expr on the right-hand side can be evaluated (and thus the constraint
7154 ** is usable) and false if it cannot.)^
7156 ** ^The optimizer automatically inverts terms of the form "expr OP column"
7157 ** and makes other simplifications to the WHERE clause in an attempt to
7158 ** get as many WHERE clause terms into the form shown above as possible.
7159 ** ^The aConstraint[] array only reports WHERE clause terms that are
7160 ** relevant to the particular virtual table being queried.
7162 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
7163 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
7165 ** The colUsed field indicates which columns of the virtual table may be
7166 ** required by the current scan. Virtual table columns are numbered from
7167 ** zero in the order in which they appear within the CREATE TABLE statement
7168 ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
7169 ** the corresponding bit is set within the colUsed mask if the column may be
7170 ** required by SQLite. If the table has at least 64 columns and any column
7171 ** to the right of the first 63 is required, then bit 63 of colUsed is also
7172 ** set. In other words, column iCol may be required if the expression
7173 ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
7174 ** non-zero.
7176 ** The [xBestIndex] method must fill aConstraintUsage[] with information
7177 ** about what parameters to pass to xFilter. ^If argvIndex>0 then
7178 ** the right-hand side of the corresponding aConstraint[] is evaluated
7179 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
7180 ** is true, then the constraint is assumed to be fully handled by the
7181 ** virtual table and is not checked again by SQLite.)^
7183 ** ^The idxNum and idxPtr values are recorded and passed into the
7184 ** [xFilter] method.
7185 ** ^[sqlite3_free()] is used to free idxPtr if and only if
7186 ** needToFreeIdxPtr is true.
7188 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
7189 ** the correct order to satisfy the ORDER BY clause so that no separate
7190 ** sorting step is required.
7192 ** ^The estimatedCost value is an estimate of the cost of a particular
7193 ** strategy. A cost of N indicates that the cost of the strategy is similar
7194 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
7195 ** indicates that the expense of the operation is similar to that of a
7196 ** binary search on a unique indexed field of an SQLite table with N rows.
7198 ** ^The estimatedRows value is an estimate of the number of rows that
7199 ** will be returned by the strategy.
7201 ** The xBestIndex method may optionally populate the idxFlags field with a
7202 ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
7203 ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
7204 ** assumes that the strategy may visit at most one row.
7206 ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
7207 ** SQLite also assumes that if a call to the xUpdate() method is made as
7208 ** part of the same statement to delete or update a virtual table row and the
7209 ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
7210 ** any database changes. In other words, if the xUpdate() returns
7211 ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
7212 ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
7213 ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
7214 ** the xUpdate method are automatically rolled back by SQLite.
7216 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
7217 ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
7218 ** If a virtual table extension is
7219 ** used with an SQLite version earlier than 3.8.2, the results of attempting
7220 ** to read or write the estimatedRows field are undefined (but are likely
7221 ** to included crashing the application). The estimatedRows field should
7222 ** therefore only be used if [sqlite3_libversion_number()] returns a
7223 ** value greater than or equal to 3008002. Similarly, the idxFlags field
7224 ** was added for [version 3.9.0] ([dateof:3.9.0]).
7225 ** It may therefore only be used if
7226 ** sqlite3_libversion_number() returns a value greater than or equal to
7227 ** 3009000.
7229 struct sqlite3_index_info {
7230 /* Inputs */
7231 int nConstraint; /* Number of entries in aConstraint */
7232 struct sqlite3_index_constraint {
7233 int iColumn; /* Column constrained. -1 for ROWID */
7234 unsigned char op; /* Constraint operator */
7235 unsigned char usable; /* True if this constraint is usable */
7236 int iTermOffset; /* Used internally - xBestIndex should ignore */
7237 } *aConstraint; /* Table of WHERE clause constraints */
7238 int nOrderBy; /* Number of terms in the ORDER BY clause */
7239 struct sqlite3_index_orderby {
7240 int iColumn; /* Column number */
7241 unsigned char desc; /* True for DESC. False for ASC. */
7242 } *aOrderBy; /* The ORDER BY clause */
7243 /* Outputs */
7244 struct sqlite3_index_constraint_usage {
7245 int argvIndex; /* if >0, constraint is part of argv to xFilter */
7246 unsigned char omit; /* Do not code a test for this constraint */
7247 } *aConstraintUsage;
7248 int idxNum; /* Number used to identify the index */
7249 char *idxStr; /* String, possibly obtained from sqlite3_malloc */
7250 int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
7251 int orderByConsumed; /* True if output is already ordered */
7252 double estimatedCost; /* Estimated cost of using this index */
7253 /* Fields below are only available in SQLite 3.8.2 and later */
7254 sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
7255 /* Fields below are only available in SQLite 3.9.0 and later */
7256 int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
7257 /* Fields below are only available in SQLite 3.10.0 and later */
7258 sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
7262 ** CAPI3REF: Virtual Table Scan Flags
7264 #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
7267 ** CAPI3REF: Virtual Table Constraint Operator Codes
7269 ** These macros defined the allowed values for the
7270 ** [sqlite3_index_info].aConstraint[].op field. Each value represents
7271 ** an operator that is part of a constraint term in the wHERE clause of
7272 ** a query that uses a [virtual table].
7274 #define SQLITE_INDEX_CONSTRAINT_EQ 2
7275 #define SQLITE_INDEX_CONSTRAINT_GT 4
7276 #define SQLITE_INDEX_CONSTRAINT_LE 8
7277 #define SQLITE_INDEX_CONSTRAINT_LT 16
7278 #define SQLITE_INDEX_CONSTRAINT_GE 32
7279 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
7280 #define SQLITE_INDEX_CONSTRAINT_LIKE 65
7281 #define SQLITE_INDEX_CONSTRAINT_GLOB 66
7282 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
7283 #define SQLITE_INDEX_CONSTRAINT_NE 68
7284 #define SQLITE_INDEX_CONSTRAINT_ISNOT 69
7285 #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
7286 #define SQLITE_INDEX_CONSTRAINT_ISNULL 71
7287 #define SQLITE_INDEX_CONSTRAINT_IS 72
7290 ** CAPI3REF: Register A Virtual Table Implementation
7291 ** METHOD: sqlite3
7293 ** ^These routines are used to register a new [virtual table module] name.
7294 ** ^Module names must be registered before
7295 ** creating a new [virtual table] using the module and before using a
7296 ** preexisting [virtual table] for the module.
7298 ** ^The module name is registered on the [database connection] specified
7299 ** by the first parameter. ^The name of the module is given by the
7300 ** second parameter. ^The third parameter is a pointer to
7301 ** the implementation of the [virtual table module]. ^The fourth
7302 ** parameter is an arbitrary client data pointer that is passed through
7303 ** into the [xCreate] and [xConnect] methods of the virtual table module
7304 ** when a new virtual table is be being created or reinitialized.
7306 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
7307 ** is a pointer to a destructor for the pClientData. ^SQLite will
7308 ** invoke the destructor function (if it is not NULL) when SQLite
7309 ** no longer needs the pClientData pointer. ^The destructor will also
7310 ** be invoked if the call to sqlite3_create_module_v2() fails.
7311 ** ^The sqlite3_create_module()
7312 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
7313 ** destructor.
7315 SQLITE_API int sqlite3_create_module(
7316 sqlite3 *db, /* SQLite connection to register module with */
7317 const char *zName, /* Name of the module */
7318 const sqlite3_module *p, /* Methods for the module */
7319 void *pClientData /* Client data for xCreate/xConnect */
7321 SQLITE_API int sqlite3_create_module_v2(
7322 sqlite3 *db, /* SQLite connection to register module with */
7323 const char *zName, /* Name of the module */
7324 const sqlite3_module *p, /* Methods for the module */
7325 void *pClientData, /* Client data for xCreate/xConnect */
7326 void(*xDestroy)(void*) /* Module destructor function */
7330 ** CAPI3REF: Virtual Table Instance Object
7331 ** KEYWORDS: sqlite3_vtab
7333 ** Every [virtual table module] implementation uses a subclass
7334 ** of this object to describe a particular instance
7335 ** of the [virtual table]. Each subclass will
7336 ** be tailored to the specific needs of the module implementation.
7337 ** The purpose of this superclass is to define certain fields that are
7338 ** common to all module implementations.
7340 ** ^Virtual tables methods can set an error message by assigning a
7341 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
7342 ** take care that any prior string is freed by a call to [sqlite3_free()]
7343 ** prior to assigning a new string to zErrMsg. ^After the error message
7344 ** is delivered up to the client application, the string will be automatically
7345 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
7347 struct sqlite3_vtab {
7348 const sqlite3_module *pModule; /* The module for this virtual table */
7349 int nRef; /* Number of open cursors */
7350 char *zErrMsg; /* Error message from sqlite3_mprintf() */
7351 /* Virtual table implementations will typically add additional fields */
7355 ** CAPI3REF: Virtual Table Cursor Object
7356 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
7358 ** Every [virtual table module] implementation uses a subclass of the
7359 ** following structure to describe cursors that point into the
7360 ** [virtual table] and are used
7361 ** to loop through the virtual table. Cursors are created using the
7362 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
7363 ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
7364 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
7365 ** of the module. Each module implementation will define
7366 ** the content of a cursor structure to suit its own needs.
7368 ** This superclass exists in order to define fields of the cursor that
7369 ** are common to all implementations.
7371 struct sqlite3_vtab_cursor {
7372 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
7373 /* Virtual table implementations will typically add additional fields */
7377 ** CAPI3REF: Declare The Schema Of A Virtual Table
7379 ** ^The [xCreate] and [xConnect] methods of a
7380 ** [virtual table module] call this interface
7381 ** to declare the format (the names and datatypes of the columns) of
7382 ** the virtual tables they implement.
7384 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
7387 ** CAPI3REF: Overload A Function For A Virtual Table
7388 ** METHOD: sqlite3
7390 ** ^(Virtual tables can provide alternative implementations of functions
7391 ** using the [xFindFunction] method of the [virtual table module].
7392 ** But global versions of those functions
7393 ** must exist in order to be overloaded.)^
7395 ** ^(This API makes sure a global version of a function with a particular
7396 ** name and number of parameters exists. If no such function exists
7397 ** before this API is called, a new function is created.)^ ^The implementation
7398 ** of the new function always causes an exception to be thrown. So
7399 ** the new function is not good for anything by itself. Its only
7400 ** purpose is to be a placeholder function that can be overloaded
7401 ** by a [virtual table].
7403 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
7406 ** The interface to the virtual-table mechanism defined above (back up
7407 ** to a comment remarkably similar to this one) is currently considered
7408 ** to be experimental. The interface might change in incompatible ways.
7409 ** If this is a problem for you, do not use the interface at this time.
7411 ** When the virtual-table mechanism stabilizes, we will declare the
7412 ** interface fixed, support it indefinitely, and remove this comment.
7416 ** CAPI3REF: A Handle To An Open BLOB
7417 ** KEYWORDS: {BLOB handle} {BLOB handles}
7419 ** An instance of this object represents an open BLOB on which
7420 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
7421 ** ^Objects of this type are created by [sqlite3_blob_open()]
7422 ** and destroyed by [sqlite3_blob_close()].
7423 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
7424 ** can be used to read or write small subsections of the BLOB.
7425 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
7427 typedef struct sqlite3_blob sqlite3_blob;
7430 ** CAPI3REF: Open A BLOB For Incremental I/O
7431 ** METHOD: sqlite3
7432 ** CONSTRUCTOR: sqlite3_blob
7434 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
7435 ** in row iRow, column zColumn, table zTable in database zDb;
7436 ** in other words, the same BLOB that would be selected by:
7438 ** <pre>
7439 ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
7440 ** </pre>)^
7442 ** ^(Parameter zDb is not the filename that contains the database, but
7443 ** rather the symbolic name of the database. For attached databases, this is
7444 ** the name that appears after the AS keyword in the [ATTACH] statement.
7445 ** For the main database file, the database name is "main". For TEMP
7446 ** tables, the database name is "temp".)^
7448 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
7449 ** and write access. ^If the flags parameter is zero, the BLOB is opened for
7450 ** read-only access.
7452 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
7453 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
7454 ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
7455 ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
7456 ** on *ppBlob after this function it returns.
7458 ** This function fails with SQLITE_ERROR if any of the following are true:
7459 ** <ul>
7460 ** <li> ^(Database zDb does not exist)^,
7461 ** <li> ^(Table zTable does not exist within database zDb)^,
7462 ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
7463 ** <li> ^(Column zColumn does not exist)^,
7464 ** <li> ^(Row iRow is not present in the table)^,
7465 ** <li> ^(The specified column of row iRow contains a value that is not
7466 ** a TEXT or BLOB value)^,
7467 ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
7468 ** constraint and the blob is being opened for read/write access)^,
7469 ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
7470 ** column zColumn is part of a [child key] definition and the blob is
7471 ** being opened for read/write access)^.
7472 ** </ul>
7474 ** ^Unless it returns SQLITE_MISUSE, this function sets the
7475 ** [database connection] error code and message accessible via
7476 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
7478 ** A BLOB referenced by sqlite3_blob_open() may be read using the
7479 ** [sqlite3_blob_read()] interface and modified by using
7480 ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
7481 ** different row of the same table using the [sqlite3_blob_reopen()]
7482 ** interface. However, the column, table, or database of a [BLOB handle]
7483 ** cannot be changed after the [BLOB handle] is opened.
7485 ** ^(If the row that a BLOB handle points to is modified by an
7486 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
7487 ** then the BLOB handle is marked as "expired".
7488 ** This is true if any column of the row is changed, even a column
7489 ** other than the one the BLOB handle is open on.)^
7490 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
7491 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
7492 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
7493 ** rolled back by the expiration of the BLOB. Such changes will eventually
7494 ** commit if the transaction continues to completion.)^
7496 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
7497 ** the opened blob. ^The size of a blob may not be changed by this
7498 ** interface. Use the [UPDATE] SQL command to change the size of a
7499 ** blob.
7501 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
7502 ** and the built-in [zeroblob] SQL function may be used to create a
7503 ** zero-filled blob to read or write using the incremental-blob interface.
7505 ** To avoid a resource leak, every open [BLOB handle] should eventually
7506 ** be released by a call to [sqlite3_blob_close()].
7508 ** See also: [sqlite3_blob_close()],
7509 ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
7510 ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
7512 SQLITE_API int sqlite3_blob_open(
7513 sqlite3*,
7514 const char *zDb,
7515 const char *zTable,
7516 const char *zColumn,
7517 sqlite3_int64 iRow,
7518 int flags,
7519 sqlite3_blob **ppBlob
7523 ** CAPI3REF: Move a BLOB Handle to a New Row
7524 ** METHOD: sqlite3_blob
7526 ** ^This function is used to move an existing [BLOB handle] so that it points
7527 ** to a different row of the same database table. ^The new row is identified
7528 ** by the rowid value passed as the second argument. Only the row can be
7529 ** changed. ^The database, table and column on which the blob handle is open
7530 ** remain the same. Moving an existing [BLOB handle] to a new row is
7531 ** faster than closing the existing handle and opening a new one.
7533 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
7534 ** it must exist and there must be either a blob or text value stored in
7535 ** the nominated column.)^ ^If the new row is not present in the table, or if
7536 ** it does not contain a blob or text value, or if another error occurs, an
7537 ** SQLite error code is returned and the blob handle is considered aborted.
7538 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
7539 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
7540 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
7541 ** always returns zero.
7543 ** ^This function sets the database handle error code and message.
7545 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
7548 ** CAPI3REF: Close A BLOB Handle
7549 ** DESTRUCTOR: sqlite3_blob
7551 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
7552 ** unconditionally. Even if this routine returns an error code, the
7553 ** handle is still closed.)^
7555 ** ^If the blob handle being closed was opened for read-write access, and if
7556 ** the database is in auto-commit mode and there are no other open read-write
7557 ** blob handles or active write statements, the current transaction is
7558 ** committed. ^If an error occurs while committing the transaction, an error
7559 ** code is returned and the transaction rolled back.
7561 ** Calling this function with an argument that is not a NULL pointer or an
7562 ** open blob handle results in undefined behaviour. ^Calling this routine
7563 ** with a null pointer (such as would be returned by a failed call to
7564 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
7565 ** is passed a valid open blob handle, the values returned by the
7566 ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
7568 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
7571 ** CAPI3REF: Return The Size Of An Open BLOB
7572 ** METHOD: sqlite3_blob
7574 ** ^Returns the size in bytes of the BLOB accessible via the
7575 ** successfully opened [BLOB handle] in its only argument. ^The
7576 ** incremental blob I/O routines can only read or overwriting existing
7577 ** blob content; they cannot change the size of a blob.
7579 ** This routine only works on a [BLOB handle] which has been created
7580 ** by a prior successful call to [sqlite3_blob_open()] and which has not
7581 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
7582 ** to this routine results in undefined and probably undesirable behavior.
7584 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
7587 ** CAPI3REF: Read Data From A BLOB Incrementally
7588 ** METHOD: sqlite3_blob
7590 ** ^(This function is used to read data from an open [BLOB handle] into a
7591 ** caller-supplied buffer. N bytes of data are copied into buffer Z
7592 ** from the open BLOB, starting at offset iOffset.)^
7594 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
7595 ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
7596 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
7597 ** ^The size of the blob (and hence the maximum value of N+iOffset)
7598 ** can be determined using the [sqlite3_blob_bytes()] interface.
7600 ** ^An attempt to read from an expired [BLOB handle] fails with an
7601 ** error code of [SQLITE_ABORT].
7603 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
7604 ** Otherwise, an [error code] or an [extended error code] is returned.)^
7606 ** This routine only works on a [BLOB handle] which has been created
7607 ** by a prior successful call to [sqlite3_blob_open()] and which has not
7608 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
7609 ** to this routine results in undefined and probably undesirable behavior.
7611 ** See also: [sqlite3_blob_write()].
7613 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
7616 ** CAPI3REF: Write Data Into A BLOB Incrementally
7617 ** METHOD: sqlite3_blob
7619 ** ^(This function is used to write data into an open [BLOB handle] from a
7620 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
7621 ** into the open BLOB, starting at offset iOffset.)^
7623 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
7624 ** Otherwise, an [error code] or an [extended error code] is returned.)^
7625 ** ^Unless SQLITE_MISUSE is returned, this function sets the
7626 ** [database connection] error code and message accessible via
7627 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
7629 ** ^If the [BLOB handle] passed as the first argument was not opened for
7630 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
7631 ** this function returns [SQLITE_READONLY].
7633 ** This function may only modify the contents of the BLOB; it is
7634 ** not possible to increase the size of a BLOB using this API.
7635 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
7636 ** [SQLITE_ERROR] is returned and no data is written. The size of the
7637 ** BLOB (and hence the maximum value of N+iOffset) can be determined
7638 ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
7639 ** than zero [SQLITE_ERROR] is returned and no data is written.
7641 ** ^An attempt to write to an expired [BLOB handle] fails with an
7642 ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
7643 ** before the [BLOB handle] expired are not rolled back by the
7644 ** expiration of the handle, though of course those changes might
7645 ** have been overwritten by the statement that expired the BLOB handle
7646 ** or by other independent statements.
7648 ** This routine only works on a [BLOB handle] which has been created
7649 ** by a prior successful call to [sqlite3_blob_open()] and which has not
7650 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
7651 ** to this routine results in undefined and probably undesirable behavior.
7653 ** See also: [sqlite3_blob_read()].
7655 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
7658 ** CAPI3REF: Virtual File System Objects
7660 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
7661 ** that SQLite uses to interact
7662 ** with the underlying operating system. Most SQLite builds come with a
7663 ** single default VFS that is appropriate for the host computer.
7664 ** New VFSes can be registered and existing VFSes can be unregistered.
7665 ** The following interfaces are provided.
7667 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
7668 ** ^Names are case sensitive.
7669 ** ^Names are zero-terminated UTF-8 strings.
7670 ** ^If there is no match, a NULL pointer is returned.
7671 ** ^If zVfsName is NULL then the default VFS is returned.
7673 ** ^New VFSes are registered with sqlite3_vfs_register().
7674 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
7675 ** ^The same VFS can be registered multiple times without injury.
7676 ** ^To make an existing VFS into the default VFS, register it again
7677 ** with the makeDflt flag set. If two different VFSes with the
7678 ** same name are registered, the behavior is undefined. If a
7679 ** VFS is registered with a name that is NULL or an empty string,
7680 ** then the behavior is undefined.
7682 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
7683 ** ^(If the default VFS is unregistered, another VFS is chosen as
7684 ** the default. The choice for the new VFS is arbitrary.)^
7686 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
7687 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
7688 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
7691 ** CAPI3REF: Mutexes
7693 ** The SQLite core uses these routines for thread
7694 ** synchronization. Though they are intended for internal
7695 ** use by SQLite, code that links against SQLite is
7696 ** permitted to use any of these routines.
7698 ** The SQLite source code contains multiple implementations
7699 ** of these mutex routines. An appropriate implementation
7700 ** is selected automatically at compile-time. The following
7701 ** implementations are available in the SQLite core:
7703 ** <ul>
7704 ** <li> SQLITE_MUTEX_PTHREADS
7705 ** <li> SQLITE_MUTEX_W32
7706 ** <li> SQLITE_MUTEX_NOOP
7707 ** </ul>
7709 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
7710 ** that does no real locking and is appropriate for use in
7711 ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
7712 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
7713 ** and Windows.
7715 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
7716 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
7717 ** implementation is included with the library. In this case the
7718 ** application must supply a custom mutex implementation using the
7719 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
7720 ** before calling sqlite3_initialize() or any other public sqlite3_
7721 ** function that calls sqlite3_initialize().
7723 ** ^The sqlite3_mutex_alloc() routine allocates a new
7724 ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
7725 ** routine returns NULL if it is unable to allocate the requested
7726 ** mutex. The argument to sqlite3_mutex_alloc() must one of these
7727 ** integer constants:
7729 ** <ul>
7730 ** <li> SQLITE_MUTEX_FAST
7731 ** <li> SQLITE_MUTEX_RECURSIVE
7732 ** <li> SQLITE_MUTEX_STATIC_MASTER
7733 ** <li> SQLITE_MUTEX_STATIC_MEM
7734 ** <li> SQLITE_MUTEX_STATIC_OPEN
7735 ** <li> SQLITE_MUTEX_STATIC_PRNG
7736 ** <li> SQLITE_MUTEX_STATIC_LRU
7737 ** <li> SQLITE_MUTEX_STATIC_PMEM
7738 ** <li> SQLITE_MUTEX_STATIC_APP1
7739 ** <li> SQLITE_MUTEX_STATIC_APP2
7740 ** <li> SQLITE_MUTEX_STATIC_APP3
7741 ** <li> SQLITE_MUTEX_STATIC_VFS1
7742 ** <li> SQLITE_MUTEX_STATIC_VFS2
7743 ** <li> SQLITE_MUTEX_STATIC_VFS3
7744 ** </ul>
7746 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
7747 ** cause sqlite3_mutex_alloc() to create
7748 ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
7749 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
7750 ** The mutex implementation does not need to make a distinction
7751 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
7752 ** not want to. SQLite will only request a recursive mutex in
7753 ** cases where it really needs one. If a faster non-recursive mutex
7754 ** implementation is available on the host platform, the mutex subsystem
7755 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
7757 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
7758 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
7759 ** a pointer to a static preexisting mutex. ^Nine static mutexes are
7760 ** used by the current version of SQLite. Future versions of SQLite
7761 ** may add additional static mutexes. Static mutexes are for internal
7762 ** use by SQLite only. Applications that use SQLite mutexes should
7763 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
7764 ** SQLITE_MUTEX_RECURSIVE.
7766 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
7767 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
7768 ** returns a different mutex on every call. ^For the static
7769 ** mutex types, the same mutex is returned on every call that has
7770 ** the same type number.
7772 ** ^The sqlite3_mutex_free() routine deallocates a previously
7773 ** allocated dynamic mutex. Attempting to deallocate a static
7774 ** mutex results in undefined behavior.
7776 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
7777 ** to enter a mutex. ^If another thread is already within the mutex,
7778 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
7779 ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
7780 ** upon successful entry. ^(Mutexes created using
7781 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
7782 ** In such cases, the
7783 ** mutex must be exited an equal number of times before another thread
7784 ** can enter.)^ If the same thread tries to enter any mutex other
7785 ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
7787 ** ^(Some systems (for example, Windows 95) do not support the operation
7788 ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
7789 ** will always return SQLITE_BUSY. The SQLite core only ever uses
7790 ** sqlite3_mutex_try() as an optimization so this is acceptable
7791 ** behavior.)^
7793 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
7794 ** previously entered by the same thread. The behavior
7795 ** is undefined if the mutex is not currently entered by the
7796 ** calling thread or is not currently allocated.
7798 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
7799 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
7800 ** behave as no-ops.
7802 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
7804 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
7805 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
7806 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
7807 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
7808 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
7811 ** CAPI3REF: Mutex Methods Object
7813 ** An instance of this structure defines the low-level routines
7814 ** used to allocate and use mutexes.
7816 ** Usually, the default mutex implementations provided by SQLite are
7817 ** sufficient, however the application has the option of substituting a custom
7818 ** implementation for specialized deployments or systems for which SQLite
7819 ** does not provide a suitable implementation. In this case, the application
7820 ** creates and populates an instance of this structure to pass
7821 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
7822 ** Additionally, an instance of this structure can be used as an
7823 ** output variable when querying the system for the current mutex
7824 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
7826 ** ^The xMutexInit method defined by this structure is invoked as
7827 ** part of system initialization by the sqlite3_initialize() function.
7828 ** ^The xMutexInit routine is called by SQLite exactly once for each
7829 ** effective call to [sqlite3_initialize()].
7831 ** ^The xMutexEnd method defined by this structure is invoked as
7832 ** part of system shutdown by the sqlite3_shutdown() function. The
7833 ** implementation of this method is expected to release all outstanding
7834 ** resources obtained by the mutex methods implementation, especially
7835 ** those obtained by the xMutexInit method. ^The xMutexEnd()
7836 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
7838 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
7839 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
7840 ** xMutexNotheld) implement the following interfaces (respectively):
7842 ** <ul>
7843 ** <li> [sqlite3_mutex_alloc()] </li>
7844 ** <li> [sqlite3_mutex_free()] </li>
7845 ** <li> [sqlite3_mutex_enter()] </li>
7846 ** <li> [sqlite3_mutex_try()] </li>
7847 ** <li> [sqlite3_mutex_leave()] </li>
7848 ** <li> [sqlite3_mutex_held()] </li>
7849 ** <li> [sqlite3_mutex_notheld()] </li>
7850 ** </ul>)^
7852 ** The only difference is that the public sqlite3_XXX functions enumerated
7853 ** above silently ignore any invocations that pass a NULL pointer instead
7854 ** of a valid mutex handle. The implementations of the methods defined
7855 ** by this structure are not required to handle this case, the results
7856 ** of passing a NULL pointer instead of a valid mutex handle are undefined
7857 ** (i.e. it is acceptable to provide an implementation that segfaults if
7858 ** it is passed a NULL pointer).
7860 ** The xMutexInit() method must be threadsafe. It must be harmless to
7861 ** invoke xMutexInit() multiple times within the same process and without
7862 ** intervening calls to xMutexEnd(). Second and subsequent calls to
7863 ** xMutexInit() must be no-ops.
7865 ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
7866 ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
7867 ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
7868 ** memory allocation for a fast or recursive mutex.
7870 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
7871 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
7872 ** If xMutexInit fails in any way, it is expected to clean up after itself
7873 ** prior to returning.
7875 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
7876 struct sqlite3_mutex_methods {
7877 int (*xMutexInit)(void);
7878 int (*xMutexEnd)(void);
7879 sqlite3_mutex *(*xMutexAlloc)(int);
7880 void (*xMutexFree)(sqlite3_mutex *);
7881 void (*xMutexEnter)(sqlite3_mutex *);
7882 int (*xMutexTry)(sqlite3_mutex *);
7883 void (*xMutexLeave)(sqlite3_mutex *);
7884 int (*xMutexHeld)(sqlite3_mutex *);
7885 int (*xMutexNotheld)(sqlite3_mutex *);
7889 ** CAPI3REF: Mutex Verification Routines
7891 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
7892 ** are intended for use inside assert() statements. The SQLite core
7893 ** never uses these routines except inside an assert() and applications
7894 ** are advised to follow the lead of the core. The SQLite core only
7895 ** provides implementations for these routines when it is compiled
7896 ** with the SQLITE_DEBUG flag. External mutex implementations
7897 ** are only required to provide these routines if SQLITE_DEBUG is
7898 ** defined and if NDEBUG is not defined.
7900 ** These routines should return true if the mutex in their argument
7901 ** is held or not held, respectively, by the calling thread.
7903 ** The implementation is not required to provide versions of these
7904 ** routines that actually work. If the implementation does not provide working
7905 ** versions of these routines, it should at least provide stubs that always
7906 ** return true so that one does not get spurious assertion failures.
7908 ** If the argument to sqlite3_mutex_held() is a NULL pointer then
7909 ** the routine should return 1. This seems counter-intuitive since
7910 ** clearly the mutex cannot be held if it does not exist. But
7911 ** the reason the mutex does not exist is because the build is not
7912 ** using mutexes. And we do not want the assert() containing the
7913 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
7914 ** the appropriate thing to do. The sqlite3_mutex_notheld()
7915 ** interface should also return 1 when given a NULL pointer.
7917 #ifndef NDEBUG
7918 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
7919 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
7920 #endif
7923 ** CAPI3REF: Mutex Types
7925 ** The [sqlite3_mutex_alloc()] interface takes a single argument
7926 ** which is one of these integer constants.
7928 ** The set of static mutexes may change from one SQLite release to the
7929 ** next. Applications that override the built-in mutex logic must be
7930 ** prepared to accommodate additional static mutexes.
7932 #define SQLITE_MUTEX_FAST 0
7933 #define SQLITE_MUTEX_RECURSIVE 1
7934 #define SQLITE_MUTEX_STATIC_MASTER 2
7935 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
7936 #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
7937 #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
7938 #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
7939 #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
7940 #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
7941 #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
7942 #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
7943 #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
7944 #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
7945 #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
7946 #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
7947 #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
7950 ** CAPI3REF: Retrieve the mutex for a database connection
7951 ** METHOD: sqlite3
7953 ** ^This interface returns a pointer the [sqlite3_mutex] object that
7954 ** serializes access to the [database connection] given in the argument
7955 ** when the [threading mode] is Serialized.
7956 ** ^If the [threading mode] is Single-thread or Multi-thread then this
7957 ** routine returns a NULL pointer.
7959 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
7962 ** CAPI3REF: Low-Level Control Of Database Files
7963 ** METHOD: sqlite3
7965 ** ^The [sqlite3_file_control()] interface makes a direct call to the
7966 ** xFileControl method for the [sqlite3_io_methods] object associated
7967 ** with a particular database identified by the second argument. ^The
7968 ** name of the database is "main" for the main database or "temp" for the
7969 ** TEMP database, or the name that appears after the AS keyword for
7970 ** databases that are added using the [ATTACH] SQL command.
7971 ** ^A NULL pointer can be used in place of "main" to refer to the
7972 ** main database file.
7973 ** ^The third and fourth parameters to this routine
7974 ** are passed directly through to the second and third parameters of
7975 ** the xFileControl method. ^The return value of the xFileControl
7976 ** method becomes the return value of this routine.
7978 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
7979 ** a pointer to the underlying [sqlite3_file] object to be written into
7980 ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
7981 ** case is a short-circuit path which does not actually invoke the
7982 ** underlying sqlite3_io_methods.xFileControl method.
7984 ** ^If the second parameter (zDbName) does not match the name of any
7985 ** open database file, then SQLITE_ERROR is returned. ^This error
7986 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
7987 ** or [sqlite3_errmsg()]. The underlying xFileControl method might
7988 ** also return SQLITE_ERROR. There is no way to distinguish between
7989 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
7990 ** xFileControl method.
7992 ** See also: [SQLITE_FCNTL_LOCKSTATE]
7994 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
7997 ** CAPI3REF: Testing Interface
7999 ** ^The sqlite3_test_control() interface is used to read out internal
8000 ** state of SQLite and to inject faults into SQLite for testing
8001 ** purposes. ^The first parameter is an operation code that determines
8002 ** the number, meaning, and operation of all subsequent parameters.
8004 ** This interface is not for use by applications. It exists solely
8005 ** for verifying the correct operation of the SQLite library. Depending
8006 ** on how the SQLite library is compiled, this interface might not exist.
8008 ** The details of the operation codes, their meanings, the parameters
8009 ** they take, and what they do are all subject to change without notice.
8010 ** Unlike most of the SQLite API, this function is not guaranteed to
8011 ** operate consistently from one release to the next.
8013 SQLITE_API int sqlite3_test_control(int op, ...);
8016 ** CAPI3REF: Testing Interface Operation Codes
8018 ** These constants are the valid operation code parameters used
8019 ** as the first argument to [sqlite3_test_control()].
8021 ** These parameters and their meanings are subject to change
8022 ** without notice. These values are for testing purposes only.
8023 ** Applications should not use any of these parameters or the
8024 ** [sqlite3_test_control()] interface.
8026 #define SQLITE_TESTCTRL_FIRST 5
8027 #define SQLITE_TESTCTRL_PRNG_SAVE 5
8028 #define SQLITE_TESTCTRL_PRNG_RESTORE 6
8029 #define SQLITE_TESTCTRL_PRNG_RESET 7
8030 #define SQLITE_TESTCTRL_BITVEC_TEST 8
8031 #define SQLITE_TESTCTRL_FAULT_INSTALL 9
8032 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
8033 #define SQLITE_TESTCTRL_PENDING_BYTE 11
8034 #define SQLITE_TESTCTRL_ASSERT 12
8035 #define SQLITE_TESTCTRL_ALWAYS 13
8036 #define SQLITE_TESTCTRL_RESERVE 14
8037 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
8038 #define SQLITE_TESTCTRL_ISKEYWORD 16
8039 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
8040 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
8041 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
8042 #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
8043 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
8044 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
8045 #define SQLITE_TESTCTRL_BYTEORDER 22
8046 #define SQLITE_TESTCTRL_ISINIT 23
8047 #define SQLITE_TESTCTRL_SORTER_MMAP 24
8048 #define SQLITE_TESTCTRL_IMPOSTER 25
8049 #define SQLITE_TESTCTRL_LAST 25
8052 ** CAPI3REF: SQLite Runtime Status
8054 ** ^These interfaces are used to retrieve runtime status information
8055 ** about the performance of SQLite, and optionally to reset various
8056 ** highwater marks. ^The first argument is an integer code for
8057 ** the specific parameter to measure. ^(Recognized integer codes
8058 ** are of the form [status parameters | SQLITE_STATUS_...].)^
8059 ** ^The current value of the parameter is returned into *pCurrent.
8060 ** ^The highest recorded value is returned in *pHighwater. ^If the
8061 ** resetFlag is true, then the highest record value is reset after
8062 ** *pHighwater is written. ^(Some parameters do not record the highest
8063 ** value. For those parameters
8064 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
8065 ** ^(Other parameters record only the highwater mark and not the current
8066 ** value. For these latter parameters nothing is written into *pCurrent.)^
8068 ** ^The sqlite3_status() and sqlite3_status64() routines return
8069 ** SQLITE_OK on success and a non-zero [error code] on failure.
8071 ** If either the current value or the highwater mark is too large to
8072 ** be represented by a 32-bit integer, then the values returned by
8073 ** sqlite3_status() are undefined.
8075 ** See also: [sqlite3_db_status()]
8077 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
8078 SQLITE_API int sqlite3_status64(
8079 int op,
8080 sqlite3_int64 *pCurrent,
8081 sqlite3_int64 *pHighwater,
8082 int resetFlag
8087 ** CAPI3REF: Status Parameters
8088 ** KEYWORDS: {status parameters}
8090 ** These integer constants designate various run-time status parameters
8091 ** that can be returned by [sqlite3_status()].
8093 ** <dl>
8094 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
8095 ** <dd>This parameter is the current amount of memory checked out
8096 ** using [sqlite3_malloc()], either directly or indirectly. The
8097 ** figure includes calls made to [sqlite3_malloc()] by the application
8098 ** and internal memory usage by the SQLite library. Auxiliary page-cache
8099 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
8100 ** this parameter. The amount returned is the sum of the allocation
8101 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
8103 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
8104 ** <dd>This parameter records the largest memory allocation request
8105 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
8106 ** internal equivalents). Only the value returned in the
8107 ** *pHighwater parameter to [sqlite3_status()] is of interest.
8108 ** The value written into the *pCurrent parameter is undefined.</dd>)^
8110 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
8111 ** <dd>This parameter records the number of separate memory allocations
8112 ** currently checked out.</dd>)^
8114 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
8115 ** <dd>This parameter returns the number of pages used out of the
8116 ** [pagecache memory allocator] that was configured using
8117 ** [SQLITE_CONFIG_PAGECACHE]. The
8118 ** value returned is in pages, not in bytes.</dd>)^
8120 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
8121 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
8122 ** <dd>This parameter returns the number of bytes of page cache
8123 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
8124 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
8125 ** returned value includes allocations that overflowed because they
8126 ** where too large (they were larger than the "sz" parameter to
8127 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
8128 ** no space was left in the page cache.</dd>)^
8130 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
8131 ** <dd>This parameter records the largest memory allocation request
8132 ** handed to [pagecache memory allocator]. Only the value returned in the
8133 ** *pHighwater parameter to [sqlite3_status()] is of interest.
8134 ** The value written into the *pCurrent parameter is undefined.</dd>)^
8136 ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
8137 ** <dd>No longer used.</dd>
8139 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
8140 ** <dd>No longer used.</dd>
8142 ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
8143 ** <dd>No longer used.</dd>
8145 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
8146 ** <dd>The *pHighwater parameter records the deepest parser stack.
8147 ** The *pCurrent value is undefined. The *pHighwater value is only
8148 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
8149 ** </dl>
8151 ** New status parameters may be added from time to time.
8153 #define SQLITE_STATUS_MEMORY_USED 0
8154 #define SQLITE_STATUS_PAGECACHE_USED 1
8155 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
8156 #define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */
8157 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
8158 #define SQLITE_STATUS_MALLOC_SIZE 5
8159 #define SQLITE_STATUS_PARSER_STACK 6
8160 #define SQLITE_STATUS_PAGECACHE_SIZE 7
8161 #define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
8162 #define SQLITE_STATUS_MALLOC_COUNT 9
8165 ** CAPI3REF: Database Connection Status
8166 ** METHOD: sqlite3
8168 ** ^This interface is used to retrieve runtime status information
8169 ** about a single [database connection]. ^The first argument is the
8170 ** database connection object to be interrogated. ^The second argument
8171 ** is an integer constant, taken from the set of
8172 ** [SQLITE_DBSTATUS options], that
8173 ** determines the parameter to interrogate. The set of
8174 ** [SQLITE_DBSTATUS options] is likely
8175 ** to grow in future releases of SQLite.
8177 ** ^The current value of the requested parameter is written into *pCur
8178 ** and the highest instantaneous value is written into *pHiwtr. ^If
8179 ** the resetFlg is true, then the highest instantaneous value is
8180 ** reset back down to the current value.
8182 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
8183 ** non-zero [error code] on failure.
8185 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
8187 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
8190 ** CAPI3REF: Status Parameters for database connections
8191 ** KEYWORDS: {SQLITE_DBSTATUS options}
8193 ** These constants are the available integer "verbs" that can be passed as
8194 ** the second argument to the [sqlite3_db_status()] interface.
8196 ** New verbs may be added in future releases of SQLite. Existing verbs
8197 ** might be discontinued. Applications should check the return code from
8198 ** [sqlite3_db_status()] to make sure that the call worked.
8199 ** The [sqlite3_db_status()] interface will return a non-zero error code
8200 ** if a discontinued or unsupported verb is invoked.
8202 ** <dl>
8203 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
8204 ** <dd>This parameter returns the number of lookaside memory slots currently
8205 ** checked out.</dd>)^
8207 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
8208 ** <dd>This parameter returns the number malloc attempts that were
8209 ** satisfied using lookaside memory. Only the high-water value is meaningful;
8210 ** the current value is always zero.)^
8212 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
8213 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
8214 ** <dd>This parameter returns the number malloc attempts that might have
8215 ** been satisfied using lookaside memory but failed due to the amount of
8216 ** memory requested being larger than the lookaside slot size.
8217 ** Only the high-water value is meaningful;
8218 ** the current value is always zero.)^
8220 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
8221 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
8222 ** <dd>This parameter returns the number malloc attempts that might have
8223 ** been satisfied using lookaside memory but failed due to all lookaside
8224 ** memory already being in use.
8225 ** Only the high-water value is meaningful;
8226 ** the current value is always zero.)^
8228 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
8229 ** <dd>This parameter returns the approximate number of bytes of heap
8230 ** memory used by all pager caches associated with the database connection.)^
8231 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
8233 ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
8234 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
8235 ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
8236 ** pager cache is shared between two or more connections the bytes of heap
8237 ** memory used by that pager cache is divided evenly between the attached
8238 ** connections.)^ In other words, if none of the pager caches associated
8239 ** with the database connection are shared, this request returns the same
8240 ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
8241 ** shared, the value returned by this call will be smaller than that returned
8242 ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
8243 ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
8245 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
8246 ** <dd>This parameter returns the approximate number of bytes of heap
8247 ** memory used to store the schema for all databases associated
8248 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
8249 ** ^The full amount of memory used by the schemas is reported, even if the
8250 ** schema memory is shared with other database connections due to
8251 ** [shared cache mode] being enabled.
8252 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
8254 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
8255 ** <dd>This parameter returns the approximate number of bytes of heap
8256 ** and lookaside memory used by all prepared statements associated with
8257 ** the database connection.)^
8258 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
8259 ** </dd>
8261 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
8262 ** <dd>This parameter returns the number of pager cache hits that have
8263 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
8264 ** is always 0.
8265 ** </dd>
8267 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
8268 ** <dd>This parameter returns the number of pager cache misses that have
8269 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
8270 ** is always 0.
8271 ** </dd>
8273 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
8274 ** <dd>This parameter returns the number of dirty cache entries that have
8275 ** been written to disk. Specifically, the number of pages written to the
8276 ** wal file in wal mode databases, or the number of pages written to the
8277 ** database file in rollback mode databases. Any pages written as part of
8278 ** transaction rollback or database recovery operations are not included.
8279 ** If an IO or other error occurs while writing a page to disk, the effect
8280 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
8281 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
8282 ** </dd>
8284 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
8285 ** <dd>This parameter returns zero for the current value if and only if
8286 ** all foreign key constraints (deferred or immediate) have been
8287 ** resolved.)^ ^The highwater mark is always 0.
8288 ** </dd>
8289 ** </dl>
8291 #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
8292 #define SQLITE_DBSTATUS_CACHE_USED 1
8293 #define SQLITE_DBSTATUS_SCHEMA_USED 2
8294 #define SQLITE_DBSTATUS_STMT_USED 3
8295 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
8296 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
8297 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
8298 #define SQLITE_DBSTATUS_CACHE_HIT 7
8299 #define SQLITE_DBSTATUS_CACHE_MISS 8
8300 #define SQLITE_DBSTATUS_CACHE_WRITE 9
8301 #define SQLITE_DBSTATUS_DEFERRED_FKS 10
8302 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
8303 #define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */
8307 ** CAPI3REF: Prepared Statement Status
8308 ** METHOD: sqlite3_stmt
8310 ** ^(Each prepared statement maintains various
8311 ** [SQLITE_STMTSTATUS counters] that measure the number
8312 ** of times it has performed specific operations.)^ These counters can
8313 ** be used to monitor the performance characteristics of the prepared
8314 ** statements. For example, if the number of table steps greatly exceeds
8315 ** the number of table searches or result rows, that would tend to indicate
8316 ** that the prepared statement is using a full table scan rather than
8317 ** an index.
8319 ** ^(This interface is used to retrieve and reset counter values from
8320 ** a [prepared statement]. The first argument is the prepared statement
8321 ** object to be interrogated. The second argument
8322 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
8323 ** to be interrogated.)^
8324 ** ^The current value of the requested counter is returned.
8325 ** ^If the resetFlg is true, then the counter is reset to zero after this
8326 ** interface call returns.
8328 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
8330 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
8333 ** CAPI3REF: Status Parameters for prepared statements
8334 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
8336 ** These preprocessor macros define integer codes that name counter
8337 ** values associated with the [sqlite3_stmt_status()] interface.
8338 ** The meanings of the various counters are as follows:
8340 ** <dl>
8341 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
8342 ** <dd>^This is the number of times that SQLite has stepped forward in
8343 ** a table as part of a full table scan. Large numbers for this counter
8344 ** may indicate opportunities for performance improvement through
8345 ** careful use of indices.</dd>
8347 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
8348 ** <dd>^This is the number of sort operations that have occurred.
8349 ** A non-zero value in this counter may indicate an opportunity to
8350 ** improvement performance through careful use of indices.</dd>
8352 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
8353 ** <dd>^This is the number of rows inserted into transient indices that
8354 ** were created automatically in order to help joins run faster.
8355 ** A non-zero value in this counter may indicate an opportunity to
8356 ** improvement performance by adding permanent indices that do not
8357 ** need to be reinitialized each time the statement is run.</dd>
8359 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
8360 ** <dd>^This is the number of virtual machine operations executed
8361 ** by the prepared statement if that number is less than or equal
8362 ** to 2147483647. The number of virtual machine operations can be
8363 ** used as a proxy for the total work done by the prepared statement.
8364 ** If the number of virtual machine operations exceeds 2147483647
8365 ** then the value returned by this statement status code is undefined.
8367 ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
8368 ** <dd>^This is the number of times that the prepare statement has been
8369 ** automatically regenerated due to schema changes or change to
8370 ** [bound parameters] that might affect the query plan.
8372 ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
8373 ** <dd>^This is the number of times that the prepared statement has
8374 ** been run. A single "run" for the purposes of this counter is one
8375 ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
8376 ** The counter is incremented on the first [sqlite3_step()] call of each
8377 ** cycle.
8379 ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
8380 ** <dd>^This is the approximate number of bytes of heap memory
8381 ** used to store the prepared statement. ^This value is not actually
8382 ** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
8383 ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
8384 ** </dd>
8385 ** </dl>
8387 #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
8388 #define SQLITE_STMTSTATUS_SORT 2
8389 #define SQLITE_STMTSTATUS_AUTOINDEX 3
8390 #define SQLITE_STMTSTATUS_VM_STEP 4
8391 #define SQLITE_STMTSTATUS_REPREPARE 5
8392 #define SQLITE_STMTSTATUS_RUN 6
8393 #define SQLITE_STMTSTATUS_MEMUSED 99
8396 ** CAPI3REF: Custom Page Cache Object
8398 ** The sqlite3_pcache type is opaque. It is implemented by
8399 ** the pluggable module. The SQLite core has no knowledge of
8400 ** its size or internal structure and never deals with the
8401 ** sqlite3_pcache object except by holding and passing pointers
8402 ** to the object.
8404 ** See [sqlite3_pcache_methods2] for additional information.
8406 typedef struct sqlite3_pcache sqlite3_pcache;
8409 ** CAPI3REF: Custom Page Cache Object
8411 ** The sqlite3_pcache_page object represents a single page in the
8412 ** page cache. The page cache will allocate instances of this
8413 ** object. Various methods of the page cache use pointers to instances
8414 ** of this object as parameters or as their return value.
8416 ** See [sqlite3_pcache_methods2] for additional information.
8418 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
8419 struct sqlite3_pcache_page {
8420 void *pBuf; /* The content of the page */
8421 void *pExtra; /* Extra information associated with the page */
8425 ** CAPI3REF: Application Defined Page Cache.
8426 ** KEYWORDS: {page cache}
8428 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
8429 ** register an alternative page cache implementation by passing in an
8430 ** instance of the sqlite3_pcache_methods2 structure.)^
8431 ** In many applications, most of the heap memory allocated by
8432 ** SQLite is used for the page cache.
8433 ** By implementing a
8434 ** custom page cache using this API, an application can better control
8435 ** the amount of memory consumed by SQLite, the way in which
8436 ** that memory is allocated and released, and the policies used to
8437 ** determine exactly which parts of a database file are cached and for
8438 ** how long.
8440 ** The alternative page cache mechanism is an
8441 ** extreme measure that is only needed by the most demanding applications.
8442 ** The built-in page cache is recommended for most uses.
8444 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
8445 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
8446 ** the application may discard the parameter after the call to
8447 ** [sqlite3_config()] returns.)^
8449 ** [[the xInit() page cache method]]
8450 ** ^(The xInit() method is called once for each effective
8451 ** call to [sqlite3_initialize()])^
8452 ** (usually only once during the lifetime of the process). ^(The xInit()
8453 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
8454 ** The intent of the xInit() method is to set up global data structures
8455 ** required by the custom page cache implementation.
8456 ** ^(If the xInit() method is NULL, then the
8457 ** built-in default page cache is used instead of the application defined
8458 ** page cache.)^
8460 ** [[the xShutdown() page cache method]]
8461 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
8462 ** It can be used to clean up
8463 ** any outstanding resources before process shutdown, if required.
8464 ** ^The xShutdown() method may be NULL.
8466 ** ^SQLite automatically serializes calls to the xInit method,
8467 ** so the xInit method need not be threadsafe. ^The
8468 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
8469 ** not need to be threadsafe either. All other methods must be threadsafe
8470 ** in multithreaded applications.
8472 ** ^SQLite will never invoke xInit() more than once without an intervening
8473 ** call to xShutdown().
8475 ** [[the xCreate() page cache methods]]
8476 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
8477 ** SQLite will typically create one cache instance for each open database file,
8478 ** though this is not guaranteed. ^The
8479 ** first parameter, szPage, is the size in bytes of the pages that must
8480 ** be allocated by the cache. ^szPage will always a power of two. ^The
8481 ** second parameter szExtra is a number of bytes of extra storage
8482 ** associated with each page cache entry. ^The szExtra parameter will
8483 ** a number less than 250. SQLite will use the
8484 ** extra szExtra bytes on each page to store metadata about the underlying
8485 ** database page on disk. The value passed into szExtra depends
8486 ** on the SQLite version, the target platform, and how SQLite was compiled.
8487 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
8488 ** created will be used to cache database pages of a file stored on disk, or
8489 ** false if it is used for an in-memory database. The cache implementation
8490 ** does not have to do anything special based with the value of bPurgeable;
8491 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
8492 ** never invoke xUnpin() except to deliberately delete a page.
8493 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
8494 ** false will always have the "discard" flag set to true.
8495 ** ^Hence, a cache created with bPurgeable false will
8496 ** never contain any unpinned pages.
8498 ** [[the xCachesize() page cache method]]
8499 ** ^(The xCachesize() method may be called at any time by SQLite to set the
8500 ** suggested maximum cache-size (number of pages stored by) the cache
8501 ** instance passed as the first argument. This is the value configured using
8502 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
8503 ** parameter, the implementation is not required to do anything with this
8504 ** value; it is advisory only.
8506 ** [[the xPagecount() page cache methods]]
8507 ** The xPagecount() method must return the number of pages currently
8508 ** stored in the cache, both pinned and unpinned.
8510 ** [[the xFetch() page cache methods]]
8511 ** The xFetch() method locates a page in the cache and returns a pointer to
8512 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
8513 ** The pBuf element of the returned sqlite3_pcache_page object will be a
8514 ** pointer to a buffer of szPage bytes used to store the content of a
8515 ** single database page. The pExtra element of sqlite3_pcache_page will be
8516 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
8517 ** for each entry in the page cache.
8519 ** The page to be fetched is determined by the key. ^The minimum key value
8520 ** is 1. After it has been retrieved using xFetch, the page is considered
8521 ** to be "pinned".
8523 ** If the requested page is already in the page cache, then the page cache
8524 ** implementation must return a pointer to the page buffer with its content
8525 ** intact. If the requested page is not already in the cache, then the
8526 ** cache implementation should use the value of the createFlag
8527 ** parameter to help it determined what action to take:
8529 ** <table border=1 width=85% align=center>
8530 ** <tr><th> createFlag <th> Behavior when page is not already in cache
8531 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
8532 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
8533 ** Otherwise return NULL.
8534 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
8535 ** NULL if allocating a new page is effectively impossible.
8536 ** </table>
8538 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
8539 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
8540 ** failed.)^ In between the to xFetch() calls, SQLite may
8541 ** attempt to unpin one or more cache pages by spilling the content of
8542 ** pinned pages to disk and synching the operating system disk cache.
8544 ** [[the xUnpin() page cache method]]
8545 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
8546 ** as its second argument. If the third parameter, discard, is non-zero,
8547 ** then the page must be evicted from the cache.
8548 ** ^If the discard parameter is
8549 ** zero, then the page may be discarded or retained at the discretion of
8550 ** page cache implementation. ^The page cache implementation
8551 ** may choose to evict unpinned pages at any time.
8553 ** The cache must not perform any reference counting. A single
8554 ** call to xUnpin() unpins the page regardless of the number of prior calls
8555 ** to xFetch().
8557 ** [[the xRekey() page cache methods]]
8558 ** The xRekey() method is used to change the key value associated with the
8559 ** page passed as the second argument. If the cache
8560 ** previously contains an entry associated with newKey, it must be
8561 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
8562 ** to be pinned.
8564 ** When SQLite calls the xTruncate() method, the cache must discard all
8565 ** existing cache entries with page numbers (keys) greater than or equal
8566 ** to the value of the iLimit parameter passed to xTruncate(). If any
8567 ** of these pages are pinned, they are implicitly unpinned, meaning that
8568 ** they can be safely discarded.
8570 ** [[the xDestroy() page cache method]]
8571 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
8572 ** All resources associated with the specified cache should be freed. ^After
8573 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
8574 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
8575 ** functions.
8577 ** [[the xShrink() page cache method]]
8578 ** ^SQLite invokes the xShrink() method when it wants the page cache to
8579 ** free up as much of heap memory as possible. The page cache implementation
8580 ** is not obligated to free any memory, but well-behaved implementations should
8581 ** do their best.
8583 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
8584 struct sqlite3_pcache_methods2 {
8585 int iVersion;
8586 void *pArg;
8587 int (*xInit)(void*);
8588 void (*xShutdown)(void*);
8589 sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
8590 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
8591 int (*xPagecount)(sqlite3_pcache*);
8592 sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
8593 void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
8594 void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
8595 unsigned oldKey, unsigned newKey);
8596 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
8597 void (*xDestroy)(sqlite3_pcache*);
8598 void (*xShrink)(sqlite3_pcache*);
8602 ** This is the obsolete pcache_methods object that has now been replaced
8603 ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
8604 ** retained in the header file for backwards compatibility only.
8606 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
8607 struct sqlite3_pcache_methods {
8608 void *pArg;
8609 int (*xInit)(void*);
8610 void (*xShutdown)(void*);
8611 sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
8612 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
8613 int (*xPagecount)(sqlite3_pcache*);
8614 void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
8615 void (*xUnpin)(sqlite3_pcache*, void*, int discard);
8616 void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
8617 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
8618 void (*xDestroy)(sqlite3_pcache*);
8623 ** CAPI3REF: Online Backup Object
8625 ** The sqlite3_backup object records state information about an ongoing
8626 ** online backup operation. ^The sqlite3_backup object is created by
8627 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
8628 ** [sqlite3_backup_finish()].
8630 ** See Also: [Using the SQLite Online Backup API]
8632 typedef struct sqlite3_backup sqlite3_backup;
8635 ** CAPI3REF: Online Backup API.
8637 ** The backup API copies the content of one database into another.
8638 ** It is useful either for creating backups of databases or
8639 ** for copying in-memory databases to or from persistent files.
8641 ** See Also: [Using the SQLite Online Backup API]
8643 ** ^SQLite holds a write transaction open on the destination database file
8644 ** for the duration of the backup operation.
8645 ** ^The source database is read-locked only while it is being read;
8646 ** it is not locked continuously for the entire backup operation.
8647 ** ^Thus, the backup may be performed on a live source database without
8648 ** preventing other database connections from
8649 ** reading or writing to the source database while the backup is underway.
8651 ** ^(To perform a backup operation:
8652 ** <ol>
8653 ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
8654 ** backup,
8655 ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
8656 ** the data between the two databases, and finally
8657 ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
8658 ** associated with the backup operation.
8659 ** </ol>)^
8660 ** There should be exactly one call to sqlite3_backup_finish() for each
8661 ** successful call to sqlite3_backup_init().
8663 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
8665 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
8666 ** [database connection] associated with the destination database
8667 ** and the database name, respectively.
8668 ** ^The database name is "main" for the main database, "temp" for the
8669 ** temporary database, or the name specified after the AS keyword in
8670 ** an [ATTACH] statement for an attached database.
8671 ** ^The S and M arguments passed to
8672 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
8673 ** and database name of the source database, respectively.
8674 ** ^The source and destination [database connections] (parameters S and D)
8675 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
8676 ** an error.
8678 ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
8679 ** there is already a read or read-write transaction open on the
8680 ** destination database.
8682 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
8683 ** returned and an error code and error message are stored in the
8684 ** destination [database connection] D.
8685 ** ^The error code and message for the failed call to sqlite3_backup_init()
8686 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
8687 ** [sqlite3_errmsg16()] functions.
8688 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
8689 ** [sqlite3_backup] object.
8690 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
8691 ** sqlite3_backup_finish() functions to perform the specified backup
8692 ** operation.
8694 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
8696 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
8697 ** the source and destination databases specified by [sqlite3_backup] object B.
8698 ** ^If N is negative, all remaining source pages are copied.
8699 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
8700 ** are still more pages to be copied, then the function returns [SQLITE_OK].
8701 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
8702 ** from source to destination, then it returns [SQLITE_DONE].
8703 ** ^If an error occurs while running sqlite3_backup_step(B,N),
8704 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
8705 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
8706 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
8707 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
8709 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
8710 ** <ol>
8711 ** <li> the destination database was opened read-only, or
8712 ** <li> the destination database is using write-ahead-log journaling
8713 ** and the destination and source page sizes differ, or
8714 ** <li> the destination database is an in-memory database and the
8715 ** destination and source page sizes differ.
8716 ** </ol>)^
8718 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
8719 ** the [sqlite3_busy_handler | busy-handler function]
8720 ** is invoked (if one is specified). ^If the
8721 ** busy-handler returns non-zero before the lock is available, then
8722 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
8723 ** sqlite3_backup_step() can be retried later. ^If the source
8724 ** [database connection]
8725 ** is being used to write to the source database when sqlite3_backup_step()
8726 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
8727 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
8728 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
8729 ** [SQLITE_READONLY] is returned, then
8730 ** there is no point in retrying the call to sqlite3_backup_step(). These
8731 ** errors are considered fatal.)^ The application must accept
8732 ** that the backup operation has failed and pass the backup operation handle
8733 ** to the sqlite3_backup_finish() to release associated resources.
8735 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
8736 ** on the destination file. ^The exclusive lock is not released until either
8737 ** sqlite3_backup_finish() is called or the backup operation is complete
8738 ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
8739 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
8740 ** lasts for the duration of the sqlite3_backup_step() call.
8741 ** ^Because the source database is not locked between calls to
8742 ** sqlite3_backup_step(), the source database may be modified mid-way
8743 ** through the backup process. ^If the source database is modified by an
8744 ** external process or via a database connection other than the one being
8745 ** used by the backup operation, then the backup will be automatically
8746 ** restarted by the next call to sqlite3_backup_step(). ^If the source
8747 ** database is modified by the using the same database connection as is used
8748 ** by the backup operation, then the backup database is automatically
8749 ** updated at the same time.
8751 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
8753 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
8754 ** application wishes to abandon the backup operation, the application
8755 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
8756 ** ^The sqlite3_backup_finish() interfaces releases all
8757 ** resources associated with the [sqlite3_backup] object.
8758 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
8759 ** active write-transaction on the destination database is rolled back.
8760 ** The [sqlite3_backup] object is invalid
8761 ** and may not be used following a call to sqlite3_backup_finish().
8763 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
8764 ** sqlite3_backup_step() errors occurred, regardless or whether or not
8765 ** sqlite3_backup_step() completed.
8766 ** ^If an out-of-memory condition or IO error occurred during any prior
8767 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
8768 ** sqlite3_backup_finish() returns the corresponding [error code].
8770 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
8771 ** is not a permanent error and does not affect the return value of
8772 ** sqlite3_backup_finish().
8774 ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
8775 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
8777 ** ^The sqlite3_backup_remaining() routine returns the number of pages still
8778 ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
8779 ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
8780 ** in the source database at the conclusion of the most recent
8781 ** sqlite3_backup_step().
8782 ** ^(The values returned by these functions are only updated by
8783 ** sqlite3_backup_step(). If the source database is modified in a way that
8784 ** changes the size of the source database or the number of pages remaining,
8785 ** those changes are not reflected in the output of sqlite3_backup_pagecount()
8786 ** and sqlite3_backup_remaining() until after the next
8787 ** sqlite3_backup_step().)^
8789 ** <b>Concurrent Usage of Database Handles</b>
8791 ** ^The source [database connection] may be used by the application for other
8792 ** purposes while a backup operation is underway or being initialized.
8793 ** ^If SQLite is compiled and configured to support threadsafe database
8794 ** connections, then the source database connection may be used concurrently
8795 ** from within other threads.
8797 ** However, the application must guarantee that the destination
8798 ** [database connection] is not passed to any other API (by any thread) after
8799 ** sqlite3_backup_init() is called and before the corresponding call to
8800 ** sqlite3_backup_finish(). SQLite does not currently check to see
8801 ** if the application incorrectly accesses the destination [database connection]
8802 ** and so no error code is reported, but the operations may malfunction
8803 ** nevertheless. Use of the destination database connection while a
8804 ** backup is in progress might also also cause a mutex deadlock.
8806 ** If running in [shared cache mode], the application must
8807 ** guarantee that the shared cache used by the destination database
8808 ** is not accessed while the backup is running. In practice this means
8809 ** that the application must guarantee that the disk file being
8810 ** backed up to is not accessed by any connection within the process,
8811 ** not just the specific connection that was passed to sqlite3_backup_init().
8813 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
8814 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
8815 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
8816 ** APIs are not strictly speaking threadsafe. If they are invoked at the
8817 ** same time as another thread is invoking sqlite3_backup_step() it is
8818 ** possible that they return invalid values.
8820 SQLITE_API sqlite3_backup *sqlite3_backup_init(
8821 sqlite3 *pDest, /* Destination database handle */
8822 const char *zDestName, /* Destination database name */
8823 sqlite3 *pSource, /* Source database handle */
8824 const char *zSourceName /* Source database name */
8826 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
8827 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
8828 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
8829 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
8832 ** CAPI3REF: Unlock Notification
8833 ** METHOD: sqlite3
8835 ** ^When running in shared-cache mode, a database operation may fail with
8836 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
8837 ** individual tables within the shared-cache cannot be obtained. See
8838 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
8839 ** ^This API may be used to register a callback that SQLite will invoke
8840 ** when the connection currently holding the required lock relinquishes it.
8841 ** ^This API is only available if the library was compiled with the
8842 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
8844 ** See Also: [Using the SQLite Unlock Notification Feature].
8846 ** ^Shared-cache locks are released when a database connection concludes
8847 ** its current transaction, either by committing it or rolling it back.
8849 ** ^When a connection (known as the blocked connection) fails to obtain a
8850 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
8851 ** identity of the database connection (the blocking connection) that
8852 ** has locked the required resource is stored internally. ^After an
8853 ** application receives an SQLITE_LOCKED error, it may call the
8854 ** sqlite3_unlock_notify() method with the blocked connection handle as
8855 ** the first argument to register for a callback that will be invoked
8856 ** when the blocking connections current transaction is concluded. ^The
8857 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
8858 ** call that concludes the blocking connections transaction.
8860 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
8861 ** there is a chance that the blocking connection will have already
8862 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
8863 ** If this happens, then the specified callback is invoked immediately,
8864 ** from within the call to sqlite3_unlock_notify().)^
8866 ** ^If the blocked connection is attempting to obtain a write-lock on a
8867 ** shared-cache table, and more than one other connection currently holds
8868 ** a read-lock on the same table, then SQLite arbitrarily selects one of
8869 ** the other connections to use as the blocking connection.
8871 ** ^(There may be at most one unlock-notify callback registered by a
8872 ** blocked connection. If sqlite3_unlock_notify() is called when the
8873 ** blocked connection already has a registered unlock-notify callback,
8874 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
8875 ** called with a NULL pointer as its second argument, then any existing
8876 ** unlock-notify callback is canceled. ^The blocked connections
8877 ** unlock-notify callback may also be canceled by closing the blocked
8878 ** connection using [sqlite3_close()].
8880 ** The unlock-notify callback is not reentrant. If an application invokes
8881 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
8882 ** crash or deadlock may be the result.
8884 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
8885 ** returns SQLITE_OK.
8887 ** <b>Callback Invocation Details</b>
8889 ** When an unlock-notify callback is registered, the application provides a
8890 ** single void* pointer that is passed to the callback when it is invoked.
8891 ** However, the signature of the callback function allows SQLite to pass
8892 ** it an array of void* context pointers. The first argument passed to
8893 ** an unlock-notify callback is a pointer to an array of void* pointers,
8894 ** and the second is the number of entries in the array.
8896 ** When a blocking connections transaction is concluded, there may be
8897 ** more than one blocked connection that has registered for an unlock-notify
8898 ** callback. ^If two or more such blocked connections have specified the
8899 ** same callback function, then instead of invoking the callback function
8900 ** multiple times, it is invoked once with the set of void* context pointers
8901 ** specified by the blocked connections bundled together into an array.
8902 ** This gives the application an opportunity to prioritize any actions
8903 ** related to the set of unblocked database connections.
8905 ** <b>Deadlock Detection</b>
8907 ** Assuming that after registering for an unlock-notify callback a
8908 ** database waits for the callback to be issued before taking any further
8909 ** action (a reasonable assumption), then using this API may cause the
8910 ** application to deadlock. For example, if connection X is waiting for
8911 ** connection Y's transaction to be concluded, and similarly connection
8912 ** Y is waiting on connection X's transaction, then neither connection
8913 ** will proceed and the system may remain deadlocked indefinitely.
8915 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
8916 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
8917 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
8918 ** unlock-notify callback is registered. The system is said to be in
8919 ** a deadlocked state if connection A has registered for an unlock-notify
8920 ** callback on the conclusion of connection B's transaction, and connection
8921 ** B has itself registered for an unlock-notify callback when connection
8922 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
8923 ** the system is also considered to be deadlocked if connection B has
8924 ** registered for an unlock-notify callback on the conclusion of connection
8925 ** C's transaction, where connection C is waiting on connection A. ^Any
8926 ** number of levels of indirection are allowed.
8928 ** <b>The "DROP TABLE" Exception</b>
8930 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
8931 ** always appropriate to call sqlite3_unlock_notify(). There is however,
8932 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
8933 ** SQLite checks if there are any currently executing SELECT statements
8934 ** that belong to the same connection. If there are, SQLITE_LOCKED is
8935 ** returned. In this case there is no "blocking connection", so invoking
8936 ** sqlite3_unlock_notify() results in the unlock-notify callback being
8937 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
8938 ** or "DROP INDEX" query, an infinite loop might be the result.
8940 ** One way around this problem is to check the extended error code returned
8941 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
8942 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
8943 ** the special "DROP TABLE/INDEX" case, the extended error code is just
8944 ** SQLITE_LOCKED.)^
8946 SQLITE_API int sqlite3_unlock_notify(
8947 sqlite3 *pBlocked, /* Waiting connection */
8948 void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
8949 void *pNotifyArg /* Argument to pass to xNotify */
8954 ** CAPI3REF: String Comparison
8956 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
8957 ** and extensions to compare the contents of two buffers containing UTF-8
8958 ** strings in a case-independent fashion, using the same definition of "case
8959 ** independence" that SQLite uses internally when comparing identifiers.
8961 SQLITE_API int sqlite3_stricmp(const char *, const char *);
8962 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
8965 ** CAPI3REF: String Globbing
8967 ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
8968 ** string X matches the [GLOB] pattern P.
8969 ** ^The definition of [GLOB] pattern matching used in
8970 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
8971 ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
8972 ** is case sensitive.
8974 ** Note that this routine returns zero on a match and non-zero if the strings
8975 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
8977 ** See also: [sqlite3_strlike()].
8979 SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
8982 ** CAPI3REF: String LIKE Matching
8984 ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
8985 ** string X matches the [LIKE] pattern P with escape character E.
8986 ** ^The definition of [LIKE] pattern matching used in
8987 ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
8988 ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
8989 ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
8990 ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
8991 ** insensitive - equivalent upper and lower case ASCII characters match
8992 ** one another.
8994 ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
8995 ** only ASCII characters are case folded.
8997 ** Note that this routine returns zero on a match and non-zero if the strings
8998 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
9000 ** See also: [sqlite3_strglob()].
9002 SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
9005 ** CAPI3REF: Error Logging Interface
9007 ** ^The [sqlite3_log()] interface writes a message into the [error log]
9008 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
9009 ** ^If logging is enabled, the zFormat string and subsequent arguments are
9010 ** used with [sqlite3_snprintf()] to generate the final output string.
9012 ** The sqlite3_log() interface is intended for use by extensions such as
9013 ** virtual tables, collating functions, and SQL functions. While there is
9014 ** nothing to prevent an application from calling sqlite3_log(), doing so
9015 ** is considered bad form.
9017 ** The zFormat string must not be NULL.
9019 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
9020 ** will not use dynamically allocated memory. The log message is stored in
9021 ** a fixed-length buffer on the stack. If the log message is longer than
9022 ** a few hundred characters, it will be truncated to the length of the
9023 ** buffer.
9025 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
9028 ** CAPI3REF: Write-Ahead Log Commit Hook
9029 ** METHOD: sqlite3
9031 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
9032 ** is invoked each time data is committed to a database in wal mode.
9034 ** ^(The callback is invoked by SQLite after the commit has taken place and
9035 ** the associated write-lock on the database released)^, so the implementation
9036 ** may read, write or [checkpoint] the database as required.
9038 ** ^The first parameter passed to the callback function when it is invoked
9039 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
9040 ** registering the callback. ^The second is a copy of the database handle.
9041 ** ^The third parameter is the name of the database that was written to -
9042 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
9043 ** is the number of pages currently in the write-ahead log file,
9044 ** including those that were just committed.
9046 ** The callback function should normally return [SQLITE_OK]. ^If an error
9047 ** code is returned, that error will propagate back up through the
9048 ** SQLite code base to cause the statement that provoked the callback
9049 ** to report an error, though the commit will have still occurred. If the
9050 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
9051 ** that does not correspond to any valid SQLite error code, the results
9052 ** are undefined.
9054 ** A single database handle may have at most a single write-ahead log callback
9055 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
9056 ** previously registered write-ahead log callback. ^Note that the
9057 ** [sqlite3_wal_autocheckpoint()] interface and the
9058 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
9059 ** overwrite any prior [sqlite3_wal_hook()] settings.
9061 SQLITE_API void *sqlite3_wal_hook(
9062 sqlite3*,
9063 int(*)(void *,sqlite3*,const char*,int),
9064 void*
9068 ** CAPI3REF: Configure an auto-checkpoint
9069 ** METHOD: sqlite3
9071 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
9072 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
9073 ** to automatically [checkpoint]
9074 ** after committing a transaction if there are N or
9075 ** more frames in the [write-ahead log] file. ^Passing zero or
9076 ** a negative value as the nFrame parameter disables automatic
9077 ** checkpoints entirely.
9079 ** ^The callback registered by this function replaces any existing callback
9080 ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
9081 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
9082 ** configured by this function.
9084 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
9085 ** from SQL.
9087 ** ^Checkpoints initiated by this mechanism are
9088 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
9090 ** ^Every new [database connection] defaults to having the auto-checkpoint
9091 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
9092 ** pages. The use of this interface
9093 ** is only necessary if the default setting is found to be suboptimal
9094 ** for a particular application.
9096 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
9099 ** CAPI3REF: Checkpoint a database
9100 ** METHOD: sqlite3
9102 ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
9103 ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
9105 ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
9106 ** [write-ahead log] for database X on [database connection] D to be
9107 ** transferred into the database file and for the write-ahead log to
9108 ** be reset. See the [checkpointing] documentation for addition
9109 ** information.
9111 ** This interface used to be the only way to cause a checkpoint to
9112 ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
9113 ** interface was added. This interface is retained for backwards
9114 ** compatibility and as a convenience for applications that need to manually
9115 ** start a callback but which do not need the full power (and corresponding
9116 ** complication) of [sqlite3_wal_checkpoint_v2()].
9118 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
9121 ** CAPI3REF: Checkpoint a database
9122 ** METHOD: sqlite3
9124 ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
9125 ** operation on database X of [database connection] D in mode M. Status
9126 ** information is written back into integers pointed to by L and C.)^
9127 ** ^(The M parameter must be a valid [checkpoint mode]:)^
9129 ** <dl>
9130 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
9131 ** ^Checkpoint as many frames as possible without waiting for any database
9132 ** readers or writers to finish, then sync the database file if all frames
9133 ** in the log were checkpointed. ^The [busy-handler callback]
9134 ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
9135 ** ^On the other hand, passive mode might leave the checkpoint unfinished
9136 ** if there are concurrent readers or writers.
9138 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
9139 ** ^This mode blocks (it invokes the
9140 ** [sqlite3_busy_handler|busy-handler callback]) until there is no
9141 ** database writer and all readers are reading from the most recent database
9142 ** snapshot. ^It then checkpoints all frames in the log file and syncs the
9143 ** database file. ^This mode blocks new database writers while it is pending,
9144 ** but new database readers are allowed to continue unimpeded.
9146 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
9147 ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
9148 ** that after checkpointing the log file it blocks (calls the
9149 ** [busy-handler callback])
9150 ** until all readers are reading from the database file only. ^This ensures
9151 ** that the next writer will restart the log file from the beginning.
9152 ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
9153 ** database writer attempts while it is pending, but does not impede readers.
9155 ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
9156 ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
9157 ** addition that it also truncates the log file to zero bytes just prior
9158 ** to a successful return.
9159 ** </dl>
9161 ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
9162 ** the log file or to -1 if the checkpoint could not run because
9163 ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
9164 ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
9165 ** log file (including any that were already checkpointed before the function
9166 ** was called) or to -1 if the checkpoint could not run due to an error or
9167 ** because the database is not in WAL mode. ^Note that upon successful
9168 ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
9169 ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
9171 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
9172 ** any other process is running a checkpoint operation at the same time, the
9173 ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
9174 ** busy-handler configured, it will not be invoked in this case.
9176 ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
9177 ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
9178 ** obtained immediately, and a busy-handler is configured, it is invoked and
9179 ** the writer lock retried until either the busy-handler returns 0 or the lock
9180 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
9181 ** database readers as described above. ^If the busy-handler returns 0 before
9182 ** the writer lock is obtained or while waiting for database readers, the
9183 ** checkpoint operation proceeds from that point in the same way as
9184 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
9185 ** without blocking any further. ^SQLITE_BUSY is returned in this case.
9187 ** ^If parameter zDb is NULL or points to a zero length string, then the
9188 ** specified operation is attempted on all WAL databases [attached] to
9189 ** [database connection] db. In this case the
9190 ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
9191 ** an SQLITE_BUSY error is encountered when processing one or more of the
9192 ** attached WAL databases, the operation is still attempted on any remaining
9193 ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
9194 ** error occurs while processing an attached database, processing is abandoned
9195 ** and the error code is returned to the caller immediately. ^If no error
9196 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
9197 ** databases, SQLITE_OK is returned.
9199 ** ^If database zDb is the name of an attached database that is not in WAL
9200 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
9201 ** zDb is not NULL (or a zero length string) and is not the name of any
9202 ** attached database, SQLITE_ERROR is returned to the caller.
9204 ** ^Unless it returns SQLITE_MISUSE,
9205 ** the sqlite3_wal_checkpoint_v2() interface
9206 ** sets the error information that is queried by
9207 ** [sqlite3_errcode()] and [sqlite3_errmsg()].
9209 ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
9210 ** from SQL.
9212 SQLITE_API int sqlite3_wal_checkpoint_v2(
9213 sqlite3 *db, /* Database handle */
9214 const char *zDb, /* Name of attached database (or NULL) */
9215 int eMode, /* SQLITE_CHECKPOINT_* value */
9216 int *pnLog, /* OUT: Size of WAL log in frames */
9217 int *pnCkpt /* OUT: Total number of frames checkpointed */
9221 ** CAPI3REF: Checkpoint Mode Values
9222 ** KEYWORDS: {checkpoint mode}
9224 ** These constants define all valid values for the "checkpoint mode" passed
9225 ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
9226 ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
9227 ** meaning of each of these checkpoint modes.
9229 #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
9230 #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
9231 #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
9232 #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
9235 ** CAPI3REF: Virtual Table Interface Configuration
9237 ** This function may be called by either the [xConnect] or [xCreate] method
9238 ** of a [virtual table] implementation to configure
9239 ** various facets of the virtual table interface.
9241 ** If this interface is invoked outside the context of an xConnect or
9242 ** xCreate virtual table method then the behavior is undefined.
9244 ** At present, there is only one option that may be configured using
9245 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
9246 ** may be added in the future.
9248 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
9251 ** CAPI3REF: Virtual Table Configuration Options
9253 ** These macros define the various options to the
9254 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
9255 ** can use to customize and optimize their behavior.
9257 ** <dl>
9258 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
9259 ** <dd>Calls of the form
9260 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
9261 ** where X is an integer. If X is zero, then the [virtual table] whose
9262 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
9263 ** support constraints. In this configuration (which is the default) if
9264 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
9265 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
9266 ** specified as part of the users SQL statement, regardless of the actual
9267 ** ON CONFLICT mode specified.
9269 ** If X is non-zero, then the virtual table implementation guarantees
9270 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
9271 ** any modifications to internal or persistent data structures have been made.
9272 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
9273 ** is able to roll back a statement or database transaction, and abandon
9274 ** or continue processing the current SQL statement as appropriate.
9275 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
9276 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
9277 ** had been ABORT.
9279 ** Virtual table implementations that are required to handle OR REPLACE
9280 ** must do so within the [xUpdate] method. If a call to the
9281 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
9282 ** CONFLICT policy is REPLACE, the virtual table implementation should
9283 ** silently replace the appropriate rows within the xUpdate callback and
9284 ** return SQLITE_OK. Or, if this is not possible, it may return
9285 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
9286 ** constraint handling.
9287 ** </dl>
9289 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
9292 ** CAPI3REF: Determine The Virtual Table Conflict Policy
9294 ** This function may only be called from within a call to the [xUpdate] method
9295 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
9296 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
9297 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
9298 ** of the SQL statement that triggered the call to the [xUpdate] method of the
9299 ** [virtual table].
9301 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
9304 ** CAPI3REF: Conflict resolution modes
9305 ** KEYWORDS: {conflict resolution mode}
9307 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
9308 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
9309 ** is for the SQL statement being evaluated.
9311 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
9312 ** return value from the [sqlite3_set_authorizer()] callback and that
9313 ** [SQLITE_ABORT] is also a [result code].
9315 #define SQLITE_ROLLBACK 1
9316 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
9317 #define SQLITE_FAIL 3
9318 /* #define SQLITE_ABORT 4 // Also an error code */
9319 #define SQLITE_REPLACE 5
9322 ** CAPI3REF: Prepared Statement Scan Status Opcodes
9323 ** KEYWORDS: {scanstatus options}
9325 ** The following constants can be used for the T parameter to the
9326 ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
9327 ** different metric for sqlite3_stmt_scanstatus() to return.
9329 ** When the value returned to V is a string, space to hold that string is
9330 ** managed by the prepared statement S and will be automatically freed when
9331 ** S is finalized.
9333 ** <dl>
9334 ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
9335 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
9336 ** set to the total number of times that the X-th loop has run.</dd>
9338 ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
9339 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
9340 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
9342 ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
9343 ** <dd>^The "double" variable pointed to by the T parameter will be set to the
9344 ** query planner's estimate for the average number of rows output from each
9345 ** iteration of the X-th loop. If the query planner's estimates was accurate,
9346 ** then this value will approximate the quotient NVISIT/NLOOP and the
9347 ** product of this value for all prior loops with the same SELECTID will
9348 ** be the NLOOP value for the current loop.
9350 ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
9351 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
9352 ** to a zero-terminated UTF-8 string containing the name of the index or table
9353 ** used for the X-th loop.
9355 ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
9356 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
9357 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
9358 ** description for the X-th loop.
9360 ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
9361 ** <dd>^The "int" variable pointed to by the T parameter will be set to the
9362 ** "select-id" for the X-th loop. The select-id identifies which query or
9363 ** subquery the loop is part of. The main query has a select-id of zero.
9364 ** The select-id is the same value as is output in the first column
9365 ** of an [EXPLAIN QUERY PLAN] query.
9366 ** </dl>
9368 #define SQLITE_SCANSTAT_NLOOP 0
9369 #define SQLITE_SCANSTAT_NVISIT 1
9370 #define SQLITE_SCANSTAT_EST 2
9371 #define SQLITE_SCANSTAT_NAME 3
9372 #define SQLITE_SCANSTAT_EXPLAIN 4
9373 #define SQLITE_SCANSTAT_SELECTID 5
9376 ** CAPI3REF: Prepared Statement Scan Status
9377 ** METHOD: sqlite3_stmt
9379 ** This interface returns information about the predicted and measured
9380 ** performance for pStmt. Advanced applications can use this
9381 ** interface to compare the predicted and the measured performance and
9382 ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
9384 ** Since this interface is expected to be rarely used, it is only
9385 ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
9386 ** compile-time option.
9388 ** The "iScanStatusOp" parameter determines which status information to return.
9389 ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
9390 ** of this interface is undefined.
9391 ** ^The requested measurement is written into a variable pointed to by
9392 ** the "pOut" parameter.
9393 ** Parameter "idx" identifies the specific loop to retrieve statistics for.
9394 ** Loops are numbered starting from zero. ^If idx is out of range - less than
9395 ** zero or greater than or equal to the total number of loops used to implement
9396 ** the statement - a non-zero value is returned and the variable that pOut
9397 ** points to is unchanged.
9399 ** ^Statistics might not be available for all loops in all statements. ^In cases
9400 ** where there exist loops with no available statistics, this function behaves
9401 ** as if the loop did not exist - it returns non-zero and leave the variable
9402 ** that pOut points to unchanged.
9404 ** See also: [sqlite3_stmt_scanstatus_reset()]
9406 SQLITE_API int sqlite3_stmt_scanstatus(
9407 sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
9408 int idx, /* Index of loop to report on */
9409 int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
9410 void *pOut /* Result written here */
9414 ** CAPI3REF: Zero Scan-Status Counters
9415 ** METHOD: sqlite3_stmt
9417 ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
9419 ** This API is only available if the library is built with pre-processor
9420 ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
9422 SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
9425 ** CAPI3REF: Flush caches to disk mid-transaction
9427 ** ^If a write-transaction is open on [database connection] D when the
9428 ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
9429 ** pages in the pager-cache that are not currently in use are written out
9430 ** to disk. A dirty page may be in use if a database cursor created by an
9431 ** active SQL statement is reading from it, or if it is page 1 of a database
9432 ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
9433 ** interface flushes caches for all schemas - "main", "temp", and
9434 ** any [attached] databases.
9436 ** ^If this function needs to obtain extra database locks before dirty pages
9437 ** can be flushed to disk, it does so. ^If those locks cannot be obtained
9438 ** immediately and there is a busy-handler callback configured, it is invoked
9439 ** in the usual manner. ^If the required lock still cannot be obtained, then
9440 ** the database is skipped and an attempt made to flush any dirty pages
9441 ** belonging to the next (if any) database. ^If any databases are skipped
9442 ** because locks cannot be obtained, but no other error occurs, this
9443 ** function returns SQLITE_BUSY.
9445 ** ^If any other error occurs while flushing dirty pages to disk (for
9446 ** example an IO error or out-of-memory condition), then processing is
9447 ** abandoned and an SQLite [error code] is returned to the caller immediately.
9449 ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
9451 ** ^This function does not set the database handle error code or message
9452 ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
9454 SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
9457 ** CAPI3REF: The pre-update hook.
9459 ** ^These interfaces are only available if SQLite is compiled using the
9460 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
9462 ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
9463 ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
9464 ** on a database table.
9465 ** ^At most one preupdate hook may be registered at a time on a single
9466 ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
9467 ** the previous setting.
9468 ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
9469 ** with a NULL pointer as the second parameter.
9470 ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
9471 ** the first parameter to callbacks.
9473 ** ^The preupdate hook only fires for changes to real database tables; the
9474 ** preupdate hook is not invoked for changes to [virtual tables] or to
9475 ** system tables like sqlite_master or sqlite_stat1.
9477 ** ^The second parameter to the preupdate callback is a pointer to
9478 ** the [database connection] that registered the preupdate hook.
9479 ** ^The third parameter to the preupdate callback is one of the constants
9480 ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
9481 ** kind of update operation that is about to occur.
9482 ** ^(The fourth parameter to the preupdate callback is the name of the
9483 ** database within the database connection that is being modified. This
9484 ** will be "main" for the main database or "temp" for TEMP tables or
9485 ** the name given after the AS keyword in the [ATTACH] statement for attached
9486 ** databases.)^
9487 ** ^The fifth parameter to the preupdate callback is the name of the
9488 ** table that is being modified.
9490 ** For an UPDATE or DELETE operation on a [rowid table], the sixth
9491 ** parameter passed to the preupdate callback is the initial [rowid] of the
9492 ** row being modified or deleted. For an INSERT operation on a rowid table,
9493 ** or any operation on a WITHOUT ROWID table, the value of the sixth
9494 ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
9495 ** seventh parameter is the final rowid value of the row being inserted
9496 ** or updated. The value of the seventh parameter passed to the callback
9497 ** function is not defined for operations on WITHOUT ROWID tables, or for
9498 ** INSERT operations on rowid tables.
9500 ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
9501 ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
9502 ** provide additional information about a preupdate event. These routines
9503 ** may only be called from within a preupdate callback. Invoking any of
9504 ** these routines from outside of a preupdate callback or with a
9505 ** [database connection] pointer that is different from the one supplied
9506 ** to the preupdate callback results in undefined and probably undesirable
9507 ** behavior.
9509 ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
9510 ** in the row that is being inserted, updated, or deleted.
9512 ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
9513 ** a [protected sqlite3_value] that contains the value of the Nth column of
9514 ** the table row before it is updated. The N parameter must be between 0
9515 ** and one less than the number of columns or the behavior will be
9516 ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
9517 ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
9518 ** behavior is undefined. The [sqlite3_value] that P points to
9519 ** will be destroyed when the preupdate callback returns.
9521 ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
9522 ** a [protected sqlite3_value] that contains the value of the Nth column of
9523 ** the table row after it is updated. The N parameter must be between 0
9524 ** and one less than the number of columns or the behavior will be
9525 ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
9526 ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
9527 ** behavior is undefined. The [sqlite3_value] that P points to
9528 ** will be destroyed when the preupdate callback returns.
9530 ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
9531 ** callback was invoked as a result of a direct insert, update, or delete
9532 ** operation; or 1 for inserts, updates, or deletes invoked by top-level
9533 ** triggers; or 2 for changes resulting from triggers called by top-level
9534 ** triggers; and so forth.
9536 ** See also: [sqlite3_update_hook()]
9538 #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
9539 SQLITE_API void *sqlite3_preupdate_hook(
9540 sqlite3 *db,
9541 void(*xPreUpdate)(
9542 void *pCtx, /* Copy of third arg to preupdate_hook() */
9543 sqlite3 *db, /* Database handle */
9544 int op, /* SQLITE_UPDATE, DELETE or INSERT */
9545 char const *zDb, /* Database name */
9546 char const *zName, /* Table name */
9547 sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
9548 sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
9550 void*
9552 SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
9553 SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
9554 SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
9555 SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
9556 #endif
9559 ** CAPI3REF: Low-level system error code
9561 ** ^Attempt to return the underlying operating system error code or error
9562 ** number that caused the most recent I/O error or failure to open a file.
9563 ** The return value is OS-dependent. For example, on unix systems, after
9564 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
9565 ** called to get back the underlying "errno" that caused the problem, such
9566 ** as ENOSPC, EAUTH, EISDIR, and so forth.
9568 SQLITE_API int sqlite3_system_errno(sqlite3*);
9571 ** CAPI3REF: Database Snapshot
9572 ** KEYWORDS: {snapshot} {sqlite3_snapshot}
9573 ** EXPERIMENTAL
9575 ** An instance of the snapshot object records the state of a [WAL mode]
9576 ** database for some specific point in history.
9578 ** In [WAL mode], multiple [database connections] that are open on the
9579 ** same database file can each be reading a different historical version
9580 ** of the database file. When a [database connection] begins a read
9581 ** transaction, that connection sees an unchanging copy of the database
9582 ** as it existed for the point in time when the transaction first started.
9583 ** Subsequent changes to the database from other connections are not seen
9584 ** by the reader until a new read transaction is started.
9586 ** The sqlite3_snapshot object records state information about an historical
9587 ** version of the database file so that it is possible to later open a new read
9588 ** transaction that sees that historical version of the database rather than
9589 ** the most recent version.
9591 ** The constructor for this object is [sqlite3_snapshot_get()]. The
9592 ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
9593 ** to an historical snapshot (if possible). The destructor for
9594 ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
9596 typedef struct sqlite3_snapshot {
9597 unsigned char hidden[48];
9598 } sqlite3_snapshot;
9601 ** CAPI3REF: Record A Database Snapshot
9602 ** EXPERIMENTAL
9604 ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
9605 ** new [sqlite3_snapshot] object that records the current state of
9606 ** schema S in database connection D. ^On success, the
9607 ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
9608 ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
9609 ** If there is not already a read-transaction open on schema S when
9610 ** this function is called, one is opened automatically.
9612 ** The following must be true for this function to succeed. If any of
9613 ** the following statements are false when sqlite3_snapshot_get() is
9614 ** called, SQLITE_ERROR is returned. The final value of *P is undefined
9615 ** in this case.
9617 ** <ul>
9618 ** <li> The database handle must be in [autocommit mode].
9620 ** <li> Schema S of [database connection] D must be a [WAL mode] database.
9622 ** <li> There must not be a write transaction open on schema S of database
9623 ** connection D.
9625 ** <li> One or more transactions must have been written to the current wal
9626 ** file since it was created on disk (by any connection). This means
9627 ** that a snapshot cannot be taken on a wal mode database with no wal
9628 ** file immediately after it is first opened. At least one transaction
9629 ** must be written to it first.
9630 ** </ul>
9632 ** This function may also return SQLITE_NOMEM. If it is called with the
9633 ** database handle in autocommit mode but fails for some other reason,
9634 ** whether or not a read transaction is opened on schema S is undefined.
9636 ** The [sqlite3_snapshot] object returned from a successful call to
9637 ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
9638 ** to avoid a memory leak.
9640 ** The [sqlite3_snapshot_get()] interface is only available when the
9641 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
9643 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
9644 sqlite3 *db,
9645 const char *zSchema,
9646 sqlite3_snapshot **ppSnapshot
9650 ** CAPI3REF: Start a read transaction on an historical snapshot
9651 ** EXPERIMENTAL
9653 ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
9654 ** read transaction for schema S of
9655 ** [database connection] D such that the read transaction
9656 ** refers to historical [snapshot] P, rather than the most
9657 ** recent change to the database.
9658 ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
9659 ** or an appropriate [error code] if it fails.
9661 ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
9662 ** the first operation following the [BEGIN] that takes the schema S
9663 ** out of [autocommit mode].
9664 ** ^In other words, schema S must not currently be in
9665 ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
9666 ** database connection D must be out of [autocommit mode].
9667 ** ^A [snapshot] will fail to open if it has been overwritten by a
9668 ** [checkpoint].
9669 ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
9670 ** database connection D does not know that the database file for
9671 ** schema S is in [WAL mode]. A database connection might not know
9672 ** that the database file is in [WAL mode] if there has been no prior
9673 ** I/O on that database connection, or if the database entered [WAL mode]
9674 ** after the most recent I/O on the database connection.)^
9675 ** (Hint: Run "[PRAGMA application_id]" against a newly opened
9676 ** database connection in order to make it ready to use snapshots.)
9678 ** The [sqlite3_snapshot_open()] interface is only available when the
9679 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
9681 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
9682 sqlite3 *db,
9683 const char *zSchema,
9684 sqlite3_snapshot *pSnapshot
9688 ** CAPI3REF: Destroy a snapshot
9689 ** EXPERIMENTAL
9691 ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
9692 ** The application must eventually free every [sqlite3_snapshot] object
9693 ** using this routine to avoid a memory leak.
9695 ** The [sqlite3_snapshot_free()] interface is only available when the
9696 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
9698 SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
9701 ** CAPI3REF: Compare the ages of two snapshot handles.
9702 ** EXPERIMENTAL
9704 ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
9705 ** of two valid snapshot handles.
9707 ** If the two snapshot handles are not associated with the same database
9708 ** file, the result of the comparison is undefined.
9710 ** Additionally, the result of the comparison is only valid if both of the
9711 ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
9712 ** last time the wal file was deleted. The wal file is deleted when the
9713 ** database is changed back to rollback mode or when the number of database
9714 ** clients drops to zero. If either snapshot handle was obtained before the
9715 ** wal file was last deleted, the value returned by this function
9716 ** is undefined.
9718 ** Otherwise, this API returns a negative value if P1 refers to an older
9719 ** snapshot than P2, zero if the two handles refer to the same database
9720 ** snapshot, and a positive value if P1 is a newer snapshot than P2.
9722 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
9723 sqlite3_snapshot *p1,
9724 sqlite3_snapshot *p2
9728 ** CAPI3REF: Recover snapshots from a wal file
9729 ** EXPERIMENTAL
9731 ** If all connections disconnect from a database file but do not perform
9732 ** a checkpoint, the existing wal file is opened along with the database
9733 ** file the next time the database is opened. At this point it is only
9734 ** possible to successfully call sqlite3_snapshot_open() to open the most
9735 ** recent snapshot of the database (the one at the head of the wal file),
9736 ** even though the wal file may contain other valid snapshots for which
9737 ** clients have sqlite3_snapshot handles.
9739 ** This function attempts to scan the wal file associated with database zDb
9740 ** of database handle db and make all valid snapshots available to
9741 ** sqlite3_snapshot_open(). It is an error if there is already a read
9742 ** transaction open on the database, or if the database is not a wal mode
9743 ** database.
9745 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9747 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
9750 ** Undo the hack that converts floating point types to integer for
9751 ** builds on processors without floating point support.
9753 #ifdef SQLITE_OMIT_FLOATING_POINT
9754 # undef double
9755 #endif
9757 #if 0
9758 } /* End of the 'extern "C"' block */
9759 #endif
9760 #endif /* SQLITE3_H */
9762 /******** Begin file sqlite3rtree.h *********/
9764 ** 2010 August 30
9766 ** The author disclaims copyright to this source code. In place of
9767 ** a legal notice, here is a blessing:
9769 ** May you do good and not evil.
9770 ** May you find forgiveness for yourself and forgive others.
9771 ** May you share freely, never taking more than you give.
9773 *************************************************************************
9776 #ifndef _SQLITE3RTREE_H_
9777 #define _SQLITE3RTREE_H_
9780 #if 0
9781 extern "C" {
9782 #endif
9784 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
9785 typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
9787 /* The double-precision datatype used by RTree depends on the
9788 ** SQLITE_RTREE_INT_ONLY compile-time option.
9790 #ifdef SQLITE_RTREE_INT_ONLY
9791 typedef sqlite3_int64 sqlite3_rtree_dbl;
9792 #else
9793 typedef double sqlite3_rtree_dbl;
9794 #endif
9797 ** Register a geometry callback named zGeom that can be used as part of an
9798 ** R-Tree geometry query as follows:
9800 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
9802 SQLITE_API int sqlite3_rtree_geometry_callback(
9803 sqlite3 *db,
9804 const char *zGeom,
9805 int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
9806 void *pContext
9811 ** A pointer to a structure of the following type is passed as the first
9812 ** argument to callbacks registered using rtree_geometry_callback().
9814 struct sqlite3_rtree_geometry {
9815 void *pContext; /* Copy of pContext passed to s_r_g_c() */
9816 int nParam; /* Size of array aParam[] */
9817 sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
9818 void *pUser; /* Callback implementation user data */
9819 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
9823 ** Register a 2nd-generation geometry callback named zScore that can be
9824 ** used as part of an R-Tree geometry query as follows:
9826 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
9828 SQLITE_API int sqlite3_rtree_query_callback(
9829 sqlite3 *db,
9830 const char *zQueryFunc,
9831 int (*xQueryFunc)(sqlite3_rtree_query_info*),
9832 void *pContext,
9833 void (*xDestructor)(void*)
9838 ** A pointer to a structure of the following type is passed as the
9839 ** argument to scored geometry callback registered using
9840 ** sqlite3_rtree_query_callback().
9842 ** Note that the first 5 fields of this structure are identical to
9843 ** sqlite3_rtree_geometry. This structure is a subclass of
9844 ** sqlite3_rtree_geometry.
9846 struct sqlite3_rtree_query_info {
9847 void *pContext; /* pContext from when function registered */
9848 int nParam; /* Number of function parameters */
9849 sqlite3_rtree_dbl *aParam; /* value of function parameters */
9850 void *pUser; /* callback can use this, if desired */
9851 void (*xDelUser)(void*); /* function to free pUser */
9852 sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
9853 unsigned int *anQueue; /* Number of pending entries in the queue */
9854 int nCoord; /* Number of coordinates */
9855 int iLevel; /* Level of current node or entry */
9856 int mxLevel; /* The largest iLevel value in the tree */
9857 sqlite3_int64 iRowid; /* Rowid for current entry */
9858 sqlite3_rtree_dbl rParentScore; /* Score of parent node */
9859 int eParentWithin; /* Visibility of parent node */
9860 int eWithin; /* OUT: Visiblity */
9861 sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
9862 /* The following fields are only available in 3.8.11 and later */
9863 sqlite3_value **apSqlParam; /* Original SQL values of parameters */
9867 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
9869 #define NOT_WITHIN 0 /* Object completely outside of query region */
9870 #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
9871 #define FULLY_WITHIN 2 /* Object fully contained within query region */
9874 #if 0
9875 } /* end of the 'extern "C"' block */
9876 #endif
9878 #endif /* ifndef _SQLITE3RTREE_H_ */
9880 /******** End of sqlite3rtree.h *********/
9881 /******** Begin file sqlite3session.h *********/
9883 #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
9884 #define __SQLITESESSION_H_ 1
9887 ** Make sure we can call this stuff from C++.
9889 #if 0
9890 extern "C" {
9891 #endif
9895 ** CAPI3REF: Session Object Handle
9897 typedef struct sqlite3_session sqlite3_session;
9900 ** CAPI3REF: Changeset Iterator Handle
9902 typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
9905 ** CAPI3REF: Create A New Session Object
9907 ** Create a new session object attached to database handle db. If successful,
9908 ** a pointer to the new object is written to *ppSession and SQLITE_OK is
9909 ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
9910 ** error code (e.g. SQLITE_NOMEM) is returned.
9912 ** It is possible to create multiple session objects attached to a single
9913 ** database handle.
9915 ** Session objects created using this function should be deleted using the
9916 ** [sqlite3session_delete()] function before the database handle that they
9917 ** are attached to is itself closed. If the database handle is closed before
9918 ** the session object is deleted, then the results of calling any session
9919 ** module function, including [sqlite3session_delete()] on the session object
9920 ** are undefined.
9922 ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
9923 ** is not possible for an application to register a pre-update hook on a
9924 ** database handle that has one or more session objects attached. Nor is
9925 ** it possible to create a session object attached to a database handle for
9926 ** which a pre-update hook is already defined. The results of attempting
9927 ** either of these things are undefined.
9929 ** The session object will be used to create changesets for tables in
9930 ** database zDb, where zDb is either "main", or "temp", or the name of an
9931 ** attached database. It is not an error if database zDb is not attached
9932 ** to the database when the session object is created.
9934 SQLITE_API int sqlite3session_create(
9935 sqlite3 *db, /* Database handle */
9936 const char *zDb, /* Name of db (e.g. "main") */
9937 sqlite3_session **ppSession /* OUT: New session object */
9941 ** CAPI3REF: Delete A Session Object
9943 ** Delete a session object previously allocated using
9944 ** [sqlite3session_create()]. Once a session object has been deleted, the
9945 ** results of attempting to use pSession with any other session module
9946 ** function are undefined.
9948 ** Session objects must be deleted before the database handle to which they
9949 ** are attached is closed. Refer to the documentation for
9950 ** [sqlite3session_create()] for details.
9952 SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
9956 ** CAPI3REF: Enable Or Disable A Session Object
9958 ** Enable or disable the recording of changes by a session object. When
9959 ** enabled, a session object records changes made to the database. When
9960 ** disabled - it does not. A newly created session object is enabled.
9961 ** Refer to the documentation for [sqlite3session_changeset()] for further
9962 ** details regarding how enabling and disabling a session object affects
9963 ** the eventual changesets.
9965 ** Passing zero to this function disables the session. Passing a value
9966 ** greater than zero enables it. Passing a value less than zero is a
9967 ** no-op, and may be used to query the current state of the session.
9969 ** The return value indicates the final state of the session object: 0 if
9970 ** the session is disabled, or 1 if it is enabled.
9972 SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
9975 ** CAPI3REF: Set Or Clear the Indirect Change Flag
9977 ** Each change recorded by a session object is marked as either direct or
9978 ** indirect. A change is marked as indirect if either:
9980 ** <ul>
9981 ** <li> The session object "indirect" flag is set when the change is
9982 ** made, or
9983 ** <li> The change is made by an SQL trigger or foreign key action
9984 ** instead of directly as a result of a users SQL statement.
9985 ** </ul>
9987 ** If a single row is affected by more than one operation within a session,
9988 ** then the change is considered indirect if all operations meet the criteria
9989 ** for an indirect change above, or direct otherwise.
9991 ** This function is used to set, clear or query the session object indirect
9992 ** flag. If the second argument passed to this function is zero, then the
9993 ** indirect flag is cleared. If it is greater than zero, the indirect flag
9994 ** is set. Passing a value less than zero does not modify the current value
9995 ** of the indirect flag, and may be used to query the current state of the
9996 ** indirect flag for the specified session object.
9998 ** The return value indicates the final state of the indirect flag: 0 if
9999 ** it is clear, or 1 if it is set.
10001 SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
10004 ** CAPI3REF: Attach A Table To A Session Object
10006 ** If argument zTab is not NULL, then it is the name of a table to attach
10007 ** to the session object passed as the first argument. All subsequent changes
10008 ** made to the table while the session object is enabled will be recorded. See
10009 ** documentation for [sqlite3session_changeset()] for further details.
10011 ** Or, if argument zTab is NULL, then changes are recorded for all tables
10012 ** in the database. If additional tables are added to the database (by
10013 ** executing "CREATE TABLE" statements) after this call is made, changes for
10014 ** the new tables are also recorded.
10016 ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
10017 ** defined as part of their CREATE TABLE statement. It does not matter if the
10018 ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
10019 ** KEY may consist of a single column, or may be a composite key.
10021 ** It is not an error if the named table does not exist in the database. Nor
10022 ** is it an error if the named table does not have a PRIMARY KEY. However,
10023 ** no changes will be recorded in either of these scenarios.
10025 ** Changes are not recorded for individual rows that have NULL values stored
10026 ** in one or more of their PRIMARY KEY columns.
10028 ** SQLITE_OK is returned if the call completes without error. Or, if an error
10029 ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
10031 SQLITE_API int sqlite3session_attach(
10032 sqlite3_session *pSession, /* Session object */
10033 const char *zTab /* Table name */
10037 ** CAPI3REF: Set a table filter on a Session Object.
10039 ** The second argument (xFilter) is the "filter callback". For changes to rows
10040 ** in tables that are not attached to the Session object, the filter is called
10041 ** to determine whether changes to the table's rows should be tracked or not.
10042 ** If xFilter returns 0, changes is not tracked. Note that once a table is
10043 ** attached, xFilter will not be called again.
10045 SQLITE_API void sqlite3session_table_filter(
10046 sqlite3_session *pSession, /* Session object */
10047 int(*xFilter)(
10048 void *pCtx, /* Copy of third arg to _filter_table() */
10049 const char *zTab /* Table name */
10051 void *pCtx /* First argument passed to xFilter */
10055 ** CAPI3REF: Generate A Changeset From A Session Object
10057 ** Obtain a changeset containing changes to the tables attached to the
10058 ** session object passed as the first argument. If successful,
10059 ** set *ppChangeset to point to a buffer containing the changeset
10060 ** and *pnChangeset to the size of the changeset in bytes before returning
10061 ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
10062 ** zero and return an SQLite error code.
10064 ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
10065 ** each representing a change to a single row of an attached table. An INSERT
10066 ** change contains the values of each field of a new database row. A DELETE
10067 ** contains the original values of each field of a deleted database row. An
10068 ** UPDATE change contains the original values of each field of an updated
10069 ** database row along with the updated values for each updated non-primary-key
10070 ** column. It is not possible for an UPDATE change to represent a change that
10071 ** modifies the values of primary key columns. If such a change is made, it
10072 ** is represented in a changeset as a DELETE followed by an INSERT.
10074 ** Changes are not recorded for rows that have NULL values stored in one or
10075 ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
10076 ** no corresponding change is present in the changesets returned by this
10077 ** function. If an existing row with one or more NULL values stored in
10078 ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
10079 ** only an INSERT is appears in the changeset. Similarly, if an existing row
10080 ** with non-NULL PRIMARY KEY values is updated so that one or more of its
10081 ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
10082 ** DELETE change only.
10084 ** The contents of a changeset may be traversed using an iterator created
10085 ** using the [sqlite3changeset_start()] API. A changeset may be applied to
10086 ** a database with a compatible schema using the [sqlite3changeset_apply()]
10087 ** API.
10089 ** Within a changeset generated by this function, all changes related to a
10090 ** single table are grouped together. In other words, when iterating through
10091 ** a changeset or when applying a changeset to a database, all changes related
10092 ** to a single table are processed before moving on to the next table. Tables
10093 ** are sorted in the same order in which they were attached (or auto-attached)
10094 ** to the sqlite3_session object. The order in which the changes related to
10095 ** a single table are stored is undefined.
10097 ** Following a successful call to this function, it is the responsibility of
10098 ** the caller to eventually free the buffer that *ppChangeset points to using
10099 ** [sqlite3_free()].
10101 ** <h3>Changeset Generation</h3>
10103 ** Once a table has been attached to a session object, the session object
10104 ** records the primary key values of all new rows inserted into the table.
10105 ** It also records the original primary key and other column values of any
10106 ** deleted or updated rows. For each unique primary key value, data is only
10107 ** recorded once - the first time a row with said primary key is inserted,
10108 ** updated or deleted in the lifetime of the session.
10110 ** There is one exception to the previous paragraph: when a row is inserted,
10111 ** updated or deleted, if one or more of its primary key columns contain a
10112 ** NULL value, no record of the change is made.
10114 ** The session object therefore accumulates two types of records - those
10115 ** that consist of primary key values only (created when the user inserts
10116 ** a new record) and those that consist of the primary key values and the
10117 ** original values of other table columns (created when the users deletes
10118 ** or updates a record).
10120 ** When this function is called, the requested changeset is created using
10121 ** both the accumulated records and the current contents of the database
10122 ** file. Specifically:
10124 ** <ul>
10125 ** <li> For each record generated by an insert, the database is queried
10126 ** for a row with a matching primary key. If one is found, an INSERT
10127 ** change is added to the changeset. If no such row is found, no change
10128 ** is added to the changeset.
10130 ** <li> For each record generated by an update or delete, the database is
10131 ** queried for a row with a matching primary key. If such a row is
10132 ** found and one or more of the non-primary key fields have been
10133 ** modified from their original values, an UPDATE change is added to
10134 ** the changeset. Or, if no such row is found in the table, a DELETE
10135 ** change is added to the changeset. If there is a row with a matching
10136 ** primary key in the database, but all fields contain their original
10137 ** values, no change is added to the changeset.
10138 ** </ul>
10140 ** This means, amongst other things, that if a row is inserted and then later
10141 ** deleted while a session object is active, neither the insert nor the delete
10142 ** will be present in the changeset. Or if a row is deleted and then later a
10143 ** row with the same primary key values inserted while a session object is
10144 ** active, the resulting changeset will contain an UPDATE change instead of
10145 ** a DELETE and an INSERT.
10147 ** When a session object is disabled (see the [sqlite3session_enable()] API),
10148 ** it does not accumulate records when rows are inserted, updated or deleted.
10149 ** This may appear to have some counter-intuitive effects if a single row
10150 ** is written to more than once during a session. For example, if a row
10151 ** is inserted while a session object is enabled, then later deleted while
10152 ** the same session object is disabled, no INSERT record will appear in the
10153 ** changeset, even though the delete took place while the session was disabled.
10154 ** Or, if one field of a row is updated while a session is disabled, and
10155 ** another field of the same row is updated while the session is enabled, the
10156 ** resulting changeset will contain an UPDATE change that updates both fields.
10158 SQLITE_API int sqlite3session_changeset(
10159 sqlite3_session *pSession, /* Session object */
10160 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
10161 void **ppChangeset /* OUT: Buffer containing changeset */
10165 ** CAPI3REF: Load The Difference Between Tables Into A Session
10167 ** If it is not already attached to the session object passed as the first
10168 ** argument, this function attaches table zTbl in the same manner as the
10169 ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
10170 ** does not have a primary key, this function is a no-op (but does not return
10171 ** an error).
10173 ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
10174 ** attached to the same database handle as the session object that contains
10175 ** a table compatible with the table attached to the session by this function.
10176 ** A table is considered compatible if it:
10178 ** <ul>
10179 ** <li> Has the same name,
10180 ** <li> Has the same set of columns declared in the same order, and
10181 ** <li> Has the same PRIMARY KEY definition.
10182 ** </ul>
10184 ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
10185 ** are compatible but do not have any PRIMARY KEY columns, it is not an error
10186 ** but no changes are added to the session object. As with other session
10187 ** APIs, tables without PRIMARY KEYs are simply ignored.
10189 ** This function adds a set of changes to the session object that could be
10190 ** used to update the table in database zFrom (call this the "from-table")
10191 ** so that its content is the same as the table attached to the session
10192 ** object (call this the "to-table"). Specifically:
10194 ** <ul>
10195 ** <li> For each row (primary key) that exists in the to-table but not in
10196 ** the from-table, an INSERT record is added to the session object.
10198 ** <li> For each row (primary key) that exists in the to-table but not in
10199 ** the from-table, a DELETE record is added to the session object.
10201 ** <li> For each row (primary key) that exists in both tables, but features
10202 ** different non-PK values in each, an UPDATE record is added to the
10203 ** session.
10204 ** </ul>
10206 ** To clarify, if this function is called and then a changeset constructed
10207 ** using [sqlite3session_changeset()], then after applying that changeset to
10208 ** database zFrom the contents of the two compatible tables would be
10209 ** identical.
10211 ** It an error if database zFrom does not exist or does not contain the
10212 ** required compatible table.
10214 ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
10215 ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
10216 ** may be set to point to a buffer containing an English language error
10217 ** message. It is the responsibility of the caller to free this buffer using
10218 ** sqlite3_free().
10220 SQLITE_API int sqlite3session_diff(
10221 sqlite3_session *pSession,
10222 const char *zFromDb,
10223 const char *zTbl,
10224 char **pzErrMsg
10229 ** CAPI3REF: Generate A Patchset From A Session Object
10231 ** The differences between a patchset and a changeset are that:
10233 ** <ul>
10234 ** <li> DELETE records consist of the primary key fields only. The
10235 ** original values of other fields are omitted.
10236 ** <li> The original values of any modified fields are omitted from
10237 ** UPDATE records.
10238 ** </ul>
10240 ** A patchset blob may be used with up to date versions of all
10241 ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
10242 ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
10243 ** attempting to use a patchset blob with old versions of the
10244 ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
10246 ** Because the non-primary key "old.*" fields are omitted, no
10247 ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
10248 ** is passed to the sqlite3changeset_apply() API. Other conflict types work
10249 ** in the same way as for changesets.
10251 ** Changes within a patchset are ordered in the same way as for changesets
10252 ** generated by the sqlite3session_changeset() function (i.e. all changes for
10253 ** a single table are grouped together, tables appear in the order in which
10254 ** they were attached to the session object).
10256 SQLITE_API int sqlite3session_patchset(
10257 sqlite3_session *pSession, /* Session object */
10258 int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
10259 void **ppPatchset /* OUT: Buffer containing patchset */
10263 ** CAPI3REF: Test if a changeset has recorded any changes.
10265 ** Return non-zero if no changes to attached tables have been recorded by
10266 ** the session object passed as the first argument. Otherwise, if one or
10267 ** more changes have been recorded, return zero.
10269 ** Even if this function returns zero, it is possible that calling
10270 ** [sqlite3session_changeset()] on the session handle may still return a
10271 ** changeset that contains no changes. This can happen when a row in
10272 ** an attached table is modified and then later on the original values
10273 ** are restored. However, if this function returns non-zero, then it is
10274 ** guaranteed that a call to sqlite3session_changeset() will return a
10275 ** changeset containing zero changes.
10277 SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
10280 ** CAPI3REF: Create An Iterator To Traverse A Changeset
10282 ** Create an iterator used to iterate through the contents of a changeset.
10283 ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
10284 ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
10285 ** SQLite error code is returned.
10287 ** The following functions can be used to advance and query a changeset
10288 ** iterator created by this function:
10290 ** <ul>
10291 ** <li> [sqlite3changeset_next()]
10292 ** <li> [sqlite3changeset_op()]
10293 ** <li> [sqlite3changeset_new()]
10294 ** <li> [sqlite3changeset_old()]
10295 ** </ul>
10297 ** It is the responsibility of the caller to eventually destroy the iterator
10298 ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
10299 ** changeset (pChangeset) must remain valid until after the iterator is
10300 ** destroyed.
10302 ** Assuming the changeset blob was created by one of the
10303 ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
10304 ** [sqlite3changeset_invert()] functions, all changes within the changeset
10305 ** that apply to a single table are grouped together. This means that when
10306 ** an application iterates through a changeset using an iterator created by
10307 ** this function, all changes that relate to a single table are visited
10308 ** consecutively. There is no chance that the iterator will visit a change
10309 ** the applies to table X, then one for table Y, and then later on visit
10310 ** another change for table X.
10312 SQLITE_API int sqlite3changeset_start(
10313 sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
10314 int nChangeset, /* Size of changeset blob in bytes */
10315 void *pChangeset /* Pointer to blob containing changeset */
10320 ** CAPI3REF: Advance A Changeset Iterator
10322 ** This function may only be used with iterators created by function
10323 ** [sqlite3changeset_start()]. If it is called on an iterator passed to
10324 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
10325 ** is returned and the call has no effect.
10327 ** Immediately after an iterator is created by sqlite3changeset_start(), it
10328 ** does not point to any change in the changeset. Assuming the changeset
10329 ** is not empty, the first call to this function advances the iterator to
10330 ** point to the first change in the changeset. Each subsequent call advances
10331 ** the iterator to point to the next change in the changeset (if any). If
10332 ** no error occurs and the iterator points to a valid change after a call
10333 ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
10334 ** Otherwise, if all changes in the changeset have already been visited,
10335 ** SQLITE_DONE is returned.
10337 ** If an error occurs, an SQLite error code is returned. Possible error
10338 ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
10339 ** SQLITE_NOMEM.
10341 SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
10344 ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
10346 ** The pIter argument passed to this function may either be an iterator
10347 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
10348 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
10349 ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
10350 ** is not the case, this function returns [SQLITE_MISUSE].
10352 ** If argument pzTab is not NULL, then *pzTab is set to point to a
10353 ** nul-terminated utf-8 encoded string containing the name of the table
10354 ** affected by the current change. The buffer remains valid until either
10355 ** sqlite3changeset_next() is called on the iterator or until the
10356 ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
10357 ** set to the number of columns in the table affected by the change. If
10358 ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
10359 ** is an indirect change, or false (0) otherwise. See the documentation for
10360 ** [sqlite3session_indirect()] for a description of direct and indirect
10361 ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
10362 ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
10363 ** type of change that the iterator currently points to.
10365 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
10366 ** SQLite error code is returned. The values of the output variables may not
10367 ** be trusted in this case.
10369 SQLITE_API int sqlite3changeset_op(
10370 sqlite3_changeset_iter *pIter, /* Iterator object */
10371 const char **pzTab, /* OUT: Pointer to table name */
10372 int *pnCol, /* OUT: Number of columns in table */
10373 int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
10374 int *pbIndirect /* OUT: True for an 'indirect' change */
10378 ** CAPI3REF: Obtain The Primary Key Definition Of A Table
10380 ** For each modified table, a changeset includes the following:
10382 ** <ul>
10383 ** <li> The number of columns in the table, and
10384 ** <li> Which of those columns make up the tables PRIMARY KEY.
10385 ** </ul>
10387 ** This function is used to find which columns comprise the PRIMARY KEY of
10388 ** the table modified by the change that iterator pIter currently points to.
10389 ** If successful, *pabPK is set to point to an array of nCol entries, where
10390 ** nCol is the number of columns in the table. Elements of *pabPK are set to
10391 ** 0x01 if the corresponding column is part of the tables primary key, or
10392 ** 0x00 if it is not.
10394 ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
10395 ** in the table.
10397 ** If this function is called when the iterator does not point to a valid
10398 ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
10399 ** SQLITE_OK is returned and the output variables populated as described
10400 ** above.
10402 SQLITE_API int sqlite3changeset_pk(
10403 sqlite3_changeset_iter *pIter, /* Iterator object */
10404 unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
10405 int *pnCol /* OUT: Number of entries in output array */
10409 ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
10411 ** The pIter argument passed to this function may either be an iterator
10412 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
10413 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
10414 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
10415 ** Furthermore, it may only be called if the type of change that the iterator
10416 ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
10417 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
10419 ** Argument iVal must be greater than or equal to 0, and less than the number
10420 ** of columns in the table affected by the current change. Otherwise,
10421 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
10423 ** If successful, this function sets *ppValue to point to a protected
10424 ** sqlite3_value object containing the iVal'th value from the vector of
10425 ** original row values stored as part of the UPDATE or DELETE change and
10426 ** returns SQLITE_OK. The name of the function comes from the fact that this
10427 ** is similar to the "old.*" columns available to update or delete triggers.
10429 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
10430 ** is returned and *ppValue is set to NULL.
10432 SQLITE_API int sqlite3changeset_old(
10433 sqlite3_changeset_iter *pIter, /* Changeset iterator */
10434 int iVal, /* Column number */
10435 sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
10439 ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
10441 ** The pIter argument passed to this function may either be an iterator
10442 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
10443 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
10444 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
10445 ** Furthermore, it may only be called if the type of change that the iterator
10446 ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
10447 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
10449 ** Argument iVal must be greater than or equal to 0, and less than the number
10450 ** of columns in the table affected by the current change. Otherwise,
10451 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
10453 ** If successful, this function sets *ppValue to point to a protected
10454 ** sqlite3_value object containing the iVal'th value from the vector of
10455 ** new row values stored as part of the UPDATE or INSERT change and
10456 ** returns SQLITE_OK. If the change is an UPDATE and does not include
10457 ** a new value for the requested column, *ppValue is set to NULL and
10458 ** SQLITE_OK returned. The name of the function comes from the fact that
10459 ** this is similar to the "new.*" columns available to update or delete
10460 ** triggers.
10462 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
10463 ** is returned and *ppValue is set to NULL.
10465 SQLITE_API int sqlite3changeset_new(
10466 sqlite3_changeset_iter *pIter, /* Changeset iterator */
10467 int iVal, /* Column number */
10468 sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
10472 ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
10474 ** This function should only be used with iterator objects passed to a
10475 ** conflict-handler callback by [sqlite3changeset_apply()] with either
10476 ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
10477 ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
10478 ** is set to NULL.
10480 ** Argument iVal must be greater than or equal to 0, and less than the number
10481 ** of columns in the table affected by the current change. Otherwise,
10482 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
10484 ** If successful, this function sets *ppValue to point to a protected
10485 ** sqlite3_value object containing the iVal'th value from the
10486 ** "conflicting row" associated with the current conflict-handler callback
10487 ** and returns SQLITE_OK.
10489 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
10490 ** is returned and *ppValue is set to NULL.
10492 SQLITE_API int sqlite3changeset_conflict(
10493 sqlite3_changeset_iter *pIter, /* Changeset iterator */
10494 int iVal, /* Column number */
10495 sqlite3_value **ppValue /* OUT: Value from conflicting row */
10499 ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
10501 ** This function may only be called with an iterator passed to an
10502 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
10503 ** it sets the output variable to the total number of known foreign key
10504 ** violations in the destination database and returns SQLITE_OK.
10506 ** In all other cases this function returns SQLITE_MISUSE.
10508 SQLITE_API int sqlite3changeset_fk_conflicts(
10509 sqlite3_changeset_iter *pIter, /* Changeset iterator */
10510 int *pnOut /* OUT: Number of FK violations */
10515 ** CAPI3REF: Finalize A Changeset Iterator
10517 ** This function is used to finalize an iterator allocated with
10518 ** [sqlite3changeset_start()].
10520 ** This function should only be called on iterators created using the
10521 ** [sqlite3changeset_start()] function. If an application calls this
10522 ** function with an iterator passed to a conflict-handler by
10523 ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
10524 ** call has no effect.
10526 ** If an error was encountered within a call to an sqlite3changeset_xxx()
10527 ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
10528 ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
10529 ** to that error is returned by this function. Otherwise, SQLITE_OK is
10530 ** returned. This is to allow the following pattern (pseudo-code):
10532 ** sqlite3changeset_start();
10533 ** while( SQLITE_ROW==sqlite3changeset_next() ){
10534 ** // Do something with change.
10535 ** }
10536 ** rc = sqlite3changeset_finalize();
10537 ** if( rc!=SQLITE_OK ){
10538 ** // An error has occurred
10539 ** }
10541 SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
10544 ** CAPI3REF: Invert A Changeset
10546 ** This function is used to "invert" a changeset object. Applying an inverted
10547 ** changeset to a database reverses the effects of applying the uninverted
10548 ** changeset. Specifically:
10550 ** <ul>
10551 ** <li> Each DELETE change is changed to an INSERT, and
10552 ** <li> Each INSERT change is changed to a DELETE, and
10553 ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
10554 ** </ul>
10556 ** This function does not change the order in which changes appear within
10557 ** the changeset. It merely reverses the sense of each individual change.
10559 ** If successful, a pointer to a buffer containing the inverted changeset
10560 ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
10561 ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
10562 ** zeroed and an SQLite error code returned.
10564 ** It is the responsibility of the caller to eventually call sqlite3_free()
10565 ** on the *ppOut pointer to free the buffer allocation following a successful
10566 ** call to this function.
10568 ** WARNING/TODO: This function currently assumes that the input is a valid
10569 ** changeset. If it is not, the results are undefined.
10571 SQLITE_API int sqlite3changeset_invert(
10572 int nIn, const void *pIn, /* Input changeset */
10573 int *pnOut, void **ppOut /* OUT: Inverse of input */
10577 ** CAPI3REF: Concatenate Two Changeset Objects
10579 ** This function is used to concatenate two changesets, A and B, into a
10580 ** single changeset. The result is a changeset equivalent to applying
10581 ** changeset A followed by changeset B.
10583 ** This function combines the two input changesets using an
10584 ** sqlite3_changegroup object. Calling it produces similar results as the
10585 ** following code fragment:
10587 ** sqlite3_changegroup *pGrp;
10588 ** rc = sqlite3_changegroup_new(&pGrp);
10589 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
10590 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
10591 ** if( rc==SQLITE_OK ){
10592 ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
10593 ** }else{
10594 ** *ppOut = 0;
10595 ** *pnOut = 0;
10596 ** }
10598 ** Refer to the sqlite3_changegroup documentation below for details.
10600 SQLITE_API int sqlite3changeset_concat(
10601 int nA, /* Number of bytes in buffer pA */
10602 void *pA, /* Pointer to buffer containing changeset A */
10603 int nB, /* Number of bytes in buffer pB */
10604 void *pB, /* Pointer to buffer containing changeset B */
10605 int *pnOut, /* OUT: Number of bytes in output changeset */
10606 void **ppOut /* OUT: Buffer containing output changeset */
10611 ** CAPI3REF: Changegroup Handle
10613 typedef struct sqlite3_changegroup sqlite3_changegroup;
10616 ** CAPI3REF: Create A New Changegroup Object
10618 ** An sqlite3_changegroup object is used to combine two or more changesets
10619 ** (or patchsets) into a single changeset (or patchset). A single changegroup
10620 ** object may combine changesets or patchsets, but not both. The output is
10621 ** always in the same format as the input.
10623 ** If successful, this function returns SQLITE_OK and populates (*pp) with
10624 ** a pointer to a new sqlite3_changegroup object before returning. The caller
10625 ** should eventually free the returned object using a call to
10626 ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
10627 ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
10629 ** The usual usage pattern for an sqlite3_changegroup object is as follows:
10631 ** <ul>
10632 ** <li> It is created using a call to sqlite3changegroup_new().
10634 ** <li> Zero or more changesets (or patchsets) are added to the object
10635 ** by calling sqlite3changegroup_add().
10637 ** <li> The result of combining all input changesets together is obtained
10638 ** by the application via a call to sqlite3changegroup_output().
10640 ** <li> The object is deleted using a call to sqlite3changegroup_delete().
10641 ** </ul>
10643 ** Any number of calls to add() and output() may be made between the calls to
10644 ** new() and delete(), and in any order.
10646 ** As well as the regular sqlite3changegroup_add() and
10647 ** sqlite3changegroup_output() functions, also available are the streaming
10648 ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
10650 SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
10653 ** CAPI3REF: Add A Changeset To A Changegroup
10655 ** Add all changes within the changeset (or patchset) in buffer pData (size
10656 ** nData bytes) to the changegroup.
10658 ** If the buffer contains a patchset, then all prior calls to this function
10659 ** on the same changegroup object must also have specified patchsets. Or, if
10660 ** the buffer contains a changeset, so must have the earlier calls to this
10661 ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
10662 ** to the changegroup.
10664 ** Rows within the changeset and changegroup are identified by the values in
10665 ** their PRIMARY KEY columns. A change in the changeset is considered to
10666 ** apply to the same row as a change already present in the changegroup if
10667 ** the two rows have the same primary key.
10669 ** Changes to rows that do not already appear in the changegroup are
10670 ** simply copied into it. Or, if both the new changeset and the changegroup
10671 ** contain changes that apply to a single row, the final contents of the
10672 ** changegroup depends on the type of each change, as follows:
10674 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
10675 ** <tr><th style="white-space:pre">Existing Change </th>
10676 ** <th style="white-space:pre">New Change </th>
10677 ** <th>Output Change
10678 ** <tr><td>INSERT <td>INSERT <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>INSERT <td>UPDATE <td>
10683 ** The INSERT change remains in the changegroup. The values in the
10684 ** INSERT change are modified as if the row was inserted by the
10685 ** existing change and then updated according to the new change.
10686 ** <tr><td>INSERT <td>DELETE <td>
10687 ** The existing INSERT is removed from the changegroup. The DELETE is
10688 ** not added.
10689 ** <tr><td>UPDATE <td>INSERT <td>
10690 ** The new change is ignored. This case does not occur if the new
10691 ** changeset was recorded immediately after the changesets already
10692 ** added to the changegroup.
10693 ** <tr><td>UPDATE <td>UPDATE <td>
10694 ** The existing UPDATE remains within the changegroup. It is amended
10695 ** so that the accompanying values are as if the row was updated once
10696 ** by the existing change and then again by the new change.
10697 ** <tr><td>UPDATE <td>DELETE <td>
10698 ** The existing UPDATE is replaced by the new DELETE within the
10699 ** changegroup.
10700 ** <tr><td>DELETE <td>INSERT <td>
10701 ** If one or more of the column values in the row inserted by the
10702 ** new change differ from those in the row deleted by the existing
10703 ** change, the existing DELETE is replaced by an UPDATE within the
10704 ** changegroup. Otherwise, if the inserted row is exactly the same
10705 ** as the deleted row, the existing DELETE is simply discarded.
10706 ** <tr><td>DELETE <td>UPDATE <td>
10707 ** The new change is ignored. This case does not occur if the new
10708 ** changeset was recorded immediately after the changesets already
10709 ** added to the changegroup.
10710 ** <tr><td>DELETE <td>DELETE <td>
10711 ** The new change is ignored. This case does not occur if the new
10712 ** changeset was recorded immediately after the changesets already
10713 ** added to the changegroup.
10714 ** </table>
10716 ** If the new changeset contains changes to a table that is already present
10717 ** in the changegroup, then the number of columns and the position of the
10718 ** primary key columns for the table must be consistent. If this is not the
10719 ** case, this function fails with SQLITE_SCHEMA. If the input changeset
10720 ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
10721 ** returned. Or, if an out-of-memory condition occurs during processing, this
10722 ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
10723 ** final contents of the changegroup is undefined.
10725 ** If no error occurs, SQLITE_OK is returned.
10727 SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
10730 ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
10732 ** Obtain a buffer containing a changeset (or patchset) representing the
10733 ** current contents of the changegroup. If the inputs to the changegroup
10734 ** were themselves changesets, the output is a changeset. Or, if the
10735 ** inputs were patchsets, the output is also a patchset.
10737 ** As with the output of the sqlite3session_changeset() and
10738 ** sqlite3session_patchset() functions, all changes related to a single
10739 ** table are grouped together in the output of this function. Tables appear
10740 ** in the same order as for the very first changeset added to the changegroup.
10741 ** If the second or subsequent changesets added to the changegroup contain
10742 ** changes for tables that do not appear in the first changeset, they are
10743 ** appended onto the end of the output changeset, again in the order in
10744 ** which they are first encountered.
10746 ** If an error occurs, an SQLite error code is returned and the output
10747 ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
10748 ** is returned and the output variables are set to the size of and a
10749 ** pointer to the output buffer, respectively. In this case it is the
10750 ** responsibility of the caller to eventually free the buffer using a
10751 ** call to sqlite3_free().
10753 SQLITE_API int sqlite3changegroup_output(
10754 sqlite3_changegroup*,
10755 int *pnData, /* OUT: Size of output buffer in bytes */
10756 void **ppData /* OUT: Pointer to output buffer */
10760 ** CAPI3REF: Delete A Changegroup Object
10762 SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
10765 ** CAPI3REF: Apply A Changeset To A Database
10767 ** Apply a changeset to a database. This function attempts to update the
10768 ** "main" database attached to handle db with the changes found in the
10769 ** changeset passed via the second and third arguments.
10771 ** The fourth argument (xFilter) passed to this function is the "filter
10772 ** callback". If it is not NULL, then for each table affected by at least one
10773 ** change in the changeset, the filter callback is invoked with
10774 ** the table name as the second argument, and a copy of the context pointer
10775 ** passed as the sixth argument to this function as the first. If the "filter
10776 ** callback" returns zero, then no attempt is made to apply any changes to
10777 ** the table. Otherwise, if the return value is non-zero or the xFilter
10778 ** argument to this function is NULL, all changes related to the table are
10779 ** attempted.
10781 ** For each table that is not excluded by the filter callback, this function
10782 ** tests that the target database contains a compatible table. A table is
10783 ** considered compatible if all of the following are true:
10785 ** <ul>
10786 ** <li> The table has the same name as the name recorded in the
10787 ** changeset, and
10788 ** <li> The table has at least as many columns as recorded in the
10789 ** changeset, and
10790 ** <li> The table has primary key columns in the same position as
10791 ** recorded in the changeset.
10792 ** </ul>
10794 ** If there is no compatible table, it is not an error, but none of the
10795 ** changes associated with the table are applied. A warning message is issued
10796 ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
10797 ** one such warning is issued for each table in the changeset.
10799 ** For each change for which there is a compatible table, an attempt is made
10800 ** to modify the table contents according to the UPDATE, INSERT or DELETE
10801 ** change. If a change cannot be applied cleanly, the conflict handler
10802 ** function passed as the fifth argument to sqlite3changeset_apply() may be
10803 ** invoked. A description of exactly when the conflict handler is invoked for
10804 ** each type of change is below.
10806 ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
10807 ** of passing anything other than a valid function pointer as the xConflict
10808 ** argument are undefined.
10810 ** Each time the conflict handler function is invoked, it must return one
10811 ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
10812 ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
10813 ** if the second argument passed to the conflict handler is either
10814 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
10815 ** returns an illegal value, any changes already made are rolled back and
10816 ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
10817 ** actions are taken by sqlite3changeset_apply() depending on the value
10818 ** returned by each invocation of the conflict-handler function. Refer to
10819 ** the documentation for the three
10820 ** [SQLITE_CHANGESET_OMIT|available return values] for details.
10822 ** <dl>
10823 ** <dt>DELETE Changes<dd>
10824 ** For each DELETE change, this function checks if the target database
10825 ** contains a row with the same primary key value (or values) as the
10826 ** original row values stored in the changeset. If it does, and the values
10827 ** stored in all non-primary key columns also match the values stored in
10828 ** the changeset the row is deleted from the target database.
10830 ** If a row with matching primary key values is found, but one or more of
10831 ** the non-primary key fields contains a value different from the original
10832 ** row value stored in the changeset, the conflict-handler function is
10833 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
10834 ** database table has more columns than are recorded in the changeset,
10835 ** only the values of those non-primary key fields are compared against
10836 ** the current database contents - any trailing database table columns
10837 ** are ignored.
10839 ** If no row with matching primary key values is found in the database,
10840 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
10841 ** passed as the second argument.
10843 ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
10844 ** (which can only happen if a foreign key constraint is violated), the
10845 ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
10846 ** passed as the second argument. This includes the case where the DELETE
10847 ** operation is attempted because an earlier call to the conflict handler
10848 ** function returned [SQLITE_CHANGESET_REPLACE].
10850 ** <dt>INSERT Changes<dd>
10851 ** For each INSERT change, an attempt is made to insert the new row into
10852 ** the database. If the changeset row contains fewer fields than the
10853 ** database table, the trailing fields are populated with their default
10854 ** values.
10856 ** If the attempt to insert the row fails because the database already
10857 ** contains a row with the same primary key values, the conflict handler
10858 ** function is invoked with the second argument set to
10859 ** [SQLITE_CHANGESET_CONFLICT].
10861 ** If the attempt to insert the row fails because of some other constraint
10862 ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
10863 ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
10864 ** This includes the case where the INSERT operation is re-attempted because
10865 ** an earlier call to the conflict handler function returned
10866 ** [SQLITE_CHANGESET_REPLACE].
10868 ** <dt>UPDATE Changes<dd>
10869 ** For each UPDATE change, this function checks if the target database
10870 ** contains a row with the same primary key value (or values) as the
10871 ** original row values stored in the changeset. If it does, and the values
10872 ** stored in all modified non-primary key columns also match the values
10873 ** stored in the changeset the row is updated within the target database.
10875 ** If a row with matching primary key values is found, but one or more of
10876 ** the modified non-primary key fields contains a value different from an
10877 ** original row value stored in the changeset, the conflict-handler function
10878 ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
10879 ** UPDATE changes only contain values for non-primary key fields that are
10880 ** to be modified, only those fields need to match the original values to
10881 ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
10883 ** If no row with matching primary key values is found in the database,
10884 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
10885 ** passed as the second argument.
10887 ** If the UPDATE operation is attempted, but SQLite returns
10888 ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
10889 ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
10890 ** This includes the case where the UPDATE operation is attempted after
10891 ** an earlier call to the conflict handler function returned
10892 ** [SQLITE_CHANGESET_REPLACE].
10893 ** </dl>
10895 ** It is safe to execute SQL statements, including those that write to the
10896 ** table that the callback related to, from within the xConflict callback.
10897 ** This can be used to further customize the applications conflict
10898 ** resolution strategy.
10900 ** All changes made by this function are enclosed in a savepoint transaction.
10901 ** If any other error (aside from a constraint failure when attempting to
10902 ** write to the target database) occurs, then the savepoint transaction is
10903 ** rolled back, restoring the target database to its original state, and an
10904 ** SQLite error code returned.
10906 SQLITE_API int sqlite3changeset_apply(
10907 sqlite3 *db, /* Apply change to "main" db of this handle */
10908 int nChangeset, /* Size of changeset in bytes */
10909 void *pChangeset, /* Changeset blob */
10910 int(*xFilter)(
10911 void *pCtx, /* Copy of sixth arg to _apply() */
10912 const char *zTab /* Table name */
10914 int(*xConflict)(
10915 void *pCtx, /* Copy of sixth arg to _apply() */
10916 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
10917 sqlite3_changeset_iter *p /* Handle describing change and conflict */
10919 void *pCtx /* First argument passed to xConflict */
10923 ** CAPI3REF: Constants Passed To The Conflict Handler
10925 ** Values that may be passed as the second argument to a conflict-handler.
10927 ** <dl>
10928 ** <dt>SQLITE_CHANGESET_DATA<dd>
10929 ** The conflict handler is invoked with CHANGESET_DATA as the second argument
10930 ** when processing a DELETE or UPDATE change if a row with the required
10931 ** PRIMARY KEY fields is present in the database, but one or more other
10932 ** (non primary-key) fields modified by the update do not contain the
10933 ** expected "before" values.
10935 ** The conflicting row, in this case, is the database row with the matching
10936 ** primary key.
10938 ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
10939 ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
10940 ** argument when processing a DELETE or UPDATE change if a row with the
10941 ** required PRIMARY KEY fields is not present in the database.
10943 ** There is no conflicting row in this case. The results of invoking the
10944 ** sqlite3changeset_conflict() API are undefined.
10946 ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
10947 ** CHANGESET_CONFLICT is passed as the second argument to the conflict
10948 ** handler while processing an INSERT change if the operation would result
10949 ** in duplicate primary key values.
10951 ** The conflicting row in this case is the database row with the matching
10952 ** primary key.
10954 ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
10955 ** If foreign key handling is enabled, and applying a changeset leaves the
10956 ** database in a state containing foreign key violations, the conflict
10957 ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
10958 ** exactly once before the changeset is committed. If the conflict handler
10959 ** returns CHANGESET_OMIT, the changes, including those that caused the
10960 ** foreign key constraint violation, are committed. Or, if it returns
10961 ** CHANGESET_ABORT, the changeset is rolled back.
10963 ** No current or conflicting row information is provided. The only function
10964 ** it is possible to call on the supplied sqlite3_changeset_iter handle
10965 ** is sqlite3changeset_fk_conflicts().
10967 ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
10968 ** If any other constraint violation occurs while applying a change (i.e.
10969 ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
10970 ** invoked with CHANGESET_CONSTRAINT as the second argument.
10972 ** There is no conflicting row in this case. The results of invoking the
10973 ** sqlite3changeset_conflict() API are undefined.
10975 ** </dl>
10977 #define SQLITE_CHANGESET_DATA 1
10978 #define SQLITE_CHANGESET_NOTFOUND 2
10979 #define SQLITE_CHANGESET_CONFLICT 3
10980 #define SQLITE_CHANGESET_CONSTRAINT 4
10981 #define SQLITE_CHANGESET_FOREIGN_KEY 5
10984 ** CAPI3REF: Constants Returned By The Conflict Handler
10986 ** A conflict handler callback must return one of the following three values.
10988 ** <dl>
10989 ** <dt>SQLITE_CHANGESET_OMIT<dd>
10990 ** If a conflict handler returns this value no special action is taken. The
10991 ** change that caused the conflict is not applied. The session module
10992 ** continues to the next change in the changeset.
10994 ** <dt>SQLITE_CHANGESET_REPLACE<dd>
10995 ** This value may only be returned if the second argument to the conflict
10996 ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
10997 ** is not the case, any changes applied so far are rolled back and the
10998 ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
11000 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
11001 ** handler, then the conflicting row is either updated or deleted, depending
11002 ** on the type of change.
11004 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
11005 ** handler, then the conflicting row is removed from the database and a
11006 ** second attempt to apply the change is made. If this second attempt fails,
11007 ** the original row is restored to the database before continuing.
11009 ** <dt>SQLITE_CHANGESET_ABORT<dd>
11010 ** If this value is returned, any changes applied so far are rolled back
11011 ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
11012 ** </dl>
11014 #define SQLITE_CHANGESET_OMIT 0
11015 #define SQLITE_CHANGESET_REPLACE 1
11016 #define SQLITE_CHANGESET_ABORT 2
11019 ** CAPI3REF: Streaming Versions of API functions.
11021 ** The six streaming API xxx_strm() functions serve similar purposes to the
11022 ** corresponding non-streaming API functions:
11024 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
11025 ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
11026 ** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
11027 ** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
11028 ** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
11029 ** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
11030 ** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
11031 ** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
11032 ** </table>
11034 ** Non-streaming functions that accept changesets (or patchsets) as input
11035 ** require that the entire changeset be stored in a single buffer in memory.
11036 ** Similarly, those that return a changeset or patchset do so by returning
11037 ** a pointer to a single large buffer allocated using sqlite3_malloc().
11038 ** Normally this is convenient. However, if an application running in a
11039 ** low-memory environment is required to handle very large changesets, the
11040 ** large contiguous memory allocations required can become onerous.
11042 ** In order to avoid this problem, instead of a single large buffer, input
11043 ** is passed to a streaming API functions by way of a callback function that
11044 ** the sessions module invokes to incrementally request input data as it is
11045 ** required. In all cases, a pair of API function parameters such as
11047 ** <pre>
11048 ** &nbsp; int nChangeset,
11049 ** &nbsp; void *pChangeset,
11050 ** </pre>
11052 ** Is replaced by:
11054 ** <pre>
11055 ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
11056 ** &nbsp; void *pIn,
11057 ** </pre>
11059 ** Each time the xInput callback is invoked by the sessions module, the first
11060 ** argument passed is a copy of the supplied pIn context pointer. The second
11061 ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
11062 ** error occurs the xInput method should copy up to (*pnData) bytes of data
11063 ** into the buffer and set (*pnData) to the actual number of bytes copied
11064 ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
11065 ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
11066 ** error code should be returned. In all cases, if an xInput callback returns
11067 ** an error, all processing is abandoned and the streaming API function
11068 ** returns a copy of the error code to the caller.
11070 ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
11071 ** invoked by the sessions module at any point during the lifetime of the
11072 ** iterator. If such an xInput callback returns an error, the iterator enters
11073 ** an error state, whereby all subsequent calls to iterator functions
11074 ** immediately fail with the same error code as returned by xInput.
11076 ** Similarly, streaming API functions that return changesets (or patchsets)
11077 ** return them in chunks by way of a callback function instead of via a
11078 ** pointer to a single large buffer. In this case, a pair of parameters such
11079 ** as:
11081 ** <pre>
11082 ** &nbsp; int *pnChangeset,
11083 ** &nbsp; void **ppChangeset,
11084 ** </pre>
11086 ** Is replaced by:
11088 ** <pre>
11089 ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
11090 ** &nbsp; void *pOut
11091 ** </pre>
11093 ** The xOutput callback is invoked zero or more times to return data to
11094 ** the application. The first parameter passed to each call is a copy of the
11095 ** pOut pointer supplied by the application. The second parameter, pData,
11096 ** points to a buffer nData bytes in size containing the chunk of output
11097 ** data being returned. If the xOutput callback successfully processes the
11098 ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
11099 ** it should return some other SQLite error code. In this case processing
11100 ** is immediately abandoned and the streaming API function returns a copy
11101 ** of the xOutput error code to the application.
11103 ** The sessions module never invokes an xOutput callback with the third
11104 ** parameter set to a value less than or equal to zero. Other than this,
11105 ** no guarantees are made as to the size of the chunks of data returned.
11107 SQLITE_API int sqlite3changeset_apply_strm(
11108 sqlite3 *db, /* Apply change to "main" db of this handle */
11109 int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
11110 void *pIn, /* First arg for xInput */
11111 int(*xFilter)(
11112 void *pCtx, /* Copy of sixth arg to _apply() */
11113 const char *zTab /* Table name */
11115 int(*xConflict)(
11116 void *pCtx, /* Copy of sixth arg to _apply() */
11117 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
11118 sqlite3_changeset_iter *p /* Handle describing change and conflict */
11120 void *pCtx /* First argument passed to xConflict */
11122 SQLITE_API int sqlite3changeset_concat_strm(
11123 int (*xInputA)(void *pIn, void *pData, int *pnData),
11124 void *pInA,
11125 int (*xInputB)(void *pIn, void *pData, int *pnData),
11126 void *pInB,
11127 int (*xOutput)(void *pOut, const void *pData, int nData),
11128 void *pOut
11130 SQLITE_API int sqlite3changeset_invert_strm(
11131 int (*xInput)(void *pIn, void *pData, int *pnData),
11132 void *pIn,
11133 int (*xOutput)(void *pOut, const void *pData, int nData),
11134 void *pOut
11136 SQLITE_API int sqlite3changeset_start_strm(
11137 sqlite3_changeset_iter **pp,
11138 int (*xInput)(void *pIn, void *pData, int *pnData),
11139 void *pIn
11141 SQLITE_API int sqlite3session_changeset_strm(
11142 sqlite3_session *pSession,
11143 int (*xOutput)(void *pOut, const void *pData, int nData),
11144 void *pOut
11146 SQLITE_API int sqlite3session_patchset_strm(
11147 sqlite3_session *pSession,
11148 int (*xOutput)(void *pOut, const void *pData, int nData),
11149 void *pOut
11151 SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
11152 int (*xInput)(void *pIn, void *pData, int *pnData),
11153 void *pIn
11155 SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
11156 int (*xOutput)(void *pOut, const void *pData, int nData),
11157 void *pOut
11162 ** Make sure we can call this stuff from C++.
11164 #if 0
11166 #endif
11168 #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
11170 /******** End of sqlite3session.h *********/
11171 /******** Begin file fts5.h *********/
11173 ** 2014 May 31
11175 ** The author disclaims copyright to this source code. In place of
11176 ** a legal notice, here is a blessing:
11178 ** May you do good and not evil.
11179 ** May you find forgiveness for yourself and forgive others.
11180 ** May you share freely, never taking more than you give.
11182 ******************************************************************************
11184 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
11185 ** FTS5 may be extended with:
11187 ** * custom tokenizers, and
11188 ** * custom auxiliary functions.
11192 #ifndef _FTS5_H
11193 #define _FTS5_H
11196 #if 0
11197 extern "C" {
11198 #endif
11200 /*************************************************************************
11201 ** CUSTOM AUXILIARY FUNCTIONS
11203 ** Virtual table implementations may overload SQL functions by implementing
11204 ** the sqlite3_module.xFindFunction() method.
11207 typedef struct Fts5ExtensionApi Fts5ExtensionApi;
11208 typedef struct Fts5Context Fts5Context;
11209 typedef struct Fts5PhraseIter Fts5PhraseIter;
11211 typedef void (*fts5_extension_function)(
11212 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
11213 Fts5Context *pFts, /* First arg to pass to pApi functions */
11214 sqlite3_context *pCtx, /* Context for returning result/error */
11215 int nVal, /* Number of values in apVal[] array */
11216 sqlite3_value **apVal /* Array of trailing arguments */
11219 struct Fts5PhraseIter {
11220 const unsigned char *a;
11221 const unsigned char *b;
11225 ** EXTENSION API FUNCTIONS
11227 ** xUserData(pFts):
11228 ** Return a copy of the context pointer the extension function was
11229 ** registered with.
11231 ** xColumnTotalSize(pFts, iCol, pnToken):
11232 ** If parameter iCol is less than zero, set output variable *pnToken
11233 ** to the total number of tokens in the FTS5 table. Or, if iCol is
11234 ** non-negative but less than the number of columns in the table, return
11235 ** the total number of tokens in column iCol, considering all rows in
11236 ** the FTS5 table.
11238 ** If parameter iCol is greater than or equal to the number of columns
11239 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
11240 ** an OOM condition or IO error), an appropriate SQLite error code is
11241 ** returned.
11243 ** xColumnCount(pFts):
11244 ** Return the number of columns in the table.
11246 ** xColumnSize(pFts, iCol, pnToken):
11247 ** If parameter iCol is less than zero, set output variable *pnToken
11248 ** to the total number of tokens in the current row. Or, if iCol is
11249 ** non-negative but less than the number of columns in the table, set
11250 ** *pnToken to the number of tokens in column iCol of the current row.
11252 ** If parameter iCol is greater than or equal to the number of columns
11253 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
11254 ** an OOM condition or IO error), an appropriate SQLite error code is
11255 ** returned.
11257 ** This function may be quite inefficient if used with an FTS5 table
11258 ** created with the "columnsize=0" option.
11260 ** xColumnText:
11261 ** This function attempts to retrieve the text of column iCol of the
11262 ** current document. If successful, (*pz) is set to point to a buffer
11263 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
11264 ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
11265 ** if an error occurs, an SQLite error code is returned and the final values
11266 ** of (*pz) and (*pn) are undefined.
11268 ** xPhraseCount:
11269 ** Returns the number of phrases in the current query expression.
11271 ** xPhraseSize:
11272 ** Returns the number of tokens in phrase iPhrase of the query. Phrases
11273 ** are numbered starting from zero.
11275 ** xInstCount:
11276 ** Set *pnInst to the total number of occurrences of all phrases within
11277 ** the query within the current row. Return SQLITE_OK if successful, or
11278 ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
11280 ** This API can be quite slow if used with an FTS5 table created with the
11281 ** "detail=none" or "detail=column" option. If the FTS5 table is created
11282 ** with either "detail=none" or "detail=column" and "content=" option
11283 ** (i.e. if it is a contentless table), then this API always returns 0.
11285 ** xInst:
11286 ** Query for the details of phrase match iIdx within the current row.
11287 ** Phrase matches are numbered starting from zero, so the iIdx argument
11288 ** should be greater than or equal to zero and smaller than the value
11289 ** output by xInstCount().
11291 ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
11292 ** to the column in which it occurs and *piOff the token offset of the
11293 ** first token of the phrase. The exception is if the table was created
11294 ** with the offsets=0 option specified. In this case *piOff is always
11295 ** set to -1.
11297 ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
11298 ** if an error occurs.
11300 ** This API can be quite slow if used with an FTS5 table created with the
11301 ** "detail=none" or "detail=column" option.
11303 ** xRowid:
11304 ** Returns the rowid of the current row.
11306 ** xTokenize:
11307 ** Tokenize text using the tokenizer belonging to the FTS5 table.
11309 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
11310 ** This API function is used to query the FTS table for phrase iPhrase
11311 ** of the current query. Specifically, a query equivalent to:
11313 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
11315 ** with $p set to a phrase equivalent to the phrase iPhrase of the
11316 ** current query is executed. Any column filter that applies to
11317 ** phrase iPhrase of the current query is included in $p. For each
11318 ** row visited, the callback function passed as the fourth argument
11319 ** is invoked. The context and API objects passed to the callback
11320 ** function may be used to access the properties of each matched row.
11321 ** Invoking Api.xUserData() returns a copy of the pointer passed as
11322 ** the third argument to pUserData.
11324 ** If the callback function returns any value other than SQLITE_OK, the
11325 ** query is abandoned and the xQueryPhrase function returns immediately.
11326 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
11327 ** Otherwise, the error code is propagated upwards.
11329 ** If the query runs to completion without incident, SQLITE_OK is returned.
11330 ** Or, if some error occurs before the query completes or is aborted by
11331 ** the callback, an SQLite error code is returned.
11334 ** xSetAuxdata(pFts5, pAux, xDelete)
11336 ** Save the pointer passed as the second argument as the extension functions
11337 ** "auxiliary data". The pointer may then be retrieved by the current or any
11338 ** future invocation of the same fts5 extension function made as part of
11339 ** of the same MATCH query using the xGetAuxdata() API.
11341 ** Each extension function is allocated a single auxiliary data slot for
11342 ** each FTS query (MATCH expression). If the extension function is invoked
11343 ** more than once for a single FTS query, then all invocations share a
11344 ** single auxiliary data context.
11346 ** If there is already an auxiliary data pointer when this function is
11347 ** invoked, then it is replaced by the new pointer. If an xDelete callback
11348 ** was specified along with the original pointer, it is invoked at this
11349 ** point.
11351 ** The xDelete callback, if one is specified, is also invoked on the
11352 ** auxiliary data pointer after the FTS5 query has finished.
11354 ** If an error (e.g. an OOM condition) occurs within this function, an
11355 ** the auxiliary data is set to NULL and an error code returned. If the
11356 ** xDelete parameter was not NULL, it is invoked on the auxiliary data
11357 ** pointer before returning.
11360 ** xGetAuxdata(pFts5, bClear)
11362 ** Returns the current auxiliary data pointer for the fts5 extension
11363 ** function. See the xSetAuxdata() method for details.
11365 ** If the bClear argument is non-zero, then the auxiliary data is cleared
11366 ** (set to NULL) before this function returns. In this case the xDelete,
11367 ** if any, is not invoked.
11370 ** xRowCount(pFts5, pnRow)
11372 ** This function is used to retrieve the total number of rows in the table.
11373 ** In other words, the same value that would be returned by:
11375 ** SELECT count(*) FROM ftstable;
11377 ** xPhraseFirst()
11378 ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
11379 ** method, to iterate through all instances of a single query phrase within
11380 ** the current row. This is the same information as is accessible via the
11381 ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
11382 ** to use, this API may be faster under some circumstances. To iterate
11383 ** through instances of phrase iPhrase, use the following code:
11385 ** Fts5PhraseIter iter;
11386 ** int iCol, iOff;
11387 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
11388 ** iCol>=0;
11389 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
11390 ** ){
11391 ** // An instance of phrase iPhrase at offset iOff of column iCol
11392 ** }
11394 ** The Fts5PhraseIter structure is defined above. Applications should not
11395 ** modify this structure directly - it should only be used as shown above
11396 ** with the xPhraseFirst() and xPhraseNext() API methods (and by
11397 ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
11399 ** This API can be quite slow if used with an FTS5 table created with the
11400 ** "detail=none" or "detail=column" option. If the FTS5 table is created
11401 ** with either "detail=none" or "detail=column" and "content=" option
11402 ** (i.e. if it is a contentless table), then this API always iterates
11403 ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
11405 ** xPhraseNext()
11406 ** See xPhraseFirst above.
11408 ** xPhraseFirstColumn()
11409 ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
11410 ** and xPhraseNext() APIs described above. The difference is that instead
11411 ** of iterating through all instances of a phrase in the current row, these
11412 ** APIs are used to iterate through the set of columns in the current row
11413 ** that contain one or more instances of a specified phrase. For example:
11415 ** Fts5PhraseIter iter;
11416 ** int iCol;
11417 ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
11418 ** iCol>=0;
11419 ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
11420 ** ){
11421 ** // Column iCol contains at least one instance of phrase iPhrase
11422 ** }
11424 ** This API can be quite slow if used with an FTS5 table created with the
11425 ** "detail=none" option. If the FTS5 table is created with either
11426 ** "detail=none" "content=" option (i.e. if it is a contentless table),
11427 ** then this API always iterates through an empty set (all calls to
11428 ** xPhraseFirstColumn() set iCol to -1).
11430 ** The information accessed using this API and its companion
11431 ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
11432 ** (or xInst/xInstCount). The chief advantage of this API is that it is
11433 ** significantly more efficient than those alternatives when used with
11434 ** "detail=column" tables.
11436 ** xPhraseNextColumn()
11437 ** See xPhraseFirstColumn above.
11439 struct Fts5ExtensionApi {
11440 int iVersion; /* Currently always set to 3 */
11442 void *(*xUserData)(Fts5Context*);
11444 int (*xColumnCount)(Fts5Context*);
11445 int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
11446 int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
11448 int (*xTokenize)(Fts5Context*,
11449 const char *pText, int nText, /* Text to tokenize */
11450 void *pCtx, /* Context passed to xToken() */
11451 int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
11454 int (*xPhraseCount)(Fts5Context*);
11455 int (*xPhraseSize)(Fts5Context*, int iPhrase);
11457 int (*xInstCount)(Fts5Context*, int *pnInst);
11458 int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
11460 sqlite3_int64 (*xRowid)(Fts5Context*);
11461 int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
11462 int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
11464 int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
11465 int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
11467 int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
11468 void *(*xGetAuxdata)(Fts5Context*, int bClear);
11470 int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
11471 void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
11473 int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
11474 void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
11478 ** CUSTOM AUXILIARY FUNCTIONS
11479 *************************************************************************/
11481 /*************************************************************************
11482 ** CUSTOM TOKENIZERS
11484 ** Applications may also register custom tokenizer types. A tokenizer
11485 ** is registered by providing fts5 with a populated instance of the
11486 ** following structure. All structure methods must be defined, setting
11487 ** any member of the fts5_tokenizer struct to NULL leads to undefined
11488 ** behaviour. The structure methods are expected to function as follows:
11490 ** xCreate:
11491 ** This function is used to allocate and initialize a tokenizer instance.
11492 ** A tokenizer instance is required to actually tokenize text.
11494 ** The first argument passed to this function is a copy of the (void*)
11495 ** pointer provided by the application when the fts5_tokenizer object
11496 ** was registered with FTS5 (the third argument to xCreateTokenizer()).
11497 ** The second and third arguments are an array of nul-terminated strings
11498 ** containing the tokenizer arguments, if any, specified following the
11499 ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
11500 ** to create the FTS5 table.
11502 ** The final argument is an output variable. If successful, (*ppOut)
11503 ** should be set to point to the new tokenizer handle and SQLITE_OK
11504 ** returned. If an error occurs, some value other than SQLITE_OK should
11505 ** be returned. In this case, fts5 assumes that the final value of *ppOut
11506 ** is undefined.
11508 ** xDelete:
11509 ** This function is invoked to delete a tokenizer handle previously
11510 ** allocated using xCreate(). Fts5 guarantees that this function will
11511 ** be invoked exactly once for each successful call to xCreate().
11513 ** xTokenize:
11514 ** This function is expected to tokenize the nText byte string indicated
11515 ** by argument pText. pText may or may not be nul-terminated. The first
11516 ** argument passed to this function is a pointer to an Fts5Tokenizer object
11517 ** returned by an earlier call to xCreate().
11519 ** The second argument indicates the reason that FTS5 is requesting
11520 ** tokenization of the supplied text. This is always one of the following
11521 ** four values:
11523 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
11524 ** or removed from the FTS table. The tokenizer is being invoked to
11525 ** determine the set of tokens to add to (or delete from) the
11526 ** FTS index.
11528 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
11529 ** against the FTS index. The tokenizer is being called to tokenize
11530 ** a bareword or quoted string specified as part of the query.
11532 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
11533 ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
11534 ** followed by a "*" character, indicating that the last token
11535 ** returned by the tokenizer will be treated as a token prefix.
11537 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
11538 ** satisfy an fts5_api.xTokenize() request made by an auxiliary
11539 ** function. Or an fts5_api.xColumnSize() request made by the same
11540 ** on a columnsize=0 database.
11541 ** </ul>
11543 ** For each token in the input string, the supplied callback xToken() must
11544 ** be invoked. The first argument to it should be a copy of the pointer
11545 ** passed as the second argument to xTokenize(). The third and fourth
11546 ** arguments are a pointer to a buffer containing the token text, and the
11547 ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
11548 ** of the first byte of and first byte immediately following the text from
11549 ** which the token is derived within the input.
11551 ** The second argument passed to the xToken() callback ("tflags") should
11552 ** normally be set to 0. The exception is if the tokenizer supports
11553 ** synonyms. In this case see the discussion below for details.
11555 ** FTS5 assumes the xToken() callback is invoked for each token in the
11556 ** order that they occur within the input text.
11558 ** If an xToken() callback returns any value other than SQLITE_OK, then
11559 ** the tokenization should be abandoned and the xTokenize() method should
11560 ** immediately return a copy of the xToken() return value. Or, if the
11561 ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
11562 ** if an error occurs with the xTokenize() implementation itself, it
11563 ** may abandon the tokenization and return any error code other than
11564 ** SQLITE_OK or SQLITE_DONE.
11566 ** SYNONYM SUPPORT
11568 ** Custom tokenizers may also support synonyms. Consider a case in which a
11569 ** user wishes to query for a phrase such as "first place". Using the
11570 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
11571 ** of "first place" within the document set, but not alternative forms
11572 ** such as "1st place". In some applications, it would be better to match
11573 ** all instances of "first place" or "1st place" regardless of which form
11574 ** the user specified in the MATCH query text.
11576 ** There are several ways to approach this in FTS5:
11578 ** <ol><li> By mapping all synonyms to a single token. In this case, the
11579 ** In the above example, this means that the tokenizer returns the
11580 ** same token for inputs "first" and "1st". Say that token is in
11581 ** fact "first", so that when the user inserts the document "I won
11582 ** 1st place" entries are added to the index for tokens "i", "won",
11583 ** "first" and "place". If the user then queries for '1st + place',
11584 ** the tokenizer substitutes "first" for "1st" and the query works
11585 ** as expected.
11587 ** <li> By adding multiple synonyms for a single term to the FTS index.
11588 ** In this case, when tokenizing query text, the tokenizer may
11589 ** provide multiple synonyms for a single term within the document.
11590 ** FTS5 then queries the index for each synonym individually. For
11591 ** example, faced with the query:
11593 ** <codeblock>
11594 ** ... MATCH 'first place'</codeblock>
11596 ** the tokenizer offers both "1st" and "first" as synonyms for the
11597 ** first token in the MATCH query and FTS5 effectively runs a query
11598 ** similar to:
11600 ** <codeblock>
11601 ** ... MATCH '(first OR 1st) place'</codeblock>
11603 ** except that, for the purposes of auxiliary functions, the query
11604 ** still appears to contain just two phrases - "(first OR 1st)"
11605 ** being treated as a single phrase.
11607 ** <li> By adding multiple synonyms for a single term to the FTS index.
11608 ** Using this method, when tokenizing document text, the tokenizer
11609 ** provides multiple synonyms for each token. So that when a
11610 ** document such as "I won first place" is tokenized, entries are
11611 ** added to the FTS index for "i", "won", "first", "1st" and
11612 ** "place".
11614 ** This way, even if the tokenizer does not provide synonyms
11615 ** when tokenizing query text (it should not - to do would be
11616 ** inefficient), it doesn't matter if the user queries for
11617 ** 'first + place' or '1st + place', as there are entires in the
11618 ** FTS index corresponding to both forms of the first token.
11619 ** </ol>
11621 ** Whether it is parsing document or query text, any call to xToken that
11622 ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
11623 ** is considered to supply a synonym for the previous token. For example,
11624 ** when parsing the document "I won first place", a tokenizer that supports
11625 ** synonyms would call xToken() 5 times, as follows:
11627 ** <codeblock>
11628 ** xToken(pCtx, 0, "i", 1, 0, 1);
11629 ** xToken(pCtx, 0, "won", 3, 2, 5);
11630 ** xToken(pCtx, 0, "first", 5, 6, 11);
11631 ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
11632 ** xToken(pCtx, 0, "place", 5, 12, 17);
11633 **</codeblock>
11635 ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
11636 ** xToken() is called. Multiple synonyms may be specified for a single token
11637 ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
11638 ** There is no limit to the number of synonyms that may be provided for a
11639 ** single token.
11641 ** In many cases, method (1) above is the best approach. It does not add
11642 ** extra data to the FTS index or require FTS5 to query for multiple terms,
11643 ** so it is efficient in terms of disk space and query speed. However, it
11644 ** does not support prefix queries very well. If, as suggested above, the
11645 ** token "first" is subsituted for "1st" by the tokenizer, then the query:
11647 ** <codeblock>
11648 ** ... MATCH '1s*'</codeblock>
11650 ** will not match documents that contain the token "1st" (as the tokenizer
11651 ** will probably not map "1s" to any prefix of "first").
11653 ** For full prefix support, method (3) may be preferred. In this case,
11654 ** because the index contains entries for both "first" and "1st", prefix
11655 ** queries such as 'fi*' or '1s*' will match correctly. However, because
11656 ** extra entries are added to the FTS index, this method uses more space
11657 ** within the database.
11659 ** Method (2) offers a midpoint between (1) and (3). Using this method,
11660 ** a query such as '1s*' will match documents that contain the literal
11661 ** token "1st", but not "first" (assuming the tokenizer is not able to
11662 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
11663 ** will match against "1st" and "first". This method does not require
11664 ** extra disk space, as no extra entries are added to the FTS index.
11665 ** On the other hand, it may require more CPU cycles to run MATCH queries,
11666 ** as separate queries of the FTS index are required for each synonym.
11668 ** When using methods (2) or (3), it is important that the tokenizer only
11669 ** provide synonyms when tokenizing document text (method (2)) or query
11670 ** text (method (3)), not both. Doing so will not cause any errors, but is
11671 ** inefficient.
11673 typedef struct Fts5Tokenizer Fts5Tokenizer;
11674 typedef struct fts5_tokenizer fts5_tokenizer;
11675 struct fts5_tokenizer {
11676 int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
11677 void (*xDelete)(Fts5Tokenizer*);
11678 int (*xTokenize)(Fts5Tokenizer*,
11679 void *pCtx,
11680 int flags, /* Mask of FTS5_TOKENIZE_* flags */
11681 const char *pText, int nText,
11682 int (*xToken)(
11683 void *pCtx, /* Copy of 2nd argument to xTokenize() */
11684 int tflags, /* Mask of FTS5_TOKEN_* flags */
11685 const char *pToken, /* Pointer to buffer containing token */
11686 int nToken, /* Size of token in bytes */
11687 int iStart, /* Byte offset of token within input text */
11688 int iEnd /* Byte offset of end of token within input text */
11693 /* Flags that may be passed as the third argument to xTokenize() */
11694 #define FTS5_TOKENIZE_QUERY 0x0001
11695 #define FTS5_TOKENIZE_PREFIX 0x0002
11696 #define FTS5_TOKENIZE_DOCUMENT 0x0004
11697 #define FTS5_TOKENIZE_AUX 0x0008
11699 /* Flags that may be passed by the tokenizer implementation back to FTS5
11700 ** as the third argument to the supplied xToken callback. */
11701 #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
11704 ** END OF CUSTOM TOKENIZERS
11705 *************************************************************************/
11707 /*************************************************************************
11708 ** FTS5 EXTENSION REGISTRATION API
11710 typedef struct fts5_api fts5_api;
11711 struct fts5_api {
11712 int iVersion; /* Currently always set to 2 */
11714 /* Create a new tokenizer */
11715 int (*xCreateTokenizer)(
11716 fts5_api *pApi,
11717 const char *zName,
11718 void *pContext,
11719 fts5_tokenizer *pTokenizer,
11720 void (*xDestroy)(void*)
11723 /* Find an existing tokenizer */
11724 int (*xFindTokenizer)(
11725 fts5_api *pApi,
11726 const char *zName,
11727 void **ppContext,
11728 fts5_tokenizer *pTokenizer
11731 /* Create a new auxiliary function */
11732 int (*xCreateFunction)(
11733 fts5_api *pApi,
11734 const char *zName,
11735 void *pContext,
11736 fts5_extension_function xFunction,
11737 void (*xDestroy)(void*)
11742 ** END OF REGISTRATION API
11743 *************************************************************************/
11745 #if 0
11746 } /* end of the 'extern "C"' block */
11747 #endif
11749 #endif /* _FTS5_H */
11751 /******** End of fts5.h *********/
11753 /************** End of sqlite3.h *********************************************/
11754 /************** Continuing where we left off in sqliteInt.h ******************/
11757 ** Include the configuration header output by 'configure' if we're using the
11758 ** autoconf-based build
11760 #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
11761 /* #include "config.h" */
11762 #define SQLITECONFIG_H 1
11763 #endif
11765 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
11766 /************** Begin file sqliteLimit.h *************************************/
11768 ** 2007 May 7
11770 ** The author disclaims copyright to this source code. In place of
11771 ** a legal notice, here is a blessing:
11773 ** May you do good and not evil.
11774 ** May you find forgiveness for yourself and forgive others.
11775 ** May you share freely, never taking more than you give.
11777 *************************************************************************
11779 ** This file defines various limits of what SQLite can process.
11783 ** The maximum length of a TEXT or BLOB in bytes. This also
11784 ** limits the size of a row in a table or index.
11786 ** The hard limit is the ability of a 32-bit signed integer
11787 ** to count the size: 2^31-1 or 2147483647.
11789 #ifndef SQLITE_MAX_LENGTH
11790 # define SQLITE_MAX_LENGTH 1000000000
11791 #endif
11794 ** This is the maximum number of
11796 ** * Columns in a table
11797 ** * Columns in an index
11798 ** * Columns in a view
11799 ** * Terms in the SET clause of an UPDATE statement
11800 ** * Terms in the result set of a SELECT statement
11801 ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
11802 ** * Terms in the VALUES clause of an INSERT statement
11804 ** The hard upper limit here is 32676. Most database people will
11805 ** tell you that in a well-normalized database, you usually should
11806 ** not have more than a dozen or so columns in any table. And if
11807 ** that is the case, there is no point in having more than a few
11808 ** dozen values in any of the other situations described above.
11810 #ifndef SQLITE_MAX_COLUMN
11811 # define SQLITE_MAX_COLUMN 2000
11812 #endif
11815 ** The maximum length of a single SQL statement in bytes.
11817 ** It used to be the case that setting this value to zero would
11818 ** turn the limit off. That is no longer true. It is not possible
11819 ** to turn this limit off.
11821 #ifndef SQLITE_MAX_SQL_LENGTH
11822 # define SQLITE_MAX_SQL_LENGTH 1000000000
11823 #endif
11826 ** The maximum depth of an expression tree. This is limited to
11827 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
11828 ** want to place more severe limits on the complexity of an
11829 ** expression.
11831 ** A value of 0 used to mean that the limit was not enforced.
11832 ** But that is no longer true. The limit is now strictly enforced
11833 ** at all times.
11835 #ifndef SQLITE_MAX_EXPR_DEPTH
11836 # define SQLITE_MAX_EXPR_DEPTH 1000
11837 #endif
11840 ** The maximum number of terms in a compound SELECT statement.
11841 ** The code generator for compound SELECT statements does one
11842 ** level of recursion for each term. A stack overflow can result
11843 ** if the number of terms is too large. In practice, most SQL
11844 ** never has more than 3 or 4 terms. Use a value of 0 to disable
11845 ** any limit on the number of terms in a compount SELECT.
11847 #ifndef SQLITE_MAX_COMPOUND_SELECT
11848 # define SQLITE_MAX_COMPOUND_SELECT 500
11849 #endif
11852 ** The maximum number of opcodes in a VDBE program.
11853 ** Not currently enforced.
11855 #ifndef SQLITE_MAX_VDBE_OP
11856 # define SQLITE_MAX_VDBE_OP 250000000
11857 #endif
11860 ** The maximum number of arguments to an SQL function.
11862 #ifndef SQLITE_MAX_FUNCTION_ARG
11863 # define SQLITE_MAX_FUNCTION_ARG 127
11864 #endif
11867 ** The suggested maximum number of in-memory pages to use for
11868 ** the main database table and for temporary tables.
11870 ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
11871 ** which means the cache size is limited to 2048000 bytes of memory.
11872 ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
11873 ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
11875 #ifndef SQLITE_DEFAULT_CACHE_SIZE
11876 # define SQLITE_DEFAULT_CACHE_SIZE -2000
11877 #endif
11880 ** The default number of frames to accumulate in the log file before
11881 ** checkpointing the database in WAL mode.
11883 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
11884 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
11885 #endif
11888 ** The maximum number of attached databases. This must be between 0
11889 ** and 125. The upper bound of 125 is because the attached databases are
11890 ** counted using a signed 8-bit integer which has a maximum value of 127
11891 ** and we have to allow 2 extra counts for the "main" and "temp" databases.
11893 #ifndef SQLITE_MAX_ATTACHED
11894 # define SQLITE_MAX_ATTACHED 10
11895 #endif
11899 ** The maximum value of a ?nnn wildcard that the parser will accept.
11901 #ifndef SQLITE_MAX_VARIABLE_NUMBER
11902 # define SQLITE_MAX_VARIABLE_NUMBER 999
11903 #endif
11905 /* Maximum page size. The upper bound on this value is 65536. This a limit
11906 ** imposed by the use of 16-bit offsets within each page.
11908 ** Earlier versions of SQLite allowed the user to change this value at
11909 ** compile time. This is no longer permitted, on the grounds that it creates
11910 ** a library that is technically incompatible with an SQLite library
11911 ** compiled with a different limit. If a process operating on a database
11912 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
11913 ** compiled with the default page-size limit will not be able to rollback
11914 ** the aborted transaction. This could lead to database corruption.
11916 #ifdef SQLITE_MAX_PAGE_SIZE
11917 # undef SQLITE_MAX_PAGE_SIZE
11918 #endif
11919 #define SQLITE_MAX_PAGE_SIZE 65536
11923 ** The default size of a database page.
11925 #ifndef SQLITE_DEFAULT_PAGE_SIZE
11926 # define SQLITE_DEFAULT_PAGE_SIZE 4096
11927 #endif
11928 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
11929 # undef SQLITE_DEFAULT_PAGE_SIZE
11930 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
11931 #endif
11934 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
11935 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
11936 ** device characteristics (sector-size and atomic write() support),
11937 ** SQLite may choose a larger value. This constant is the maximum value
11938 ** SQLite will choose on its own.
11940 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
11941 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
11942 #endif
11943 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
11944 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
11945 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
11946 #endif
11950 ** Maximum number of pages in one database file.
11952 ** This is really just the default value for the max_page_count pragma.
11953 ** This value can be lowered (or raised) at run-time using that the
11954 ** max_page_count macro.
11956 #ifndef SQLITE_MAX_PAGE_COUNT
11957 # define SQLITE_MAX_PAGE_COUNT 1073741823
11958 #endif
11961 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
11962 ** operator.
11964 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
11965 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
11966 #endif
11969 ** Maximum depth of recursion for triggers.
11971 ** A value of 1 means that a trigger program will not be able to itself
11972 ** fire any triggers. A value of 0 means that no trigger programs at all
11973 ** may be executed.
11975 #ifndef SQLITE_MAX_TRIGGER_DEPTH
11976 # define SQLITE_MAX_TRIGGER_DEPTH 1000
11977 #endif
11979 /************** End of sqliteLimit.h *****************************************/
11980 /************** Continuing where we left off in sqliteInt.h ******************/
11982 /* Disable nuisance warnings on Borland compilers */
11983 #if defined(__BORLANDC__)
11984 #pragma warn -rch /* unreachable code */
11985 #pragma warn -ccc /* Condition is always true or false */
11986 #pragma warn -aus /* Assigned value is never used */
11987 #pragma warn -csu /* Comparing signed and unsigned */
11988 #pragma warn -spa /* Suspicious pointer arithmetic */
11989 #endif
11992 ** Include standard header files as necessary
11994 #ifdef HAVE_STDINT_H
11995 #include <stdint.h>
11996 #endif
11997 #ifdef HAVE_INTTYPES_H
11998 #include <inttypes.h>
11999 #endif
12002 ** The following macros are used to cast pointers to integers and
12003 ** integers to pointers. The way you do this varies from one compiler
12004 ** to the next, so we have developed the following set of #if statements
12005 ** to generate appropriate macros for a wide range of compilers.
12007 ** The correct "ANSI" way to do this is to use the intptr_t type.
12008 ** Unfortunately, that typedef is not available on all compilers, or
12009 ** if it is available, it requires an #include of specific headers
12010 ** that vary from one machine to the next.
12012 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
12013 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
12014 ** So we have to define the macros in different ways depending on the
12015 ** compiler.
12017 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
12018 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
12019 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
12020 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
12021 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
12022 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
12023 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
12024 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
12025 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
12026 #else /* Generates a warning - but it always works */
12027 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
12028 # define SQLITE_PTR_TO_INT(X) ((int)(X))
12029 #endif
12032 ** A macro to hint to the compiler that a function should not be
12033 ** inlined.
12035 #if defined(__GNUC__)
12036 # define SQLITE_NOINLINE __attribute__((noinline))
12037 #elif defined(_MSC_VER) && _MSC_VER>=1310
12038 # define SQLITE_NOINLINE __declspec(noinline)
12039 #else
12040 # define SQLITE_NOINLINE
12041 #endif
12044 ** Make sure that the compiler intrinsics we desire are enabled when
12045 ** compiling with an appropriate version of MSVC unless prevented by
12046 ** the SQLITE_DISABLE_INTRINSIC define.
12048 #if !defined(SQLITE_DISABLE_INTRINSIC)
12049 # if defined(_MSC_VER) && _MSC_VER>=1400
12050 # if !defined(_WIN32_WCE)
12051 # include <intrin.h>
12052 # pragma intrinsic(_byteswap_ushort)
12053 # pragma intrinsic(_byteswap_ulong)
12054 # pragma intrinsic(_byteswap_uint64)
12055 # pragma intrinsic(_ReadWriteBarrier)
12056 # else
12057 # include <cmnintrin.h>
12058 # endif
12059 # endif
12060 #endif
12063 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
12064 ** 0 means mutexes are permanently disable and the library is never
12065 ** threadsafe. 1 means the library is serialized which is the highest
12066 ** level of threadsafety. 2 means the library is multithreaded - multiple
12067 ** threads can use SQLite as long as no two threads try to use the same
12068 ** database connection at the same time.
12070 ** Older versions of SQLite used an optional THREADSAFE macro.
12071 ** We support that for legacy.
12073 ** To ensure that the correct value of "THREADSAFE" is reported when querying
12074 ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
12075 ** logic is partially replicated in ctime.c. If it is updated here, it should
12076 ** also be updated there.
12078 #if !defined(SQLITE_THREADSAFE)
12079 # if defined(THREADSAFE)
12080 # define SQLITE_THREADSAFE THREADSAFE
12081 # else
12082 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
12083 # endif
12084 #endif
12087 ** Powersafe overwrite is on by default. But can be turned off using
12088 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
12090 #ifndef SQLITE_POWERSAFE_OVERWRITE
12091 # define SQLITE_POWERSAFE_OVERWRITE 1
12092 #endif
12095 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
12096 ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
12097 ** which case memory allocation statistics are disabled by default.
12099 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
12100 # define SQLITE_DEFAULT_MEMSTATUS 1
12101 #endif
12104 ** Exactly one of the following macros must be defined in order to
12105 ** specify which memory allocation subsystem to use.
12107 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
12108 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
12109 ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
12110 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
12112 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
12113 ** assert() macro is enabled, each call into the Win32 native heap subsystem
12114 ** will cause HeapValidate to be called. If heap validation should fail, an
12115 ** assertion will be triggered.
12117 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
12118 ** the default.
12120 #if defined(SQLITE_SYSTEM_MALLOC) \
12121 + defined(SQLITE_WIN32_MALLOC) \
12122 + defined(SQLITE_ZERO_MALLOC) \
12123 + defined(SQLITE_MEMDEBUG)>1
12124 # error "Two or more of the following compile-time configuration options\
12125 are defined but at most one is allowed:\
12126 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
12127 SQLITE_ZERO_MALLOC"
12128 #endif
12129 #if defined(SQLITE_SYSTEM_MALLOC) \
12130 + defined(SQLITE_WIN32_MALLOC) \
12131 + defined(SQLITE_ZERO_MALLOC) \
12132 + defined(SQLITE_MEMDEBUG)==0
12133 # define SQLITE_SYSTEM_MALLOC 1
12134 #endif
12137 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
12138 ** sizes of memory allocations below this value where possible.
12140 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
12141 # define SQLITE_MALLOC_SOFT_LIMIT 1024
12142 #endif
12145 ** We need to define _XOPEN_SOURCE as follows in order to enable
12146 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
12147 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
12148 ** it.
12150 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
12151 # define _XOPEN_SOURCE 600
12152 #endif
12155 ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
12156 ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
12157 ** make it true by defining or undefining NDEBUG.
12159 ** Setting NDEBUG makes the code smaller and faster by disabling the
12160 ** assert() statements in the code. So we want the default action
12161 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
12162 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
12163 ** feature.
12165 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
12166 # define NDEBUG 1
12167 #endif
12168 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
12169 # undef NDEBUG
12170 #endif
12173 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
12175 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
12176 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
12177 #endif
12180 ** The testcase() macro is used to aid in coverage testing. When
12181 ** doing coverage testing, the condition inside the argument to
12182 ** testcase() must be evaluated both true and false in order to
12183 ** get full branch coverage. The testcase() macro is inserted
12184 ** to help ensure adequate test coverage in places where simple
12185 ** condition/decision coverage is inadequate. For example, testcase()
12186 ** can be used to make sure boundary values are tested. For
12187 ** bitmask tests, testcase() can be used to make sure each bit
12188 ** is significant and used at least once. On switch statements
12189 ** where multiple cases go to the same block of code, testcase()
12190 ** can insure that all cases are evaluated.
12193 #ifdef SQLITE_COVERAGE_TEST
12194 SQLITE_PRIVATE void sqlite3Coverage(int);
12195 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
12196 #else
12197 # define testcase(X)
12198 #endif
12201 ** The TESTONLY macro is used to enclose variable declarations or
12202 ** other bits of code that are needed to support the arguments
12203 ** within testcase() and assert() macros.
12205 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
12206 # define TESTONLY(X) X
12207 #else
12208 # define TESTONLY(X)
12209 #endif
12212 ** Sometimes we need a small amount of code such as a variable initialization
12213 ** to setup for a later assert() statement. We do not want this code to
12214 ** appear when assert() is disabled. The following macro is therefore
12215 ** used to contain that setup code. The "VVA" acronym stands for
12216 ** "Verification, Validation, and Accreditation". In other words, the
12217 ** code within VVA_ONLY() will only run during verification processes.
12219 #ifndef NDEBUG
12220 # define VVA_ONLY(X) X
12221 #else
12222 # define VVA_ONLY(X)
12223 #endif
12226 ** The ALWAYS and NEVER macros surround boolean expressions which
12227 ** are intended to always be true or false, respectively. Such
12228 ** expressions could be omitted from the code completely. But they
12229 ** are included in a few cases in order to enhance the resilience
12230 ** of SQLite to unexpected behavior - to make the code "self-healing"
12231 ** or "ductile" rather than being "brittle" and crashing at the first
12232 ** hint of unplanned behavior.
12234 ** In other words, ALWAYS and NEVER are added for defensive code.
12236 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
12237 ** be true and false so that the unreachable code they specify will
12238 ** not be counted as untested code.
12240 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
12241 # define ALWAYS(X) (1)
12242 # define NEVER(X) (0)
12243 #elif !defined(NDEBUG)
12244 # define ALWAYS(X) ((X)?1:(assert(0),0))
12245 # define NEVER(X) ((X)?(assert(0),1):0)
12246 #else
12247 # define ALWAYS(X) (X)
12248 # define NEVER(X) (X)
12249 #endif
12252 ** Some conditionals are optimizations only. In other words, if the
12253 ** conditionals are replaced with a constant 1 (true) or 0 (false) then
12254 ** the correct answer is still obtained, though perhaps not as quickly.
12256 ** The following macros mark these optimizations conditionals.
12258 #if defined(SQLITE_MUTATION_TEST)
12259 # define OK_IF_ALWAYS_TRUE(X) (1)
12260 # define OK_IF_ALWAYS_FALSE(X) (0)
12261 #else
12262 # define OK_IF_ALWAYS_TRUE(X) (X)
12263 # define OK_IF_ALWAYS_FALSE(X) (X)
12264 #endif
12267 ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
12268 ** defined. We need to defend against those failures when testing with
12269 ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
12270 ** during a normal build. The following macro can be used to disable tests
12271 ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
12273 #if defined(SQLITE_TEST_REALLOC_STRESS)
12274 # define ONLY_IF_REALLOC_STRESS(X) (X)
12275 #elif !defined(NDEBUG)
12276 # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
12277 #else
12278 # define ONLY_IF_REALLOC_STRESS(X) (0)
12279 #endif
12282 ** Declarations used for tracing the operating system interfaces.
12284 #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
12285 (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
12286 extern int sqlite3OSTrace;
12287 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
12288 # define SQLITE_HAVE_OS_TRACE
12289 #else
12290 # define OSTRACE(X)
12291 # undef SQLITE_HAVE_OS_TRACE
12292 #endif
12295 ** Is the sqlite3ErrName() function needed in the build? Currently,
12296 ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
12297 ** OSTRACE is enabled), and by several "test*.c" files (which are
12298 ** compiled using SQLITE_TEST).
12300 #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
12301 (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
12302 # define SQLITE_NEED_ERR_NAME
12303 #else
12304 # undef SQLITE_NEED_ERR_NAME
12305 #endif
12308 ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
12310 #ifdef SQLITE_OMIT_EXPLAIN
12311 # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
12312 #endif
12315 ** Return true (non-zero) if the input is an integer that is too large
12316 ** to fit in 32-bits. This macro is used inside of various testcase()
12317 ** macros to verify that we have tested SQLite for large-file support.
12319 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
12322 ** The macro unlikely() is a hint that surrounds a boolean
12323 ** expression that is usually false. Macro likely() surrounds
12324 ** a boolean expression that is usually true. These hints could,
12325 ** in theory, be used by the compiler to generate better code, but
12326 ** currently they are just comments for human readers.
12328 #define likely(X) (X)
12329 #define unlikely(X) (X)
12331 /************** Include hash.h in the middle of sqliteInt.h ******************/
12332 /************** Begin file hash.h ********************************************/
12334 ** 2001 September 22
12336 ** The author disclaims copyright to this source code. In place of
12337 ** a legal notice, here is a blessing:
12339 ** May you do good and not evil.
12340 ** May you find forgiveness for yourself and forgive others.
12341 ** May you share freely, never taking more than you give.
12343 *************************************************************************
12344 ** This is the header file for the generic hash-table implementation
12345 ** used in SQLite.
12347 #ifndef SQLITE_HASH_H
12348 #define SQLITE_HASH_H
12350 /* Forward declarations of structures. */
12351 typedef struct Hash Hash;
12352 typedef struct HashElem HashElem;
12354 /* A complete hash table is an instance of the following structure.
12355 ** The internals of this structure are intended to be opaque -- client
12356 ** code should not attempt to access or modify the fields of this structure
12357 ** directly. Change this structure only by using the routines below.
12358 ** However, some of the "procedures" and "functions" for modifying and
12359 ** accessing this structure are really macros, so we can't really make
12360 ** this structure opaque.
12362 ** All elements of the hash table are on a single doubly-linked list.
12363 ** Hash.first points to the head of this list.
12365 ** There are Hash.htsize buckets. Each bucket points to a spot in
12366 ** the global doubly-linked list. The contents of the bucket are the
12367 ** element pointed to plus the next _ht.count-1 elements in the list.
12369 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
12370 ** by a linear search of the global list. For small tables, the
12371 ** Hash.ht table is never allocated because if there are few elements
12372 ** in the table, it is faster to do a linear search than to manage
12373 ** the hash table.
12375 struct Hash {
12376 unsigned int htsize; /* Number of buckets in the hash table */
12377 unsigned int count; /* Number of entries in this table */
12378 HashElem *first; /* The first element of the array */
12379 struct _ht { /* the hash table */
12380 int count; /* Number of entries with this hash */
12381 HashElem *chain; /* Pointer to first entry with this hash */
12382 } *ht;
12385 /* Each element in the hash table is an instance of the following
12386 ** structure. All elements are stored on a single doubly-linked list.
12388 ** Again, this structure is intended to be opaque, but it can't really
12389 ** be opaque because it is used by macros.
12391 struct HashElem {
12392 HashElem *next, *prev; /* Next and previous elements in the table */
12393 void *data; /* Data associated with this element */
12394 const char *pKey; /* Key associated with this element */
12398 ** Access routines. To delete, insert a NULL pointer.
12400 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
12401 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
12402 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
12403 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
12406 ** Macros for looping over all elements of a hash table. The idiom is
12407 ** like this:
12409 ** Hash h;
12410 ** HashElem *p;
12411 ** ...
12412 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
12413 ** SomeStructure *pData = sqliteHashData(p);
12414 ** // do something with pData
12415 ** }
12417 #define sqliteHashFirst(H) ((H)->first)
12418 #define sqliteHashNext(E) ((E)->next)
12419 #define sqliteHashData(E) ((E)->data)
12420 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
12421 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
12424 ** Number of entries in a hash table
12426 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
12428 #endif /* SQLITE_HASH_H */
12430 /************** End of hash.h ************************************************/
12431 /************** Continuing where we left off in sqliteInt.h ******************/
12432 /************** Include parse.h in the middle of sqliteInt.h *****************/
12433 /************** Begin file parse.h *******************************************/
12434 #define TK_SEMI 1
12435 #define TK_EXPLAIN 2
12436 #define TK_QUERY 3
12437 #define TK_PLAN 4
12438 #define TK_BEGIN 5
12439 #define TK_TRANSACTION 6
12440 #define TK_DEFERRED 7
12441 #define TK_IMMEDIATE 8
12442 #define TK_EXCLUSIVE 9
12443 #define TK_COMMIT 10
12444 #define TK_END 11
12445 #define TK_ROLLBACK 12
12446 #define TK_SAVEPOINT 13
12447 #define TK_RELEASE 14
12448 #define TK_TO 15
12449 #define TK_TABLE 16
12450 #define TK_CREATE 17
12451 #define TK_IF 18
12452 #define TK_NOT 19
12453 #define TK_EXISTS 20
12454 #define TK_TEMP 21
12455 #define TK_LP 22
12456 #define TK_RP 23
12457 #define TK_AS 24
12458 #define TK_WITHOUT 25
12459 #define TK_COMMA 26
12460 #define TK_ABORT 27
12461 #define TK_ACTION 28
12462 #define TK_AFTER 29
12463 #define TK_ANALYZE 30
12464 #define TK_ASC 31
12465 #define TK_ATTACH 32
12466 #define TK_BEFORE 33
12467 #define TK_BY 34
12468 #define TK_CASCADE 35
12469 #define TK_CAST 36
12470 #define TK_CONFLICT 37
12471 #define TK_DATABASE 38
12472 #define TK_DESC 39
12473 #define TK_DETACH 40
12474 #define TK_EACH 41
12475 #define TK_FAIL 42
12476 #define TK_OR 43
12477 #define TK_AND 44
12478 #define TK_IS 45
12479 #define TK_MATCH 46
12480 #define TK_LIKE_KW 47
12481 #define TK_BETWEEN 48
12482 #define TK_IN 49
12483 #define TK_ISNULL 50
12484 #define TK_NOTNULL 51
12485 #define TK_NE 52
12486 #define TK_EQ 53
12487 #define TK_GT 54
12488 #define TK_LE 55
12489 #define TK_LT 56
12490 #define TK_GE 57
12491 #define TK_ESCAPE 58
12492 #define TK_ID 59
12493 #define TK_COLUMNKW 60
12494 #define TK_FOR 61
12495 #define TK_IGNORE 62
12496 #define TK_INITIALLY 63
12497 #define TK_INSTEAD 64
12498 #define TK_NO 65
12499 #define TK_KEY 66
12500 #define TK_OF 67
12501 #define TK_OFFSET 68
12502 #define TK_PRAGMA 69
12503 #define TK_RAISE 70
12504 #define TK_RECURSIVE 71
12505 #define TK_REPLACE 72
12506 #define TK_RESTRICT 73
12507 #define TK_ROW 74
12508 #define TK_TRIGGER 75
12509 #define TK_VACUUM 76
12510 #define TK_VIEW 77
12511 #define TK_VIRTUAL 78
12512 #define TK_WITH 79
12513 #define TK_REINDEX 80
12514 #define TK_RENAME 81
12515 #define TK_CTIME_KW 82
12516 #define TK_ANY 83
12517 #define TK_BITAND 84
12518 #define TK_BITOR 85
12519 #define TK_LSHIFT 86
12520 #define TK_RSHIFT 87
12521 #define TK_PLUS 88
12522 #define TK_MINUS 89
12523 #define TK_STAR 90
12524 #define TK_SLASH 91
12525 #define TK_REM 92
12526 #define TK_CONCAT 93
12527 #define TK_COLLATE 94
12528 #define TK_BITNOT 95
12529 #define TK_INDEXED 96
12530 #define TK_STRING 97
12531 #define TK_JOIN_KW 98
12532 #define TK_CONSTRAINT 99
12533 #define TK_DEFAULT 100
12534 #define TK_NULL 101
12535 #define TK_PRIMARY 102
12536 #define TK_UNIQUE 103
12537 #define TK_CHECK 104
12538 #define TK_REFERENCES 105
12539 #define TK_AUTOINCR 106
12540 #define TK_ON 107
12541 #define TK_INSERT 108
12542 #define TK_DELETE 109
12543 #define TK_UPDATE 110
12544 #define TK_SET 111
12545 #define TK_DEFERRABLE 112
12546 #define TK_FOREIGN 113
12547 #define TK_DROP 114
12548 #define TK_UNION 115
12549 #define TK_ALL 116
12550 #define TK_EXCEPT 117
12551 #define TK_INTERSECT 118
12552 #define TK_SELECT 119
12553 #define TK_VALUES 120
12554 #define TK_DISTINCT 121
12555 #define TK_DOT 122
12556 #define TK_FROM 123
12557 #define TK_JOIN 124
12558 #define TK_USING 125
12559 #define TK_ORDER 126
12560 #define TK_GROUP 127
12561 #define TK_HAVING 128
12562 #define TK_LIMIT 129
12563 #define TK_WHERE 130
12564 #define TK_INTO 131
12565 #define TK_FLOAT 132
12566 #define TK_BLOB 133
12567 #define TK_INTEGER 134
12568 #define TK_VARIABLE 135
12569 #define TK_CASE 136
12570 #define TK_WHEN 137
12571 #define TK_THEN 138
12572 #define TK_ELSE 139
12573 #define TK_INDEX 140
12574 #define TK_ALTER 141
12575 #define TK_ADD 142
12576 #define TK_ISNOT 143
12577 #define TK_FUNCTION 144
12578 #define TK_COLUMN 145
12579 #define TK_AGG_FUNCTION 146
12580 #define TK_AGG_COLUMN 147
12581 #define TK_UMINUS 148
12582 #define TK_UPLUS 149
12583 #define TK_REGISTER 150
12584 #define TK_VECTOR 151
12585 #define TK_SELECT_COLUMN 152
12586 #define TK_IF_NULL_ROW 153
12587 #define TK_ASTERISK 154
12588 #define TK_SPAN 155
12589 #define TK_END_OF_FILE 156
12590 #define TK_UNCLOSED_STRING 157
12591 #define TK_SPACE 158
12592 #define TK_ILLEGAL 159
12594 /* The token codes above must all fit in 8 bits */
12595 #define TKFLG_MASK 0xff
12597 /* Flags that can be added to a token code when it is not
12598 ** being stored in a u8: */
12599 #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
12601 /************** End of parse.h ***********************************************/
12602 /************** Continuing where we left off in sqliteInt.h ******************/
12603 #include <stdio.h>
12604 #include <stdlib.h>
12605 #include <string.h>
12606 #include <assert.h>
12607 #include <stddef.h>
12610 ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
12611 ** This allows better measurements of where memcpy() is used when running
12612 ** cachegrind. But this macro version of memcpy() is very slow so it
12613 ** should not be used in production. This is a performance measurement
12614 ** hack only.
12616 #ifdef SQLITE_INLINE_MEMCPY
12617 # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
12618 int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
12619 #endif
12622 ** If compiling for a processor that lacks floating point support,
12623 ** substitute integer for floating-point
12625 #ifdef SQLITE_OMIT_FLOATING_POINT
12626 # define double sqlite_int64
12627 # define float sqlite_int64
12628 # define LONGDOUBLE_TYPE sqlite_int64
12629 # ifndef SQLITE_BIG_DBL
12630 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
12631 # endif
12632 # define SQLITE_OMIT_DATETIME_FUNCS 1
12633 # define SQLITE_OMIT_TRACE 1
12634 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12635 # undef SQLITE_HAVE_ISNAN
12636 #endif
12637 #ifndef SQLITE_BIG_DBL
12638 # define SQLITE_BIG_DBL (1e99)
12639 #endif
12642 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
12643 ** afterward. Having this macro allows us to cause the C compiler
12644 ** to omit code used by TEMP tables without messy #ifndef statements.
12646 #ifdef SQLITE_OMIT_TEMPDB
12647 #define OMIT_TEMPDB 1
12648 #else
12649 #define OMIT_TEMPDB 0
12650 #endif
12653 ** The "file format" number is an integer that is incremented whenever
12654 ** the VDBE-level file format changes. The following macros define the
12655 ** the default file format for new databases and the maximum file format
12656 ** that the library can read.
12658 #define SQLITE_MAX_FILE_FORMAT 4
12659 #ifndef SQLITE_DEFAULT_FILE_FORMAT
12660 # define SQLITE_DEFAULT_FILE_FORMAT 4
12661 #endif
12664 ** Determine whether triggers are recursive by default. This can be
12665 ** changed at run-time using a pragma.
12667 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
12668 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
12669 #endif
12672 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
12673 ** on the command-line
12675 #ifndef SQLITE_TEMP_STORE
12676 # define SQLITE_TEMP_STORE 1
12677 #endif
12680 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
12681 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
12682 ** to zero.
12684 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
12685 # undef SQLITE_MAX_WORKER_THREADS
12686 # define SQLITE_MAX_WORKER_THREADS 0
12687 #endif
12688 #ifndef SQLITE_MAX_WORKER_THREADS
12689 # define SQLITE_MAX_WORKER_THREADS 8
12690 #endif
12691 #ifndef SQLITE_DEFAULT_WORKER_THREADS
12692 # define SQLITE_DEFAULT_WORKER_THREADS 0
12693 #endif
12694 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
12695 # undef SQLITE_MAX_WORKER_THREADS
12696 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
12697 #endif
12700 ** The default initial allocation for the pagecache when using separate
12701 ** pagecaches for each database connection. A positive number is the
12702 ** number of pages. A negative number N translations means that a buffer
12703 ** of -1024*N bytes is allocated and used for as many pages as it will hold.
12705 ** The default value of "20" was choosen to minimize the run-time of the
12706 ** speedtest1 test program with options: --shrink-memory --reprepare
12708 #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
12709 # define SQLITE_DEFAULT_PCACHE_INITSZ 20
12710 #endif
12713 ** The compile-time options SQLITE_MMAP_READWRITE and
12714 ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
12715 ** You must choose one or the other (or neither) but not both.
12717 #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
12718 #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
12719 #endif
12722 ** GCC does not define the offsetof() macro so we'll have to do it
12723 ** ourselves.
12725 #ifndef offsetof
12726 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
12727 #endif
12730 ** Macros to compute minimum and maximum of two numbers.
12732 #ifndef MIN
12733 # define MIN(A,B) ((A)<(B)?(A):(B))
12734 #endif
12735 #ifndef MAX
12736 # define MAX(A,B) ((A)>(B)?(A):(B))
12737 #endif
12740 ** Swap two objects of type TYPE.
12742 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
12745 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
12746 ** not, there are still machines out there that use EBCDIC.)
12748 #if 'A' == '\301'
12749 # define SQLITE_EBCDIC 1
12750 #else
12751 # define SQLITE_ASCII 1
12752 #endif
12755 ** Integers of known sizes. These typedefs might change for architectures
12756 ** where the sizes very. Preprocessor macros are available so that the
12757 ** types can be conveniently redefined at compile-type. Like this:
12759 ** cc '-DUINTPTR_TYPE=long long int' ...
12761 #ifndef UINT32_TYPE
12762 # ifdef HAVE_UINT32_T
12763 # define UINT32_TYPE uint32_t
12764 # else
12765 # define UINT32_TYPE unsigned int
12766 # endif
12767 #endif
12768 #ifndef UINT16_TYPE
12769 # ifdef HAVE_UINT16_T
12770 # define UINT16_TYPE uint16_t
12771 # else
12772 # define UINT16_TYPE unsigned short int
12773 # endif
12774 #endif
12775 #ifndef INT16_TYPE
12776 # ifdef HAVE_INT16_T
12777 # define INT16_TYPE int16_t
12778 # else
12779 # define INT16_TYPE short int
12780 # endif
12781 #endif
12782 #ifndef UINT8_TYPE
12783 # ifdef HAVE_UINT8_T
12784 # define UINT8_TYPE uint8_t
12785 # else
12786 # define UINT8_TYPE unsigned char
12787 # endif
12788 #endif
12789 #ifndef INT8_TYPE
12790 # ifdef HAVE_INT8_T
12791 # define INT8_TYPE int8_t
12792 # else
12793 # define INT8_TYPE signed char
12794 # endif
12795 #endif
12796 #ifndef LONGDOUBLE_TYPE
12797 # define LONGDOUBLE_TYPE long double
12798 #endif
12799 typedef sqlite_int64 i64; /* 8-byte signed integer */
12800 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
12801 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
12802 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
12803 typedef INT16_TYPE i16; /* 2-byte signed integer */
12804 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
12805 typedef INT8_TYPE i8; /* 1-byte signed integer */
12808 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
12809 ** that can be stored in a u32 without loss of data. The value
12810 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
12811 ** have to specify the value in the less intuitive manner shown:
12813 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
12816 ** The datatype used to store estimates of the number of rows in a
12817 ** table or index. This is an unsigned integer type. For 99.9% of
12818 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
12819 ** can be used at compile-time if desired.
12821 #ifdef SQLITE_64BIT_STATS
12822 typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
12823 #else
12824 typedef u32 tRowcnt; /* 32-bit is the default */
12825 #endif
12828 ** Estimated quantities used for query planning are stored as 16-bit
12829 ** logarithms. For quantity X, the value stored is 10*log2(X). This
12830 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
12831 ** But the allowed values are "grainy". Not every value is representable.
12832 ** For example, quantities 16 and 17 are both represented by a LogEst
12833 ** of 40. However, since LogEst quantities are suppose to be estimates,
12834 ** not exact values, this imprecision is not a problem.
12836 ** "LogEst" is short for "Logarithmic Estimate".
12838 ** Examples:
12839 ** 1 -> 0 20 -> 43 10000 -> 132
12840 ** 2 -> 10 25 -> 46 25000 -> 146
12841 ** 3 -> 16 100 -> 66 1000000 -> 199
12842 ** 4 -> 20 1000 -> 99 1048576 -> 200
12843 ** 10 -> 33 1024 -> 100 4294967296 -> 320
12845 ** The LogEst can be negative to indicate fractional values.
12846 ** Examples:
12848 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
12850 typedef INT16_TYPE LogEst;
12853 ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
12855 #ifndef SQLITE_PTRSIZE
12856 # if defined(__SIZEOF_POINTER__)
12857 # define SQLITE_PTRSIZE __SIZEOF_POINTER__
12858 # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
12859 defined(_M_ARM) || defined(__arm__) || defined(__x86)
12860 # define SQLITE_PTRSIZE 4
12861 # else
12862 # define SQLITE_PTRSIZE 8
12863 # endif
12864 #endif
12866 /* The uptr type is an unsigned integer large enough to hold a pointer
12868 #if defined(HAVE_STDINT_H)
12869 typedef uintptr_t uptr;
12870 #elif SQLITE_PTRSIZE==4
12871 typedef u32 uptr;
12872 #else
12873 typedef u64 uptr;
12874 #endif
12877 ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
12878 ** something between S (inclusive) and E (exclusive).
12880 ** In other words, S is a buffer and E is a pointer to the first byte after
12881 ** the end of buffer S. This macro returns true if P points to something
12882 ** contained within the buffer S.
12884 #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
12888 ** Macros to determine whether the machine is big or little endian,
12889 ** and whether or not that determination is run-time or compile-time.
12891 ** For best performance, an attempt is made to guess at the byte-order
12892 ** using C-preprocessor macros. If that is unsuccessful, or if
12893 ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
12894 ** at run-time.
12896 #ifndef SQLITE_BYTEORDER
12897 # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
12898 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
12899 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
12900 defined(__arm__)
12901 # define SQLITE_BYTEORDER 1234
12902 # elif defined(sparc) || defined(__ppc__)
12903 # define SQLITE_BYTEORDER 4321
12904 # else
12905 # define SQLITE_BYTEORDER 0
12906 # endif
12907 #endif
12908 #if SQLITE_BYTEORDER==4321
12909 # define SQLITE_BIGENDIAN 1
12910 # define SQLITE_LITTLEENDIAN 0
12911 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
12912 #elif SQLITE_BYTEORDER==1234
12913 # define SQLITE_BIGENDIAN 0
12914 # define SQLITE_LITTLEENDIAN 1
12915 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
12916 #else
12917 # ifdef SQLITE_AMALGAMATION
12918 const int sqlite3one = 1;
12919 # else
12920 extern const int sqlite3one;
12921 # endif
12922 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
12923 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
12924 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
12925 #endif
12928 ** Constants for the largest and smallest possible 64-bit signed integers.
12929 ** These macros are designed to work correctly on both 32-bit and 64-bit
12930 ** compilers.
12932 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
12933 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
12936 ** Round up a number to the next larger multiple of 8. This is used
12937 ** to force 8-byte alignment on 64-bit architectures.
12939 #define ROUND8(x) (((x)+7)&~7)
12942 ** Round down to the nearest multiple of 8
12944 #define ROUNDDOWN8(x) ((x)&~7)
12947 ** Assert that the pointer X is aligned to an 8-byte boundary. This
12948 ** macro is used only within assert() to verify that the code gets
12949 ** all alignment restrictions correct.
12951 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
12952 ** underlying malloc() implementation might return us 4-byte aligned
12953 ** pointers. In that case, only verify 4-byte alignment.
12955 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12956 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
12957 #else
12958 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
12959 #endif
12962 ** Disable MMAP on platforms where it is known to not work
12964 #if defined(__OpenBSD__) || defined(__QNXNTO__)
12965 # undef SQLITE_MAX_MMAP_SIZE
12966 # define SQLITE_MAX_MMAP_SIZE 0
12967 #endif
12970 ** Default maximum size of memory used by memory-mapped I/O in the VFS
12972 #ifdef __APPLE__
12973 # include <TargetConditionals.h>
12974 #endif
12975 #ifndef SQLITE_MAX_MMAP_SIZE
12976 # if defined(__linux__) \
12977 || defined(_WIN32) \
12978 || (defined(__APPLE__) && defined(__MACH__)) \
12979 || defined(__sun) \
12980 || defined(__FreeBSD__) \
12981 || defined(__DragonFly__)
12982 # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
12983 # else
12984 # define SQLITE_MAX_MMAP_SIZE 0
12985 # endif
12986 #endif
12989 ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
12990 ** default MMAP_SIZE is specified at compile-time, make sure that it does
12991 ** not exceed the maximum mmap size.
12993 #ifndef SQLITE_DEFAULT_MMAP_SIZE
12994 # define SQLITE_DEFAULT_MMAP_SIZE 0
12995 #endif
12996 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
12997 # undef SQLITE_DEFAULT_MMAP_SIZE
12998 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
12999 #endif
13002 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
13003 ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
13004 ** define SQLITE_ENABLE_STAT3_OR_STAT4
13006 #ifdef SQLITE_ENABLE_STAT4
13007 # undef SQLITE_ENABLE_STAT3
13008 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
13009 #elif SQLITE_ENABLE_STAT3
13010 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
13011 #elif SQLITE_ENABLE_STAT3_OR_STAT4
13012 # undef SQLITE_ENABLE_STAT3_OR_STAT4
13013 #endif
13016 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
13017 ** the Select query generator tracing logic is turned on.
13019 #if defined(SQLITE_ENABLE_SELECTTRACE)
13020 # define SELECTTRACE_ENABLED 1
13021 #else
13022 # define SELECTTRACE_ENABLED 0
13023 #endif
13026 ** An instance of the following structure is used to store the busy-handler
13027 ** callback for a given sqlite handle.
13029 ** The sqlite.busyHandler member of the sqlite struct contains the busy
13030 ** callback for the database handle. Each pager opened via the sqlite
13031 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
13032 ** callback is currently invoked only from within pager.c.
13034 typedef struct BusyHandler BusyHandler;
13035 struct BusyHandler {
13036 int (*xFunc)(void *,int); /* The busy callback */
13037 void *pArg; /* First arg to busy callback */
13038 int nBusy; /* Incremented with each busy call */
13042 ** Name of the master database table. The master database table
13043 ** is a special table that holds the names and attributes of all
13044 ** user tables and indices.
13046 #define MASTER_NAME "sqlite_master"
13047 #define TEMP_MASTER_NAME "sqlite_temp_master"
13050 ** The root-page of the master database table.
13052 #define MASTER_ROOT 1
13055 ** The name of the schema table.
13057 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
13060 ** A convenience macro that returns the number of elements in
13061 ** an array.
13063 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
13066 ** Determine if the argument is a power of two
13068 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
13071 ** The following value as a destructor means to use sqlite3DbFree().
13072 ** The sqlite3DbFree() routine requires two parameters instead of the
13073 ** one parameter that destructors normally want. So we have to introduce
13074 ** this magic value that the code knows to handle differently. Any
13075 ** pointer will work here as long as it is distinct from SQLITE_STATIC
13076 ** and SQLITE_TRANSIENT.
13078 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
13081 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
13082 ** not support Writable Static Data (WSD) such as global and static variables.
13083 ** All variables must either be on the stack or dynamically allocated from
13084 ** the heap. When WSD is unsupported, the variable declarations scattered
13085 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
13086 ** macro is used for this purpose. And instead of referencing the variable
13087 ** directly, we use its constant as a key to lookup the run-time allocated
13088 ** buffer that holds real variable. The constant is also the initializer
13089 ** for the run-time allocated buffer.
13091 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
13092 ** macros become no-ops and have zero performance impact.
13094 #ifdef SQLITE_OMIT_WSD
13095 #define SQLITE_WSD const
13096 #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
13097 #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
13098 SQLITE_API int sqlite3_wsd_init(int N, int J);
13099 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
13100 #else
13101 #define SQLITE_WSD
13102 #define GLOBAL(t,v) v
13103 #define sqlite3GlobalConfig sqlite3Config
13104 #endif
13107 ** The following macros are used to suppress compiler warnings and to
13108 ** make it clear to human readers when a function parameter is deliberately
13109 ** left unused within the body of a function. This usually happens when
13110 ** a function is called via a function pointer. For example the
13111 ** implementation of an SQL aggregate step callback may not use the
13112 ** parameter indicating the number of arguments passed to the aggregate,
13113 ** if it knows that this is enforced elsewhere.
13115 ** When a function parameter is not used at all within the body of a function,
13116 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
13117 ** However, these macros may also be used to suppress warnings related to
13118 ** parameters that may or may not be used depending on compilation options.
13119 ** For example those parameters only used in assert() statements. In these
13120 ** cases the parameters are named as per the usual conventions.
13122 #define UNUSED_PARAMETER(x) (void)(x)
13123 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
13126 ** Forward references to structures
13128 typedef struct AggInfo AggInfo;
13129 typedef struct AuthContext AuthContext;
13130 typedef struct AutoincInfo AutoincInfo;
13131 typedef struct Bitvec Bitvec;
13132 typedef struct CollSeq CollSeq;
13133 typedef struct Column Column;
13134 typedef struct Db Db;
13135 typedef struct Schema Schema;
13136 typedef struct Expr Expr;
13137 typedef struct ExprList ExprList;
13138 typedef struct ExprSpan ExprSpan;
13139 typedef struct FKey FKey;
13140 typedef struct FuncDestructor FuncDestructor;
13141 typedef struct FuncDef FuncDef;
13142 typedef struct FuncDefHash FuncDefHash;
13143 typedef struct IdList IdList;
13144 typedef struct Index Index;
13145 typedef struct IndexSample IndexSample;
13146 typedef struct KeyClass KeyClass;
13147 typedef struct KeyInfo KeyInfo;
13148 typedef struct Lookaside Lookaside;
13149 typedef struct LookasideSlot LookasideSlot;
13150 typedef struct Module Module;
13151 typedef struct NameContext NameContext;
13152 typedef struct Parse Parse;
13153 typedef struct PreUpdate PreUpdate;
13154 typedef struct PrintfArguments PrintfArguments;
13155 typedef struct RowSet RowSet;
13156 typedef struct Savepoint Savepoint;
13157 typedef struct Select Select;
13158 typedef struct SQLiteThread SQLiteThread;
13159 typedef struct SelectDest SelectDest;
13160 typedef struct SrcList SrcList;
13161 typedef struct StrAccum StrAccum;
13162 typedef struct Table Table;
13163 typedef struct TableLock TableLock;
13164 typedef struct Token Token;
13165 typedef struct TreeView TreeView;
13166 typedef struct Trigger Trigger;
13167 typedef struct TriggerPrg TriggerPrg;
13168 typedef struct TriggerStep TriggerStep;
13169 typedef struct UnpackedRecord UnpackedRecord;
13170 typedef struct VTable VTable;
13171 typedef struct VtabCtx VtabCtx;
13172 typedef struct Walker Walker;
13173 typedef struct WhereInfo WhereInfo;
13174 typedef struct With With;
13176 /* A VList object records a mapping between parameters/variables/wildcards
13177 ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
13178 ** variable number associated with that parameter. See the format description
13179 ** on the sqlite3VListAdd() routine for more information. A VList is really
13180 ** just an array of integers.
13182 typedef int VList;
13185 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
13186 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
13187 ** pointer types (i.e. FuncDef) defined above.
13189 /************** Include btree.h in the middle of sqliteInt.h *****************/
13190 /************** Begin file btree.h *******************************************/
13192 ** 2001 September 15
13194 ** The author disclaims copyright to this source code. In place of
13195 ** a legal notice, here is a blessing:
13197 ** May you do good and not evil.
13198 ** May you find forgiveness for yourself and forgive others.
13199 ** May you share freely, never taking more than you give.
13201 *************************************************************************
13202 ** This header file defines the interface that the sqlite B-Tree file
13203 ** subsystem. See comments in the source code for a detailed description
13204 ** of what each interface routine does.
13206 #ifndef SQLITE_BTREE_H
13207 #define SQLITE_BTREE_H
13209 /* TODO: This definition is just included so other modules compile. It
13210 ** needs to be revisited.
13212 #define SQLITE_N_BTREE_META 16
13215 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
13216 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
13218 #ifndef SQLITE_DEFAULT_AUTOVACUUM
13219 #define SQLITE_DEFAULT_AUTOVACUUM 0
13220 #endif
13222 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
13223 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
13224 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
13227 ** Forward declarations of structure
13229 typedef struct Btree Btree;
13230 typedef struct BtCursor BtCursor;
13231 typedef struct BtShared BtShared;
13232 typedef struct BtreePayload BtreePayload;
13235 SQLITE_PRIVATE int sqlite3BtreeOpen(
13236 sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
13237 const char *zFilename, /* Name of database file to open */
13238 sqlite3 *db, /* Associated database connection */
13239 Btree **ppBtree, /* Return open Btree* here */
13240 int flags, /* Flags */
13241 int vfsFlags /* Flags passed through to VFS open */
13244 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
13245 ** following values.
13247 ** NOTE: These values must match the corresponding PAGER_ values in
13248 ** pager.h.
13250 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
13251 #define BTREE_MEMORY 2 /* This is an in-memory DB */
13252 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
13253 #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
13255 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
13256 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
13257 SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
13258 #if SQLITE_MAX_MMAP_SIZE>0
13259 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
13260 #endif
13261 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
13262 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
13263 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
13264 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
13265 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
13266 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
13267 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
13268 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
13269 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
13270 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
13271 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
13272 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
13273 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
13274 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
13275 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
13276 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
13277 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
13278 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
13279 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
13280 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
13281 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
13282 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
13283 #ifndef SQLITE_OMIT_SHARED_CACHE
13284 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
13285 #endif
13286 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
13288 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
13289 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
13290 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
13292 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
13294 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
13295 ** of the flags shown below.
13297 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
13298 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
13299 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
13300 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
13301 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
13302 ** indices.)
13304 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
13305 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
13307 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
13308 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
13309 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
13310 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
13312 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
13313 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
13315 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
13318 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
13319 ** should be one of the following values. The integer values are assigned
13320 ** to constants so that the offset of the corresponding field in an
13321 ** SQLite database header may be found using the following formula:
13323 ** offset = 36 + (idx * 4)
13325 ** For example, the free-page-count field is located at byte offset 36 of
13326 ** the database file header. The incr-vacuum-flag field is located at
13327 ** byte offset 64 (== 36+4*7).
13329 ** The BTREE_DATA_VERSION value is not really a value stored in the header.
13330 ** It is a read-only number computed by the pager. But we merge it with
13331 ** the header value access routines since its access pattern is the same.
13332 ** Call it a "virtual meta value".
13334 #define BTREE_FREE_PAGE_COUNT 0
13335 #define BTREE_SCHEMA_VERSION 1
13336 #define BTREE_FILE_FORMAT 2
13337 #define BTREE_DEFAULT_CACHE_SIZE 3
13338 #define BTREE_LARGEST_ROOT_PAGE 4
13339 #define BTREE_TEXT_ENCODING 5
13340 #define BTREE_USER_VERSION 6
13341 #define BTREE_INCR_VACUUM 7
13342 #define BTREE_APPLICATION_ID 8
13343 #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
13346 ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
13347 ** interface.
13349 ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
13351 ** The first argument is an Expr* (which is guaranteed to be constant for
13352 ** the lifetime of the cursor) that defines constraints on which rows
13353 ** might be fetched with this cursor. The Expr* tree may contain
13354 ** TK_REGISTER nodes that refer to values stored in the array of registers
13355 ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
13356 ** then the value of the node is the value in Mem[pExpr.iTable]. Any
13357 ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
13358 ** column of the b-tree of the cursor. The Expr tree will not contain
13359 ** any function calls nor subqueries nor references to b-trees other than
13360 ** the cursor being hinted.
13362 ** The design of the _RANGE hint is aid b-tree implementations that try
13363 ** to prefetch content from remote machines - to provide those
13364 ** implementations with limits on what needs to be prefetched and thereby
13365 ** reduce network bandwidth.
13367 ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
13368 ** standard SQLite. The other hints are provided for extentions that use
13369 ** the SQLite parser and code generator but substitute their own storage
13370 ** engine.
13372 #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
13375 ** Values that may be OR'd together to form the argument to the
13376 ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
13378 ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
13379 ** to be filled with content that is already in sorted order.
13381 ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
13382 ** OP_SeekLE opcodes for a range search, but where the range of entries
13383 ** selected will all have the same key. In other words, the cursor will
13384 ** be used only for equality key searches.
13387 #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
13388 #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
13391 ** Flags passed as the third argument to sqlite3BtreeCursor().
13393 ** For read-only cursors the wrFlag argument is always zero. For read-write
13394 ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
13395 ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
13396 ** only be used by SQLite for the following:
13398 ** * to seek to and then delete specific entries, and/or
13400 ** * to read values that will be used to create keys that other
13401 ** BTREE_FORDELETE cursors will seek to and delete.
13403 ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
13404 ** by this, the native b-tree engine of SQLite, but it is available to
13405 ** alternative storage engines that might be substituted in place of this
13406 ** b-tree system. For alternative storage engines in which a delete of
13407 ** the main table row automatically deletes corresponding index rows,
13408 ** the FORDELETE flag hint allows those alternative storage engines to
13409 ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
13410 ** and DELETE operations as no-ops, and any READ operation against a
13411 ** FORDELETE cursor may return a null row: 0x01 0x00.
13413 #define BTREE_WRCSR 0x00000004 /* read-write cursor */
13414 #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
13416 SQLITE_PRIVATE int sqlite3BtreeCursor(
13417 Btree*, /* BTree containing table to open */
13418 int iTable, /* Index of root page */
13419 int wrFlag, /* 1 for writing. 0 for read-only */
13420 struct KeyInfo*, /* First argument to compare function */
13421 BtCursor *pCursor /* Space to write cursor structure */
13423 SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
13424 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
13425 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
13426 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
13427 #ifdef SQLITE_ENABLE_CURSOR_HINTS
13428 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
13429 #endif
13431 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
13432 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
13433 BtCursor*,
13434 UnpackedRecord *pUnKey,
13435 i64 intKey,
13436 int bias,
13437 int *pRes
13439 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
13440 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
13441 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
13443 /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
13444 #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
13445 #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
13446 #define BTREE_APPEND 0x08 /* Insert is likely an append */
13448 /* An instance of the BtreePayload object describes the content of a single
13449 ** entry in either an index or table btree.
13451 ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
13452 ** an arbitrary key and no data. These btrees have pKey,nKey set to their
13453 ** key and pData,nData,nZero set to zero.
13455 ** Table btrees (used for rowid tables) contain an integer rowid used as
13456 ** the key and passed in the nKey field. The pKey field is zero.
13457 ** pData,nData hold the content of the new entry. nZero extra zero bytes
13458 ** are appended to the end of the content when constructing the entry.
13460 ** This object is used to pass information into sqlite3BtreeInsert(). The
13461 ** same information used to be passed as five separate parameters. But placing
13462 ** the information into this object helps to keep the interface more
13463 ** organized and understandable, and it also helps the resulting code to
13464 ** run a little faster by using fewer registers for parameter passing.
13466 struct BtreePayload {
13467 const void *pKey; /* Key content for indexes. NULL for tables */
13468 sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
13469 const void *pData; /* Data for tables. NULL for indexes */
13470 sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
13471 u16 nMem; /* Number of aMem[] value. Might be zero */
13472 int nData; /* Size of pData. 0 if none. */
13473 int nZero; /* Extra zero data appended after pData,nData */
13476 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
13477 int flags, int seekResult);
13478 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
13479 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
13480 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
13481 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
13482 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
13483 SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
13484 SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
13485 SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
13486 SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
13488 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
13489 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
13490 SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
13492 #ifndef SQLITE_OMIT_INCRBLOB
13493 SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
13494 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
13495 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
13496 #endif
13497 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
13498 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
13499 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
13500 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
13501 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
13503 #ifndef NDEBUG
13504 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
13505 #endif
13506 SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
13508 #ifndef SQLITE_OMIT_BTREECOUNT
13509 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
13510 #endif
13512 #ifdef SQLITE_TEST
13513 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
13514 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
13515 #endif
13517 #ifndef SQLITE_OMIT_WAL
13518 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
13519 #endif
13522 ** If we are not using shared cache, then there is no need to
13523 ** use mutexes to access the BtShared structures. So make the
13524 ** Enter and Leave procedures no-ops.
13526 #ifndef SQLITE_OMIT_SHARED_CACHE
13527 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
13528 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
13529 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
13530 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
13531 SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
13532 #else
13533 # define sqlite3BtreeEnter(X)
13534 # define sqlite3BtreeEnterAll(X)
13535 # define sqlite3BtreeSharable(X) 0
13536 # define sqlite3BtreeEnterCursor(X)
13537 # define sqlite3BtreeConnectionCount(X) 1
13538 #endif
13540 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
13541 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
13542 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
13543 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
13544 #ifndef NDEBUG
13545 /* These routines are used inside assert() statements only. */
13546 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
13547 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
13548 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
13549 #endif
13550 #else
13552 # define sqlite3BtreeLeave(X)
13553 # define sqlite3BtreeLeaveCursor(X)
13554 # define sqlite3BtreeLeaveAll(X)
13556 # define sqlite3BtreeHoldsMutex(X) 1
13557 # define sqlite3BtreeHoldsAllMutexes(X) 1
13558 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
13559 #endif
13562 #endif /* SQLITE_BTREE_H */
13564 /************** End of btree.h ***********************************************/
13565 /************** Continuing where we left off in sqliteInt.h ******************/
13566 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
13567 /************** Begin file vdbe.h ********************************************/
13569 ** 2001 September 15
13571 ** The author disclaims copyright to this source code. In place of
13572 ** a legal notice, here is a blessing:
13574 ** May you do good and not evil.
13575 ** May you find forgiveness for yourself and forgive others.
13576 ** May you share freely, never taking more than you give.
13578 *************************************************************************
13579 ** Header file for the Virtual DataBase Engine (VDBE)
13581 ** This header defines the interface to the virtual database engine
13582 ** or VDBE. The VDBE implements an abstract machine that runs a
13583 ** simple program to access and modify the underlying database.
13585 #ifndef SQLITE_VDBE_H
13586 #define SQLITE_VDBE_H
13587 /* #include <stdio.h> */
13590 ** A single VDBE is an opaque structure named "Vdbe". Only routines
13591 ** in the source file sqliteVdbe.c are allowed to see the insides
13592 ** of this structure.
13594 typedef struct Vdbe Vdbe;
13597 ** The names of the following types declared in vdbeInt.h are required
13598 ** for the VdbeOp definition.
13600 typedef struct sqlite3_value Mem;
13601 typedef struct SubProgram SubProgram;
13604 ** A single instruction of the virtual machine has an opcode
13605 ** and as many as three operands. The instruction is recorded
13606 ** as an instance of the following structure:
13608 struct VdbeOp {
13609 u8 opcode; /* What operation to perform */
13610 signed char p4type; /* One of the P4_xxx constants for p4 */
13611 u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
13612 int p1; /* First operand */
13613 int p2; /* Second parameter (often the jump destination) */
13614 int p3; /* The third parameter */
13615 union p4union { /* fourth parameter */
13616 int i; /* Integer value if p4type==P4_INT32 */
13617 void *p; /* Generic pointer */
13618 char *z; /* Pointer to data for string (char array) types */
13619 i64 *pI64; /* Used when p4type is P4_INT64 */
13620 double *pReal; /* Used when p4type is P4_REAL */
13621 FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
13622 sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
13623 CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
13624 Mem *pMem; /* Used when p4type is P4_MEM */
13625 VTable *pVtab; /* Used when p4type is P4_VTAB */
13626 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
13627 int *ai; /* Used when p4type is P4_INTARRAY */
13628 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
13629 Table *pTab; /* Used when p4type is P4_TABLE */
13630 #ifdef SQLITE_ENABLE_CURSOR_HINTS
13631 Expr *pExpr; /* Used when p4type is P4_EXPR */
13632 #endif
13633 int (*xAdvance)(BtCursor *, int);
13634 } p4;
13635 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
13636 char *zComment; /* Comment to improve readability */
13637 #endif
13638 #ifdef VDBE_PROFILE
13639 u32 cnt; /* Number of times this instruction was executed */
13640 u64 cycles; /* Total time spent executing this instruction */
13641 #endif
13642 #ifdef SQLITE_VDBE_COVERAGE
13643 int iSrcLine; /* Source-code line that generated this opcode */
13644 #endif
13646 typedef struct VdbeOp VdbeOp;
13650 ** A sub-routine used to implement a trigger program.
13652 struct SubProgram {
13653 VdbeOp *aOp; /* Array of opcodes for sub-program */
13654 int nOp; /* Elements in aOp[] */
13655 int nMem; /* Number of memory cells required */
13656 int nCsr; /* Number of cursors required */
13657 u8 *aOnce; /* Array of OP_Once flags */
13658 void *token; /* id that may be used to recursive triggers */
13659 SubProgram *pNext; /* Next sub-program already visited */
13663 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
13664 ** it takes up less space.
13666 struct VdbeOpList {
13667 u8 opcode; /* What operation to perform */
13668 signed char p1; /* First operand */
13669 signed char p2; /* Second parameter (often the jump destination) */
13670 signed char p3; /* Third parameter */
13672 typedef struct VdbeOpList VdbeOpList;
13675 ** Allowed values of VdbeOp.p4type
13677 #define P4_NOTUSED 0 /* The P4 parameter is not used */
13678 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
13679 #define P4_STATIC (-1) /* Pointer to a static string */
13680 #define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
13681 #define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
13682 #define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
13683 #define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */
13684 #define P4_TABLE (-6) /* P4 is a pointer to a Table structure */
13685 /* Above do not own any resources. Must free those below */
13686 #define P4_FREE_IF_LE (-7)
13687 #define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */
13688 #define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */
13689 #define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */
13690 #define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */
13691 #define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */
13692 #define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */
13693 #define P4_REAL (-13) /* P4 is a 64-bit floating point value */
13694 #define P4_INT64 (-14) /* P4 is a 64-bit signed integer */
13695 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
13696 #define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
13698 /* Error message codes for OP_Halt */
13699 #define P5_ConstraintNotNull 1
13700 #define P5_ConstraintUnique 2
13701 #define P5_ConstraintCheck 3
13702 #define P5_ConstraintFK 4
13705 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
13706 ** number of columns of data returned by the statement.
13708 #define COLNAME_NAME 0
13709 #define COLNAME_DECLTYPE 1
13710 #define COLNAME_DATABASE 2
13711 #define COLNAME_TABLE 3
13712 #define COLNAME_COLUMN 4
13713 #ifdef SQLITE_ENABLE_COLUMN_METADATA
13714 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
13715 #else
13716 # ifdef SQLITE_OMIT_DECLTYPE
13717 # define COLNAME_N 1 /* Store only the name */
13718 # else
13719 # define COLNAME_N 2 /* Store the name and decltype */
13720 # endif
13721 #endif
13724 ** The following macro converts a relative address in the p2 field
13725 ** of a VdbeOp structure into a negative number so that
13726 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
13727 ** the macro again restores the address.
13729 #define ADDR(X) (-1-(X))
13732 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
13733 ** header file that defines a number for each opcode used by the VDBE.
13735 /************** Include opcodes.h in the middle of vdbe.h ********************/
13736 /************** Begin file opcodes.h *****************************************/
13737 /* Automatically generated. Do not edit */
13738 /* See the tool/mkopcodeh.tcl script for details */
13739 #define OP_Savepoint 0
13740 #define OP_AutoCommit 1
13741 #define OP_Transaction 2
13742 #define OP_SorterNext 3 /* jump */
13743 #define OP_PrevIfOpen 4 /* jump */
13744 #define OP_NextIfOpen 5 /* jump */
13745 #define OP_Prev 6 /* jump */
13746 #define OP_Next 7 /* jump */
13747 #define OP_Checkpoint 8
13748 #define OP_JournalMode 9
13749 #define OP_Vacuum 10
13750 #define OP_VFilter 11 /* jump, synopsis: iplan=r[P3] zplan='P4' */
13751 #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
13752 #define OP_Goto 13 /* jump */
13753 #define OP_Gosub 14 /* jump */
13754 #define OP_InitCoroutine 15 /* jump */
13755 #define OP_Yield 16 /* jump */
13756 #define OP_MustBeInt 17 /* jump */
13757 #define OP_Jump 18 /* jump */
13758 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
13759 #define OP_Once 20 /* jump */
13760 #define OP_If 21 /* jump */
13761 #define OP_IfNot 22 /* jump */
13762 #define OP_IfNullRow 23 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
13763 #define OP_SeekLT 24 /* jump, synopsis: key=r[P3@P4] */
13764 #define OP_SeekLE 25 /* jump, synopsis: key=r[P3@P4] */
13765 #define OP_SeekGE 26 /* jump, synopsis: key=r[P3@P4] */
13766 #define OP_SeekGT 27 /* jump, synopsis: key=r[P3@P4] */
13767 #define OP_NoConflict 28 /* jump, synopsis: key=r[P3@P4] */
13768 #define OP_NotFound 29 /* jump, synopsis: key=r[P3@P4] */
13769 #define OP_Found 30 /* jump, synopsis: key=r[P3@P4] */
13770 #define OP_SeekRowid 31 /* jump, synopsis: intkey=r[P3] */
13771 #define OP_NotExists 32 /* jump, synopsis: intkey=r[P3] */
13772 #define OP_Last 33 /* jump */
13773 #define OP_IfSmaller 34 /* jump */
13774 #define OP_SorterSort 35 /* jump */
13775 #define OP_Sort 36 /* jump */
13776 #define OP_Rewind 37 /* jump */
13777 #define OP_IdxLE 38 /* jump, synopsis: key=r[P3@P4] */
13778 #define OP_IdxGT 39 /* jump, synopsis: key=r[P3@P4] */
13779 #define OP_IdxLT 40 /* jump, synopsis: key=r[P3@P4] */
13780 #define OP_IdxGE 41 /* jump, synopsis: key=r[P3@P4] */
13781 #define OP_RowSetRead 42 /* jump, synopsis: r[P3]=rowset(P1) */
13782 #define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
13783 #define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
13784 #define OP_RowSetTest 45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
13785 #define OP_Program 46 /* jump */
13786 #define OP_FkIfZero 47 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
13787 #define OP_IfPos 48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
13788 #define OP_IfNotZero 49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
13789 #define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
13790 #define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
13791 #define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
13792 #define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
13793 #define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
13794 #define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
13795 #define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
13796 #define OP_Ge 57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
13797 #define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */
13798 #define OP_DecrJumpZero 59 /* jump, synopsis: if (--r[P1])==0 goto P2 */
13799 #define OP_IncrVacuum 60 /* jump */
13800 #define OP_VNext 61 /* jump */
13801 #define OP_Init 62 /* jump, synopsis: Start at P2 */
13802 #define OP_Return 63
13803 #define OP_EndCoroutine 64
13804 #define OP_HaltIfNull 65 /* synopsis: if r[P3]=null halt */
13805 #define OP_Halt 66
13806 #define OP_Integer 67 /* synopsis: r[P2]=P1 */
13807 #define OP_Int64 68 /* synopsis: r[P2]=P4 */
13808 #define OP_String 69 /* synopsis: r[P2]='P4' (len=P1) */
13809 #define OP_Null 70 /* synopsis: r[P2..P3]=NULL */
13810 #define OP_SoftNull 71 /* synopsis: r[P1]=NULL */
13811 #define OP_Blob 72 /* synopsis: r[P2]=P4 (len=P1) */
13812 #define OP_Variable 73 /* synopsis: r[P2]=parameter(P1,P4) */
13813 #define OP_Move 74 /* synopsis: r[P2@P3]=r[P1@P3] */
13814 #define OP_Copy 75 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
13815 #define OP_SCopy 76 /* synopsis: r[P2]=r[P1] */
13816 #define OP_IntCopy 77 /* synopsis: r[P2]=r[P1] */
13817 #define OP_ResultRow 78 /* synopsis: output=r[P1@P2] */
13818 #define OP_CollSeq 79
13819 #define OP_AddImm 80 /* synopsis: r[P1]=r[P1]+P2 */
13820 #define OP_RealAffinity 81
13821 #define OP_Cast 82 /* synopsis: affinity(r[P1]) */
13822 #define OP_Permutation 83
13823 #define OP_BitAnd 84 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
13824 #define OP_BitOr 85 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
13825 #define OP_ShiftLeft 86 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
13826 #define OP_ShiftRight 87 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
13827 #define OP_Add 88 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
13828 #define OP_Subtract 89 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
13829 #define OP_Multiply 90 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
13830 #define OP_Divide 91 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
13831 #define OP_Remainder 92 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
13832 #define OP_Concat 93 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
13833 #define OP_Compare 94 /* synopsis: r[P1@P3] <-> r[P2@P3] */
13834 #define OP_BitNot 95 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
13835 #define OP_Column 96 /* synopsis: r[P3]=PX */
13836 #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
13837 #define OP_Affinity 98 /* synopsis: affinity(r[P1@P2]) */
13838 #define OP_MakeRecord 99 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
13839 #define OP_Count 100 /* synopsis: r[P2]=count() */
13840 #define OP_ReadCookie 101
13841 #define OP_SetCookie 102
13842 #define OP_ReopenIdx 103 /* synopsis: root=P2 iDb=P3 */
13843 #define OP_OpenRead 104 /* synopsis: root=P2 iDb=P3 */
13844 #define OP_OpenWrite 105 /* synopsis: root=P2 iDb=P3 */
13845 #define OP_OpenDup 106
13846 #define OP_OpenAutoindex 107 /* synopsis: nColumn=P2 */
13847 #define OP_OpenEphemeral 108 /* synopsis: nColumn=P2 */
13848 #define OP_SorterOpen 109
13849 #define OP_SequenceTest 110 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
13850 #define OP_OpenPseudo 111 /* synopsis: P3 columns in r[P2] */
13851 #define OP_Close 112
13852 #define OP_ColumnsUsed 113
13853 #define OP_Sequence 114 /* synopsis: r[P2]=cursor[P1].ctr++ */
13854 #define OP_NewRowid 115 /* synopsis: r[P2]=rowid */
13855 #define OP_Insert 116 /* synopsis: intkey=r[P3] data=r[P2] */
13856 #define OP_InsertInt 117 /* synopsis: intkey=P3 data=r[P2] */
13857 #define OP_Delete 118
13858 #define OP_ResetCount 119
13859 #define OP_SorterCompare 120 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
13860 #define OP_SorterData 121 /* synopsis: r[P2]=data */
13861 #define OP_RowData 122 /* synopsis: r[P2]=data */
13862 #define OP_Rowid 123 /* synopsis: r[P2]=rowid */
13863 #define OP_NullRow 124
13864 #define OP_SeekEnd 125
13865 #define OP_SorterInsert 126 /* synopsis: key=r[P2] */
13866 #define OP_IdxInsert 127 /* synopsis: key=r[P2] */
13867 #define OP_IdxDelete 128 /* synopsis: key=r[P2@P3] */
13868 #define OP_DeferredSeek 129 /* synopsis: Move P3 to P1.rowid if needed */
13869 #define OP_IdxRowid 130 /* synopsis: r[P2]=rowid */
13870 #define OP_Destroy 131
13871 #define OP_Real 132 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
13872 #define OP_Clear 133
13873 #define OP_ResetSorter 134
13874 #define OP_CreateBtree 135 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
13875 #define OP_SqlExec 136
13876 #define OP_ParseSchema 137
13877 #define OP_LoadAnalysis 138
13878 #define OP_DropTable 139
13879 #define OP_DropIndex 140
13880 #define OP_DropTrigger 141
13881 #define OP_IntegrityCk 142
13882 #define OP_RowSetAdd 143 /* synopsis: rowset(P1)=r[P2] */
13883 #define OP_Param 144
13884 #define OP_FkCounter 145 /* synopsis: fkctr[P1]+=P2 */
13885 #define OP_MemMax 146 /* synopsis: r[P1]=max(r[P1],r[P2]) */
13886 #define OP_OffsetLimit 147 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
13887 #define OP_AggStep0 148 /* synopsis: accum=r[P3] step(r[P2@P5]) */
13888 #define OP_AggStep 149 /* synopsis: accum=r[P3] step(r[P2@P5]) */
13889 #define OP_AggFinal 150 /* synopsis: accum=r[P1] N=P2 */
13890 #define OP_Expire 151
13891 #define OP_TableLock 152 /* synopsis: iDb=P1 root=P2 write=P3 */
13892 #define OP_VBegin 153
13893 #define OP_VCreate 154
13894 #define OP_VDestroy 155
13895 #define OP_VOpen 156
13896 #define OP_VColumn 157 /* synopsis: r[P3]=vcolumn(P2) */
13897 #define OP_VRename 158
13898 #define OP_Pagecount 159
13899 #define OP_MaxPgcnt 160
13900 #define OP_PureFunc0 161
13901 #define OP_Function0 162 /* synopsis: r[P3]=func(r[P2@P5]) */
13902 #define OP_PureFunc 163
13903 #define OP_Function 164 /* synopsis: r[P3]=func(r[P2@P5]) */
13904 #define OP_CursorHint 165
13905 #define OP_Noop 166
13906 #define OP_Explain 167
13908 /* Properties such as "out2" or "jump" that are specified in
13909 ** comments following the "case" for each opcode in the vdbe.c
13910 ** are encoded into bitvectors as follows:
13912 #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
13913 #define OPFLG_IN1 0x02 /* in1: P1 is an input */
13914 #define OPFLG_IN2 0x04 /* in2: P2 is an input */
13915 #define OPFLG_IN3 0x08 /* in3: P3 is an input */
13916 #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
13917 #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
13918 #define OPFLG_INITIALIZER {\
13919 /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
13920 /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
13921 /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x01,\
13922 /* 24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
13923 /* 32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
13924 /* 40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\
13925 /* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
13926 /* 56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x02,\
13927 /* 64 */ 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00,\
13928 /* 72 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
13929 /* 80 */ 0x02, 0x02, 0x02, 0x00, 0x26, 0x26, 0x26, 0x26,\
13930 /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x12,\
13931 /* 96 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
13932 /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
13933 /* 112 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
13934 /* 120 */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x04, 0x04,\
13935 /* 128 */ 0x00, 0x00, 0x10, 0x10, 0x10, 0x00, 0x00, 0x10,\
13936 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,\
13937 /* 144 */ 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00,\
13938 /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
13939 /* 160 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
13942 /* The sqlite3P2Values() routine is able to run faster if it knows
13943 ** the value of the largest JUMP opcode. The smaller the maximum
13944 ** JUMP opcode the better, so the mkopcodeh.tcl script that
13945 ** generated this include file strives to group all JUMP opcodes
13946 ** together near the beginning of the list.
13948 #define SQLITE_MX_JUMP_OPCODE 62 /* Maximum JUMP opcode */
13950 /************** End of opcodes.h *********************************************/
13951 /************** Continuing where we left off in vdbe.h ***********************/
13954 ** Additional non-public SQLITE_PREPARE_* flags
13956 #define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
13957 #define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */
13960 ** Prototypes for the VDBE interface. See comments on the implementation
13961 ** for a description of what each of these routines does.
13963 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
13964 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
13965 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
13966 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
13967 SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
13968 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
13969 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
13970 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
13971 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
13972 SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
13973 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
13974 SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
13975 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
13976 SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
13977 SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
13978 #else
13979 # define sqlite3VdbeVerifyNoMallocRequired(A,B)
13980 # define sqlite3VdbeVerifyNoResultRow(A)
13981 #endif
13982 SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
13983 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
13984 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
13985 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
13986 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
13987 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
13988 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
13989 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
13990 SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
13991 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
13992 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
13993 SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
13994 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
13995 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
13996 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
13997 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
13998 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
13999 SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
14000 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
14001 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
14002 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
14003 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
14004 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
14005 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
14006 #ifdef SQLITE_DEBUG
14007 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
14008 #endif
14009 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
14010 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
14011 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
14012 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
14013 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
14014 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
14015 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
14016 SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
14017 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
14018 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
14019 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
14020 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
14021 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
14022 #ifndef SQLITE_OMIT_TRACE
14023 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
14024 #endif
14025 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
14027 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
14028 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
14029 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
14030 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
14032 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
14033 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
14035 #ifndef SQLITE_OMIT_TRIGGER
14036 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
14037 #endif
14039 SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
14041 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
14042 ** each VDBE opcode.
14044 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
14045 ** comments in VDBE programs that show key decision points in the code
14046 ** generator.
14048 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
14049 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
14050 # define VdbeComment(X) sqlite3VdbeComment X
14051 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
14052 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
14053 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
14054 # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
14055 # else
14056 # define VdbeModuleComment(X)
14057 # endif
14058 #else
14059 # define VdbeComment(X)
14060 # define VdbeNoopComment(X)
14061 # define VdbeModuleComment(X)
14062 #endif
14065 ** The VdbeCoverage macros are used to set a coverage testing point
14066 ** for VDBE branch instructions. The coverage testing points are line
14067 ** numbers in the sqlite3.c source file. VDBE branch coverage testing
14068 ** only works with an amalagmation build. That's ok since a VDBE branch
14069 ** coverage build designed for testing the test suite only. No application
14070 ** should ever ship with VDBE branch coverage measuring turned on.
14072 ** VdbeCoverage(v) // Mark the previously coded instruction
14073 ** // as a branch
14075 ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
14077 ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
14079 ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
14081 ** Every VDBE branch operation must be tagged with one of the macros above.
14082 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
14083 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
14084 ** routine in vdbe.c, alerting the developer to the missed tag.
14086 #ifdef SQLITE_VDBE_COVERAGE
14087 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
14088 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
14089 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
14090 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
14091 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
14092 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
14093 #else
14094 # define VdbeCoverage(v)
14095 # define VdbeCoverageIf(v,x)
14096 # define VdbeCoverageAlwaysTaken(v)
14097 # define VdbeCoverageNeverTaken(v)
14098 # define VDBE_OFFSET_LINENO(x) 0
14099 #endif
14101 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
14102 SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
14103 #else
14104 # define sqlite3VdbeScanStatus(a,b,c,d,e)
14105 #endif
14107 #endif /* SQLITE_VDBE_H */
14109 /************** End of vdbe.h ************************************************/
14110 /************** Continuing where we left off in sqliteInt.h ******************/
14111 /************** Include pager.h in the middle of sqliteInt.h *****************/
14112 /************** Begin file pager.h *******************************************/
14114 ** 2001 September 15
14116 ** The author disclaims copyright to this source code. In place of
14117 ** a legal notice, here is a blessing:
14119 ** May you do good and not evil.
14120 ** May you find forgiveness for yourself and forgive others.
14121 ** May you share freely, never taking more than you give.
14123 *************************************************************************
14124 ** This header file defines the interface that the sqlite page cache
14125 ** subsystem. The page cache subsystem reads and writes a file a page
14126 ** at a time and provides a journal for rollback.
14129 #ifndef SQLITE_PAGER_H
14130 #define SQLITE_PAGER_H
14133 ** Default maximum size for persistent journal files. A negative
14134 ** value means no limit. This value may be overridden using the
14135 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
14137 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
14138 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
14139 #endif
14142 ** The type used to represent a page number. The first page in a file
14143 ** is called page 1. 0 is used to represent "not a page".
14145 typedef u32 Pgno;
14148 ** Each open file is managed by a separate instance of the "Pager" structure.
14150 typedef struct Pager Pager;
14153 ** Handle type for pages.
14155 typedef struct PgHdr DbPage;
14158 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
14159 ** reserved for working around a windows/posix incompatibility). It is
14160 ** used in the journal to signify that the remainder of the journal file
14161 ** is devoted to storing a master journal name - there are no more pages to
14162 ** roll back. See comments for function writeMasterJournal() in pager.c
14163 ** for details.
14165 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
14168 ** Allowed values for the flags parameter to sqlite3PagerOpen().
14170 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
14172 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
14173 #define PAGER_MEMORY 0x0002 /* In-memory database */
14176 ** Valid values for the second argument to sqlite3PagerLockingMode().
14178 #define PAGER_LOCKINGMODE_QUERY -1
14179 #define PAGER_LOCKINGMODE_NORMAL 0
14180 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
14183 ** Numeric constants that encode the journalmode.
14185 ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
14186 ** are exposed in the API via the "PRAGMA journal_mode" command and
14187 ** therefore cannot be changed without a compatibility break.
14189 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
14190 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
14191 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
14192 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
14193 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
14194 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
14195 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
14198 ** Flags that make up the mask passed to sqlite3PagerGet().
14200 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
14201 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
14204 ** Flags for sqlite3PagerSetFlags()
14206 ** Value constraints (enforced via assert()):
14207 ** PAGER_FULLFSYNC == SQLITE_FullFSync
14208 ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
14209 ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
14211 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
14212 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
14213 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
14214 #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
14215 #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
14216 #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
14217 #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
14218 #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
14219 #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
14222 ** The remainder of this file contains the declarations of the functions
14223 ** that make up the Pager sub-system API. See source code comments for
14224 ** a detailed description of each routine.
14227 /* Open and close a Pager connection. */
14228 SQLITE_PRIVATE int sqlite3PagerOpen(
14229 sqlite3_vfs*,
14230 Pager **ppPager,
14231 const char*,
14232 int,
14233 int,
14234 int,
14235 void(*)(DbPage*)
14237 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
14238 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
14240 /* Functions used to configure a Pager object. */
14241 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
14242 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
14243 #ifdef SQLITE_HAS_CODEC
14244 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
14245 #endif
14246 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
14247 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
14248 SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
14249 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
14250 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
14251 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
14252 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
14253 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
14254 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
14255 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
14256 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
14257 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
14258 SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
14260 /* Functions used to obtain and release page references. */
14261 SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
14262 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
14263 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
14264 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
14265 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
14266 SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
14268 /* Operations on page references. */
14269 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
14270 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
14271 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
14272 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
14273 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
14274 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
14276 /* Functions used to manage pager transactions and savepoints. */
14277 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
14278 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
14279 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
14280 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
14281 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
14282 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
14283 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
14284 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
14285 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
14286 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
14288 #ifndef SQLITE_OMIT_WAL
14289 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
14290 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
14291 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
14292 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
14293 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
14294 # ifdef SQLITE_DIRECT_OVERFLOW_READ
14295 SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno);
14296 # endif
14297 # ifdef SQLITE_ENABLE_SNAPSHOT
14298 SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
14299 SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
14300 SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
14301 # endif
14302 #else
14303 # define sqlite3PagerUseWal(x,y) 0
14304 #endif
14306 #ifdef SQLITE_ENABLE_ZIPVFS
14307 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
14308 #endif
14310 /* Functions used to query pager state and configuration. */
14311 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
14312 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
14313 #ifdef SQLITE_DEBUG
14314 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
14315 #endif
14316 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
14317 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
14318 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
14319 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
14320 SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
14321 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
14322 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
14323 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
14324 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
14325 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
14326 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
14328 /* Functions used to truncate the database file. */
14329 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
14331 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
14333 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
14334 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
14335 #endif
14337 /* Functions to support testing and debugging. */
14338 #if !defined(NDEBUG) || defined(SQLITE_TEST)
14339 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
14340 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
14341 #endif
14342 #ifdef SQLITE_TEST
14343 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
14344 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
14345 void disable_simulated_io_errors(void);
14346 void enable_simulated_io_errors(void);
14347 #else
14348 # define disable_simulated_io_errors()
14349 # define enable_simulated_io_errors()
14350 #endif
14352 #endif /* SQLITE_PAGER_H */
14354 /************** End of pager.h ***********************************************/
14355 /************** Continuing where we left off in sqliteInt.h ******************/
14356 /************** Include pcache.h in the middle of sqliteInt.h ****************/
14357 /************** Begin file pcache.h ******************************************/
14359 ** 2008 August 05
14361 ** The author disclaims copyright to this source code. In place of
14362 ** a legal notice, here is a blessing:
14364 ** May you do good and not evil.
14365 ** May you find forgiveness for yourself and forgive others.
14366 ** May you share freely, never taking more than you give.
14368 *************************************************************************
14369 ** This header file defines the interface that the sqlite page cache
14370 ** subsystem.
14373 #ifndef _PCACHE_H_
14375 typedef struct PgHdr PgHdr;
14376 typedef struct PCache PCache;
14379 ** Every page in the cache is controlled by an instance of the following
14380 ** structure.
14382 struct PgHdr {
14383 sqlite3_pcache_page *pPage; /* Pcache object page handle */
14384 void *pData; /* Page data */
14385 void *pExtra; /* Extra content */
14386 PCache *pCache; /* PRIVATE: Cache that owns this page */
14387 PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
14388 Pager *pPager; /* The pager this page is part of */
14389 Pgno pgno; /* Page number for this page */
14390 #ifdef SQLITE_CHECK_PAGES
14391 u32 pageHash; /* Hash of page content */
14392 #endif
14393 u16 flags; /* PGHDR flags defined below */
14395 /**********************************************************************
14396 ** Elements above, except pCache, are public. All that follow are
14397 ** private to pcache.c and should not be accessed by other modules.
14398 ** pCache is grouped with the public elements for efficiency.
14400 i16 nRef; /* Number of users of this page */
14401 PgHdr *pDirtyNext; /* Next element in list of dirty pages */
14402 PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
14403 /* NB: pDirtyNext and pDirtyPrev are undefined if the
14404 ** PgHdr object is not dirty */
14407 /* Bit values for PgHdr.flags */
14408 #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
14409 #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
14410 #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
14411 #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
14412 ** writing this page to the database */
14413 #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
14414 #define PGHDR_MMAP 0x020 /* This is an mmap page object */
14416 #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
14418 /* Initialize and shutdown the page cache subsystem */
14419 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
14420 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
14422 /* Page cache buffer management:
14423 ** These routines implement SQLITE_CONFIG_PAGECACHE.
14425 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
14427 /* Create a new pager cache.
14428 ** Under memory stress, invoke xStress to try to make pages clean.
14429 ** Only clean and unpinned pages can be reclaimed.
14431 SQLITE_PRIVATE int sqlite3PcacheOpen(
14432 int szPage, /* Size of every page */
14433 int szExtra, /* Extra space associated with each page */
14434 int bPurgeable, /* True if pages are on backing store */
14435 int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
14436 void *pStress, /* Argument to xStress */
14437 PCache *pToInit /* Preallocated space for the PCache */
14440 /* Modify the page-size after the cache has been created. */
14441 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
14443 /* Return the size in bytes of a PCache object. Used to preallocate
14444 ** storage space.
14446 SQLITE_PRIVATE int sqlite3PcacheSize(void);
14448 /* One release per successful fetch. Page is pinned until released.
14449 ** Reference counted.
14451 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
14452 SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
14453 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
14454 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
14456 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
14457 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
14458 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
14459 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
14460 SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
14462 /* Change a page number. Used by incr-vacuum. */
14463 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
14465 /* Remove all pages with pgno>x. Reset the cache if x==0 */
14466 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
14468 /* Get a list of all dirty pages in the cache, sorted by page number */
14469 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
14471 /* Reset and close the cache object */
14472 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
14474 /* Clear flags from pages of the page cache */
14475 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
14477 /* Discard the contents of the cache */
14478 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
14480 /* Return the total number of outstanding page references */
14481 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
14483 /* Increment the reference count of an existing page */
14484 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
14486 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
14488 /* Return the total number of pages stored in the cache */
14489 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
14491 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
14492 /* Iterate through all dirty pages currently stored in the cache. This
14493 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
14494 ** library is built.
14496 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
14497 #endif
14499 #if defined(SQLITE_DEBUG)
14500 /* Check invariants on a PgHdr object */
14501 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
14502 #endif
14504 /* Set and get the suggested cache-size for the specified pager-cache.
14506 ** If no global maximum is configured, then the system attempts to limit
14507 ** the total number of pages cached by purgeable pager-caches to the sum
14508 ** of the suggested cache-sizes.
14510 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
14511 #ifdef SQLITE_TEST
14512 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
14513 #endif
14515 /* Set or get the suggested spill-size for the specified pager-cache.
14517 ** The spill-size is the minimum number of pages in cache before the cache
14518 ** will attempt to spill dirty pages by calling xStress.
14520 SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
14522 /* Free up as much memory as possible from the page cache */
14523 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
14525 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
14526 /* Try to return memory used by the pcache module to the main memory heap */
14527 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
14528 #endif
14530 #ifdef SQLITE_TEST
14531 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
14532 #endif
14534 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
14536 /* Return the header size */
14537 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
14538 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
14540 /* Number of dirty pages as a percentage of the configured cache size */
14541 SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
14543 #endif /* _PCACHE_H_ */
14545 /************** End of pcache.h **********************************************/
14546 /************** Continuing where we left off in sqliteInt.h ******************/
14547 /************** Include os.h in the middle of sqliteInt.h ********************/
14548 /************** Begin file os.h **********************************************/
14550 ** 2001 September 16
14552 ** The author disclaims copyright to this source code. In place of
14553 ** a legal notice, here is a blessing:
14555 ** May you do good and not evil.
14556 ** May you find forgiveness for yourself and forgive others.
14557 ** May you share freely, never taking more than you give.
14559 ******************************************************************************
14561 ** This header file (together with is companion C source-code file
14562 ** "os.c") attempt to abstract the underlying operating system so that
14563 ** the SQLite library will work on both POSIX and windows systems.
14565 ** This header file is #include-ed by sqliteInt.h and thus ends up
14566 ** being included by every source file.
14568 #ifndef _SQLITE_OS_H_
14569 #define _SQLITE_OS_H_
14572 ** Attempt to automatically detect the operating system and setup the
14573 ** necessary pre-processor macros for it.
14575 /************** Include os_setup.h in the middle of os.h *********************/
14576 /************** Begin file os_setup.h ****************************************/
14578 ** 2013 November 25
14580 ** The author disclaims copyright to this source code. In place of
14581 ** a legal notice, here is a blessing:
14583 ** May you do good and not evil.
14584 ** May you find forgiveness for yourself and forgive others.
14585 ** May you share freely, never taking more than you give.
14587 ******************************************************************************
14589 ** This file contains pre-processor directives related to operating system
14590 ** detection and/or setup.
14592 #ifndef SQLITE_OS_SETUP_H
14593 #define SQLITE_OS_SETUP_H
14596 ** Figure out if we are dealing with Unix, Windows, or some other operating
14597 ** system.
14599 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
14600 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
14601 ** the three will be 1. The other two will be 0.
14603 #if defined(SQLITE_OS_OTHER)
14604 # if SQLITE_OS_OTHER==1
14605 # undef SQLITE_OS_UNIX
14606 # define SQLITE_OS_UNIX 0
14607 # undef SQLITE_OS_WIN
14608 # define SQLITE_OS_WIN 0
14609 # else
14610 # undef SQLITE_OS_OTHER
14611 # endif
14612 #endif
14613 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
14614 # define SQLITE_OS_OTHER 0
14615 # ifndef SQLITE_OS_WIN
14616 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
14617 defined(__MINGW32__) || defined(__BORLANDC__)
14618 # define SQLITE_OS_WIN 1
14619 # define SQLITE_OS_UNIX 0
14620 # else
14621 # define SQLITE_OS_WIN 0
14622 # define SQLITE_OS_UNIX 1
14623 # endif
14624 # else
14625 # define SQLITE_OS_UNIX 0
14626 # endif
14627 #else
14628 # ifndef SQLITE_OS_WIN
14629 # define SQLITE_OS_WIN 0
14630 # endif
14631 #endif
14633 #endif /* SQLITE_OS_SETUP_H */
14635 /************** End of os_setup.h ********************************************/
14636 /************** Continuing where we left off in os.h *************************/
14638 /* If the SET_FULLSYNC macro is not defined above, then make it
14639 ** a no-op
14641 #ifndef SET_FULLSYNC
14642 # define SET_FULLSYNC(x,y)
14643 #endif
14646 ** The default size of a disk sector
14648 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
14649 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
14650 #endif
14653 ** Temporary files are named starting with this prefix followed by 16 random
14654 ** alphanumeric characters, and no file extension. They are stored in the
14655 ** OS's standard temporary file directory, and are deleted prior to exit.
14656 ** If sqlite is being embedded in another program, you may wish to change the
14657 ** prefix to reflect your program's name, so that if your program exits
14658 ** prematurely, old temporary files can be easily identified. This can be done
14659 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
14661 ** 2006-10-31: The default prefix used to be "sqlite_". But then
14662 ** Mcafee started using SQLite in their anti-virus product and it
14663 ** started putting files with the "sqlite" name in the c:/temp folder.
14664 ** This annoyed many windows users. Those users would then do a
14665 ** Google search for "sqlite", find the telephone numbers of the
14666 ** developers and call to wake them up at night and complain.
14667 ** For this reason, the default name prefix is changed to be "sqlite"
14668 ** spelled backwards. So the temp files are still identified, but
14669 ** anybody smart enough to figure out the code is also likely smart
14670 ** enough to know that calling the developer will not help get rid
14671 ** of the file.
14673 #ifndef SQLITE_TEMP_FILE_PREFIX
14674 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
14675 #endif
14678 ** The following values may be passed as the second argument to
14679 ** sqlite3OsLock(). The various locks exhibit the following semantics:
14681 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
14682 ** RESERVED: A single process may hold a RESERVED lock on a file at
14683 ** any time. Other processes may hold and obtain new SHARED locks.
14684 ** PENDING: A single process may hold a PENDING lock on a file at
14685 ** any one time. Existing SHARED locks may persist, but no new
14686 ** SHARED locks may be obtained by other processes.
14687 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
14689 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
14690 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
14691 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
14692 ** sqlite3OsLock().
14694 #define NO_LOCK 0
14695 #define SHARED_LOCK 1
14696 #define RESERVED_LOCK 2
14697 #define PENDING_LOCK 3
14698 #define EXCLUSIVE_LOCK 4
14701 ** File Locking Notes: (Mostly about windows but also some info for Unix)
14703 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
14704 ** those functions are not available. So we use only LockFile() and
14705 ** UnlockFile().
14707 ** LockFile() prevents not just writing but also reading by other processes.
14708 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
14709 ** byte out of a specific range of bytes. The lock byte is obtained at
14710 ** random so two separate readers can probably access the file at the
14711 ** same time, unless they are unlucky and choose the same lock byte.
14712 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
14713 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
14714 ** a single byte of the file that is designated as the reserved lock byte.
14715 ** A PENDING_LOCK is obtained by locking a designated byte different from
14716 ** the RESERVED_LOCK byte.
14718 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
14719 ** which means we can use reader/writer locks. When reader/writer locks
14720 ** are used, the lock is placed on the same range of bytes that is used
14721 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
14722 ** will support two or more Win95 readers or two or more WinNT readers.
14723 ** But a single Win95 reader will lock out all WinNT readers and a single
14724 ** WinNT reader will lock out all other Win95 readers.
14726 ** The following #defines specify the range of bytes used for locking.
14727 ** SHARED_SIZE is the number of bytes available in the pool from which
14728 ** a random byte is selected for a shared lock. The pool of bytes for
14729 ** shared locks begins at SHARED_FIRST.
14731 ** The same locking strategy and
14732 ** byte ranges are used for Unix. This leaves open the possibility of having
14733 ** clients on win95, winNT, and unix all talking to the same shared file
14734 ** and all locking correctly. To do so would require that samba (or whatever
14735 ** tool is being used for file sharing) implements locks correctly between
14736 ** windows and unix. I'm guessing that isn't likely to happen, but by
14737 ** using the same locking range we are at least open to the possibility.
14739 ** Locking in windows is manditory. For this reason, we cannot store
14740 ** actual data in the bytes used for locking. The pager never allocates
14741 ** the pages involved in locking therefore. SHARED_SIZE is selected so
14742 ** that all locks will fit on a single page even at the minimum page size.
14743 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
14744 ** is set high so that we don't have to allocate an unused page except
14745 ** for very large databases. But one should test the page skipping logic
14746 ** by setting PENDING_BYTE low and running the entire regression suite.
14748 ** Changing the value of PENDING_BYTE results in a subtly incompatible
14749 ** file format. Depending on how it is changed, you might not notice
14750 ** the incompatibility right away, even running a full regression test.
14751 ** The default location of PENDING_BYTE is the first byte past the
14752 ** 1GB boundary.
14755 #ifdef SQLITE_OMIT_WSD
14756 # define PENDING_BYTE (0x40000000)
14757 #else
14758 # define PENDING_BYTE sqlite3PendingByte
14759 #endif
14760 #define RESERVED_BYTE (PENDING_BYTE+1)
14761 #define SHARED_FIRST (PENDING_BYTE+2)
14762 #define SHARED_SIZE 510
14765 ** Wrapper around OS specific sqlite3_os_init() function.
14767 SQLITE_PRIVATE int sqlite3OsInit(void);
14770 ** Functions for accessing sqlite3_file methods
14772 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
14773 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
14774 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
14775 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
14776 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
14777 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
14778 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
14779 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
14780 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
14781 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
14782 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
14783 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
14784 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
14785 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
14786 #ifndef SQLITE_OMIT_WAL
14787 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
14788 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
14789 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
14790 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
14791 #endif /* SQLITE_OMIT_WAL */
14792 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
14793 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
14797 ** Functions for accessing sqlite3_vfs methods
14799 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
14800 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
14801 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
14802 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
14803 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14804 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
14805 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
14806 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
14807 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
14808 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
14809 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
14810 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
14811 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
14812 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
14815 ** Convenience functions for opening and closing files using
14816 ** sqlite3_malloc() to obtain space for the file-handle structure.
14818 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
14819 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
14821 #endif /* _SQLITE_OS_H_ */
14823 /************** End of os.h **************************************************/
14824 /************** Continuing where we left off in sqliteInt.h ******************/
14825 /************** Include mutex.h in the middle of sqliteInt.h *****************/
14826 /************** Begin file mutex.h *******************************************/
14828 ** 2007 August 28
14830 ** The author disclaims copyright to this source code. In place of
14831 ** a legal notice, here is a blessing:
14833 ** May you do good and not evil.
14834 ** May you find forgiveness for yourself and forgive others.
14835 ** May you share freely, never taking more than you give.
14837 *************************************************************************
14839 ** This file contains the common header for all mutex implementations.
14840 ** The sqliteInt.h header #includes this file so that it is available
14841 ** to all source files. We break it out in an effort to keep the code
14842 ** better organized.
14844 ** NOTE: source files should *not* #include this header file directly.
14845 ** Source files should #include the sqliteInt.h file and let that file
14846 ** include this one indirectly.
14851 ** Figure out what version of the code to use. The choices are
14853 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
14854 ** mutexes implementation cannot be overridden
14855 ** at start-time.
14857 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
14858 ** mutual exclusion is provided. But this
14859 ** implementation can be overridden at
14860 ** start-time.
14862 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
14864 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
14866 #if !SQLITE_THREADSAFE
14867 # define SQLITE_MUTEX_OMIT
14868 #endif
14869 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
14870 # if SQLITE_OS_UNIX
14871 # define SQLITE_MUTEX_PTHREADS
14872 # elif SQLITE_OS_WIN
14873 # define SQLITE_MUTEX_W32
14874 # else
14875 # define SQLITE_MUTEX_NOOP
14876 # endif
14877 #endif
14879 #ifdef SQLITE_MUTEX_OMIT
14881 ** If this is a no-op implementation, implement everything as macros.
14883 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
14884 #define sqlite3_mutex_free(X)
14885 #define sqlite3_mutex_enter(X)
14886 #define sqlite3_mutex_try(X) SQLITE_OK
14887 #define sqlite3_mutex_leave(X)
14888 #define sqlite3_mutex_held(X) ((void)(X),1)
14889 #define sqlite3_mutex_notheld(X) ((void)(X),1)
14890 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
14891 #define sqlite3MutexInit() SQLITE_OK
14892 #define sqlite3MutexEnd()
14893 #define MUTEX_LOGIC(X)
14894 #else
14895 #define MUTEX_LOGIC(X) X
14896 #endif /* defined(SQLITE_MUTEX_OMIT) */
14898 /************** End of mutex.h ***********************************************/
14899 /************** Continuing where we left off in sqliteInt.h ******************/
14901 /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
14902 ** synchronous setting to EXTRA. It is no longer supported.
14904 #ifdef SQLITE_EXTRA_DURABLE
14905 # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
14906 # define SQLITE_DEFAULT_SYNCHRONOUS 3
14907 #endif
14910 ** Default synchronous levels.
14912 ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
14913 ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
14915 ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
14916 ** OFF 1 0
14917 ** NORMAL 2 1
14918 ** FULL 3 2
14919 ** EXTRA 4 3
14921 ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
14922 ** In other words, the zero-based numbers are used for all external interfaces
14923 ** and the one-based values are used internally.
14925 #ifndef SQLITE_DEFAULT_SYNCHRONOUS
14926 # define SQLITE_DEFAULT_SYNCHRONOUS 2
14927 #endif
14928 #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
14929 # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
14930 #endif
14933 ** Each database file to be accessed by the system is an instance
14934 ** of the following structure. There are normally two of these structures
14935 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
14936 ** aDb[1] is the database file used to hold temporary tables. Additional
14937 ** databases may be attached.
14939 struct Db {
14940 char *zDbSName; /* Name of this database. (schema name, not filename) */
14941 Btree *pBt; /* The B*Tree structure for this database file */
14942 u8 safety_level; /* How aggressive at syncing data to disk */
14943 u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
14944 Schema *pSchema; /* Pointer to database schema (possibly shared) */
14948 ** An instance of the following structure stores a database schema.
14950 ** Most Schema objects are associated with a Btree. The exception is
14951 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
14952 ** In shared cache mode, a single Schema object can be shared by multiple
14953 ** Btrees that refer to the same underlying BtShared object.
14955 ** Schema objects are automatically deallocated when the last Btree that
14956 ** references them is destroyed. The TEMP Schema is manually freed by
14957 ** sqlite3_close().
14959 ** A thread must be holding a mutex on the corresponding Btree in order
14960 ** to access Schema content. This implies that the thread must also be
14961 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
14962 ** For a TEMP Schema, only the connection mutex is required.
14964 struct Schema {
14965 int schema_cookie; /* Database schema version number for this file */
14966 int iGeneration; /* Generation counter. Incremented with each change */
14967 Hash tblHash; /* All tables indexed by name */
14968 Hash idxHash; /* All (named) indices indexed by name */
14969 Hash trigHash; /* All triggers indexed by name */
14970 Hash fkeyHash; /* All foreign keys by referenced table name */
14971 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
14972 u8 file_format; /* Schema format version for this file */
14973 u8 enc; /* Text encoding used by this database */
14974 u16 schemaFlags; /* Flags associated with this schema */
14975 int cache_size; /* Number of pages to use in the cache */
14979 ** These macros can be used to test, set, or clear bits in the
14980 ** Db.pSchema->flags field.
14982 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
14983 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
14984 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
14985 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
14988 ** Allowed values for the DB.pSchema->flags field.
14990 ** The DB_SchemaLoaded flag is set after the database schema has been
14991 ** read into internal hash tables.
14993 ** DB_UnresetViews means that one or more views have column names that
14994 ** have been filled out. If the schema changes, these column names might
14995 ** changes and so the view will need to be reset.
14997 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
14998 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
14999 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
15000 #define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
15003 ** The number of different kinds of things that can be limited
15004 ** using the sqlite3_limit() interface.
15006 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
15009 ** Lookaside malloc is a set of fixed-size buffers that can be used
15010 ** to satisfy small transient memory allocation requests for objects
15011 ** associated with a particular database connection. The use of
15012 ** lookaside malloc provides a significant performance enhancement
15013 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
15014 ** SQL statements.
15016 ** The Lookaside structure holds configuration information about the
15017 ** lookaside malloc subsystem. Each available memory allocation in
15018 ** the lookaside subsystem is stored on a linked list of LookasideSlot
15019 ** objects.
15021 ** Lookaside allocations are only allowed for objects that are associated
15022 ** with a particular database connection. Hence, schema information cannot
15023 ** be stored in lookaside because in shared cache mode the schema information
15024 ** is shared by multiple database connections. Therefore, while parsing
15025 ** schema information, the Lookaside.bEnabled flag is cleared so that
15026 ** lookaside allocations are not used to construct the schema objects.
15028 struct Lookaside {
15029 u32 bDisable; /* Only operate the lookaside when zero */
15030 u16 sz; /* Size of each buffer in bytes */
15031 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
15032 u32 nSlot; /* Number of lookaside slots allocated */
15033 u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
15034 LookasideSlot *pInit; /* List of buffers not previously used */
15035 LookasideSlot *pFree; /* List of available buffers */
15036 void *pStart; /* First byte of available memory space */
15037 void *pEnd; /* First byte past end of available space */
15039 struct LookasideSlot {
15040 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
15044 ** A hash table for built-in function definitions. (Application-defined
15045 ** functions use a regular table table from hash.h.)
15047 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
15048 ** Collisions are on the FuncDef.u.pHash chain.
15050 #define SQLITE_FUNC_HASH_SZ 23
15051 struct FuncDefHash {
15052 FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
15055 #ifdef SQLITE_USER_AUTHENTICATION
15057 ** Information held in the "sqlite3" database connection object and used
15058 ** to manage user authentication.
15060 typedef struct sqlite3_userauth sqlite3_userauth;
15061 struct sqlite3_userauth {
15062 u8 authLevel; /* Current authentication level */
15063 int nAuthPW; /* Size of the zAuthPW in bytes */
15064 char *zAuthPW; /* Password used to authenticate */
15065 char *zAuthUser; /* User name used to authenticate */
15068 /* Allowed values for sqlite3_userauth.authLevel */
15069 #define UAUTH_Unknown 0 /* Authentication not yet checked */
15070 #define UAUTH_Fail 1 /* User authentication failed */
15071 #define UAUTH_User 2 /* Authenticated as a normal user */
15072 #define UAUTH_Admin 3 /* Authenticated as an administrator */
15074 /* Functions used only by user authorization logic */
15075 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
15076 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
15077 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
15078 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
15080 #endif /* SQLITE_USER_AUTHENTICATION */
15083 ** typedef for the authorization callback function.
15085 #ifdef SQLITE_USER_AUTHENTICATION
15086 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
15087 const char*, const char*);
15088 #else
15089 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
15090 const char*);
15091 #endif
15093 #ifndef SQLITE_OMIT_DEPRECATED
15094 /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
15095 ** in the style of sqlite3_trace()
15097 #define SQLITE_TRACE_LEGACY 0x80
15098 #else
15099 #define SQLITE_TRACE_LEGACY 0
15100 #endif /* SQLITE_OMIT_DEPRECATED */
15104 ** Each database connection is an instance of the following structure.
15106 struct sqlite3 {
15107 sqlite3_vfs *pVfs; /* OS Interface */
15108 struct Vdbe *pVdbe; /* List of active virtual machines */
15109 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
15110 sqlite3_mutex *mutex; /* Connection mutex */
15111 Db *aDb; /* All backends */
15112 int nDb; /* Number of backends currently in use */
15113 u32 mDbFlags; /* flags recording internal state */
15114 u32 flags; /* flags settable by pragmas. See below */
15115 i64 lastRowid; /* ROWID of most recent insert (see above) */
15116 i64 szMmap; /* Default mmap_size setting */
15117 u32 nSchemaLock; /* Do not reset the schema when non-zero */
15118 unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
15119 int errCode; /* Most recent error code (SQLITE_*) */
15120 int errMask; /* & result codes with this before returning */
15121 int iSysErrno; /* Errno value from last system error */
15122 u16 dbOptFlags; /* Flags to enable/disable optimizations */
15123 u8 enc; /* Text encoding */
15124 u8 autoCommit; /* The auto-commit flag. */
15125 u8 temp_store; /* 1: file 2: memory 0: default */
15126 u8 mallocFailed; /* True if we have seen a malloc failure */
15127 u8 bBenignMalloc; /* Do not require OOMs if true */
15128 u8 dfltLockMode; /* Default locking-mode for attached dbs */
15129 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
15130 u8 suppressErr; /* Do not issue error messages if true */
15131 u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
15132 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
15133 u8 mTrace; /* zero or more SQLITE_TRACE flags */
15134 u8 skipBtreeMutex; /* True if no shared-cache backends */
15135 u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
15136 int nextPagesize; /* Pagesize after VACUUM if >0 */
15137 u32 magic; /* Magic number for detect library misuse */
15138 int nChange; /* Value returned by sqlite3_changes() */
15139 int nTotalChange; /* Value returned by sqlite3_total_changes() */
15140 int aLimit[SQLITE_N_LIMIT]; /* Limits */
15141 int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
15142 struct sqlite3InitInfo { /* Information used during initialization */
15143 int newTnum; /* Rootpage of table being initialized */
15144 u8 iDb; /* Which db file is being initialized */
15145 u8 busy; /* TRUE if currently initializing */
15146 u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
15147 u8 imposterTable; /* Building an imposter table */
15148 } init;
15149 int nVdbeActive; /* Number of VDBEs currently running */
15150 int nVdbeRead; /* Number of active VDBEs that read or write */
15151 int nVdbeWrite; /* Number of active VDBEs that read and write */
15152 int nVdbeExec; /* Number of nested calls to VdbeExec() */
15153 int nVDestroy; /* Number of active OP_VDestroy operations */
15154 int nExtension; /* Number of loaded extensions */
15155 void **aExtension; /* Array of shared library handles */
15156 int (*xTrace)(u32,void*,void*,void*); /* Trace function */
15157 void *pTraceArg; /* Argument to the trace function */
15158 void (*xProfile)(void*,const char*,u64); /* Profiling function */
15159 void *pProfileArg; /* Argument to profile function */
15160 void *pCommitArg; /* Argument to xCommitCallback() */
15161 int (*xCommitCallback)(void*); /* Invoked at every commit. */
15162 void *pRollbackArg; /* Argument to xRollbackCallback() */
15163 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
15164 void *pUpdateArg;
15165 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
15166 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
15167 void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
15168 void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
15169 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
15171 PreUpdate *pPreUpdate; /* Context for active pre-update callback */
15172 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
15173 #ifndef SQLITE_OMIT_WAL
15174 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
15175 void *pWalArg;
15176 #endif
15177 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
15178 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
15179 void *pCollNeededArg;
15180 sqlite3_value *pErr; /* Most recent error message */
15181 union {
15182 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
15183 double notUsed1; /* Spacer */
15184 } u1;
15185 Lookaside lookaside; /* Lookaside malloc configuration */
15186 #ifndef SQLITE_OMIT_AUTHORIZATION
15187 sqlite3_xauth xAuth; /* Access authorization function */
15188 void *pAuthArg; /* 1st argument to the access auth function */
15189 #endif
15190 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
15191 int (*xProgress)(void *); /* The progress callback */
15192 void *pProgressArg; /* Argument to the progress callback */
15193 unsigned nProgressOps; /* Number of opcodes for progress callback */
15194 #endif
15195 #ifndef SQLITE_OMIT_VIRTUALTABLE
15196 int nVTrans; /* Allocated size of aVTrans */
15197 Hash aModule; /* populated by sqlite3_create_module() */
15198 VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
15199 VTable **aVTrans; /* Virtual tables with open transactions */
15200 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
15201 #endif
15202 Hash aFunc; /* Hash table of connection functions */
15203 Hash aCollSeq; /* All collating sequences */
15204 BusyHandler busyHandler; /* Busy callback */
15205 Db aDbStatic[2]; /* Static space for the 2 default backends */
15206 Savepoint *pSavepoint; /* List of active savepoints */
15207 int busyTimeout; /* Busy handler timeout, in msec */
15208 int nSavepoint; /* Number of non-transaction savepoints */
15209 int nStatement; /* Number of nested statement-transactions */
15210 i64 nDeferredCons; /* Net deferred constraints this transaction. */
15211 i64 nDeferredImmCons; /* Net deferred immediate constraints */
15212 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
15213 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
15214 /* The following variables are all protected by the STATIC_MASTER
15215 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
15217 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
15218 ** unlock so that it can proceed.
15220 ** When X.pBlockingConnection==Y, that means that something that X tried
15221 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
15222 ** held by Y.
15224 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
15225 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
15226 void *pUnlockArg; /* Argument to xUnlockNotify */
15227 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
15228 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
15229 #endif
15230 #ifdef SQLITE_USER_AUTHENTICATION
15231 sqlite3_userauth auth; /* User authentication information */
15232 #endif
15236 ** A macro to discover the encoding of a database.
15238 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
15239 #define ENC(db) ((db)->enc)
15242 ** Possible values for the sqlite3.flags.
15244 ** Value constraints (enforced via assert()):
15245 ** SQLITE_FullFSync == PAGER_FULLFSYNC
15246 ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
15247 ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
15249 #define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_MASTER */
15250 #define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
15251 #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
15252 #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
15253 #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
15254 #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
15255 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
15256 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
15257 /* DELETE, or UPDATE and return */
15258 /* the count using a callback. */
15259 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
15260 /* result set is empty */
15261 #define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
15262 #define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
15263 #define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
15264 #define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
15265 #define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
15266 #define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
15267 #define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
15268 #define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
15269 #define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
15270 #define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
15271 #define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
15272 #define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
15273 #define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
15274 #define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
15275 #define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee */
15276 /* Flags used only if debugging */
15277 #ifdef SQLITE_DEBUG
15278 #define SQLITE_SqlTrace 0x08000000 /* Debug print SQL as it executes */
15279 #define SQLITE_VdbeListing 0x10000000 /* Debug listings of VDBE programs */
15280 #define SQLITE_VdbeTrace 0x20000000 /* True to trace VDBE execution */
15281 #define SQLITE_VdbeAddopTrace 0x40000000 /* Trace sqlite3VdbeAddOp() calls */
15282 #define SQLITE_VdbeEQP 0x80000000 /* Debug EXPLAIN QUERY PLAN */
15283 #endif
15286 ** Allowed values for sqlite3.mDbFlags
15288 #define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
15289 #define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
15290 #define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
15293 ** Bits of the sqlite3.dbOptFlags field that are used by the
15294 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
15295 ** selectively disable various optimizations.
15297 #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
15298 #define SQLITE_ColumnCache 0x0002 /* Column cache */
15299 #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
15300 #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
15301 #define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */
15302 #define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */
15303 #define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */
15304 #define SQLITE_Transitive 0x0080 /* Transitive constraints */
15305 #define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */
15306 #define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */
15307 #define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */
15308 #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
15309 /* TH3 expects the Stat34 ^^^^^^ value to be 0x0800. Don't change it */
15310 #define SQLITE_AllOpts 0xffff /* All optimizations */
15313 ** Macros for testing whether or not optimizations are enabled or disabled.
15315 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
15316 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
15319 ** Return true if it OK to factor constant expressions into the initialization
15320 ** code. The argument is a Parse object for the code generator.
15322 #define ConstFactorOk(P) ((P)->okConstFactor)
15325 ** Possible values for the sqlite.magic field.
15326 ** The numbers are obtained at random and have no special meaning, other
15327 ** than being distinct from one another.
15329 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
15330 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
15331 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
15332 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
15333 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
15334 #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
15337 ** Each SQL function is defined by an instance of the following
15338 ** structure. For global built-in functions (ex: substr(), max(), count())
15339 ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
15340 ** For per-connection application-defined functions, a pointer to this
15341 ** structure is held in the db->aHash hash table.
15343 ** The u.pHash field is used by the global built-ins. The u.pDestructor
15344 ** field is used by per-connection app-def functions.
15346 struct FuncDef {
15347 i8 nArg; /* Number of arguments. -1 means unlimited */
15348 u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
15349 void *pUserData; /* User data parameter */
15350 FuncDef *pNext; /* Next function with same name */
15351 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
15352 void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
15353 const char *zName; /* SQL name of the function. */
15354 union {
15355 FuncDef *pHash; /* Next with a different name but the same hash */
15356 FuncDestructor *pDestructor; /* Reference counted destructor function */
15357 } u;
15361 ** This structure encapsulates a user-function destructor callback (as
15362 ** configured using create_function_v2()) and a reference counter. When
15363 ** create_function_v2() is called to create a function with a destructor,
15364 ** a single object of this type is allocated. FuncDestructor.nRef is set to
15365 ** the number of FuncDef objects created (either 1 or 3, depending on whether
15366 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
15367 ** member of each of the new FuncDef objects is set to point to the allocated
15368 ** FuncDestructor.
15370 ** Thereafter, when one of the FuncDef objects is deleted, the reference
15371 ** count on this object is decremented. When it reaches 0, the destructor
15372 ** is invoked and the FuncDestructor structure freed.
15374 struct FuncDestructor {
15375 int nRef;
15376 void (*xDestroy)(void *);
15377 void *pUserData;
15381 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
15382 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
15383 ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
15384 ** are assert() statements in the code to verify this.
15386 ** Value constraints (enforced via assert()):
15387 ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
15388 ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
15389 ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
15390 ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
15391 ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
15393 #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
15394 #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
15395 #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
15396 #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
15397 #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
15398 #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
15399 #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
15400 #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
15401 #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
15402 #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
15403 #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
15404 #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
15405 #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
15406 ** single query - might change over time */
15407 #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
15410 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
15411 ** used to create the initializers for the FuncDef structures.
15413 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
15414 ** Used to create a scalar function definition of a function zName
15415 ** implemented by C function xFunc that accepts nArg arguments. The
15416 ** value passed as iArg is cast to a (void*) and made available
15417 ** as the user-data (sqlite3_user_data()) for the function. If
15418 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
15420 ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
15421 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
15423 ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
15424 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
15425 ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
15426 ** and functions like sqlite_version() that can change, but not during
15427 ** a single query. The iArg is ignored. The user-data is always set
15428 ** to a NULL pointer. The bNC parameter is not used.
15430 ** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
15431 ** Used for "pure" date/time functions, this macro is like DFUNCTION
15432 ** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
15433 ** ignored and the user-data for these functions is set to an
15434 ** arbitrary non-NULL pointer. The bNC parameter is not used.
15436 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
15437 ** Used to create an aggregate function definition implemented by
15438 ** the C functions xStep and xFinal. The first four parameters
15439 ** are interpreted in the same way as the first 4 parameters to
15440 ** FUNCTION().
15442 ** LIKEFUNC(zName, nArg, pArg, flags)
15443 ** Used to create a scalar function definition of a function zName
15444 ** that accepts nArg arguments and is implemented by a call to C
15445 ** function likeFunc. Argument pArg is cast to a (void *) and made
15446 ** available as the function user-data (sqlite3_user_data()). The
15447 ** FuncDef.flags variable is set to the value passed as the flags
15448 ** parameter.
15450 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
15451 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
15452 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
15453 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
15454 {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
15455 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
15456 #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
15457 {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
15458 0, 0, xFunc, 0, #zName, {0} }
15459 #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
15460 {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
15461 (void*)&sqlite3Config, 0, xFunc, 0, #zName, {0} }
15462 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
15463 {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
15464 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
15465 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
15466 {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
15467 pArg, 0, xFunc, 0, #zName, }
15468 #define LIKEFUNC(zName, nArg, arg, flags) \
15469 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
15470 (void *)arg, 0, likeFunc, 0, #zName, {0} }
15471 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
15472 {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
15473 SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
15474 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
15475 {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
15476 SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
15479 ** All current savepoints are stored in a linked list starting at
15480 ** sqlite3.pSavepoint. The first element in the list is the most recently
15481 ** opened savepoint. Savepoints are added to the list by the vdbe
15482 ** OP_Savepoint instruction.
15484 struct Savepoint {
15485 char *zName; /* Savepoint name (nul-terminated) */
15486 i64 nDeferredCons; /* Number of deferred fk violations */
15487 i64 nDeferredImmCons; /* Number of deferred imm fk. */
15488 Savepoint *pNext; /* Parent savepoint (if any) */
15492 ** The following are used as the second parameter to sqlite3Savepoint(),
15493 ** and as the P1 argument to the OP_Savepoint instruction.
15495 #define SAVEPOINT_BEGIN 0
15496 #define SAVEPOINT_RELEASE 1
15497 #define SAVEPOINT_ROLLBACK 2
15501 ** Each SQLite module (virtual table definition) is defined by an
15502 ** instance of the following structure, stored in the sqlite3.aModule
15503 ** hash table.
15505 struct Module {
15506 const sqlite3_module *pModule; /* Callback pointers */
15507 const char *zName; /* Name passed to create_module() */
15508 void *pAux; /* pAux passed to create_module() */
15509 void (*xDestroy)(void *); /* Module destructor function */
15510 Table *pEpoTab; /* Eponymous table for this module */
15514 ** information about each column of an SQL table is held in an instance
15515 ** of this structure.
15517 struct Column {
15518 char *zName; /* Name of this column, \000, then the type */
15519 Expr *pDflt; /* Default value of this column */
15520 char *zColl; /* Collating sequence. If NULL, use the default */
15521 u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
15522 char affinity; /* One of the SQLITE_AFF_... values */
15523 u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
15524 u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
15527 /* Allowed values for Column.colFlags:
15529 #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
15530 #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
15531 #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
15534 ** A "Collating Sequence" is defined by an instance of the following
15535 ** structure. Conceptually, a collating sequence consists of a name and
15536 ** a comparison routine that defines the order of that sequence.
15538 ** If CollSeq.xCmp is NULL, it means that the
15539 ** collating sequence is undefined. Indices built on an undefined
15540 ** collating sequence may not be read or written.
15542 struct CollSeq {
15543 char *zName; /* Name of the collating sequence, UTF-8 encoded */
15544 u8 enc; /* Text encoding handled by xCmp() */
15545 void *pUser; /* First argument to xCmp() */
15546 int (*xCmp)(void*,int, const void*, int, const void*);
15547 void (*xDel)(void*); /* Destructor for pUser */
15551 ** A sort order can be either ASC or DESC.
15553 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
15554 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
15555 #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
15558 ** Column affinity types.
15560 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
15561 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
15562 ** the speed a little by numbering the values consecutively.
15564 ** But rather than start with 0 or 1, we begin with 'A'. That way,
15565 ** when multiple affinity types are concatenated into a string and
15566 ** used as the P4 operand, they will be more readable.
15568 ** Note also that the numeric types are grouped together so that testing
15569 ** for a numeric type is a single comparison. And the BLOB type is first.
15571 #define SQLITE_AFF_BLOB 'A'
15572 #define SQLITE_AFF_TEXT 'B'
15573 #define SQLITE_AFF_NUMERIC 'C'
15574 #define SQLITE_AFF_INTEGER 'D'
15575 #define SQLITE_AFF_REAL 'E'
15577 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
15580 ** The SQLITE_AFF_MASK values masks off the significant bits of an
15581 ** affinity value.
15583 #define SQLITE_AFF_MASK 0x47
15586 ** Additional bit values that can be ORed with an affinity without
15587 ** changing the affinity.
15589 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
15590 ** It causes an assert() to fire if either operand to a comparison
15591 ** operator is NULL. It is added to certain comparison operators to
15592 ** prove that the operands are always NOT NULL.
15594 #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
15595 #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
15596 #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
15597 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
15598 #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
15601 ** An object of this type is created for each virtual table present in
15602 ** the database schema.
15604 ** If the database schema is shared, then there is one instance of this
15605 ** structure for each database connection (sqlite3*) that uses the shared
15606 ** schema. This is because each database connection requires its own unique
15607 ** instance of the sqlite3_vtab* handle used to access the virtual table
15608 ** implementation. sqlite3_vtab* handles can not be shared between
15609 ** database connections, even when the rest of the in-memory database
15610 ** schema is shared, as the implementation often stores the database
15611 ** connection handle passed to it via the xConnect() or xCreate() method
15612 ** during initialization internally. This database connection handle may
15613 ** then be used by the virtual table implementation to access real tables
15614 ** within the database. So that they appear as part of the callers
15615 ** transaction, these accesses need to be made via the same database
15616 ** connection as that used to execute SQL operations on the virtual table.
15618 ** All VTable objects that correspond to a single table in a shared
15619 ** database schema are initially stored in a linked-list pointed to by
15620 ** the Table.pVTable member variable of the corresponding Table object.
15621 ** When an sqlite3_prepare() operation is required to access the virtual
15622 ** table, it searches the list for the VTable that corresponds to the
15623 ** database connection doing the preparing so as to use the correct
15624 ** sqlite3_vtab* handle in the compiled query.
15626 ** When an in-memory Table object is deleted (for example when the
15627 ** schema is being reloaded for some reason), the VTable objects are not
15628 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
15629 ** immediately. Instead, they are moved from the Table.pVTable list to
15630 ** another linked list headed by the sqlite3.pDisconnect member of the
15631 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
15632 ** next time a statement is prepared using said sqlite3*. This is done
15633 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
15634 ** Refer to comments above function sqlite3VtabUnlockList() for an
15635 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
15636 ** list without holding the corresponding sqlite3.mutex mutex.
15638 ** The memory for objects of this type is always allocated by
15639 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
15640 ** the first argument.
15642 struct VTable {
15643 sqlite3 *db; /* Database connection associated with this table */
15644 Module *pMod; /* Pointer to module implementation */
15645 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
15646 int nRef; /* Number of pointers to this structure */
15647 u8 bConstraint; /* True if constraints are supported */
15648 int iSavepoint; /* Depth of the SAVEPOINT stack */
15649 VTable *pNext; /* Next in linked list (see above) */
15653 ** The schema for each SQL table and view is represented in memory
15654 ** by an instance of the following structure.
15656 struct Table {
15657 char *zName; /* Name of the table or view */
15658 Column *aCol; /* Information about each column */
15659 Index *pIndex; /* List of SQL indexes on this table. */
15660 Select *pSelect; /* NULL for tables. Points to definition if a view. */
15661 FKey *pFKey; /* Linked list of all foreign keys in this table */
15662 char *zColAff; /* String defining the affinity of each column */
15663 ExprList *pCheck; /* All CHECK constraints */
15664 /* ... also used as column name list in a VIEW */
15665 int tnum; /* Root BTree page for this table */
15666 u32 nTabRef; /* Number of pointers to this Table */
15667 u32 tabFlags; /* Mask of TF_* values */
15668 i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
15669 i16 nCol; /* Number of columns in this table */
15670 LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
15671 LogEst szTabRow; /* Estimated size of each table row in bytes */
15672 #ifdef SQLITE_ENABLE_COSTMULT
15673 LogEst costMult; /* Cost multiplier for using this table */
15674 #endif
15675 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
15676 #ifndef SQLITE_OMIT_ALTERTABLE
15677 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
15678 #endif
15679 #ifndef SQLITE_OMIT_VIRTUALTABLE
15680 int nModuleArg; /* Number of arguments to the module */
15681 char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
15682 VTable *pVTable; /* List of VTable objects. */
15683 #endif
15684 Trigger *pTrigger; /* List of triggers stored in pSchema */
15685 Schema *pSchema; /* Schema that contains this table */
15686 Table *pNextZombie; /* Next on the Parse.pZombieTab list */
15690 ** Allowed values for Table.tabFlags.
15692 ** TF_OOOHidden applies to tables or view that have hidden columns that are
15693 ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
15694 ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
15695 ** the TF_OOOHidden attribute would apply in this case. Such tables require
15696 ** special handling during INSERT processing.
15698 #define TF_Readonly 0x0001 /* Read-only system table */
15699 #define TF_Ephemeral 0x0002 /* An ephemeral table */
15700 #define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
15701 #define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
15702 #define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
15703 #define TF_WithoutRowid 0x0020 /* No rowid. PRIMARY KEY is the key */
15704 #define TF_NoVisibleRowid 0x0040 /* No user-visible "rowid" column */
15705 #define TF_OOOHidden 0x0080 /* Out-of-Order hidden columns */
15706 #define TF_StatsUsed 0x0100 /* Query planner decisions affected by
15707 ** Index.aiRowLogEst[] values */
15708 #define TF_HasNotNull 0x0200 /* Contains NOT NULL constraints */
15711 ** Test to see whether or not a table is a virtual table. This is
15712 ** done as a macro so that it will be optimized out when virtual
15713 ** table support is omitted from the build.
15715 #ifndef SQLITE_OMIT_VIRTUALTABLE
15716 # define IsVirtual(X) ((X)->nModuleArg)
15717 #else
15718 # define IsVirtual(X) 0
15719 #endif
15722 ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
15723 ** only works for non-virtual tables (ordinary tables and views) and is
15724 ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
15725 ** IsHiddenColumn() macro is general purpose.
15727 #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
15728 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
15729 # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
15730 #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
15731 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
15732 # define IsOrdinaryHiddenColumn(X) 0
15733 #else
15734 # define IsHiddenColumn(X) 0
15735 # define IsOrdinaryHiddenColumn(X) 0
15736 #endif
15739 /* Does the table have a rowid */
15740 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
15741 #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
15744 ** Each foreign key constraint is an instance of the following structure.
15746 ** A foreign key is associated with two tables. The "from" table is
15747 ** the table that contains the REFERENCES clause that creates the foreign
15748 ** key. The "to" table is the table that is named in the REFERENCES clause.
15749 ** Consider this example:
15751 ** CREATE TABLE ex1(
15752 ** a INTEGER PRIMARY KEY,
15753 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
15754 ** );
15756 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
15757 ** Equivalent names:
15759 ** from-table == child-table
15760 ** to-table == parent-table
15762 ** Each REFERENCES clause generates an instance of the following structure
15763 ** which is attached to the from-table. The to-table need not exist when
15764 ** the from-table is created. The existence of the to-table is not checked.
15766 ** The list of all parents for child Table X is held at X.pFKey.
15768 ** A list of all children for a table named Z (which might not even exist)
15769 ** is held in Schema.fkeyHash with a hash key of Z.
15771 struct FKey {
15772 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
15773 FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
15774 char *zTo; /* Name of table that the key points to (aka: Parent) */
15775 FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
15776 FKey *pPrevTo; /* Previous with the same zTo */
15777 int nCol; /* Number of columns in this key */
15778 /* EV: R-30323-21917 */
15779 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
15780 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
15781 Trigger *apTrigger[2];/* Triggers for aAction[] actions */
15782 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
15783 int iFrom; /* Index of column in pFrom */
15784 char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
15785 } aCol[1]; /* One entry for each of nCol columns */
15789 ** SQLite supports many different ways to resolve a constraint
15790 ** error. ROLLBACK processing means that a constraint violation
15791 ** causes the operation in process to fail and for the current transaction
15792 ** to be rolled back. ABORT processing means the operation in process
15793 ** fails and any prior changes from that one operation are backed out,
15794 ** but the transaction is not rolled back. FAIL processing means that
15795 ** the operation in progress stops and returns an error code. But prior
15796 ** changes due to the same operation are not backed out and no rollback
15797 ** occurs. IGNORE means that the particular row that caused the constraint
15798 ** error is not inserted or updated. Processing continues and no error
15799 ** is returned. REPLACE means that preexisting database rows that caused
15800 ** a UNIQUE constraint violation are removed so that the new insert or
15801 ** update can proceed. Processing continues and no error is reported.
15803 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
15804 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
15805 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
15806 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
15807 ** referenced table row is propagated into the row that holds the
15808 ** foreign key.
15810 ** The following symbolic values are used to record which type
15811 ** of action to take.
15813 #define OE_None 0 /* There is no constraint to check */
15814 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
15815 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
15816 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
15817 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
15818 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
15820 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
15821 #define OE_SetNull 7 /* Set the foreign key value to NULL */
15822 #define OE_SetDflt 8 /* Set the foreign key value to its default */
15823 #define OE_Cascade 9 /* Cascade the changes */
15825 #define OE_Default 10 /* Do whatever the default action is */
15829 ** An instance of the following structure is passed as the first
15830 ** argument to sqlite3VdbeKeyCompare and is used to control the
15831 ** comparison of the two index keys.
15833 ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
15834 ** are nField slots for the columns of an index then one extra slot
15835 ** for the rowid at the end.
15837 struct KeyInfo {
15838 u32 nRef; /* Number of references to this KeyInfo object */
15839 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
15840 u16 nKeyField; /* Number of key columns in the index */
15841 u16 nAllField; /* Total columns, including key plus others */
15842 sqlite3 *db; /* The database connection */
15843 u8 *aSortOrder; /* Sort order for each column. */
15844 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
15848 ** This object holds a record which has been parsed out into individual
15849 ** fields, for the purposes of doing a comparison.
15851 ** A record is an object that contains one or more fields of data.
15852 ** Records are used to store the content of a table row and to store
15853 ** the key of an index. A blob encoding of a record is created by
15854 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
15855 ** OP_Column opcode.
15857 ** An instance of this object serves as a "key" for doing a search on
15858 ** an index b+tree. The goal of the search is to find the entry that
15859 ** is closed to the key described by this object. This object might hold
15860 ** just a prefix of the key. The number of fields is given by
15861 ** pKeyInfo->nField.
15863 ** The r1 and r2 fields are the values to return if this key is less than
15864 ** or greater than a key in the btree, respectively. These are normally
15865 ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
15866 ** is in DESC order.
15868 ** The key comparison functions actually return default_rc when they find
15869 ** an equals comparison. default_rc can be -1, 0, or +1. If there are
15870 ** multiple entries in the b-tree with the same key (when only looking
15871 ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
15872 ** cause the search to find the last match, or +1 to cause the search to
15873 ** find the first match.
15875 ** The key comparison functions will set eqSeen to true if they ever
15876 ** get and equal results when comparing this structure to a b-tree record.
15877 ** When default_rc!=0, the search might end up on the record immediately
15878 ** before the first match or immediately after the last match. The
15879 ** eqSeen field will indicate whether or not an exact match exists in the
15880 ** b-tree.
15882 struct UnpackedRecord {
15883 KeyInfo *pKeyInfo; /* Collation and sort-order information */
15884 Mem *aMem; /* Values */
15885 u16 nField; /* Number of entries in apMem[] */
15886 i8 default_rc; /* Comparison result if keys are equal */
15887 u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
15888 i8 r1; /* Value to return if (lhs < rhs) */
15889 i8 r2; /* Value to return if (lhs > rhs) */
15890 u8 eqSeen; /* True if an equality comparison has been seen */
15895 ** Each SQL index is represented in memory by an
15896 ** instance of the following structure.
15898 ** The columns of the table that are to be indexed are described
15899 ** by the aiColumn[] field of this structure. For example, suppose
15900 ** we have the following table and index:
15902 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
15903 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
15905 ** In the Table structure describing Ex1, nCol==3 because there are
15906 ** three columns in the table. In the Index structure describing
15907 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
15908 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
15909 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
15910 ** The second column to be indexed (c1) has an index of 0 in
15911 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
15913 ** The Index.onError field determines whether or not the indexed columns
15914 ** must be unique and what to do if they are not. When Index.onError=OE_None,
15915 ** it means this is not a unique index. Otherwise it is a unique index
15916 ** and the value of Index.onError indicate the which conflict resolution
15917 ** algorithm to employ whenever an attempt is made to insert a non-unique
15918 ** element.
15920 ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
15921 ** generate VDBE code (as opposed to parsing one read from an sqlite_master
15922 ** table as part of parsing an existing database schema), transient instances
15923 ** of this structure may be created. In this case the Index.tnum variable is
15924 ** used to store the address of a VDBE instruction, not a database page
15925 ** number (it cannot - the database page is not allocated until the VDBE
15926 ** program is executed). See convertToWithoutRowidTable() for details.
15928 struct Index {
15929 char *zName; /* Name of this index */
15930 i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
15931 LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
15932 Table *pTable; /* The SQL table being indexed */
15933 char *zColAff; /* String defining the affinity of each column */
15934 Index *pNext; /* The next index associated with the same table */
15935 Schema *pSchema; /* Schema containing this index */
15936 u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
15937 const char **azColl; /* Array of collation sequence names for index */
15938 Expr *pPartIdxWhere; /* WHERE clause for partial indices */
15939 ExprList *aColExpr; /* Column expressions */
15940 int tnum; /* DB Page containing root of this index */
15941 LogEst szIdxRow; /* Estimated average row size in bytes */
15942 u16 nKeyCol; /* Number of columns forming the key */
15943 u16 nColumn; /* Number of columns stored in the index */
15944 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
15945 unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
15946 unsigned bUnordered:1; /* Use this index for == or IN queries only */
15947 unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
15948 unsigned isResized:1; /* True if resizeIndexObject() has been called */
15949 unsigned isCovering:1; /* True if this is a covering index */
15950 unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
15951 unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
15952 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
15953 int nSample; /* Number of elements in aSample[] */
15954 int nSampleCol; /* Size of IndexSample.anEq[] and so on */
15955 tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
15956 IndexSample *aSample; /* Samples of the left-most key */
15957 tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
15958 tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
15959 #endif
15963 ** Allowed values for Index.idxType
15965 #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
15966 #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
15967 #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
15969 /* Return true if index X is a PRIMARY KEY index */
15970 #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
15972 /* Return true if index X is a UNIQUE index */
15973 #define IsUniqueIndex(X) ((X)->onError!=OE_None)
15975 /* The Index.aiColumn[] values are normally positive integer. But
15976 ** there are some negative values that have special meaning:
15978 #define XN_ROWID (-1) /* Indexed column is the rowid */
15979 #define XN_EXPR (-2) /* Indexed column is an expression */
15982 ** Each sample stored in the sqlite_stat3 table is represented in memory
15983 ** using a structure of this type. See documentation at the top of the
15984 ** analyze.c source file for additional information.
15986 struct IndexSample {
15987 void *p; /* Pointer to sampled record */
15988 int n; /* Size of record in bytes */
15989 tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
15990 tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
15991 tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
15995 ** Each token coming out of the lexer is an instance of
15996 ** this structure. Tokens are also used as part of an expression.
15998 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
15999 ** may contain random values. Do not make any assumptions about Token.dyn
16000 ** and Token.n when Token.z==0.
16002 struct Token {
16003 const char *z; /* Text of the token. Not NULL-terminated! */
16004 unsigned int n; /* Number of characters in this token */
16008 ** An instance of this structure contains information needed to generate
16009 ** code for a SELECT that contains aggregate functions.
16011 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
16012 ** pointer to this structure. The Expr.iColumn field is the index in
16013 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
16014 ** code for that node.
16016 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
16017 ** original Select structure that describes the SELECT statement. These
16018 ** fields do not need to be freed when deallocating the AggInfo structure.
16020 struct AggInfo {
16021 u8 directMode; /* Direct rendering mode means take data directly
16022 ** from source tables rather than from accumulators */
16023 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
16024 ** than the source table */
16025 int sortingIdx; /* Cursor number of the sorting index */
16026 int sortingIdxPTab; /* Cursor number of pseudo-table */
16027 int nSortingColumn; /* Number of columns in the sorting index */
16028 int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
16029 ExprList *pGroupBy; /* The group by clause */
16030 struct AggInfo_col { /* For each column used in source tables */
16031 Table *pTab; /* Source table */
16032 int iTable; /* Cursor number of the source table */
16033 int iColumn; /* Column number within the source table */
16034 int iSorterColumn; /* Column number in the sorting index */
16035 int iMem; /* Memory location that acts as accumulator */
16036 Expr *pExpr; /* The original expression */
16037 } *aCol;
16038 int nColumn; /* Number of used entries in aCol[] */
16039 int nAccumulator; /* Number of columns that show through to the output.
16040 ** Additional columns are used only as parameters to
16041 ** aggregate functions */
16042 struct AggInfo_func { /* For each aggregate function */
16043 Expr *pExpr; /* Expression encoding the function */
16044 FuncDef *pFunc; /* The aggregate function implementation */
16045 int iMem; /* Memory location that acts as accumulator */
16046 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
16047 } *aFunc;
16048 int nFunc; /* Number of entries in aFunc[] */
16052 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
16053 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
16054 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
16055 ** it uses less memory in the Expr object, which is a big memory user
16056 ** in systems with lots of prepared statements. And few applications
16057 ** need more than about 10 or 20 variables. But some extreme users want
16058 ** to have prepared statements with over 32767 variables, and for them
16059 ** the option is available (at compile-time).
16061 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
16062 typedef i16 ynVar;
16063 #else
16064 typedef int ynVar;
16065 #endif
16068 ** Each node of an expression in the parse tree is an instance
16069 ** of this structure.
16071 ** Expr.op is the opcode. The integer parser token codes are reused
16072 ** as opcodes here. For example, the parser defines TK_GE to be an integer
16073 ** code representing the ">=" operator. This same integer code is reused
16074 ** to represent the greater-than-or-equal-to operator in the expression
16075 ** tree.
16077 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
16078 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
16079 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
16080 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
16081 ** then Expr.token contains the name of the function.
16083 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
16084 ** binary operator. Either or both may be NULL.
16086 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
16087 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
16088 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
16089 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
16090 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
16091 ** valid.
16093 ** An expression of the form ID or ID.ID refers to a column in a table.
16094 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
16095 ** the integer cursor number of a VDBE cursor pointing to that table and
16096 ** Expr.iColumn is the column number for the specific column. If the
16097 ** expression is used as a result in an aggregate SELECT, then the
16098 ** value is also stored in the Expr.iAgg column in the aggregate so that
16099 ** it can be accessed after all aggregates are computed.
16101 ** If the expression is an unbound variable marker (a question mark
16102 ** character '?' in the original SQL) then the Expr.iTable holds the index
16103 ** number for that variable.
16105 ** If the expression is a subquery then Expr.iColumn holds an integer
16106 ** register number containing the result of the subquery. If the
16107 ** subquery gives a constant result, then iTable is -1. If the subquery
16108 ** gives a different answer at different times during statement processing
16109 ** then iTable is the address of a subroutine that computes the subquery.
16111 ** If the Expr is of type OP_Column, and the table it is selecting from
16112 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
16113 ** corresponding table definition.
16115 ** ALLOCATION NOTES:
16117 ** Expr objects can use a lot of memory space in database schema. To
16118 ** help reduce memory requirements, sometimes an Expr object will be
16119 ** truncated. And to reduce the number of memory allocations, sometimes
16120 ** two or more Expr objects will be stored in a single memory allocation,
16121 ** together with Expr.zToken strings.
16123 ** If the EP_Reduced and EP_TokenOnly flags are set when
16124 ** an Expr object is truncated. When EP_Reduced is set, then all
16125 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
16126 ** are contained within the same memory allocation. Note, however, that
16127 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
16128 ** allocated, regardless of whether or not EP_Reduced is set.
16130 struct Expr {
16131 u8 op; /* Operation performed by this node */
16132 char affinity; /* The affinity of the column or 0 if not a column */
16133 u32 flags; /* Various flags. EP_* See below */
16134 union {
16135 char *zToken; /* Token value. Zero terminated and dequoted */
16136 int iValue; /* Non-negative integer value if EP_IntValue */
16137 } u;
16139 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
16140 ** space is allocated for the fields below this point. An attempt to
16141 ** access them will result in a segfault or malfunction.
16142 *********************************************************************/
16144 Expr *pLeft; /* Left subnode */
16145 Expr *pRight; /* Right subnode */
16146 union {
16147 ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
16148 Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
16149 } x;
16151 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
16152 ** space is allocated for the fields below this point. An attempt to
16153 ** access them will result in a segfault or malfunction.
16154 *********************************************************************/
16156 #if SQLITE_MAX_EXPR_DEPTH>0
16157 int nHeight; /* Height of the tree headed by this node */
16158 #endif
16159 int iTable; /* TK_COLUMN: cursor number of table holding column
16160 ** TK_REGISTER: register number
16161 ** TK_TRIGGER: 1 -> new, 0 -> old
16162 ** EP_Unlikely: 134217728 times likelihood
16163 ** TK_SELECT: 1st register of result vector */
16164 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
16165 ** TK_VARIABLE: variable number (always >= 1).
16166 ** TK_SELECT_COLUMN: column of the result vector */
16167 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
16168 i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
16169 u8 op2; /* TK_REGISTER: original value of Expr.op
16170 ** TK_COLUMN: the value of p5 for OP_Column
16171 ** TK_AGG_FUNCTION: nesting depth */
16172 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
16173 Table *pTab; /* Table for TK_COLUMN expressions. Can be NULL
16174 ** for a column of an index on an expression */
16178 ** The following are the meanings of bits in the Expr.flags field.
16180 #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
16181 #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
16182 /* 0x000004 // available for use */
16183 /* 0x000008 // available for use */
16184 #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
16185 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
16186 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
16187 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
16188 #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
16189 #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
16190 #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
16191 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
16192 #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
16193 #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
16194 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
16195 #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
16196 #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
16197 #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
16198 #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
16199 #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
16200 #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
16201 #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
16202 #define EP_Alias 0x400000 /* Is an alias for a result set column */
16203 #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
16206 ** Combinations of two or more EP_* flags
16208 #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
16211 ** These macros can be used to test, set, or clear bits in the
16212 ** Expr.flags field.
16214 #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
16215 #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
16216 #define ExprSetProperty(E,P) (E)->flags|=(P)
16217 #define ExprClearProperty(E,P) (E)->flags&=~(P)
16219 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
16220 ** and Accreditation only. It works like ExprSetProperty() during VVA
16221 ** processes but is a no-op for delivery.
16223 #ifdef SQLITE_DEBUG
16224 # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
16225 #else
16226 # define ExprSetVVAProperty(E,P)
16227 #endif
16230 ** Macros to determine the number of bytes required by a normal Expr
16231 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
16232 ** and an Expr struct with the EP_TokenOnly flag set.
16234 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
16235 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
16236 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
16239 ** Flags passed to the sqlite3ExprDup() function. See the header comment
16240 ** above sqlite3ExprDup() for details.
16242 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
16245 ** A list of expressions. Each expression may optionally have a
16246 ** name. An expr/name combination can be used in several ways, such
16247 ** as the list of "expr AS ID" fields following a "SELECT" or in the
16248 ** list of "ID = expr" items in an UPDATE. A list of expressions can
16249 ** also be used as the argument to a function, in which case the a.zName
16250 ** field is not used.
16252 ** By default the Expr.zSpan field holds a human-readable description of
16253 ** the expression that is used in the generation of error messages and
16254 ** column labels. In this case, Expr.zSpan is typically the text of a
16255 ** column expression as it exists in a SELECT statement. However, if
16256 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
16257 ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
16258 ** form is used for name resolution with nested FROM clauses.
16260 struct ExprList {
16261 int nExpr; /* Number of expressions on the list */
16262 struct ExprList_item { /* For each expression in the list */
16263 Expr *pExpr; /* The parse tree for this expression */
16264 char *zName; /* Token associated with this expression */
16265 char *zSpan; /* Original text of the expression */
16266 u8 sortOrder; /* 1 for DESC or 0 for ASC */
16267 unsigned done :1; /* A flag to indicate when processing is finished */
16268 unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
16269 unsigned reusable :1; /* Constant expression is reusable */
16270 union {
16271 struct {
16272 u16 iOrderByCol; /* For ORDER BY, column number in result set */
16273 u16 iAlias; /* Index into Parse.aAlias[] for zName */
16274 } x;
16275 int iConstExprReg; /* Register in which Expr value is cached */
16276 } u;
16277 } a[1]; /* One slot for each expression in the list */
16281 ** An instance of this structure is used by the parser to record both
16282 ** the parse tree for an expression and the span of input text for an
16283 ** expression.
16285 struct ExprSpan {
16286 Expr *pExpr; /* The expression parse tree */
16287 const char *zStart; /* First character of input text */
16288 const char *zEnd; /* One character past the end of input text */
16292 ** An instance of this structure can hold a simple list of identifiers,
16293 ** such as the list "a,b,c" in the following statements:
16295 ** INSERT INTO t(a,b,c) VALUES ...;
16296 ** CREATE INDEX idx ON t(a,b,c);
16297 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
16299 ** The IdList.a.idx field is used when the IdList represents the list of
16300 ** column names after a table name in an INSERT statement. In the statement
16302 ** INSERT INTO t(a,b,c) ...
16304 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
16306 struct IdList {
16307 struct IdList_item {
16308 char *zName; /* Name of the identifier */
16309 int idx; /* Index in some Table.aCol[] of a column named zName */
16310 } *a;
16311 int nId; /* Number of identifiers on the list */
16315 ** The bitmask datatype defined below is used for various optimizations.
16317 ** Changing this from a 64-bit to a 32-bit type limits the number of
16318 ** tables in a join to 32 instead of 64. But it also reduces the size
16319 ** of the library by 738 bytes on ix86.
16321 #ifdef SQLITE_BITMASK_TYPE
16322 typedef SQLITE_BITMASK_TYPE Bitmask;
16323 #else
16324 typedef u64 Bitmask;
16325 #endif
16328 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
16330 #define BMS ((int)(sizeof(Bitmask)*8))
16333 ** A bit in a Bitmask
16335 #define MASKBIT(n) (((Bitmask)1)<<(n))
16336 #define MASKBIT32(n) (((unsigned int)1)<<(n))
16337 #define ALLBITS ((Bitmask)-1)
16340 ** The following structure describes the FROM clause of a SELECT statement.
16341 ** Each table or subquery in the FROM clause is a separate element of
16342 ** the SrcList.a[] array.
16344 ** With the addition of multiple database support, the following structure
16345 ** can also be used to describe a particular table such as the table that
16346 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
16347 ** such a table must be a simple name: ID. But in SQLite, the table can
16348 ** now be identified by a database name, a dot, then the table name: ID.ID.
16350 ** The jointype starts out showing the join type between the current table
16351 ** and the next table on the list. The parser builds the list this way.
16352 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
16353 ** jointype expresses the join between the table and the previous table.
16355 ** In the colUsed field, the high-order bit (bit 63) is set if the table
16356 ** contains more than 63 columns and the 64-th or later column is used.
16358 struct SrcList {
16359 int nSrc; /* Number of tables or subqueries in the FROM clause */
16360 u32 nAlloc; /* Number of entries allocated in a[] below */
16361 struct SrcList_item {
16362 Schema *pSchema; /* Schema to which this item is fixed */
16363 char *zDatabase; /* Name of database holding this table */
16364 char *zName; /* Name of the table */
16365 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
16366 Table *pTab; /* An SQL table corresponding to zName */
16367 Select *pSelect; /* A SELECT statement used in place of a table name */
16368 int addrFillSub; /* Address of subroutine to manifest a subquery */
16369 int regReturn; /* Register holding return address of addrFillSub */
16370 int regResult; /* Registers holding results of a co-routine */
16371 struct {
16372 u8 jointype; /* Type of join between this table and the previous */
16373 unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
16374 unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
16375 unsigned isTabFunc :1; /* True if table-valued-function syntax */
16376 unsigned isCorrelated :1; /* True if sub-query is correlated */
16377 unsigned viaCoroutine :1; /* Implemented as a co-routine */
16378 unsigned isRecursive :1; /* True for recursive reference in WITH */
16379 } fg;
16380 #ifndef SQLITE_OMIT_EXPLAIN
16381 u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
16382 #endif
16383 int iCursor; /* The VDBE cursor number used to access this table */
16384 Expr *pOn; /* The ON clause of a join */
16385 IdList *pUsing; /* The USING clause of a join */
16386 Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
16387 union {
16388 char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
16389 ExprList *pFuncArg; /* Arguments to table-valued-function */
16390 } u1;
16391 Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
16392 } a[1]; /* One entry for each identifier on the list */
16396 ** Permitted values of the SrcList.a.jointype field
16398 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
16399 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
16400 #define JT_NATURAL 0x0004 /* True for a "natural" join */
16401 #define JT_LEFT 0x0008 /* Left outer join */
16402 #define JT_RIGHT 0x0010 /* Right outer join */
16403 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
16404 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
16408 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
16409 ** and the WhereInfo.wctrlFlags member.
16411 ** Value constraints (enforced via assert()):
16412 ** WHERE_USE_LIMIT == SF_FixedLimit
16414 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
16415 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
16416 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
16417 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
16418 #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
16419 #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
16420 #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
16421 ** the OR optimization */
16422 #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
16423 #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
16424 #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
16425 #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
16426 #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
16427 #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
16428 #define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */
16429 /* 0x2000 not currently used */
16430 #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
16431 /* 0x8000 not currently used */
16433 /* Allowed return values from sqlite3WhereIsDistinct()
16435 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
16436 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
16437 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
16438 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
16441 ** A NameContext defines a context in which to resolve table and column
16442 ** names. The context consists of a list of tables (the pSrcList) field and
16443 ** a list of named expression (pEList). The named expression list may
16444 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
16445 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
16446 ** pEList corresponds to the result set of a SELECT and is NULL for
16447 ** other statements.
16449 ** NameContexts can be nested. When resolving names, the inner-most
16450 ** context is searched first. If no match is found, the next outer
16451 ** context is checked. If there is still no match, the next context
16452 ** is checked. This process continues until either a match is found
16453 ** or all contexts are check. When a match is found, the nRef member of
16454 ** the context containing the match is incremented.
16456 ** Each subquery gets a new NameContext. The pNext field points to the
16457 ** NameContext in the parent query. Thus the process of scanning the
16458 ** NameContext list corresponds to searching through successively outer
16459 ** subqueries looking for a match.
16461 struct NameContext {
16462 Parse *pParse; /* The parser */
16463 SrcList *pSrcList; /* One or more tables used to resolve names */
16464 ExprList *pEList; /* Optional list of result-set columns */
16465 AggInfo *pAggInfo; /* Information about aggregates at this level */
16466 NameContext *pNext; /* Next outer name context. NULL for outermost */
16467 int nRef; /* Number of names resolved by this context */
16468 int nErr; /* Number of errors encountered while resolving names */
16469 u16 ncFlags; /* Zero or more NC_* flags defined below */
16473 ** Allowed values for the NameContext, ncFlags field.
16475 ** Value constraints (all checked via assert()):
16476 ** NC_HasAgg == SF_HasAgg
16477 ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
16480 #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
16481 #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
16482 #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
16483 #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
16484 #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
16485 #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
16486 #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
16487 #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
16490 ** An instance of the following structure contains all information
16491 ** needed to generate code for a single SELECT statement.
16493 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
16494 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
16495 ** limit and nOffset to the value of the offset (or 0 if there is not
16496 ** offset). But later on, nLimit and nOffset become the memory locations
16497 ** in the VDBE that record the limit and offset counters.
16499 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
16500 ** These addresses must be stored so that we can go back and fill in
16501 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
16502 ** the number of columns in P2 can be computed at the same time
16503 ** as the OP_OpenEphm instruction is coded because not
16504 ** enough information about the compound query is known at that point.
16505 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
16506 ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
16507 ** sequences for the ORDER BY clause.
16509 struct Select {
16510 ExprList *pEList; /* The fields of the result */
16511 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
16512 LogEst nSelectRow; /* Estimated number of result rows */
16513 u32 selFlags; /* Various SF_* values */
16514 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
16515 #if SELECTTRACE_ENABLED
16516 char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
16517 #endif
16518 int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
16519 SrcList *pSrc; /* The FROM clause */
16520 Expr *pWhere; /* The WHERE clause */
16521 ExprList *pGroupBy; /* The GROUP BY clause */
16522 Expr *pHaving; /* The HAVING clause */
16523 ExprList *pOrderBy; /* The ORDER BY clause */
16524 Select *pPrior; /* Prior select in a compound select statement */
16525 Select *pNext; /* Next select to the left in a compound */
16526 Expr *pLimit; /* LIMIT expression. NULL means not used. */
16527 Expr *pOffset; /* OFFSET expression. NULL means not used. */
16528 With *pWith; /* WITH clause attached to this select. Or NULL. */
16532 ** Allowed values for Select.selFlags. The "SF" prefix stands for
16533 ** "Select Flag".
16535 ** Value constraints (all checked via assert())
16536 ** SF_HasAgg == NC_HasAgg
16537 ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
16538 ** SF_FixedLimit == WHERE_USE_LIMIT
16540 #define SF_Distinct 0x00001 /* Output should be DISTINCT */
16541 #define SF_All 0x00002 /* Includes the ALL keyword */
16542 #define SF_Resolved 0x00004 /* Identifiers have been resolved */
16543 #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
16544 #define SF_HasAgg 0x00010 /* Contains aggregate functions */
16545 #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
16546 #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
16547 #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
16548 #define SF_Compound 0x00100 /* Part of a compound query */
16549 #define SF_Values 0x00200 /* Synthesized from VALUES clause */
16550 #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
16551 #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
16552 #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
16553 #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
16554 #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
16555 #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
16556 #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
16557 #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
16561 ** The results of a SELECT can be distributed in several ways, as defined
16562 ** by one of the following macros. The "SRT" prefix means "SELECT Result
16563 ** Type".
16565 ** SRT_Union Store results as a key in a temporary index
16566 ** identified by pDest->iSDParm.
16568 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
16570 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
16571 ** set is not empty.
16573 ** SRT_Discard Throw the results away. This is used by SELECT
16574 ** statements within triggers whose only purpose is
16575 ** the side-effects of functions.
16577 ** All of the above are free to ignore their ORDER BY clause. Those that
16578 ** follow must honor the ORDER BY clause.
16580 ** SRT_Output Generate a row of output (using the OP_ResultRow
16581 ** opcode) for each row in the result set.
16583 ** SRT_Mem Only valid if the result is a single column.
16584 ** Store the first column of the first result row
16585 ** in register pDest->iSDParm then abandon the rest
16586 ** of the query. This destination implies "LIMIT 1".
16588 ** SRT_Set The result must be a single column. Store each
16589 ** row of result as the key in table pDest->iSDParm.
16590 ** Apply the affinity pDest->affSdst before storing
16591 ** results. Used to implement "IN (SELECT ...)".
16593 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
16594 ** the result there. The cursor is left open after
16595 ** returning. This is like SRT_Table except that
16596 ** this destination uses OP_OpenEphemeral to create
16597 ** the table first.
16599 ** SRT_Coroutine Generate a co-routine that returns a new row of
16600 ** results each time it is invoked. The entry point
16601 ** of the co-routine is stored in register pDest->iSDParm
16602 ** and the result row is stored in pDest->nDest registers
16603 ** starting with pDest->iSdst.
16605 ** SRT_Table Store results in temporary table pDest->iSDParm.
16606 ** SRT_Fifo This is like SRT_EphemTab except that the table
16607 ** is assumed to already be open. SRT_Fifo has
16608 ** the additional property of being able to ignore
16609 ** the ORDER BY clause.
16611 ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
16612 ** But also use temporary table pDest->iSDParm+1 as
16613 ** a record of all prior results and ignore any duplicate
16614 ** rows. Name means: "Distinct Fifo".
16616 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
16617 ** an index). Append a sequence number so that all entries
16618 ** are distinct.
16620 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
16621 ** the same record has never been stored before. The
16622 ** index at pDest->iSDParm+1 hold all prior stores.
16624 #define SRT_Union 1 /* Store result as keys in an index */
16625 #define SRT_Except 2 /* Remove result from a UNION index */
16626 #define SRT_Exists 3 /* Store 1 if the result is not empty */
16627 #define SRT_Discard 4 /* Do not save the results anywhere */
16628 #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
16629 #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
16630 #define SRT_Queue 7 /* Store result in an queue */
16631 #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
16633 /* The ORDER BY clause is ignored for all of the above */
16634 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
16636 #define SRT_Output 9 /* Output each row of result */
16637 #define SRT_Mem 10 /* Store result in a memory cell */
16638 #define SRT_Set 11 /* Store results as keys in an index */
16639 #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
16640 #define SRT_Coroutine 13 /* Generate a single row of result */
16641 #define SRT_Table 14 /* Store result as data with an automatic rowid */
16644 ** An instance of this object describes where to put of the results of
16645 ** a SELECT statement.
16647 struct SelectDest {
16648 u8 eDest; /* How to dispose of the results. On of SRT_* above. */
16649 int iSDParm; /* A parameter used by the eDest disposal method */
16650 int iSdst; /* Base register where results are written */
16651 int nSdst; /* Number of registers allocated */
16652 char *zAffSdst; /* Affinity used when eDest==SRT_Set */
16653 ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
16657 ** During code generation of statements that do inserts into AUTOINCREMENT
16658 ** tables, the following information is attached to the Table.u.autoInc.p
16659 ** pointer of each autoincrement table to record some side information that
16660 ** the code generator needs. We have to keep per-table autoincrement
16661 ** information in case inserts are done within triggers. Triggers do not
16662 ** normally coordinate their activities, but we do need to coordinate the
16663 ** loading and saving of autoincrement information.
16665 struct AutoincInfo {
16666 AutoincInfo *pNext; /* Next info block in a list of them all */
16667 Table *pTab; /* Table this info block refers to */
16668 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
16669 int regCtr; /* Memory register holding the rowid counter */
16673 ** Size of the column cache
16675 #ifndef SQLITE_N_COLCACHE
16676 # define SQLITE_N_COLCACHE 10
16677 #endif
16680 ** At least one instance of the following structure is created for each
16681 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
16682 ** statement. All such objects are stored in the linked list headed at
16683 ** Parse.pTriggerPrg and deleted once statement compilation has been
16684 ** completed.
16686 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
16687 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
16688 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
16689 ** The Parse.pTriggerPrg list never contains two entries with the same
16690 ** values for both pTrigger and orconf.
16692 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
16693 ** accessed (or set to 0 for triggers fired as a result of INSERT
16694 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
16695 ** a mask of new.* columns used by the program.
16697 struct TriggerPrg {
16698 Trigger *pTrigger; /* Trigger this program was coded from */
16699 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
16700 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
16701 int orconf; /* Default ON CONFLICT policy */
16702 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
16706 ** The yDbMask datatype for the bitmask of all attached databases.
16708 #if SQLITE_MAX_ATTACHED>30
16709 typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
16710 # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
16711 # define DbMaskZero(M) memset((M),0,sizeof(M))
16712 # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
16713 # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
16714 # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
16715 #else
16716 typedef unsigned int yDbMask;
16717 # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
16718 # define DbMaskZero(M) (M)=0
16719 # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
16720 # define DbMaskAllZero(M) (M)==0
16721 # define DbMaskNonZero(M) (M)!=0
16722 #endif
16725 ** An SQL parser context. A copy of this structure is passed through
16726 ** the parser and down into all the parser action routine in order to
16727 ** carry around information that is global to the entire parse.
16729 ** The structure is divided into two parts. When the parser and code
16730 ** generate call themselves recursively, the first part of the structure
16731 ** is constant but the second part is reset at the beginning and end of
16732 ** each recursion.
16734 ** The nTableLock and aTableLock variables are only used if the shared-cache
16735 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
16736 ** used to store the set of table-locks required by the statement being
16737 ** compiled. Function sqlite3TableLock() is used to add entries to the
16738 ** list.
16740 struct Parse {
16741 sqlite3 *db; /* The main database structure */
16742 char *zErrMsg; /* An error message */
16743 Vdbe *pVdbe; /* An engine for executing database bytecode */
16744 int rc; /* Return code from execution */
16745 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
16746 u8 checkSchema; /* Causes schema cookie check after an error */
16747 u8 nested; /* Number of nested calls to the parser/code generator */
16748 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
16749 u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
16750 u8 mayAbort; /* True if statement may throw an ABORT exception */
16751 u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
16752 u8 okConstFactor; /* OK to factor out constants */
16753 u8 disableLookaside; /* Number of times lookaside has been disabled */
16754 u8 nColCache; /* Number of entries in aColCache[] */
16755 int nRangeReg; /* Size of the temporary register block */
16756 int iRangeReg; /* First register in temporary register block */
16757 int nErr; /* Number of errors seen */
16758 int nTab; /* Number of previously allocated VDBE cursors */
16759 int nMem; /* Number of memory cells used so far */
16760 int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
16761 int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
16762 int iSelfTab; /* Table for associated with an index on expr, or negative
16763 ** of the base register during check-constraint eval */
16764 int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
16765 int iCacheCnt; /* Counter used to generate aColCache[].lru values */
16766 int nLabel; /* Number of labels used */
16767 int *aLabel; /* Space to hold the labels */
16768 ExprList *pConstExpr;/* Constant expressions */
16769 Token constraintName;/* Name of the constraint currently being parsed */
16770 yDbMask writeMask; /* Start a write transaction on these databases */
16771 yDbMask cookieMask; /* Bitmask of schema verified databases */
16772 int regRowid; /* Register holding rowid of CREATE TABLE entry */
16773 int regRoot; /* Register holding root page number for new objects */
16774 int nMaxArg; /* Max args passed to user function by sub-program */
16775 #if SELECTTRACE_ENABLED
16776 int nSelect; /* Number of SELECT statements seen */
16777 int nSelectIndent; /* How far to indent SELECTTRACE() output */
16778 #endif
16779 #ifndef SQLITE_OMIT_SHARED_CACHE
16780 int nTableLock; /* Number of locks in aTableLock */
16781 TableLock *aTableLock; /* Required table locks for shared-cache mode */
16782 #endif
16783 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
16784 Parse *pToplevel; /* Parse structure for main program (or NULL) */
16785 Table *pTriggerTab; /* Table triggers are being coded for */
16786 int addrCrTab; /* Address of OP_CreateBtree opcode on CREATE TABLE */
16787 u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
16788 u32 oldmask; /* Mask of old.* columns referenced */
16789 u32 newmask; /* Mask of new.* columns referenced */
16790 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
16791 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
16792 u8 disableTriggers; /* True to disable triggers */
16794 /**************************************************************************
16795 ** Fields above must be initialized to zero. The fields that follow,
16796 ** down to the beginning of the recursive section, do not need to be
16797 ** initialized as they will be set before being used. The boundary is
16798 ** determined by offsetof(Parse,aColCache).
16799 **************************************************************************/
16801 struct yColCache {
16802 int iTable; /* Table cursor number */
16803 i16 iColumn; /* Table column number */
16804 u8 tempReg; /* iReg is a temp register that needs to be freed */
16805 int iLevel; /* Nesting level */
16806 int iReg; /* Reg with value of this column. 0 means none. */
16807 int lru; /* Least recently used entry has the smallest value */
16808 } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
16809 int aTempReg[8]; /* Holding area for temporary registers */
16810 Token sNameToken; /* Token with unqualified schema object name */
16812 /************************************************************************
16813 ** Above is constant between recursions. Below is reset before and after
16814 ** each recursion. The boundary between these two regions is determined
16815 ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
16816 ** first field in the recursive region.
16817 ************************************************************************/
16819 Token sLastToken; /* The last token parsed */
16820 ynVar nVar; /* Number of '?' variables seen in the SQL so far */
16821 u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
16822 u8 explain; /* True if the EXPLAIN flag is found on the query */
16823 #ifndef SQLITE_OMIT_VIRTUALTABLE
16824 u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
16825 int nVtabLock; /* Number of virtual tables to lock */
16826 #endif
16827 int nHeight; /* Expression tree height of current sub-select */
16828 #ifndef SQLITE_OMIT_EXPLAIN
16829 int iSelectId; /* ID of current select for EXPLAIN output */
16830 int iNextSelectId; /* Next available select ID for EXPLAIN output */
16831 #endif
16832 VList *pVList; /* Mapping between variable names and numbers */
16833 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
16834 const char *zTail; /* All SQL text past the last semicolon parsed */
16835 Table *pNewTable; /* A table being constructed by CREATE TABLE */
16836 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
16837 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
16838 #ifndef SQLITE_OMIT_VIRTUALTABLE
16839 Token sArg; /* Complete text of a module argument */
16840 Table **apVtabLock; /* Pointer to virtual tables needing locking */
16841 #endif
16842 Table *pZombieTab; /* List of Table objects to delete after code gen */
16843 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
16844 With *pWith; /* Current WITH clause, or NULL */
16845 With *pWithToFree; /* Free this WITH object at the end of the parse */
16849 ** Sizes and pointers of various parts of the Parse object.
16851 #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
16852 #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
16853 #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
16854 #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
16857 ** Return true if currently inside an sqlite3_declare_vtab() call.
16859 #ifdef SQLITE_OMIT_VIRTUALTABLE
16860 #define IN_DECLARE_VTAB 0
16861 #else
16862 #define IN_DECLARE_VTAB (pParse->declareVtab)
16863 #endif
16866 ** An instance of the following structure can be declared on a stack and used
16867 ** to save the Parse.zAuthContext value so that it can be restored later.
16869 struct AuthContext {
16870 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
16871 Parse *pParse; /* The Parse structure */
16875 ** Bitfield flags for P5 value in various opcodes.
16877 ** Value constraints (enforced via assert()):
16878 ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
16879 ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
16880 ** OPFLAG_BULKCSR == BTREE_BULKLOAD
16881 ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
16882 ** OPFLAG_FORDELETE == BTREE_FORDELETE
16883 ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
16884 ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
16886 #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
16887 /* Also used in P2 (not P5) of OP_Delete */
16888 #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
16889 #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
16890 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
16891 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
16892 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
16893 #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
16894 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
16895 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
16896 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
16897 #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
16898 #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
16899 #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
16900 #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
16901 #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
16902 #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
16905 * Each trigger present in the database schema is stored as an instance of
16906 * struct Trigger.
16908 * Pointers to instances of struct Trigger are stored in two ways.
16909 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
16910 * database). This allows Trigger structures to be retrieved by name.
16911 * 2. All triggers associated with a single table form a linked list, using the
16912 * pNext member of struct Trigger. A pointer to the first element of the
16913 * linked list is stored as the "pTrigger" member of the associated
16914 * struct Table.
16916 * The "step_list" member points to the first element of a linked list
16917 * containing the SQL statements specified as the trigger program.
16919 struct Trigger {
16920 char *zName; /* The name of the trigger */
16921 char *table; /* The table or view to which the trigger applies */
16922 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
16923 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
16924 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
16925 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
16926 the <column-list> is stored here */
16927 Schema *pSchema; /* Schema containing the trigger */
16928 Schema *pTabSchema; /* Schema containing the table */
16929 TriggerStep *step_list; /* Link list of trigger program steps */
16930 Trigger *pNext; /* Next trigger associated with the table */
16934 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
16935 ** determine which.
16937 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
16938 ** In that cases, the constants below can be ORed together.
16940 #define TRIGGER_BEFORE 1
16941 #define TRIGGER_AFTER 2
16944 * An instance of struct TriggerStep is used to store a single SQL statement
16945 * that is a part of a trigger-program.
16947 * Instances of struct TriggerStep are stored in a singly linked list (linked
16948 * using the "pNext" member) referenced by the "step_list" member of the
16949 * associated struct Trigger instance. The first element of the linked list is
16950 * the first step of the trigger-program.
16952 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
16953 * "SELECT" statement. The meanings of the other members is determined by the
16954 * value of "op" as follows:
16956 * (op == TK_INSERT)
16957 * orconf -> stores the ON CONFLICT algorithm
16958 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
16959 * this stores a pointer to the SELECT statement. Otherwise NULL.
16960 * zTarget -> Dequoted name of the table to insert into.
16961 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
16962 * this stores values to be inserted. Otherwise NULL.
16963 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
16964 * statement, then this stores the column-names to be
16965 * inserted into.
16967 * (op == TK_DELETE)
16968 * zTarget -> Dequoted name of the table to delete from.
16969 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
16970 * Otherwise NULL.
16972 * (op == TK_UPDATE)
16973 * zTarget -> Dequoted name of the table to update.
16974 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
16975 * Otherwise NULL.
16976 * pExprList -> A list of the columns to update and the expressions to update
16977 * them to. See sqlite3Update() documentation of "pChanges"
16978 * argument.
16981 struct TriggerStep {
16982 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
16983 u8 orconf; /* OE_Rollback etc. */
16984 Trigger *pTrig; /* The trigger that this step is a part of */
16985 Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
16986 char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
16987 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
16988 ExprList *pExprList; /* SET clause for UPDATE. */
16989 IdList *pIdList; /* Column names for INSERT */
16990 TriggerStep *pNext; /* Next in the link-list */
16991 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
16995 ** The following structure contains information used by the sqliteFix...
16996 ** routines as they walk the parse tree to make database references
16997 ** explicit.
16999 typedef struct DbFixer DbFixer;
17000 struct DbFixer {
17001 Parse *pParse; /* The parsing context. Error messages written here */
17002 Schema *pSchema; /* Fix items to this schema */
17003 int bVarOnly; /* Check for variable references only */
17004 const char *zDb; /* Make sure all objects are contained in this database */
17005 const char *zType; /* Type of the container - used for error messages */
17006 const Token *pName; /* Name of the container - used for error messages */
17010 ** An objected used to accumulate the text of a string where we
17011 ** do not necessarily know how big the string will be in the end.
17013 struct StrAccum {
17014 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
17015 char *zText; /* The string collected so far */
17016 u32 nAlloc; /* Amount of space allocated in zText */
17017 u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
17018 u32 nChar; /* Length of the string so far */
17019 u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
17020 u8 printfFlags; /* SQLITE_PRINTF flags below */
17022 #define STRACCUM_NOMEM 1
17023 #define STRACCUM_TOOBIG 2
17024 #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
17025 #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
17026 #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
17028 #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
17032 ** A pointer to this structure is used to communicate information
17033 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
17035 typedef struct {
17036 sqlite3 *db; /* The database being initialized */
17037 char **pzErrMsg; /* Error message stored here */
17038 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
17039 int rc; /* Result code stored here */
17040 } InitData;
17043 ** Structure containing global configuration data for the SQLite library.
17045 ** This structure also contains some state information.
17047 struct Sqlite3Config {
17048 int bMemstat; /* True to enable memory status */
17049 int bCoreMutex; /* True to enable core mutexing */
17050 int bFullMutex; /* True to enable full mutexing */
17051 int bOpenUri; /* True to interpret filenames as URIs */
17052 int bUseCis; /* Use covering indices for full-scans */
17053 int bSmallMalloc; /* Avoid large memory allocations if true */
17054 int mxStrlen; /* Maximum string length */
17055 int neverCorrupt; /* Database is always well-formed */
17056 int szLookaside; /* Default lookaside buffer size */
17057 int nLookaside; /* Default lookaside buffer count */
17058 int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
17059 sqlite3_mem_methods m; /* Low-level memory allocation interface */
17060 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
17061 sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
17062 void *pHeap; /* Heap storage space */
17063 int nHeap; /* Size of pHeap[] */
17064 int mnReq, mxReq; /* Min and max heap requests sizes */
17065 sqlite3_int64 szMmap; /* mmap() space per open file */
17066 sqlite3_int64 mxMmap; /* Maximum value for szMmap */
17067 void *pPage; /* Page cache memory */
17068 int szPage; /* Size of each page in pPage[] */
17069 int nPage; /* Number of pages in pPage[] */
17070 int mxParserStack; /* maximum depth of the parser stack */
17071 int sharedCacheEnabled; /* true if shared-cache mode enabled */
17072 u32 szPma; /* Maximum Sorter PMA size */
17073 /* The above might be initialized to non-zero. The following need to always
17074 ** initially be zero, however. */
17075 int isInit; /* True after initialization has finished */
17076 int inProgress; /* True while initialization in progress */
17077 int isMutexInit; /* True after mutexes are initialized */
17078 int isMallocInit; /* True after malloc is initialized */
17079 int isPCacheInit; /* True after malloc is initialized */
17080 int nRefInitMutex; /* Number of users of pInitMutex */
17081 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
17082 void (*xLog)(void*,int,const char*); /* Function for logging */
17083 void *pLogArg; /* First argument to xLog() */
17084 #ifdef SQLITE_ENABLE_SQLLOG
17085 void(*xSqllog)(void*,sqlite3*,const char*, int);
17086 void *pSqllogArg;
17087 #endif
17088 #ifdef SQLITE_VDBE_COVERAGE
17089 /* The following callback (if not NULL) is invoked on every VDBE branch
17090 ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
17092 void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
17093 void *pVdbeBranchArg; /* 1st argument */
17094 #endif
17095 #ifndef SQLITE_UNTESTABLE
17096 int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
17097 #endif
17098 int bLocaltimeFault; /* True to fail localtime() calls */
17099 int iOnceResetThreshold; /* When to reset OP_Once counters */
17103 ** This macro is used inside of assert() statements to indicate that
17104 ** the assert is only valid on a well-formed database. Instead of:
17106 ** assert( X );
17108 ** One writes:
17110 ** assert( X || CORRUPT_DB );
17112 ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
17113 ** that the database is definitely corrupt, only that it might be corrupt.
17114 ** For most test cases, CORRUPT_DB is set to false using a special
17115 ** sqlite3_test_control(). This enables assert() statements to prove
17116 ** things that are always true for well-formed databases.
17118 #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
17121 ** Context pointer passed down through the tree-walk.
17123 struct Walker {
17124 Parse *pParse; /* Parser context. */
17125 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
17126 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
17127 void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
17128 int walkerDepth; /* Number of subqueries */
17129 u8 eCode; /* A small processing code */
17130 union { /* Extra data for callback */
17131 NameContext *pNC; /* Naming context */
17132 int n; /* A counter */
17133 int iCur; /* A cursor number */
17134 SrcList *pSrcList; /* FROM clause */
17135 struct SrcCount *pSrcCount; /* Counting column references */
17136 struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
17137 int *aiCol; /* array of column indexes */
17138 struct IdxCover *pIdxCover; /* Check for index coverage */
17139 struct IdxExprTrans *pIdxTrans; /* Convert indexed expr to column */
17140 ExprList *pGroupBy; /* GROUP BY clause */
17141 struct HavingToWhereCtx *pHavingCtx; /* HAVING to WHERE clause ctx */
17142 } u;
17145 /* Forward declarations */
17146 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
17147 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
17148 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
17149 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
17150 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
17151 SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
17152 SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
17153 SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
17154 #ifdef SQLITE_DEBUG
17155 SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
17156 #endif
17159 ** Return code from the parse-tree walking primitives and their
17160 ** callbacks.
17162 #define WRC_Continue 0 /* Continue down into children */
17163 #define WRC_Prune 1 /* Omit children but continue walking siblings */
17164 #define WRC_Abort 2 /* Abandon the tree walk */
17167 ** An instance of this structure represents a set of one or more CTEs
17168 ** (common table expressions) created by a single WITH clause.
17170 struct With {
17171 int nCte; /* Number of CTEs in the WITH clause */
17172 With *pOuter; /* Containing WITH clause, or NULL */
17173 struct Cte { /* For each CTE in the WITH clause.... */
17174 char *zName; /* Name of this CTE */
17175 ExprList *pCols; /* List of explicit column names, or NULL */
17176 Select *pSelect; /* The definition of this CTE */
17177 const char *zCteErr; /* Error message for circular references */
17178 } a[1];
17181 #ifdef SQLITE_DEBUG
17183 ** An instance of the TreeView object is used for printing the content of
17184 ** data structures on sqlite3DebugPrintf() using a tree-like view.
17186 struct TreeView {
17187 int iLevel; /* Which level of the tree we are on */
17188 u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
17190 #endif /* SQLITE_DEBUG */
17193 ** Assuming zIn points to the first byte of a UTF-8 character,
17194 ** advance zIn to point to the first byte of the next UTF-8 character.
17196 #define SQLITE_SKIP_UTF8(zIn) { \
17197 if( (*(zIn++))>=0xc0 ){ \
17198 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
17203 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
17204 ** the same name but without the _BKPT suffix. These macros invoke
17205 ** routines that report the line-number on which the error originated
17206 ** using sqlite3_log(). The routines also provide a convenient place
17207 ** to set a debugger breakpoint.
17209 SQLITE_PRIVATE int sqlite3CorruptError(int);
17210 SQLITE_PRIVATE int sqlite3MisuseError(int);
17211 SQLITE_PRIVATE int sqlite3CantopenError(int);
17212 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
17213 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
17214 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
17215 #ifdef SQLITE_DEBUG
17216 SQLITE_PRIVATE int sqlite3NomemError(int);
17217 SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
17218 SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno);
17219 # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
17220 # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
17221 # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
17222 #else
17223 # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
17224 # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
17225 # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
17226 #endif
17229 ** FTS3 and FTS4 both require virtual table support
17231 #if defined(SQLITE_OMIT_VIRTUALTABLE)
17232 # undef SQLITE_ENABLE_FTS3
17233 # undef SQLITE_ENABLE_FTS4
17234 #endif
17237 ** FTS4 is really an extension for FTS3. It is enabled using the
17238 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
17239 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
17241 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
17242 # define SQLITE_ENABLE_FTS3 1
17243 #endif
17246 ** The ctype.h header is needed for non-ASCII systems. It is also
17247 ** needed by FTS3 when FTS3 is included in the amalgamation.
17249 #if !defined(SQLITE_ASCII) || \
17250 (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
17251 # include <ctype.h>
17252 #endif
17255 ** The following macros mimic the standard library functions toupper(),
17256 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
17257 ** sqlite versions only work for ASCII characters, regardless of locale.
17259 #ifdef SQLITE_ASCII
17260 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
17261 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
17262 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
17263 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
17264 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
17265 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
17266 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
17267 # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
17268 #else
17269 # define sqlite3Toupper(x) toupper((unsigned char)(x))
17270 # define sqlite3Isspace(x) isspace((unsigned char)(x))
17271 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
17272 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
17273 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
17274 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
17275 # define sqlite3Tolower(x) tolower((unsigned char)(x))
17276 # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
17277 #endif
17278 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
17279 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
17280 #endif
17283 ** Internal function prototypes
17285 SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
17286 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
17287 SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
17288 #define sqlite3StrNICmp sqlite3_strnicmp
17290 SQLITE_PRIVATE int sqlite3MallocInit(void);
17291 SQLITE_PRIVATE void sqlite3MallocEnd(void);
17292 SQLITE_PRIVATE void *sqlite3Malloc(u64);
17293 SQLITE_PRIVATE void *sqlite3MallocZero(u64);
17294 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
17295 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
17296 SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
17297 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
17298 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
17299 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
17300 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
17301 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
17302 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
17303 SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
17304 SQLITE_PRIVATE int sqlite3MallocSize(void*);
17305 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
17306 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
17307 SQLITE_PRIVATE void sqlite3PageFree(void*);
17308 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
17309 #ifndef SQLITE_UNTESTABLE
17310 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
17311 #endif
17312 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
17315 ** On systems with ample stack space and that support alloca(), make
17316 ** use of alloca() to obtain space for large automatic objects. By default,
17317 ** obtain space from malloc().
17319 ** The alloca() routine never returns NULL. This will cause code paths
17320 ** that deal with sqlite3StackAlloc() failures to be unreachable.
17322 #ifdef SQLITE_USE_ALLOCA
17323 # define sqlite3StackAllocRaw(D,N) alloca(N)
17324 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
17325 # define sqlite3StackFree(D,P)
17326 #else
17327 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
17328 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
17329 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
17330 #endif
17332 /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
17333 ** are, disable MEMSYS3
17335 #ifdef SQLITE_ENABLE_MEMSYS5
17336 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
17337 #undef SQLITE_ENABLE_MEMSYS3
17338 #endif
17339 #ifdef SQLITE_ENABLE_MEMSYS3
17340 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
17341 #endif
17344 #ifndef SQLITE_MUTEX_OMIT
17345 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
17346 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
17347 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
17348 SQLITE_PRIVATE int sqlite3MutexInit(void);
17349 SQLITE_PRIVATE int sqlite3MutexEnd(void);
17350 #endif
17351 #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
17352 SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
17353 #else
17354 # define sqlite3MemoryBarrier()
17355 #endif
17357 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
17358 SQLITE_PRIVATE void sqlite3StatusUp(int, int);
17359 SQLITE_PRIVATE void sqlite3StatusDown(int, int);
17360 SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
17361 SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
17363 /* Access to mutexes used by sqlite3_status() */
17364 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
17365 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
17367 #ifndef SQLITE_OMIT_FLOATING_POINT
17368 SQLITE_PRIVATE int sqlite3IsNaN(double);
17369 #else
17370 # define sqlite3IsNaN(X) 0
17371 #endif
17374 ** An instance of the following structure holds information about SQL
17375 ** functions arguments that are the parameters to the printf() function.
17377 struct PrintfArguments {
17378 int nArg; /* Total number of arguments */
17379 int nUsed; /* Number of arguments used so far */
17380 sqlite3_value **apArg; /* The argument values */
17383 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
17384 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
17385 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
17386 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
17387 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
17388 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
17389 #endif
17390 #if defined(SQLITE_TEST)
17391 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
17392 #endif
17394 #if defined(SQLITE_DEBUG)
17395 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
17396 SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
17397 SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
17398 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
17399 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
17400 #endif
17403 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
17404 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
17405 SQLITE_PRIVATE void sqlite3Dequote(char*);
17406 SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
17407 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
17408 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
17409 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
17410 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
17411 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
17412 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
17413 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
17414 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
17415 #ifdef SQLITE_DEBUG
17416 SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
17417 #endif
17418 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
17419 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
17420 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
17421 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
17422 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
17423 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
17424 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
17425 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
17426 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
17427 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
17428 SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
17429 SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
17430 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
17431 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
17432 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
17433 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
17434 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
17435 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
17436 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
17437 #ifndef SQLITE_OMIT_VIRTUALTABLE
17438 SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
17439 #endif
17440 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
17441 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
17442 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
17443 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
17444 SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
17445 SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
17446 SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
17447 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
17448 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
17449 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
17450 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
17451 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
17452 #if SQLITE_ENABLE_HIDDEN_COLUMNS
17453 SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
17454 #else
17455 # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
17456 #endif
17457 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
17458 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
17459 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
17460 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
17461 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
17462 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
17463 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
17464 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
17465 sqlite3_vfs**,char**,char **);
17466 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
17468 #ifdef SQLITE_UNTESTABLE
17469 # define sqlite3FaultSim(X) SQLITE_OK
17470 #else
17471 SQLITE_PRIVATE int sqlite3FaultSim(int);
17472 #endif
17474 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
17475 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
17476 SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
17477 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
17478 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
17479 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
17480 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
17481 #ifndef SQLITE_UNTESTABLE
17482 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
17483 #endif
17485 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
17486 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
17487 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
17488 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
17489 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
17491 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
17493 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
17494 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
17495 #else
17496 # define sqlite3ViewGetColumnNames(A,B) 0
17497 #endif
17499 #if SQLITE_MAX_ATTACHED>30
17500 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
17501 #endif
17502 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
17503 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
17504 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
17505 #ifndef SQLITE_OMIT_AUTOINCREMENT
17506 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
17507 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
17508 #else
17509 # define sqlite3AutoincrementBegin(X)
17510 # define sqlite3AutoincrementEnd(X)
17511 #endif
17512 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
17513 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
17514 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
17515 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
17516 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
17517 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
17518 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
17519 Token*, Select*, Expr*, IdList*);
17520 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
17521 SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
17522 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
17523 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
17524 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
17525 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
17526 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
17527 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
17528 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
17529 Expr*, int, int, u8);
17530 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
17531 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
17532 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
17533 Expr*,ExprList*,u32,Expr*,Expr*);
17534 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
17535 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
17536 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
17537 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
17538 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
17539 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
17540 #endif
17541 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
17542 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
17543 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
17544 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
17545 SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
17546 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
17547 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
17548 SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
17549 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
17550 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
17551 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
17552 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
17553 #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
17554 #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
17555 #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
17556 SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
17557 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
17558 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
17559 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
17560 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
17561 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
17562 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
17563 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
17564 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
17565 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
17566 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
17567 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
17568 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
17569 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
17570 SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
17571 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
17572 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
17573 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
17574 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
17575 #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
17576 #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
17577 #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
17578 #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
17579 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
17580 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
17581 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
17582 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
17583 #define LOCATE_VIEW 0x01
17584 #define LOCATE_NOERR 0x02
17585 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
17586 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
17587 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
17588 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
17589 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
17590 SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
17591 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
17592 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
17593 SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
17594 SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
17595 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
17596 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
17597 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
17598 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
17599 SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
17600 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
17601 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
17602 #ifndef SQLITE_UNTESTABLE
17603 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
17604 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
17605 #endif
17606 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
17607 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
17608 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
17609 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
17610 SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
17611 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
17612 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
17613 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
17614 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
17615 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
17616 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
17617 SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
17618 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
17619 #ifdef SQLITE_ENABLE_CURSOR_HINTS
17620 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
17621 #endif
17622 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
17623 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
17624 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
17625 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
17626 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
17627 Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
17628 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
17629 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
17630 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
17631 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
17632 u8,u8,int,int*,int*);
17633 #ifdef SQLITE_ENABLE_NULL_TRIM
17634 SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
17635 #else
17636 # define sqlite3SetMakeRecordP5(A,B)
17637 #endif
17638 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
17639 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
17640 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
17641 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
17642 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
17643 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
17644 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
17645 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
17646 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
17647 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
17648 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
17649 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
17650 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
17651 #if SELECTTRACE_ENABLED
17652 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
17653 #else
17654 # define sqlite3SelectSetName(A,B)
17655 #endif
17656 SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
17657 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
17658 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
17659 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
17660 SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
17661 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
17662 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
17663 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
17665 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
17666 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
17667 #endif
17669 #ifndef SQLITE_OMIT_TRIGGER
17670 SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
17671 Expr*,int, int);
17672 SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
17673 SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
17674 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
17675 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
17676 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
17677 SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
17678 int, int, int);
17679 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
17680 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
17681 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
17682 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
17683 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
17684 Select*,u8);
17685 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
17686 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
17687 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
17688 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
17689 SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
17690 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
17691 # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
17692 #else
17693 # define sqlite3TriggersExist(B,C,D,E,F) 0
17694 # define sqlite3DeleteTrigger(A,B)
17695 # define sqlite3DropTriggerPtr(A,B)
17696 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
17697 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
17698 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
17699 # define sqlite3TriggerList(X, Y) 0
17700 # define sqlite3ParseToplevel(p) p
17701 # define sqlite3IsToplevel(p) 1
17702 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
17703 #endif
17705 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
17706 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
17707 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
17708 #ifndef SQLITE_OMIT_AUTHORIZATION
17709 SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
17710 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
17711 SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
17712 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
17713 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
17714 #else
17715 # define sqlite3AuthRead(a,b,c,d)
17716 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
17717 # define sqlite3AuthContextPush(a,b,c)
17718 # define sqlite3AuthContextPop(a) ((void)(a))
17719 #endif
17720 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
17721 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
17722 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
17723 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
17724 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
17725 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
17726 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
17727 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
17728 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
17729 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
17730 SQLITE_PRIVATE int sqlite3Atoi(const char*);
17731 #ifndef SQLITE_OMIT_UTF16
17732 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
17733 #endif
17734 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
17735 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
17736 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
17737 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
17738 #ifndef SQLITE_OMIT_VIRTUALTABLE
17739 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
17740 #endif
17741 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
17742 defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
17743 defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
17744 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
17745 #endif
17746 SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
17747 SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
17748 SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
17751 ** Routines to read and write variable-length integers. These used to
17752 ** be defined locally, but now we use the varint routines in the util.c
17753 ** file.
17755 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
17756 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
17757 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
17758 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
17761 ** The common case is for a varint to be a single byte. They following
17762 ** macros handle the common case without a procedure call, but then call
17763 ** the procedure for larger varints.
17765 #define getVarint32(A,B) \
17766 (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
17767 #define putVarint32(A,B) \
17768 (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
17769 sqlite3PutVarint((A),(B)))
17770 #define getVarint sqlite3GetVarint
17771 #define putVarint sqlite3PutVarint
17774 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
17775 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
17776 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
17777 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
17778 SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
17779 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
17780 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
17781 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
17782 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
17783 SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
17784 SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
17785 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
17786 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
17787 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
17789 #if defined(SQLITE_NEED_ERR_NAME)
17790 SQLITE_PRIVATE const char *sqlite3ErrName(int);
17791 #endif
17793 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
17794 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
17795 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
17796 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
17797 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
17798 SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
17799 SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
17800 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
17801 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
17802 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
17803 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
17804 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
17805 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
17806 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
17807 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
17808 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
17809 SQLITE_PRIVATE int sqlite3AbsInt32(int);
17810 #ifdef SQLITE_ENABLE_8_3_NAMES
17811 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
17812 #else
17813 # define sqlite3FileSuffix3(X,Y)
17814 #endif
17815 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
17817 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
17818 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
17819 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
17820 void(*)(void*));
17821 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
17822 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
17823 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
17824 #ifndef SQLITE_OMIT_UTF16
17825 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
17826 #endif
17827 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
17828 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
17829 #ifndef SQLITE_AMALGAMATION
17830 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
17831 SQLITE_PRIVATE const char sqlite3StrBINARY[];
17832 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
17833 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
17834 SQLITE_PRIVATE const Token sqlite3IntTokens[];
17835 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
17836 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
17837 #ifndef SQLITE_OMIT_WSD
17838 SQLITE_PRIVATE int sqlite3PendingByte;
17839 #endif
17840 #endif
17841 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
17842 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
17843 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
17844 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
17845 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
17846 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
17847 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
17848 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
17849 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
17850 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
17851 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
17852 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
17853 SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
17854 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
17855 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
17856 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
17857 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
17858 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
17859 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
17860 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
17861 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
17862 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
17863 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
17864 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
17865 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
17866 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
17867 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
17868 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
17869 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
17870 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
17871 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
17872 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
17873 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
17874 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
17875 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
17876 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
17877 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
17878 #ifdef SQLITE_DEBUG
17879 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
17880 #endif
17881 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
17882 void (*)(sqlite3_context*,int,sqlite3_value **),
17883 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
17884 FuncDestructor *pDestructor
17886 SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
17887 SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
17888 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
17889 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
17891 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
17892 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
17893 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
17894 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
17895 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
17896 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
17897 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
17898 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
17900 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
17901 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
17903 #ifndef SQLITE_OMIT_SUBQUERY
17904 SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
17905 #else
17906 # define sqlite3ExprCheckIN(x,y) SQLITE_OK
17907 #endif
17909 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
17910 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
17911 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
17912 Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
17913 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
17914 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
17915 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
17916 SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
17917 #endif
17920 ** The interface to the LEMON-generated parser
17922 #ifndef SQLITE_AMALGAMATION
17923 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
17924 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
17925 #endif
17926 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
17927 #ifdef YYTRACKMAXSTACKDEPTH
17928 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
17929 #endif
17931 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
17932 #ifndef SQLITE_OMIT_LOAD_EXTENSION
17933 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
17934 #else
17935 # define sqlite3CloseExtensions(X)
17936 #endif
17938 #ifndef SQLITE_OMIT_SHARED_CACHE
17939 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
17940 #else
17941 #define sqlite3TableLock(v,w,x,y,z)
17942 #endif
17944 #ifdef SQLITE_TEST
17945 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
17946 #endif
17948 #ifdef SQLITE_OMIT_VIRTUALTABLE
17949 # define sqlite3VtabClear(Y)
17950 # define sqlite3VtabSync(X,Y) SQLITE_OK
17951 # define sqlite3VtabRollback(X)
17952 # define sqlite3VtabCommit(X)
17953 # define sqlite3VtabInSync(db) 0
17954 # define sqlite3VtabLock(X)
17955 # define sqlite3VtabUnlock(X)
17956 # define sqlite3VtabUnlockList(X)
17957 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
17958 # define sqlite3GetVTable(X,Y) ((VTable*)0)
17959 #else
17960 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
17961 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
17962 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
17963 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
17964 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
17965 SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
17966 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
17967 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
17968 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
17969 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
17970 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
17971 SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
17972 sqlite3*,
17973 const char*,
17974 const sqlite3_module*,
17975 void*,
17976 void(*)(void*)
17978 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
17979 #endif
17980 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
17981 SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
17982 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
17983 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
17984 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
17985 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
17986 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
17987 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
17988 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
17989 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
17990 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
17991 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
17992 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
17993 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
17994 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
17995 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
17996 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
17997 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
17998 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
17999 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
18000 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
18001 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
18002 #ifndef SQLITE_OMIT_WAL
18003 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
18004 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
18005 #endif
18006 #ifndef SQLITE_OMIT_CTE
18007 SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
18008 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
18009 SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
18010 #else
18011 #define sqlite3WithPush(x,y,z)
18012 #define sqlite3WithDelete(x,y)
18013 #endif
18015 /* Declarations for functions in fkey.c. All of these are replaced by
18016 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
18017 ** key functionality is available. If OMIT_TRIGGER is defined but
18018 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
18019 ** this case foreign keys are parsed, but no other functionality is
18020 ** provided (enforcement of FK constraints requires the triggers sub-system).
18022 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
18023 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
18024 SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
18025 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
18026 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
18027 SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
18028 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
18029 #else
18030 #define sqlite3FkActions(a,b,c,d,e,f)
18031 #define sqlite3FkCheck(a,b,c,d,e,f)
18032 #define sqlite3FkDropTable(a,b,c)
18033 #define sqlite3FkOldmask(a,b) 0
18034 #define sqlite3FkRequired(a,b,c,d) 0
18035 #define sqlite3FkReferences(a) 0
18036 #endif
18037 #ifndef SQLITE_OMIT_FOREIGN_KEY
18038 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
18039 SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
18040 #else
18041 #define sqlite3FkDelete(a,b)
18042 #define sqlite3FkLocateIndex(a,b,c,d,e)
18043 #endif
18047 ** Available fault injectors. Should be numbered beginning with 0.
18049 #define SQLITE_FAULTINJECTOR_MALLOC 0
18050 #define SQLITE_FAULTINJECTOR_COUNT 1
18053 ** The interface to the code in fault.c used for identifying "benign"
18054 ** malloc failures. This is only present if SQLITE_UNTESTABLE
18055 ** is not defined.
18057 #ifndef SQLITE_UNTESTABLE
18058 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
18059 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
18060 #else
18061 #define sqlite3BeginBenignMalloc()
18062 #define sqlite3EndBenignMalloc()
18063 #endif
18066 ** Allowed return values from sqlite3FindInIndex()
18068 #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
18069 #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
18070 #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
18071 #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
18072 #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
18074 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
18076 #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
18077 #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
18078 #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
18079 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
18081 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
18082 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
18083 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
18084 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
18085 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
18086 #endif
18088 SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
18089 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
18091 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
18092 #if SQLITE_MAX_EXPR_DEPTH>0
18093 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
18094 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
18095 #else
18096 #define sqlite3SelectExprHeight(x) 0
18097 #define sqlite3ExprCheckHeight(x,y)
18098 #endif
18100 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
18101 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
18103 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
18104 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
18105 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
18106 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
18107 #else
18108 #define sqlite3ConnectionBlocked(x,y)
18109 #define sqlite3ConnectionUnlocked(x)
18110 #define sqlite3ConnectionClosed(x)
18111 #endif
18113 #ifdef SQLITE_DEBUG
18114 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
18115 #endif
18118 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
18119 ** sqlite3IoTrace is a pointer to a printf-like routine used to
18120 ** print I/O tracing messages.
18122 #ifdef SQLITE_ENABLE_IOTRACE
18123 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
18124 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
18125 SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
18126 #else
18127 # define IOTRACE(A)
18128 # define sqlite3VdbeIOTraceSql(X)
18129 #endif
18132 ** These routines are available for the mem2.c debugging memory allocator
18133 ** only. They are used to verify that different "types" of memory
18134 ** allocations are properly tracked by the system.
18136 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
18137 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
18138 ** a single bit set.
18140 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
18141 ** argument match the type set by the previous sqlite3MemdebugSetType().
18142 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
18144 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
18145 ** argument match the type set by the previous sqlite3MemdebugSetType().
18147 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
18148 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
18149 ** it might have been allocated by lookaside, except the allocation was
18150 ** too large or lookaside was already full. It is important to verify
18151 ** that allocations that might have been satisfied by lookaside are not
18152 ** passed back to non-lookaside free() routines. Asserts such as the
18153 ** example above are placed on the non-lookaside free() routines to verify
18154 ** this constraint.
18156 ** All of this is no-op for a production build. It only comes into
18157 ** play when the SQLITE_MEMDEBUG compile-time option is used.
18159 #ifdef SQLITE_MEMDEBUG
18160 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
18161 SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
18162 SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
18163 #else
18164 # define sqlite3MemdebugSetType(X,Y) /* no-op */
18165 # define sqlite3MemdebugHasType(X,Y) 1
18166 # define sqlite3MemdebugNoType(X,Y) 1
18167 #endif
18168 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
18169 #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
18170 #define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
18173 ** Threading interface
18175 #if SQLITE_MAX_WORKER_THREADS>0
18176 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
18177 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
18178 #endif
18180 #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
18181 SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
18182 #endif
18183 #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
18184 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
18185 #endif
18187 SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
18188 SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
18189 SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
18190 SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
18191 SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
18193 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
18194 SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
18195 #endif
18197 #endif /* SQLITEINT_H */
18199 /************** End of sqliteInt.h *******************************************/
18200 /************** Begin file global.c ******************************************/
18202 ** 2008 June 13
18204 ** The author disclaims copyright to this source code. In place of
18205 ** a legal notice, here is a blessing:
18207 ** May you do good and not evil.
18208 ** May you find forgiveness for yourself and forgive others.
18209 ** May you share freely, never taking more than you give.
18211 *************************************************************************
18213 ** This file contains definitions of global variables and constants.
18215 /* #include "sqliteInt.h" */
18217 /* An array to map all upper-case characters into their corresponding
18218 ** lower-case character.
18220 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
18221 ** handle case conversions for the UTF character set since the tables
18222 ** involved are nearly as big or bigger than SQLite itself.
18224 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
18225 #ifdef SQLITE_ASCII
18226 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18227 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
18228 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
18229 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
18230 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
18231 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
18232 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
18233 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
18234 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
18235 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
18236 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
18237 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
18238 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
18239 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
18240 252,253,254,255
18241 #endif
18242 #ifdef SQLITE_EBCDIC
18243 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
18244 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
18245 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
18246 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
18247 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
18248 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
18249 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
18250 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
18251 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
18252 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
18253 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
18254 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
18255 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
18256 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
18257 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
18258 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
18259 #endif
18263 ** The following 256 byte lookup table is used to support SQLites built-in
18264 ** equivalents to the following standard library functions:
18266 ** isspace() 0x01
18267 ** isalpha() 0x02
18268 ** isdigit() 0x04
18269 ** isalnum() 0x06
18270 ** isxdigit() 0x08
18271 ** toupper() 0x20
18272 ** SQLite identifier character 0x40
18273 ** Quote character 0x80
18275 ** Bit 0x20 is set if the mapped character requires translation to upper
18276 ** case. i.e. if the character is a lower-case ASCII character.
18277 ** If x is a lower-case ASCII character, then its upper-case equivalent
18278 ** is (x - 0x20). Therefore toupper() can be implemented as:
18280 ** (x & ~(map[x]&0x20))
18282 ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
18283 ** array. tolower() is used more often than toupper() by SQLite.
18285 ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
18286 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
18287 ** non-ASCII UTF character. Hence the test for whether or not a character is
18288 ** part of an identifier is 0x46.
18290 #ifdef SQLITE_ASCII
18291 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
18292 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
18293 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
18294 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
18295 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
18296 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
18297 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
18298 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
18299 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
18301 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
18302 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
18303 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
18304 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
18305 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
18306 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
18307 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
18308 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
18310 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
18311 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
18312 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
18313 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
18314 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
18315 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
18316 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
18317 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
18319 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
18320 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
18321 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
18322 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
18323 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
18324 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
18325 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
18326 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
18328 #endif
18330 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
18331 ** compatibility for legacy applications, the URI filename capability is
18332 ** disabled by default.
18334 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
18335 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
18337 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
18338 ** disabled. The default value may be changed by compiling with the
18339 ** SQLITE_USE_URI symbol defined.
18341 ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
18342 ** enabled.
18344 #ifndef SQLITE_USE_URI
18345 # ifdef SQLITE_HAS_CODEC
18346 # define SQLITE_USE_URI 1
18347 # else
18348 # define SQLITE_USE_URI 0
18349 # endif
18350 #endif
18352 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
18353 ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
18354 ** that compile-time option is omitted.
18356 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
18357 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
18358 #endif
18360 /* The minimum PMA size is set to this value multiplied by the database
18361 ** page size in bytes.
18363 #ifndef SQLITE_SORTER_PMASZ
18364 # define SQLITE_SORTER_PMASZ 250
18365 #endif
18367 /* Statement journals spill to disk when their size exceeds the following
18368 ** threshold (in bytes). 0 means that statement journals are created and
18369 ** written to disk immediately (the default behavior for SQLite versions
18370 ** before 3.12.0). -1 means always keep the entire statement journal in
18371 ** memory. (The statement journal is also always held entirely in memory
18372 ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
18373 ** setting.)
18375 #ifndef SQLITE_STMTJRNL_SPILL
18376 # define SQLITE_STMTJRNL_SPILL (64*1024)
18377 #endif
18380 ** The default lookaside-configuration, the format "SZ,N". SZ is the
18381 ** number of bytes in each lookaside slot (should be a multiple of 8)
18382 ** and N is the number of slots. The lookaside-configuration can be
18383 ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
18384 ** or at run-time for an individual database connection using
18385 ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
18387 #ifndef SQLITE_DEFAULT_LOOKASIDE
18388 # define SQLITE_DEFAULT_LOOKASIDE 1200,100
18389 #endif
18393 ** The following singleton contains the global configuration for
18394 ** the SQLite library.
18396 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
18397 SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
18398 1, /* bCoreMutex */
18399 SQLITE_THREADSAFE==1, /* bFullMutex */
18400 SQLITE_USE_URI, /* bOpenUri */
18401 SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
18402 0, /* bSmallMalloc */
18403 0x7ffffffe, /* mxStrlen */
18404 0, /* neverCorrupt */
18405 SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
18406 SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
18407 {0,0,0,0,0,0,0,0}, /* m */
18408 {0,0,0,0,0,0,0,0,0}, /* mutex */
18409 {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
18410 (void*)0, /* pHeap */
18411 0, /* nHeap */
18412 0, 0, /* mnHeap, mxHeap */
18413 SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
18414 SQLITE_MAX_MMAP_SIZE, /* mxMmap */
18415 (void*)0, /* pPage */
18416 0, /* szPage */
18417 SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
18418 0, /* mxParserStack */
18419 0, /* sharedCacheEnabled */
18420 SQLITE_SORTER_PMASZ, /* szPma */
18421 /* All the rest should always be initialized to zero */
18422 0, /* isInit */
18423 0, /* inProgress */
18424 0, /* isMutexInit */
18425 0, /* isMallocInit */
18426 0, /* isPCacheInit */
18427 0, /* nRefInitMutex */
18428 0, /* pInitMutex */
18429 0, /* xLog */
18430 0, /* pLogArg */
18431 #ifdef SQLITE_ENABLE_SQLLOG
18432 0, /* xSqllog */
18433 0, /* pSqllogArg */
18434 #endif
18435 #ifdef SQLITE_VDBE_COVERAGE
18436 0, /* xVdbeBranch */
18437 0, /* pVbeBranchArg */
18438 #endif
18439 #ifndef SQLITE_UNTESTABLE
18440 0, /* xTestCallback */
18441 #endif
18442 0, /* bLocaltimeFault */
18443 0x7ffffffe /* iOnceResetThreshold */
18447 ** Hash table for global functions - functions common to all
18448 ** database connections. After initialization, this table is
18449 ** read-only.
18451 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
18454 ** Constant tokens for values 0 and 1.
18456 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
18457 { "0", 1 },
18458 { "1", 1 }
18463 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
18464 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
18465 ** the database page that contains the pending byte. It never attempts
18466 ** to read or write that page. The pending byte page is set aside
18467 ** for use by the VFS layers as space for managing file locks.
18469 ** During testing, it is often desirable to move the pending byte to
18470 ** a different position in the file. This allows code that has to
18471 ** deal with the pending byte to run on files that are much smaller
18472 ** than 1 GiB. The sqlite3_test_control() interface can be used to
18473 ** move the pending byte.
18475 ** IMPORTANT: Changing the pending byte to any value other than
18476 ** 0x40000000 results in an incompatible database file format!
18477 ** Changing the pending byte during operation will result in undefined
18478 ** and incorrect behavior.
18480 #ifndef SQLITE_OMIT_WSD
18481 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
18482 #endif
18484 /* #include "opcodes.h" */
18486 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
18487 ** created by mkopcodeh.awk during compilation. Data is obtained
18488 ** from the comments following the "case OP_xxxx:" statements in
18489 ** the vdbe.c file.
18491 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
18494 ** Name of the default collating sequence
18496 SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
18498 /************** End of global.c **********************************************/
18499 /************** Begin file status.c ******************************************/
18501 ** 2008 June 18
18503 ** The author disclaims copyright to this source code. In place of
18504 ** a legal notice, here is a blessing:
18506 ** May you do good and not evil.
18507 ** May you find forgiveness for yourself and forgive others.
18508 ** May you share freely, never taking more than you give.
18510 *************************************************************************
18512 ** This module implements the sqlite3_status() interface and related
18513 ** functionality.
18515 /* #include "sqliteInt.h" */
18516 /************** Include vdbeInt.h in the middle of status.c ******************/
18517 /************** Begin file vdbeInt.h *****************************************/
18519 ** 2003 September 6
18521 ** The author disclaims copyright to this source code. In place of
18522 ** a legal notice, here is a blessing:
18524 ** May you do good and not evil.
18525 ** May you find forgiveness for yourself and forgive others.
18526 ** May you share freely, never taking more than you give.
18528 *************************************************************************
18529 ** This is the header file for information that is private to the
18530 ** VDBE. This information used to all be at the top of the single
18531 ** source code file "vdbe.c". When that file became too big (over
18532 ** 6000 lines long) it was split up into several smaller files and
18533 ** this header information was factored out.
18535 #ifndef SQLITE_VDBEINT_H
18536 #define SQLITE_VDBEINT_H
18539 ** The maximum number of times that a statement will try to reparse
18540 ** itself before giving up and returning SQLITE_SCHEMA.
18542 #ifndef SQLITE_MAX_SCHEMA_RETRY
18543 # define SQLITE_MAX_SCHEMA_RETRY 50
18544 #endif
18547 ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
18548 ** "explain" P4 display logic is enabled.
18550 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
18551 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
18552 # define VDBE_DISPLAY_P4 1
18553 #else
18554 # define VDBE_DISPLAY_P4 0
18555 #endif
18558 ** SQL is translated into a sequence of instructions to be
18559 ** executed by a virtual machine. Each instruction is an instance
18560 ** of the following structure.
18562 typedef struct VdbeOp Op;
18565 ** Boolean values
18567 typedef unsigned Bool;
18569 /* Opaque type used by code in vdbesort.c */
18570 typedef struct VdbeSorter VdbeSorter;
18572 /* Elements of the linked list at Vdbe.pAuxData */
18573 typedef struct AuxData AuxData;
18575 /* Types of VDBE cursors */
18576 #define CURTYPE_BTREE 0
18577 #define CURTYPE_SORTER 1
18578 #define CURTYPE_VTAB 2
18579 #define CURTYPE_PSEUDO 3
18582 ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
18584 ** * A b-tree cursor
18585 ** - In the main database or in an ephemeral database
18586 ** - On either an index or a table
18587 ** * A sorter
18588 ** * A virtual table
18589 ** * A one-row "pseudotable" stored in a single register
18591 typedef struct VdbeCursor VdbeCursor;
18592 struct VdbeCursor {
18593 u8 eCurType; /* One of the CURTYPE_* values above */
18594 i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
18595 u8 nullRow; /* True if pointing to a row with no data */
18596 u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
18597 u8 isTable; /* True for rowid tables. False for indexes */
18598 #ifdef SQLITE_DEBUG
18599 u8 seekOp; /* Most recent seek operation on this cursor */
18600 u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
18601 #endif
18602 Bool isEphemeral:1; /* True for an ephemeral table */
18603 Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
18604 Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
18605 Btree *pBtx; /* Separate file holding temporary table */
18606 i64 seqCount; /* Sequence counter */
18607 int *aAltMap; /* Mapping from table to index column numbers */
18609 /* Cached OP_Column parse information is only valid if cacheStatus matches
18610 ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
18611 ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
18612 ** the cache is out of date. */
18613 u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
18614 int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
18615 ** if there have been no prior seeks on the cursor. */
18616 /* seekResult does not distinguish between "no seeks have ever occurred
18617 ** on this cursor" and "the most recent seek was an exact match".
18618 ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
18620 /* When a new VdbeCursor is allocated, only the fields above are zeroed.
18621 ** The fields that follow are uninitialized, and must be individually
18622 ** initialized prior to first use. */
18623 VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
18624 union {
18625 BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
18626 sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
18627 VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
18628 } uc;
18629 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
18630 u32 iHdrOffset; /* Offset to next unparsed byte of the header */
18631 Pgno pgnoRoot; /* Root page of the open btree cursor */
18632 i16 nField; /* Number of fields in the header */
18633 u16 nHdrParsed; /* Number of header fields parsed so far */
18634 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
18635 u32 *aOffset; /* Pointer to aType[nField] */
18636 const u8 *aRow; /* Data for the current row, if all on one page */
18637 u32 payloadSize; /* Total number of bytes in the record */
18638 u32 szRow; /* Byte available in aRow */
18639 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
18640 u64 maskUsed; /* Mask of columns used by this cursor */
18641 #endif
18643 /* 2*nField extra array elements allocated for aType[], beyond the one
18644 ** static element declared in the structure. nField total array slots for
18645 ** aType[] and nField+1 array slots for aOffset[] */
18646 u32 aType[1]; /* Type values record decode. MUST BE LAST */
18651 ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
18653 #define CACHE_STALE 0
18656 ** When a sub-program is executed (OP_Program), a structure of this type
18657 ** is allocated to store the current value of the program counter, as
18658 ** well as the current memory cell array and various other frame specific
18659 ** values stored in the Vdbe struct. When the sub-program is finished,
18660 ** these values are copied back to the Vdbe from the VdbeFrame structure,
18661 ** restoring the state of the VM to as it was before the sub-program
18662 ** began executing.
18664 ** The memory for a VdbeFrame object is allocated and managed by a memory
18665 ** cell in the parent (calling) frame. When the memory cell is deleted or
18666 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
18667 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
18668 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
18669 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
18670 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
18671 ** child frame are released.
18673 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
18674 ** set to NULL if the currently executing frame is the main program.
18676 typedef struct VdbeFrame VdbeFrame;
18677 struct VdbeFrame {
18678 Vdbe *v; /* VM this frame belongs to */
18679 VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
18680 Op *aOp; /* Program instructions for parent frame */
18681 i64 *anExec; /* Event counters from parent frame */
18682 Mem *aMem; /* Array of memory cells for parent frame */
18683 VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
18684 u8 *aOnce; /* Bitmask used by OP_Once */
18685 void *token; /* Copy of SubProgram.token */
18686 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
18687 AuxData *pAuxData; /* Linked list of auxdata allocations */
18688 int nCursor; /* Number of entries in apCsr */
18689 int pc; /* Program Counter in parent (calling) frame */
18690 int nOp; /* Size of aOp array */
18691 int nMem; /* Number of entries in aMem */
18692 int nChildMem; /* Number of memory cells for child frame */
18693 int nChildCsr; /* Number of cursors for child frame */
18694 int nChange; /* Statement changes (Vdbe.nChange) */
18695 int nDbChange; /* Value of db->nChange */
18698 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
18701 ** Internally, the vdbe manipulates nearly all SQL values as Mem
18702 ** structures. Each Mem struct may cache multiple representations (string,
18703 ** integer etc.) of the same value.
18705 struct sqlite3_value {
18706 union MemValue {
18707 double r; /* Real value used when MEM_Real is set in flags */
18708 i64 i; /* Integer value used when MEM_Int is set in flags */
18709 int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
18710 const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
18711 FuncDef *pDef; /* Used only when flags==MEM_Agg */
18712 RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
18713 VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
18714 } u;
18715 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
18716 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
18717 u8 eSubtype; /* Subtype for this value */
18718 int n; /* Number of characters in string value, excluding '\0' */
18719 char *z; /* String or BLOB value */
18720 /* ShallowCopy only needs to copy the information above */
18721 char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
18722 int szMalloc; /* Size of the zMalloc allocation */
18723 u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
18724 sqlite3 *db; /* The associated database connection */
18725 void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
18726 #ifdef SQLITE_DEBUG
18727 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
18728 void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
18729 #endif
18733 ** Size of struct Mem not including the Mem.zMalloc member or anything that
18734 ** follows.
18736 #define MEMCELLSIZE offsetof(Mem,zMalloc)
18738 /* One or more of the following flags are set to indicate the validOK
18739 ** representations of the value stored in the Mem struct.
18741 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
18742 ** For a pointer type created using sqlite3_bind_pointer() or
18743 ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
18745 ** If the MEM_Str flag is set then Mem.z points at a string representation.
18746 ** Usually this is encoded in the same unicode encoding as the main
18747 ** database (see below for exceptions). If the MEM_Term flag is also
18748 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
18749 ** flags may coexist with the MEM_Str flag.
18751 #define MEM_Null 0x0001 /* Value is NULL (or a pointer) */
18752 #define MEM_Str 0x0002 /* Value is a string */
18753 #define MEM_Int 0x0004 /* Value is an integer */
18754 #define MEM_Real 0x0008 /* Value is a real number */
18755 #define MEM_Blob 0x0010 /* Value is a BLOB */
18756 #define MEM_AffMask 0x001f /* Mask of affinity bits */
18757 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
18758 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
18759 #define MEM_Undefined 0x0080 /* Value is undefined */
18760 #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
18761 #define MEM_TypeMask 0xc1ff /* Mask of type bits */
18764 /* Whenever Mem contains a valid string or blob representation, one of
18765 ** the following flags must be set to determine the memory management
18766 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
18767 ** string is \000 or \u0000 terminated
18769 #define MEM_Term 0x0200 /* String in Mem.z is zero terminated */
18770 #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
18771 #define MEM_Static 0x0800 /* Mem.z points to a static string */
18772 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
18773 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
18774 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
18775 #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
18776 #ifdef SQLITE_OMIT_INCRBLOB
18777 #undef MEM_Zero
18778 #define MEM_Zero 0x0000
18779 #endif
18781 /* Return TRUE if Mem X contains dynamically allocated content - anything
18782 ** that needs to be deallocated to avoid a leak.
18784 #define VdbeMemDynamic(X) \
18785 (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
18788 ** Clear any existing type flags from a Mem and replace them with f
18790 #define MemSetTypeFlag(p, f) \
18791 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
18794 ** Return true if a memory cell is not marked as invalid. This macro
18795 ** is for use inside assert() statements only.
18797 #ifdef SQLITE_DEBUG
18798 #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
18799 #endif
18802 ** Each auxiliary data pointer stored by a user defined function
18803 ** implementation calling sqlite3_set_auxdata() is stored in an instance
18804 ** of this structure. All such structures associated with a single VM
18805 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
18806 ** when the VM is halted (if not before).
18808 struct AuxData {
18809 int iAuxOp; /* Instruction number of OP_Function opcode */
18810 int iAuxArg; /* Index of function argument. */
18811 void *pAux; /* Aux data pointer */
18812 void (*xDeleteAux)(void*); /* Destructor for the aux data */
18813 AuxData *pNextAux; /* Next element in list */
18817 ** The "context" argument for an installable function. A pointer to an
18818 ** instance of this structure is the first argument to the routines used
18819 ** implement the SQL functions.
18821 ** There is a typedef for this structure in sqlite.h. So all routines,
18822 ** even the public interface to SQLite, can use a pointer to this structure.
18823 ** But this file is the only place where the internal details of this
18824 ** structure are known.
18826 ** This structure is defined inside of vdbeInt.h because it uses substructures
18827 ** (Mem) which are only defined there.
18829 struct sqlite3_context {
18830 Mem *pOut; /* The return value is stored here */
18831 FuncDef *pFunc; /* Pointer to function information */
18832 Mem *pMem; /* Memory cell used to store aggregate context */
18833 Vdbe *pVdbe; /* The VM that owns this context */
18834 int iOp; /* Instruction number of OP_Function */
18835 int isError; /* Error code returned by the function. */
18836 u8 skipFlag; /* Skip accumulator loading if true */
18837 u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
18838 u8 argc; /* Number of arguments */
18839 sqlite3_value *argv[1]; /* Argument set */
18842 /* A bitfield type for use inside of structures. Always follow with :N where
18843 ** N is the number of bits.
18845 typedef unsigned bft; /* Bit Field Type */
18847 typedef struct ScanStatus ScanStatus;
18848 struct ScanStatus {
18849 int addrExplain; /* OP_Explain for loop */
18850 int addrLoop; /* Address of "loops" counter */
18851 int addrVisit; /* Address of "rows visited" counter */
18852 int iSelectID; /* The "Select-ID" for this loop */
18853 LogEst nEst; /* Estimated output rows per loop */
18854 char *zName; /* Name of table or index */
18858 ** An instance of the virtual machine. This structure contains the complete
18859 ** state of the virtual machine.
18861 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
18862 ** is really a pointer to an instance of this structure.
18864 struct Vdbe {
18865 sqlite3 *db; /* The database connection that owns this statement */
18866 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
18867 Parse *pParse; /* Parsing context used to create this Vdbe */
18868 ynVar nVar; /* Number of entries in aVar[] */
18869 u32 magic; /* Magic number for sanity checking */
18870 int nMem; /* Number of memory locations currently allocated */
18871 int nCursor; /* Number of slots in apCsr[] */
18872 u32 cacheCtr; /* VdbeCursor row cache generation counter */
18873 int pc; /* The program counter */
18874 int rc; /* Value to return */
18875 int nChange; /* Number of db changes made since last reset */
18876 int iStatement; /* Statement number (or 0 if has not opened stmt) */
18877 i64 iCurrentTime; /* Value of julianday('now') for this statement */
18878 i64 nFkConstraint; /* Number of imm. FK constraints this VM */
18879 i64 nStmtDefCons; /* Number of def. constraints when stmt started */
18880 i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
18882 /* When allocating a new Vdbe object, all of the fields below should be
18883 ** initialized to zero or NULL */
18885 Op *aOp; /* Space to hold the virtual machine's program */
18886 Mem *aMem; /* The memory locations */
18887 Mem **apArg; /* Arguments to currently executing user function */
18888 Mem *aColName; /* Column names to return */
18889 Mem *pResultSet; /* Pointer to an array of results */
18890 char *zErrMsg; /* Error message written here */
18891 VdbeCursor **apCsr; /* One element of this array for each open cursor */
18892 Mem *aVar; /* Values for the OP_Variable opcode. */
18893 VList *pVList; /* Name of variables */
18894 #ifndef SQLITE_OMIT_TRACE
18895 i64 startTime; /* Time when query started - used for profiling */
18896 #endif
18897 int nOp; /* Number of instructions in the program */
18898 #ifdef SQLITE_DEBUG
18899 int rcApp; /* errcode set by sqlite3_result_error_code() */
18900 #endif
18901 u16 nResColumn; /* Number of columns in one row of the result set */
18902 u8 errorAction; /* Recovery action to do in case of an error */
18903 u8 minWriteFileFormat; /* Minimum file format for writable database files */
18904 u8 prepFlags; /* SQLITE_PREPARE_* flags */
18905 bft expired:1; /* True if the VM needs to be recompiled */
18906 bft doingRerun:1; /* True if rerunning after an auto-reprepare */
18907 bft explain:2; /* True if EXPLAIN present on SQL command */
18908 bft changeCntOn:1; /* True to update the change-counter */
18909 bft runOnlyOnce:1; /* Automatically expire on reset */
18910 bft usesStmtJournal:1; /* True if uses a statement journal */
18911 bft readOnly:1; /* True for statements that do not write */
18912 bft bIsReader:1; /* True for statements that read */
18913 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
18914 yDbMask lockMask; /* Subset of btreeMask that requires a lock */
18915 u32 aCounter[7]; /* Counters used by sqlite3_stmt_status() */
18916 char *zSql; /* Text of the SQL statement that generated this */
18917 void *pFree; /* Free this when deleting the vdbe */
18918 VdbeFrame *pFrame; /* Parent frame */
18919 VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
18920 int nFrame; /* Number of frames in pFrame list */
18921 u32 expmask; /* Binding to these vars invalidates VM */
18922 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
18923 AuxData *pAuxData; /* Linked list of auxdata allocations */
18924 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
18925 i64 *anExec; /* Number of times each op has been executed */
18926 int nScan; /* Entries in aScan[] */
18927 ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
18928 #endif
18932 ** The following are allowed values for Vdbe.magic
18934 #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
18935 #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
18936 #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
18937 #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
18938 #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
18941 ** Structure used to store the context required by the
18942 ** sqlite3_preupdate_*() API functions.
18944 struct PreUpdate {
18945 Vdbe *v;
18946 VdbeCursor *pCsr; /* Cursor to read old values from */
18947 int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
18948 u8 *aRecord; /* old.* database record */
18949 KeyInfo keyinfo;
18950 UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
18951 UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
18952 int iNewReg; /* Register for new.* values */
18953 i64 iKey1; /* First key value passed to hook */
18954 i64 iKey2; /* Second key value passed to hook */
18955 Mem *aNew; /* Array of new.* values */
18956 Table *pTab; /* Schema object being upated */
18957 Index *pPk; /* PK index if pTab is WITHOUT ROWID */
18961 ** Function prototypes
18963 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
18964 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18965 void sqliteVdbePopStack(Vdbe*,int);
18966 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
18967 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
18968 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18969 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18970 #endif
18971 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
18972 SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
18973 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
18974 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
18975 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18976 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
18978 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18979 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
18980 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
18981 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18982 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18983 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18984 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18985 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18986 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18987 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18988 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18989 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18990 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18991 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18992 #ifdef SQLITE_OMIT_FLOATING_POINT
18993 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18994 #else
18995 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
18996 #endif
18997 SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
18998 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
18999 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
19000 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
19001 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
19002 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
19003 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
19004 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
19005 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
19006 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
19007 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
19008 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
19009 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
19010 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
19011 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
19012 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
19013 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
19014 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
19015 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
19016 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
19017 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
19018 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
19019 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
19020 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
19021 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
19022 #endif
19023 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
19025 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
19026 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
19027 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
19028 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
19029 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
19030 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
19031 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
19032 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
19034 #if !defined(SQLITE_OMIT_SHARED_CACHE)
19035 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
19036 #else
19037 # define sqlite3VdbeEnter(X)
19038 #endif
19040 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
19041 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
19042 #else
19043 # define sqlite3VdbeLeave(X)
19044 #endif
19046 #ifdef SQLITE_DEBUG
19047 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
19048 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
19049 #endif
19051 #ifndef SQLITE_OMIT_FOREIGN_KEY
19052 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
19053 #else
19054 # define sqlite3VdbeCheckFk(p,i) 0
19055 #endif
19057 #ifdef SQLITE_DEBUG
19058 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
19059 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
19060 #endif
19061 #ifndef SQLITE_OMIT_UTF16
19062 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
19063 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
19064 #endif
19066 #ifndef SQLITE_OMIT_INCRBLOB
19067 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
19068 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
19069 #else
19070 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
19071 #define ExpandBlob(P) SQLITE_OK
19072 #endif
19074 #endif /* !defined(SQLITE_VDBEINT_H) */
19076 /************** End of vdbeInt.h *********************************************/
19077 /************** Continuing where we left off in status.c *********************/
19080 ** Variables in which to record status information.
19082 #if SQLITE_PTRSIZE>4
19083 typedef sqlite3_int64 sqlite3StatValueType;
19084 #else
19085 typedef u32 sqlite3StatValueType;
19086 #endif
19087 typedef struct sqlite3StatType sqlite3StatType;
19088 static SQLITE_WSD struct sqlite3StatType {
19089 sqlite3StatValueType nowValue[10]; /* Current value */
19090 sqlite3StatValueType mxValue[10]; /* Maximum value */
19091 } sqlite3Stat = { {0,}, {0,} };
19094 ** Elements of sqlite3Stat[] are protected by either the memory allocator
19095 ** mutex, or by the pcache1 mutex. The following array determines which.
19097 static const char statMutex[] = {
19098 0, /* SQLITE_STATUS_MEMORY_USED */
19099 1, /* SQLITE_STATUS_PAGECACHE_USED */
19100 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
19101 0, /* SQLITE_STATUS_SCRATCH_USED */
19102 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
19103 0, /* SQLITE_STATUS_MALLOC_SIZE */
19104 0, /* SQLITE_STATUS_PARSER_STACK */
19105 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
19106 0, /* SQLITE_STATUS_SCRATCH_SIZE */
19107 0, /* SQLITE_STATUS_MALLOC_COUNT */
19111 /* The "wsdStat" macro will resolve to the status information
19112 ** state vector. If writable static data is unsupported on the target,
19113 ** we have to locate the state vector at run-time. In the more common
19114 ** case where writable static data is supported, wsdStat can refer directly
19115 ** to the "sqlite3Stat" state vector declared above.
19117 #ifdef SQLITE_OMIT_WSD
19118 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
19119 # define wsdStat x[0]
19120 #else
19121 # define wsdStatInit
19122 # define wsdStat sqlite3Stat
19123 #endif
19126 ** Return the current value of a status parameter. The caller must
19127 ** be holding the appropriate mutex.
19129 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
19130 wsdStatInit;
19131 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
19132 assert( op>=0 && op<ArraySize(statMutex) );
19133 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
19134 : sqlite3MallocMutex()) );
19135 return wsdStat.nowValue[op];
19139 ** Add N to the value of a status record. The caller must hold the
19140 ** appropriate mutex. (Locking is checked by assert()).
19142 ** The StatusUp() routine can accept positive or negative values for N.
19143 ** The value of N is added to the current status value and the high-water
19144 ** mark is adjusted if necessary.
19146 ** The StatusDown() routine lowers the current value by N. The highwater
19147 ** mark is unchanged. N must be non-negative for StatusDown().
19149 SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
19150 wsdStatInit;
19151 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
19152 assert( op>=0 && op<ArraySize(statMutex) );
19153 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
19154 : sqlite3MallocMutex()) );
19155 wsdStat.nowValue[op] += N;
19156 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
19157 wsdStat.mxValue[op] = wsdStat.nowValue[op];
19160 SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
19161 wsdStatInit;
19162 assert( N>=0 );
19163 assert( op>=0 && op<ArraySize(statMutex) );
19164 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
19165 : sqlite3MallocMutex()) );
19166 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
19167 wsdStat.nowValue[op] -= N;
19171 ** Adjust the highwater mark if necessary.
19172 ** The caller must hold the appropriate mutex.
19174 SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
19175 sqlite3StatValueType newValue;
19176 wsdStatInit;
19177 assert( X>=0 );
19178 newValue = (sqlite3StatValueType)X;
19179 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
19180 assert( op>=0 && op<ArraySize(statMutex) );
19181 assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
19182 : sqlite3MallocMutex()) );
19183 assert( op==SQLITE_STATUS_MALLOC_SIZE
19184 || op==SQLITE_STATUS_PAGECACHE_SIZE
19185 || op==SQLITE_STATUS_PARSER_STACK );
19186 if( newValue>wsdStat.mxValue[op] ){
19187 wsdStat.mxValue[op] = newValue;
19192 ** Query status information.
19194 SQLITE_API int sqlite3_status64(
19195 int op,
19196 sqlite3_int64 *pCurrent,
19197 sqlite3_int64 *pHighwater,
19198 int resetFlag
19200 sqlite3_mutex *pMutex;
19201 wsdStatInit;
19202 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
19203 return SQLITE_MISUSE_BKPT;
19205 #ifdef SQLITE_ENABLE_API_ARMOR
19206 if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
19207 #endif
19208 pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
19209 sqlite3_mutex_enter(pMutex);
19210 *pCurrent = wsdStat.nowValue[op];
19211 *pHighwater = wsdStat.mxValue[op];
19212 if( resetFlag ){
19213 wsdStat.mxValue[op] = wsdStat.nowValue[op];
19215 sqlite3_mutex_leave(pMutex);
19216 (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
19217 return SQLITE_OK;
19219 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
19220 sqlite3_int64 iCur = 0, iHwtr = 0;
19221 int rc;
19222 #ifdef SQLITE_ENABLE_API_ARMOR
19223 if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
19224 #endif
19225 rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
19226 if( rc==0 ){
19227 *pCurrent = (int)iCur;
19228 *pHighwater = (int)iHwtr;
19230 return rc;
19234 ** Return the number of LookasideSlot elements on the linked list
19236 static u32 countLookasideSlots(LookasideSlot *p){
19237 u32 cnt = 0;
19238 while( p ){
19239 p = p->pNext;
19240 cnt++;
19242 return cnt;
19246 ** Count the number of slots of lookaside memory that are outstanding
19248 SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
19249 u32 nInit = countLookasideSlots(db->lookaside.pInit);
19250 u32 nFree = countLookasideSlots(db->lookaside.pFree);
19251 if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
19252 return db->lookaside.nSlot - (nInit+nFree);
19256 ** Query status information for a single database connection
19258 SQLITE_API int sqlite3_db_status(
19259 sqlite3 *db, /* The database connection whose status is desired */
19260 int op, /* Status verb */
19261 int *pCurrent, /* Write current value here */
19262 int *pHighwater, /* Write high-water mark here */
19263 int resetFlag /* Reset high-water mark if true */
19265 int rc = SQLITE_OK; /* Return code */
19266 #ifdef SQLITE_ENABLE_API_ARMOR
19267 if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
19268 return SQLITE_MISUSE_BKPT;
19270 #endif
19271 sqlite3_mutex_enter(db->mutex);
19272 switch( op ){
19273 case SQLITE_DBSTATUS_LOOKASIDE_USED: {
19274 *pCurrent = sqlite3LookasideUsed(db, pHighwater);
19275 if( resetFlag ){
19276 LookasideSlot *p = db->lookaside.pFree;
19277 if( p ){
19278 while( p->pNext ) p = p->pNext;
19279 p->pNext = db->lookaside.pInit;
19280 db->lookaside.pInit = db->lookaside.pFree;
19281 db->lookaside.pFree = 0;
19284 break;
19287 case SQLITE_DBSTATUS_LOOKASIDE_HIT:
19288 case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
19289 case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
19290 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
19291 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
19292 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
19293 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
19294 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
19295 *pCurrent = 0;
19296 *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
19297 if( resetFlag ){
19298 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
19300 break;
19304 ** Return an approximation for the amount of memory currently used
19305 ** by all pagers associated with the given database connection. The
19306 ** highwater mark is meaningless and is returned as zero.
19308 case SQLITE_DBSTATUS_CACHE_USED_SHARED:
19309 case SQLITE_DBSTATUS_CACHE_USED: {
19310 int totalUsed = 0;
19311 int i;
19312 sqlite3BtreeEnterAll(db);
19313 for(i=0; i<db->nDb; i++){
19314 Btree *pBt = db->aDb[i].pBt;
19315 if( pBt ){
19316 Pager *pPager = sqlite3BtreePager(pBt);
19317 int nByte = sqlite3PagerMemUsed(pPager);
19318 if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
19319 nByte = nByte / sqlite3BtreeConnectionCount(pBt);
19321 totalUsed += nByte;
19324 sqlite3BtreeLeaveAll(db);
19325 *pCurrent = totalUsed;
19326 *pHighwater = 0;
19327 break;
19331 ** *pCurrent gets an accurate estimate of the amount of memory used
19332 ** to store the schema for all databases (main, temp, and any ATTACHed
19333 ** databases. *pHighwater is set to zero.
19335 case SQLITE_DBSTATUS_SCHEMA_USED: {
19336 int i; /* Used to iterate through schemas */
19337 int nByte = 0; /* Used to accumulate return value */
19339 sqlite3BtreeEnterAll(db);
19340 db->pnBytesFreed = &nByte;
19341 for(i=0; i<db->nDb; i++){
19342 Schema *pSchema = db->aDb[i].pSchema;
19343 if( ALWAYS(pSchema!=0) ){
19344 HashElem *p;
19346 nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
19347 pSchema->tblHash.count
19348 + pSchema->trigHash.count
19349 + pSchema->idxHash.count
19350 + pSchema->fkeyHash.count
19352 nByte += sqlite3_msize(pSchema->tblHash.ht);
19353 nByte += sqlite3_msize(pSchema->trigHash.ht);
19354 nByte += sqlite3_msize(pSchema->idxHash.ht);
19355 nByte += sqlite3_msize(pSchema->fkeyHash.ht);
19357 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
19358 sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
19360 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
19361 sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
19365 db->pnBytesFreed = 0;
19366 sqlite3BtreeLeaveAll(db);
19368 *pHighwater = 0;
19369 *pCurrent = nByte;
19370 break;
19374 ** *pCurrent gets an accurate estimate of the amount of memory used
19375 ** to store all prepared statements.
19376 ** *pHighwater is set to zero.
19378 case SQLITE_DBSTATUS_STMT_USED: {
19379 struct Vdbe *pVdbe; /* Used to iterate through VMs */
19380 int nByte = 0; /* Used to accumulate return value */
19382 db->pnBytesFreed = &nByte;
19383 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
19384 sqlite3VdbeClearObject(db, pVdbe);
19385 sqlite3DbFree(db, pVdbe);
19387 db->pnBytesFreed = 0;
19389 *pHighwater = 0; /* IMP: R-64479-57858 */
19390 *pCurrent = nByte;
19392 break;
19396 ** Set *pCurrent to the total cache hits or misses encountered by all
19397 ** pagers the database handle is connected to. *pHighwater is always set
19398 ** to zero.
19400 case SQLITE_DBSTATUS_CACHE_HIT:
19401 case SQLITE_DBSTATUS_CACHE_MISS:
19402 case SQLITE_DBSTATUS_CACHE_WRITE:{
19403 int i;
19404 int nRet = 0;
19405 assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
19406 assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
19408 for(i=0; i<db->nDb; i++){
19409 if( db->aDb[i].pBt ){
19410 Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
19411 sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
19414 *pHighwater = 0; /* IMP: R-42420-56072 */
19415 /* IMP: R-54100-20147 */
19416 /* IMP: R-29431-39229 */
19417 *pCurrent = nRet;
19418 break;
19421 /* Set *pCurrent to non-zero if there are unresolved deferred foreign
19422 ** key constraints. Set *pCurrent to zero if all foreign key constraints
19423 ** have been satisfied. The *pHighwater is always set to zero.
19425 case SQLITE_DBSTATUS_DEFERRED_FKS: {
19426 *pHighwater = 0; /* IMP: R-11967-56545 */
19427 *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
19428 break;
19431 default: {
19432 rc = SQLITE_ERROR;
19435 sqlite3_mutex_leave(db->mutex);
19436 return rc;
19439 /************** End of status.c **********************************************/
19440 /************** Begin file date.c ********************************************/
19442 ** 2003 October 31
19444 ** The author disclaims copyright to this source code. In place of
19445 ** a legal notice, here is a blessing:
19447 ** May you do good and not evil.
19448 ** May you find forgiveness for yourself and forgive others.
19449 ** May you share freely, never taking more than you give.
19451 *************************************************************************
19452 ** This file contains the C functions that implement date and time
19453 ** functions for SQLite.
19455 ** There is only one exported symbol in this file - the function
19456 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
19457 ** All other code has file scope.
19459 ** SQLite processes all times and dates as julian day numbers. The
19460 ** dates and times are stored as the number of days since noon
19461 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
19462 ** calendar system.
19464 ** 1970-01-01 00:00:00 is JD 2440587.5
19465 ** 2000-01-01 00:00:00 is JD 2451544.5
19467 ** This implementation requires years to be expressed as a 4-digit number
19468 ** which means that only dates between 0000-01-01 and 9999-12-31 can
19469 ** be represented, even though julian day numbers allow a much wider
19470 ** range of dates.
19472 ** The Gregorian calendar system is used for all dates and times,
19473 ** even those that predate the Gregorian calendar. Historians usually
19474 ** use the julian calendar for dates prior to 1582-10-15 and for some
19475 ** dates afterwards, depending on locale. Beware of this difference.
19477 ** The conversion algorithms are implemented based on descriptions
19478 ** in the following text:
19480 ** Jean Meeus
19481 ** Astronomical Algorithms, 2nd Edition, 1998
19482 ** ISBM 0-943396-61-1
19483 ** Willmann-Bell, Inc
19484 ** Richmond, Virginia (USA)
19486 /* #include "sqliteInt.h" */
19487 /* #include <stdlib.h> */
19488 /* #include <assert.h> */
19489 #include <time.h>
19491 #ifndef SQLITE_OMIT_DATETIME_FUNCS
19494 ** The MSVC CRT on Windows CE may not have a localtime() function.
19495 ** So declare a substitute. The substitute function itself is
19496 ** defined in "os_win.c".
19498 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
19499 (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
19500 struct tm *__cdecl localtime(const time_t *);
19501 #endif
19504 ** A structure for holding a single date and time.
19506 typedef struct DateTime DateTime;
19507 struct DateTime {
19508 sqlite3_int64 iJD; /* The julian day number times 86400000 */
19509 int Y, M, D; /* Year, month, and day */
19510 int h, m; /* Hour and minutes */
19511 int tz; /* Timezone offset in minutes */
19512 double s; /* Seconds */
19513 char validJD; /* True (1) if iJD is valid */
19514 char rawS; /* Raw numeric value stored in s */
19515 char validYMD; /* True (1) if Y,M,D are valid */
19516 char validHMS; /* True (1) if h,m,s are valid */
19517 char validTZ; /* True (1) if tz is valid */
19518 char tzSet; /* Timezone was set explicitly */
19519 char isError; /* An overflow has occurred */
19524 ** Convert zDate into one or more integers according to the conversion
19525 ** specifier zFormat.
19527 ** zFormat[] contains 4 characters for each integer converted, except for
19528 ** the last integer which is specified by three characters. The meaning
19529 ** of a four-character format specifiers ABCD is:
19531 ** A: number of digits to convert. Always "2" or "4".
19532 ** B: minimum value. Always "0" or "1".
19533 ** C: maximum value, decoded as:
19534 ** a: 12
19535 ** b: 14
19536 ** c: 24
19537 ** d: 31
19538 ** e: 59
19539 ** f: 9999
19540 ** D: the separator character, or \000 to indicate this is the
19541 ** last number to convert.
19543 ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
19544 ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
19545 ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
19546 ** the 2-digit day which is the last integer in the set.
19548 ** The function returns the number of successful conversions.
19550 static int getDigits(const char *zDate, const char *zFormat, ...){
19551 /* The aMx[] array translates the 3rd character of each format
19552 ** spec into a max size: a b c d e f */
19553 static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
19554 va_list ap;
19555 int cnt = 0;
19556 char nextC;
19557 va_start(ap, zFormat);
19559 char N = zFormat[0] - '0';
19560 char min = zFormat[1] - '0';
19561 int val = 0;
19562 u16 max;
19564 assert( zFormat[2]>='a' && zFormat[2]<='f' );
19565 max = aMx[zFormat[2] - 'a'];
19566 nextC = zFormat[3];
19567 val = 0;
19568 while( N-- ){
19569 if( !sqlite3Isdigit(*zDate) ){
19570 goto end_getDigits;
19572 val = val*10 + *zDate - '0';
19573 zDate++;
19575 if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
19576 goto end_getDigits;
19578 *va_arg(ap,int*) = val;
19579 zDate++;
19580 cnt++;
19581 zFormat += 4;
19582 }while( nextC );
19583 end_getDigits:
19584 va_end(ap);
19585 return cnt;
19589 ** Parse a timezone extension on the end of a date-time.
19590 ** The extension is of the form:
19592 ** (+/-)HH:MM
19594 ** Or the "zulu" notation:
19596 ** Z
19598 ** If the parse is successful, write the number of minutes
19599 ** of change in p->tz and return 0. If a parser error occurs,
19600 ** return non-zero.
19602 ** A missing specifier is not considered an error.
19604 static int parseTimezone(const char *zDate, DateTime *p){
19605 int sgn = 0;
19606 int nHr, nMn;
19607 int c;
19608 while( sqlite3Isspace(*zDate) ){ zDate++; }
19609 p->tz = 0;
19610 c = *zDate;
19611 if( c=='-' ){
19612 sgn = -1;
19613 }else if( c=='+' ){
19614 sgn = +1;
19615 }else if( c=='Z' || c=='z' ){
19616 zDate++;
19617 goto zulu_time;
19618 }else{
19619 return c!=0;
19621 zDate++;
19622 if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
19623 return 1;
19625 zDate += 5;
19626 p->tz = sgn*(nMn + nHr*60);
19627 zulu_time:
19628 while( sqlite3Isspace(*zDate) ){ zDate++; }
19629 p->tzSet = 1;
19630 return *zDate!=0;
19634 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
19635 ** The HH, MM, and SS must each be exactly 2 digits. The
19636 ** fractional seconds FFFF can be one or more digits.
19638 ** Return 1 if there is a parsing error and 0 on success.
19640 static int parseHhMmSs(const char *zDate, DateTime *p){
19641 int h, m, s;
19642 double ms = 0.0;
19643 if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
19644 return 1;
19646 zDate += 5;
19647 if( *zDate==':' ){
19648 zDate++;
19649 if( getDigits(zDate, "20e", &s)!=1 ){
19650 return 1;
19652 zDate += 2;
19653 if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
19654 double rScale = 1.0;
19655 zDate++;
19656 while( sqlite3Isdigit(*zDate) ){
19657 ms = ms*10.0 + *zDate - '0';
19658 rScale *= 10.0;
19659 zDate++;
19661 ms /= rScale;
19663 }else{
19664 s = 0;
19666 p->validJD = 0;
19667 p->rawS = 0;
19668 p->validHMS = 1;
19669 p->h = h;
19670 p->m = m;
19671 p->s = s + ms;
19672 if( parseTimezone(zDate, p) ) return 1;
19673 p->validTZ = (p->tz!=0)?1:0;
19674 return 0;
19678 ** Put the DateTime object into its error state.
19680 static void datetimeError(DateTime *p){
19681 memset(p, 0, sizeof(*p));
19682 p->isError = 1;
19686 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
19687 ** that the YYYY-MM-DD is according to the Gregorian calendar.
19689 ** Reference: Meeus page 61
19691 static void computeJD(DateTime *p){
19692 int Y, M, D, A, B, X1, X2;
19694 if( p->validJD ) return;
19695 if( p->validYMD ){
19696 Y = p->Y;
19697 M = p->M;
19698 D = p->D;
19699 }else{
19700 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
19701 M = 1;
19702 D = 1;
19704 if( Y<-4713 || Y>9999 || p->rawS ){
19705 datetimeError(p);
19706 return;
19708 if( M<=2 ){
19709 Y--;
19710 M += 12;
19712 A = Y/100;
19713 B = 2 - A + (A/4);
19714 X1 = 36525*(Y+4716)/100;
19715 X2 = 306001*(M+1)/10000;
19716 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
19717 p->validJD = 1;
19718 if( p->validHMS ){
19719 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
19720 if( p->validTZ ){
19721 p->iJD -= p->tz*60000;
19722 p->validYMD = 0;
19723 p->validHMS = 0;
19724 p->validTZ = 0;
19730 ** Parse dates of the form
19732 ** YYYY-MM-DD HH:MM:SS.FFF
19733 ** YYYY-MM-DD HH:MM:SS
19734 ** YYYY-MM-DD HH:MM
19735 ** YYYY-MM-DD
19737 ** Write the result into the DateTime structure and return 0
19738 ** on success and 1 if the input string is not a well-formed
19739 ** date.
19741 static int parseYyyyMmDd(const char *zDate, DateTime *p){
19742 int Y, M, D, neg;
19744 if( zDate[0]=='-' ){
19745 zDate++;
19746 neg = 1;
19747 }else{
19748 neg = 0;
19750 if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
19751 return 1;
19753 zDate += 10;
19754 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
19755 if( parseHhMmSs(zDate, p)==0 ){
19756 /* We got the time */
19757 }else if( *zDate==0 ){
19758 p->validHMS = 0;
19759 }else{
19760 return 1;
19762 p->validJD = 0;
19763 p->validYMD = 1;
19764 p->Y = neg ? -Y : Y;
19765 p->M = M;
19766 p->D = D;
19767 if( p->validTZ ){
19768 computeJD(p);
19770 return 0;
19774 ** Set the time to the current time reported by the VFS.
19776 ** Return the number of errors.
19778 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
19779 p->iJD = sqlite3StmtCurrentTime(context);
19780 if( p->iJD>0 ){
19781 p->validJD = 1;
19782 return 0;
19783 }else{
19784 return 1;
19789 ** Input "r" is a numeric quantity which might be a julian day number,
19790 ** or the number of seconds since 1970. If the value if r is within
19791 ** range of a julian day number, install it as such and set validJD.
19792 ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
19794 static void setRawDateNumber(DateTime *p, double r){
19795 p->s = r;
19796 p->rawS = 1;
19797 if( r>=0.0 && r<5373484.5 ){
19798 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
19799 p->validJD = 1;
19804 ** Attempt to parse the given string into a julian day number. Return
19805 ** the number of errors.
19807 ** The following are acceptable forms for the input string:
19809 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
19810 ** DDDD.DD
19811 ** now
19813 ** In the first form, the +/-HH:MM is always optional. The fractional
19814 ** seconds extension (the ".FFF") is optional. The seconds portion
19815 ** (":SS.FFF") is option. The year and date can be omitted as long
19816 ** as there is a time string. The time string can be omitted as long
19817 ** as there is a year and date.
19819 static int parseDateOrTime(
19820 sqlite3_context *context,
19821 const char *zDate,
19822 DateTime *p
19824 double r;
19825 if( parseYyyyMmDd(zDate,p)==0 ){
19826 return 0;
19827 }else if( parseHhMmSs(zDate, p)==0 ){
19828 return 0;
19829 }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
19830 return setDateTimeToCurrent(context, p);
19831 }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
19832 setRawDateNumber(p, r);
19833 return 0;
19835 return 1;
19838 /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
19839 ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
19840 ** for DateTime.iJD.
19842 ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
19843 ** such a large integer literal, so we have to encode it.
19845 #define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
19848 ** Return TRUE if the given julian day number is within range.
19850 ** The input is the JulianDay times 86400000.
19852 static int validJulianDay(sqlite3_int64 iJD){
19853 return iJD>=0 && iJD<=INT_464269060799999;
19857 ** Compute the Year, Month, and Day from the julian day number.
19859 static void computeYMD(DateTime *p){
19860 int Z, A, B, C, D, E, X1;
19861 if( p->validYMD ) return;
19862 if( !p->validJD ){
19863 p->Y = 2000;
19864 p->M = 1;
19865 p->D = 1;
19866 }else if( !validJulianDay(p->iJD) ){
19867 datetimeError(p);
19868 return;
19869 }else{
19870 Z = (int)((p->iJD + 43200000)/86400000);
19871 A = (int)((Z - 1867216.25)/36524.25);
19872 A = Z + 1 + A - (A/4);
19873 B = A + 1524;
19874 C = (int)((B - 122.1)/365.25);
19875 D = (36525*(C&32767))/100;
19876 E = (int)((B-D)/30.6001);
19877 X1 = (int)(30.6001*E);
19878 p->D = B - D - X1;
19879 p->M = E<14 ? E-1 : E-13;
19880 p->Y = p->M>2 ? C - 4716 : C - 4715;
19882 p->validYMD = 1;
19886 ** Compute the Hour, Minute, and Seconds from the julian day number.
19888 static void computeHMS(DateTime *p){
19889 int s;
19890 if( p->validHMS ) return;
19891 computeJD(p);
19892 s = (int)((p->iJD + 43200000) % 86400000);
19893 p->s = s/1000.0;
19894 s = (int)p->s;
19895 p->s -= s;
19896 p->h = s/3600;
19897 s -= p->h*3600;
19898 p->m = s/60;
19899 p->s += s - p->m*60;
19900 p->rawS = 0;
19901 p->validHMS = 1;
19905 ** Compute both YMD and HMS
19907 static void computeYMD_HMS(DateTime *p){
19908 computeYMD(p);
19909 computeHMS(p);
19913 ** Clear the YMD and HMS and the TZ
19915 static void clearYMD_HMS_TZ(DateTime *p){
19916 p->validYMD = 0;
19917 p->validHMS = 0;
19918 p->validTZ = 0;
19921 #ifndef SQLITE_OMIT_LOCALTIME
19923 ** On recent Windows platforms, the localtime_s() function is available
19924 ** as part of the "Secure CRT". It is essentially equivalent to
19925 ** localtime_r() available under most POSIX platforms, except that the
19926 ** order of the parameters is reversed.
19928 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
19930 ** If the user has not indicated to use localtime_r() or localtime_s()
19931 ** already, check for an MSVC build environment that provides
19932 ** localtime_s().
19934 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
19935 && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
19936 #undef HAVE_LOCALTIME_S
19937 #define HAVE_LOCALTIME_S 1
19938 #endif
19941 ** The following routine implements the rough equivalent of localtime_r()
19942 ** using whatever operating-system specific localtime facility that
19943 ** is available. This routine returns 0 on success and
19944 ** non-zero on any kind of error.
19946 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
19947 ** routine will always fail.
19949 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
19950 ** library function localtime_r() is used to assist in the calculation of
19951 ** local time.
19953 static int osLocaltime(time_t *t, struct tm *pTm){
19954 int rc;
19955 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
19956 struct tm *pX;
19957 #if SQLITE_THREADSAFE>0
19958 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
19959 #endif
19960 sqlite3_mutex_enter(mutex);
19961 pX = localtime(t);
19962 #ifndef SQLITE_UNTESTABLE
19963 if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
19964 #endif
19965 if( pX ) *pTm = *pX;
19966 sqlite3_mutex_leave(mutex);
19967 rc = pX==0;
19968 #else
19969 #ifndef SQLITE_UNTESTABLE
19970 if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
19971 #endif
19972 #if HAVE_LOCALTIME_R
19973 rc = localtime_r(t, pTm)==0;
19974 #else
19975 rc = localtime_s(pTm, t);
19976 #endif /* HAVE_LOCALTIME_R */
19977 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
19978 return rc;
19980 #endif /* SQLITE_OMIT_LOCALTIME */
19983 #ifndef SQLITE_OMIT_LOCALTIME
19985 ** Compute the difference (in milliseconds) between localtime and UTC
19986 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
19987 ** return this value and set *pRc to SQLITE_OK.
19989 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
19990 ** is undefined in this case.
19992 static sqlite3_int64 localtimeOffset(
19993 DateTime *p, /* Date at which to calculate offset */
19994 sqlite3_context *pCtx, /* Write error here if one occurs */
19995 int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
19997 DateTime x, y;
19998 time_t t;
19999 struct tm sLocal;
20001 /* Initialize the contents of sLocal to avoid a compiler warning. */
20002 memset(&sLocal, 0, sizeof(sLocal));
20004 x = *p;
20005 computeYMD_HMS(&x);
20006 if( x.Y<1971 || x.Y>=2038 ){
20007 /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
20008 ** works for years between 1970 and 2037. For dates outside this range,
20009 ** SQLite attempts to map the year into an equivalent year within this
20010 ** range, do the calculation, then map the year back.
20012 x.Y = 2000;
20013 x.M = 1;
20014 x.D = 1;
20015 x.h = 0;
20016 x.m = 0;
20017 x.s = 0.0;
20018 } else {
20019 int s = (int)(x.s + 0.5);
20020 x.s = s;
20022 x.tz = 0;
20023 x.validJD = 0;
20024 computeJD(&x);
20025 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
20026 if( osLocaltime(&t, &sLocal) ){
20027 sqlite3_result_error(pCtx, "local time unavailable", -1);
20028 *pRc = SQLITE_ERROR;
20029 return 0;
20031 y.Y = sLocal.tm_year + 1900;
20032 y.M = sLocal.tm_mon + 1;
20033 y.D = sLocal.tm_mday;
20034 y.h = sLocal.tm_hour;
20035 y.m = sLocal.tm_min;
20036 y.s = sLocal.tm_sec;
20037 y.validYMD = 1;
20038 y.validHMS = 1;
20039 y.validJD = 0;
20040 y.rawS = 0;
20041 y.validTZ = 0;
20042 y.isError = 0;
20043 computeJD(&y);
20044 *pRc = SQLITE_OK;
20045 return y.iJD - x.iJD;
20047 #endif /* SQLITE_OMIT_LOCALTIME */
20050 ** The following table defines various date transformations of the form
20052 ** 'NNN days'
20054 ** Where NNN is an arbitrary floating-point number and "days" can be one
20055 ** of several units of time.
20057 static const struct {
20058 u8 eType; /* Transformation type code */
20059 u8 nName; /* Length of th name */
20060 char *zName; /* Name of the transformation */
20061 double rLimit; /* Maximum NNN value for this transform */
20062 double rXform; /* Constant used for this transform */
20063 } aXformType[] = {
20064 { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
20065 { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) },
20066 { 0, 4, "hour", 128963628.0, 86400000.0/24.0 },
20067 { 0, 3, "day", 5373485.0, 86400000.0 },
20068 { 1, 5, "month", 176546.0, 30.0*86400000.0 },
20069 { 2, 4, "year", 14713.0, 365.0*86400000.0 },
20073 ** Process a modifier to a date-time stamp. The modifiers are
20074 ** as follows:
20076 ** NNN days
20077 ** NNN hours
20078 ** NNN minutes
20079 ** NNN.NNNN seconds
20080 ** NNN months
20081 ** NNN years
20082 ** start of month
20083 ** start of year
20084 ** start of week
20085 ** start of day
20086 ** weekday N
20087 ** unixepoch
20088 ** localtime
20089 ** utc
20091 ** Return 0 on success and 1 if there is any kind of error. If the error
20092 ** is in a system call (i.e. localtime()), then an error message is written
20093 ** to context pCtx. If the error is an unrecognized modifier, no error is
20094 ** written to pCtx.
20096 static int parseModifier(
20097 sqlite3_context *pCtx, /* Function context */
20098 const char *z, /* The text of the modifier */
20099 int n, /* Length of zMod in bytes */
20100 DateTime *p /* The date/time value to be modified */
20102 int rc = 1;
20103 double r;
20104 switch(sqlite3UpperToLower[(u8)z[0]] ){
20105 #ifndef SQLITE_OMIT_LOCALTIME
20106 case 'l': {
20107 /* localtime
20109 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
20110 ** show local time.
20112 if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
20113 computeJD(p);
20114 p->iJD += localtimeOffset(p, pCtx, &rc);
20115 clearYMD_HMS_TZ(p);
20117 break;
20119 #endif
20120 case 'u': {
20122 ** unixepoch
20124 ** Treat the current value of p->s as the number of
20125 ** seconds since 1970. Convert to a real julian day number.
20127 if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
20128 r = p->s*1000.0 + 210866760000000.0;
20129 if( r>=0.0 && r<464269060800000.0 ){
20130 clearYMD_HMS_TZ(p);
20131 p->iJD = (sqlite3_int64)r;
20132 p->validJD = 1;
20133 p->rawS = 0;
20134 rc = 0;
20137 #ifndef SQLITE_OMIT_LOCALTIME
20138 else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
20139 if( p->tzSet==0 ){
20140 sqlite3_int64 c1;
20141 computeJD(p);
20142 c1 = localtimeOffset(p, pCtx, &rc);
20143 if( rc==SQLITE_OK ){
20144 p->iJD -= c1;
20145 clearYMD_HMS_TZ(p);
20146 p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
20148 p->tzSet = 1;
20149 }else{
20150 rc = SQLITE_OK;
20153 #endif
20154 break;
20156 case 'w': {
20158 ** weekday N
20160 ** Move the date to the same time on the next occurrence of
20161 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
20162 ** date is already on the appropriate weekday, this is a no-op.
20164 if( sqlite3_strnicmp(z, "weekday ", 8)==0
20165 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
20166 && (n=(int)r)==r && n>=0 && r<7 ){
20167 sqlite3_int64 Z;
20168 computeYMD_HMS(p);
20169 p->validTZ = 0;
20170 p->validJD = 0;
20171 computeJD(p);
20172 Z = ((p->iJD + 129600000)/86400000) % 7;
20173 if( Z>n ) Z -= 7;
20174 p->iJD += (n - Z)*86400000;
20175 clearYMD_HMS_TZ(p);
20176 rc = 0;
20178 break;
20180 case 's': {
20182 ** start of TTTTT
20184 ** Move the date backwards to the beginning of the current day,
20185 ** or month or year.
20187 if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
20188 if( !p->validJD && !p->validYMD && !p->validHMS ) break;
20189 z += 9;
20190 computeYMD(p);
20191 p->validHMS = 1;
20192 p->h = p->m = 0;
20193 p->s = 0.0;
20194 p->rawS = 0;
20195 p->validTZ = 0;
20196 p->validJD = 0;
20197 if( sqlite3_stricmp(z,"month")==0 ){
20198 p->D = 1;
20199 rc = 0;
20200 }else if( sqlite3_stricmp(z,"year")==0 ){
20201 p->M = 1;
20202 p->D = 1;
20203 rc = 0;
20204 }else if( sqlite3_stricmp(z,"day")==0 ){
20205 rc = 0;
20207 break;
20209 case '+':
20210 case '-':
20211 case '0':
20212 case '1':
20213 case '2':
20214 case '3':
20215 case '4':
20216 case '5':
20217 case '6':
20218 case '7':
20219 case '8':
20220 case '9': {
20221 double rRounder;
20222 int i;
20223 for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
20224 if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
20225 rc = 1;
20226 break;
20228 if( z[n]==':' ){
20229 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
20230 ** specified number of hours, minutes, seconds, and fractional seconds
20231 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
20232 ** omitted.
20234 const char *z2 = z;
20235 DateTime tx;
20236 sqlite3_int64 day;
20237 if( !sqlite3Isdigit(*z2) ) z2++;
20238 memset(&tx, 0, sizeof(tx));
20239 if( parseHhMmSs(z2, &tx) ) break;
20240 computeJD(&tx);
20241 tx.iJD -= 43200000;
20242 day = tx.iJD/86400000;
20243 tx.iJD -= day*86400000;
20244 if( z[0]=='-' ) tx.iJD = -tx.iJD;
20245 computeJD(p);
20246 clearYMD_HMS_TZ(p);
20247 p->iJD += tx.iJD;
20248 rc = 0;
20249 break;
20252 /* If control reaches this point, it means the transformation is
20253 ** one of the forms like "+NNN days". */
20254 z += n;
20255 while( sqlite3Isspace(*z) ) z++;
20256 n = sqlite3Strlen30(z);
20257 if( n>10 || n<3 ) break;
20258 if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
20259 computeJD(p);
20260 rc = 1;
20261 rRounder = r<0 ? -0.5 : +0.5;
20262 for(i=0; i<ArraySize(aXformType); i++){
20263 if( aXformType[i].nName==n
20264 && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
20265 && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
20267 switch( aXformType[i].eType ){
20268 case 1: { /* Special processing to add months */
20269 int x;
20270 computeYMD_HMS(p);
20271 p->M += (int)r;
20272 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
20273 p->Y += x;
20274 p->M -= x*12;
20275 p->validJD = 0;
20276 r -= (int)r;
20277 break;
20279 case 2: { /* Special processing to add years */
20280 int y = (int)r;
20281 computeYMD_HMS(p);
20282 p->Y += y;
20283 p->validJD = 0;
20284 r -= (int)r;
20285 break;
20288 computeJD(p);
20289 p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
20290 rc = 0;
20291 break;
20294 clearYMD_HMS_TZ(p);
20295 break;
20297 default: {
20298 break;
20301 return rc;
20305 ** Process time function arguments. argv[0] is a date-time stamp.
20306 ** argv[1] and following are modifiers. Parse them all and write
20307 ** the resulting time into the DateTime structure p. Return 0
20308 ** on success and 1 if there are any errors.
20310 ** If there are zero parameters (if even argv[0] is undefined)
20311 ** then assume a default value of "now" for argv[0].
20313 static int isDate(
20314 sqlite3_context *context,
20315 int argc,
20316 sqlite3_value **argv,
20317 DateTime *p
20319 int i, n;
20320 const unsigned char *z;
20321 int eType;
20322 memset(p, 0, sizeof(*p));
20323 if( argc==0 ){
20324 return setDateTimeToCurrent(context, p);
20326 if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
20327 || eType==SQLITE_INTEGER ){
20328 setRawDateNumber(p, sqlite3_value_double(argv[0]));
20329 }else{
20330 z = sqlite3_value_text(argv[0]);
20331 if( !z || parseDateOrTime(context, (char*)z, p) ){
20332 return 1;
20335 for(i=1; i<argc; i++){
20336 z = sqlite3_value_text(argv[i]);
20337 n = sqlite3_value_bytes(argv[i]);
20338 if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
20340 computeJD(p);
20341 if( p->isError || !validJulianDay(p->iJD) ) return 1;
20342 return 0;
20347 ** The following routines implement the various date and time functions
20348 ** of SQLite.
20352 ** julianday( TIMESTRING, MOD, MOD, ...)
20354 ** Return the julian day number of the date specified in the arguments
20356 static void juliandayFunc(
20357 sqlite3_context *context,
20358 int argc,
20359 sqlite3_value **argv
20361 DateTime x;
20362 if( isDate(context, argc, argv, &x)==0 ){
20363 computeJD(&x);
20364 sqlite3_result_double(context, x.iJD/86400000.0);
20369 ** datetime( TIMESTRING, MOD, MOD, ...)
20371 ** Return YYYY-MM-DD HH:MM:SS
20373 static void datetimeFunc(
20374 sqlite3_context *context,
20375 int argc,
20376 sqlite3_value **argv
20378 DateTime x;
20379 if( isDate(context, argc, argv, &x)==0 ){
20380 char zBuf[100];
20381 computeYMD_HMS(&x);
20382 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
20383 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
20384 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
20389 ** time( TIMESTRING, MOD, MOD, ...)
20391 ** Return HH:MM:SS
20393 static void timeFunc(
20394 sqlite3_context *context,
20395 int argc,
20396 sqlite3_value **argv
20398 DateTime x;
20399 if( isDate(context, argc, argv, &x)==0 ){
20400 char zBuf[100];
20401 computeHMS(&x);
20402 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
20403 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
20408 ** date( TIMESTRING, MOD, MOD, ...)
20410 ** Return YYYY-MM-DD
20412 static void dateFunc(
20413 sqlite3_context *context,
20414 int argc,
20415 sqlite3_value **argv
20417 DateTime x;
20418 if( isDate(context, argc, argv, &x)==0 ){
20419 char zBuf[100];
20420 computeYMD(&x);
20421 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
20422 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
20427 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
20429 ** Return a string described by FORMAT. Conversions as follows:
20431 ** %d day of month
20432 ** %f ** fractional seconds SS.SSS
20433 ** %H hour 00-24
20434 ** %j day of year 000-366
20435 ** %J ** julian day number
20436 ** %m month 01-12
20437 ** %M minute 00-59
20438 ** %s seconds since 1970-01-01
20439 ** %S seconds 00-59
20440 ** %w day of week 0-6 sunday==0
20441 ** %W week of year 00-53
20442 ** %Y year 0000-9999
20443 ** %% %
20445 static void strftimeFunc(
20446 sqlite3_context *context,
20447 int argc,
20448 sqlite3_value **argv
20450 DateTime x;
20451 u64 n;
20452 size_t i,j;
20453 char *z;
20454 sqlite3 *db;
20455 const char *zFmt;
20456 char zBuf[100];
20457 if( argc==0 ) return;
20458 zFmt = (const char*)sqlite3_value_text(argv[0]);
20459 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
20460 db = sqlite3_context_db_handle(context);
20461 for(i=0, n=1; zFmt[i]; i++, n++){
20462 if( zFmt[i]=='%' ){
20463 switch( zFmt[i+1] ){
20464 case 'd':
20465 case 'H':
20466 case 'm':
20467 case 'M':
20468 case 'S':
20469 case 'W':
20470 n++;
20471 /* fall thru */
20472 case 'w':
20473 case '%':
20474 break;
20475 case 'f':
20476 n += 8;
20477 break;
20478 case 'j':
20479 n += 3;
20480 break;
20481 case 'Y':
20482 n += 8;
20483 break;
20484 case 's':
20485 case 'J':
20486 n += 50;
20487 break;
20488 default:
20489 return; /* ERROR. return a NULL */
20491 i++;
20494 testcase( n==sizeof(zBuf)-1 );
20495 testcase( n==sizeof(zBuf) );
20496 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
20497 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
20498 if( n<sizeof(zBuf) ){
20499 z = zBuf;
20500 }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
20501 sqlite3_result_error_toobig(context);
20502 return;
20503 }else{
20504 z = sqlite3DbMallocRawNN(db, (int)n);
20505 if( z==0 ){
20506 sqlite3_result_error_nomem(context);
20507 return;
20510 computeJD(&x);
20511 computeYMD_HMS(&x);
20512 for(i=j=0; zFmt[i]; i++){
20513 if( zFmt[i]!='%' ){
20514 z[j++] = zFmt[i];
20515 }else{
20516 i++;
20517 switch( zFmt[i] ){
20518 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
20519 case 'f': {
20520 double s = x.s;
20521 if( s>59.999 ) s = 59.999;
20522 sqlite3_snprintf(7, &z[j],"%06.3f", s);
20523 j += sqlite3Strlen30(&z[j]);
20524 break;
20526 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
20527 case 'W': /* Fall thru */
20528 case 'j': {
20529 int nDay; /* Number of days since 1st day of year */
20530 DateTime y = x;
20531 y.validJD = 0;
20532 y.M = 1;
20533 y.D = 1;
20534 computeJD(&y);
20535 nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
20536 if( zFmt[i]=='W' ){
20537 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
20538 wd = (int)(((x.iJD+43200000)/86400000)%7);
20539 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
20540 j += 2;
20541 }else{
20542 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
20543 j += 3;
20545 break;
20547 case 'J': {
20548 sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
20549 j+=sqlite3Strlen30(&z[j]);
20550 break;
20552 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
20553 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
20554 case 's': {
20555 sqlite3_snprintf(30,&z[j],"%lld",
20556 (i64)(x.iJD/1000 - 21086676*(i64)10000));
20557 j += sqlite3Strlen30(&z[j]);
20558 break;
20560 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
20561 case 'w': {
20562 z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
20563 break;
20565 case 'Y': {
20566 sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
20567 break;
20569 default: z[j++] = '%'; break;
20573 z[j] = 0;
20574 sqlite3_result_text(context, z, -1,
20575 z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
20579 ** current_time()
20581 ** This function returns the same value as time('now').
20583 static void ctimeFunc(
20584 sqlite3_context *context,
20585 int NotUsed,
20586 sqlite3_value **NotUsed2
20588 UNUSED_PARAMETER2(NotUsed, NotUsed2);
20589 timeFunc(context, 0, 0);
20593 ** current_date()
20595 ** This function returns the same value as date('now').
20597 static void cdateFunc(
20598 sqlite3_context *context,
20599 int NotUsed,
20600 sqlite3_value **NotUsed2
20602 UNUSED_PARAMETER2(NotUsed, NotUsed2);
20603 dateFunc(context, 0, 0);
20607 ** current_timestamp()
20609 ** This function returns the same value as datetime('now').
20611 static void ctimestampFunc(
20612 sqlite3_context *context,
20613 int NotUsed,
20614 sqlite3_value **NotUsed2
20616 UNUSED_PARAMETER2(NotUsed, NotUsed2);
20617 datetimeFunc(context, 0, 0);
20619 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
20621 #ifdef SQLITE_OMIT_DATETIME_FUNCS
20623 ** If the library is compiled to omit the full-scale date and time
20624 ** handling (to get a smaller binary), the following minimal version
20625 ** of the functions current_time(), current_date() and current_timestamp()
20626 ** are included instead. This is to support column declarations that
20627 ** include "DEFAULT CURRENT_TIME" etc.
20629 ** This function uses the C-library functions time(), gmtime()
20630 ** and strftime(). The format string to pass to strftime() is supplied
20631 ** as the user-data for the function.
20633 static void currentTimeFunc(
20634 sqlite3_context *context,
20635 int argc,
20636 sqlite3_value **argv
20638 time_t t;
20639 char *zFormat = (char *)sqlite3_user_data(context);
20640 sqlite3_int64 iT;
20641 struct tm *pTm;
20642 struct tm sNow;
20643 char zBuf[20];
20645 UNUSED_PARAMETER(argc);
20646 UNUSED_PARAMETER(argv);
20648 iT = sqlite3StmtCurrentTime(context);
20649 if( iT<=0 ) return;
20650 t = iT/1000 - 10000*(sqlite3_int64)21086676;
20651 #if HAVE_GMTIME_R
20652 pTm = gmtime_r(&t, &sNow);
20653 #else
20654 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
20655 pTm = gmtime(&t);
20656 if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
20657 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
20658 #endif
20659 if( pTm ){
20660 strftime(zBuf, 20, zFormat, &sNow);
20661 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
20664 #endif
20667 ** This function registered all of the above C functions as SQL
20668 ** functions. This should be the only routine in this file with
20669 ** external linkage.
20671 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
20672 static FuncDef aDateTimeFuncs[] = {
20673 #ifndef SQLITE_OMIT_DATETIME_FUNCS
20674 PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
20675 PURE_DATE(date, -1, 0, 0, dateFunc ),
20676 PURE_DATE(time, -1, 0, 0, timeFunc ),
20677 PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
20678 PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
20679 DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
20680 DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
20681 DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
20682 #else
20683 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
20684 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
20685 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
20686 #endif
20688 sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
20691 /************** End of date.c ************************************************/
20692 /************** Begin file os.c **********************************************/
20694 ** 2005 November 29
20696 ** The author disclaims copyright to this source code. In place of
20697 ** a legal notice, here is a blessing:
20699 ** May you do good and not evil.
20700 ** May you find forgiveness for yourself and forgive others.
20701 ** May you share freely, never taking more than you give.
20703 ******************************************************************************
20705 ** This file contains OS interface code that is common to all
20706 ** architectures.
20708 /* #include "sqliteInt.h" */
20711 ** If we compile with the SQLITE_TEST macro set, then the following block
20712 ** of code will give us the ability to simulate a disk I/O error. This
20713 ** is used for testing the I/O recovery logic.
20715 #if defined(SQLITE_TEST)
20716 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
20717 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
20718 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
20719 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
20720 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
20721 SQLITE_API int sqlite3_diskfull_pending = 0;
20722 SQLITE_API int sqlite3_diskfull = 0;
20723 #endif /* defined(SQLITE_TEST) */
20726 ** When testing, also keep a count of the number of open files.
20728 #if defined(SQLITE_TEST)
20729 SQLITE_API int sqlite3_open_file_count = 0;
20730 #endif /* defined(SQLITE_TEST) */
20733 ** The default SQLite sqlite3_vfs implementations do not allocate
20734 ** memory (actually, os_unix.c allocates a small amount of memory
20735 ** from within OsOpen()), but some third-party implementations may.
20736 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
20737 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
20739 ** The following functions are instrumented for malloc() failure
20740 ** testing:
20742 ** sqlite3OsRead()
20743 ** sqlite3OsWrite()
20744 ** sqlite3OsSync()
20745 ** sqlite3OsFileSize()
20746 ** sqlite3OsLock()
20747 ** sqlite3OsCheckReservedLock()
20748 ** sqlite3OsFileControl()
20749 ** sqlite3OsShmMap()
20750 ** sqlite3OsOpen()
20751 ** sqlite3OsDelete()
20752 ** sqlite3OsAccess()
20753 ** sqlite3OsFullPathname()
20756 #if defined(SQLITE_TEST)
20757 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
20758 #define DO_OS_MALLOC_TEST(x) \
20759 if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
20760 void *pTstAlloc = sqlite3Malloc(10); \
20761 if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
20762 sqlite3_free(pTstAlloc); \
20764 #else
20765 #define DO_OS_MALLOC_TEST(x)
20766 #endif
20769 ** The following routines are convenience wrappers around methods
20770 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
20771 ** of this would be completely automatic if SQLite were coded using
20772 ** C++ instead of plain old C.
20774 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
20775 if( pId->pMethods ){
20776 pId->pMethods->xClose(pId);
20777 pId->pMethods = 0;
20780 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
20781 DO_OS_MALLOC_TEST(id);
20782 return id->pMethods->xRead(id, pBuf, amt, offset);
20784 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
20785 DO_OS_MALLOC_TEST(id);
20786 return id->pMethods->xWrite(id, pBuf, amt, offset);
20788 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
20789 return id->pMethods->xTruncate(id, size);
20791 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
20792 DO_OS_MALLOC_TEST(id);
20793 return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
20795 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
20796 DO_OS_MALLOC_TEST(id);
20797 return id->pMethods->xFileSize(id, pSize);
20799 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
20800 DO_OS_MALLOC_TEST(id);
20801 return id->pMethods->xLock(id, lockType);
20803 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
20804 return id->pMethods->xUnlock(id, lockType);
20806 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
20807 DO_OS_MALLOC_TEST(id);
20808 return id->pMethods->xCheckReservedLock(id, pResOut);
20812 ** Use sqlite3OsFileControl() when we are doing something that might fail
20813 ** and we need to know about the failures. Use sqlite3OsFileControlHint()
20814 ** when simply tossing information over the wall to the VFS and we do not
20815 ** really care if the VFS receives and understands the information since it
20816 ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
20817 ** routine has no return value since the return value would be meaningless.
20819 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
20820 #ifdef SQLITE_TEST
20821 if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
20822 /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
20823 ** is using a regular VFS, it is called after the corresponding
20824 ** transaction has been committed. Injecting a fault at this point
20825 ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
20826 ** but the transaction is committed anyway.
20828 ** The core must call OsFileControl() though, not OsFileControlHint(),
20829 ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
20830 ** means the commit really has failed and an error should be returned
20831 ** to the user. */
20832 DO_OS_MALLOC_TEST(id);
20834 #endif
20835 return id->pMethods->xFileControl(id, op, pArg);
20837 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
20838 (void)id->pMethods->xFileControl(id, op, pArg);
20841 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
20842 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
20843 return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
20845 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
20846 return id->pMethods->xDeviceCharacteristics(id);
20848 #ifndef SQLITE_OMIT_WAL
20849 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
20850 return id->pMethods->xShmLock(id, offset, n, flags);
20852 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
20853 id->pMethods->xShmBarrier(id);
20855 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
20856 return id->pMethods->xShmUnmap(id, deleteFlag);
20858 SQLITE_PRIVATE int sqlite3OsShmMap(
20859 sqlite3_file *id, /* Database file handle */
20860 int iPage,
20861 int pgsz,
20862 int bExtend, /* True to extend file if necessary */
20863 void volatile **pp /* OUT: Pointer to mapping */
20865 DO_OS_MALLOC_TEST(id);
20866 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
20868 #endif /* SQLITE_OMIT_WAL */
20870 #if SQLITE_MAX_MMAP_SIZE>0
20871 /* The real implementation of xFetch and xUnfetch */
20872 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
20873 DO_OS_MALLOC_TEST(id);
20874 return id->pMethods->xFetch(id, iOff, iAmt, pp);
20876 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
20877 return id->pMethods->xUnfetch(id, iOff, p);
20879 #else
20880 /* No-op stubs to use when memory-mapped I/O is disabled */
20881 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
20882 *pp = 0;
20883 return SQLITE_OK;
20885 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
20886 return SQLITE_OK;
20888 #endif
20891 ** The next group of routines are convenience wrappers around the
20892 ** VFS methods.
20894 SQLITE_PRIVATE int sqlite3OsOpen(
20895 sqlite3_vfs *pVfs,
20896 const char *zPath,
20897 sqlite3_file *pFile,
20898 int flags,
20899 int *pFlagsOut
20901 int rc;
20902 DO_OS_MALLOC_TEST(0);
20903 /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
20904 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
20905 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
20906 ** reaching the VFS. */
20907 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
20908 assert( rc==SQLITE_OK || pFile->pMethods==0 );
20909 return rc;
20911 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
20912 DO_OS_MALLOC_TEST(0);
20913 assert( dirSync==0 || dirSync==1 );
20914 return pVfs->xDelete(pVfs, zPath, dirSync);
20916 SQLITE_PRIVATE int sqlite3OsAccess(
20917 sqlite3_vfs *pVfs,
20918 const char *zPath,
20919 int flags,
20920 int *pResOut
20922 DO_OS_MALLOC_TEST(0);
20923 return pVfs->xAccess(pVfs, zPath, flags, pResOut);
20925 SQLITE_PRIVATE int sqlite3OsFullPathname(
20926 sqlite3_vfs *pVfs,
20927 const char *zPath,
20928 int nPathOut,
20929 char *zPathOut
20931 DO_OS_MALLOC_TEST(0);
20932 zPathOut[0] = 0;
20933 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
20935 #ifndef SQLITE_OMIT_LOAD_EXTENSION
20936 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
20937 return pVfs->xDlOpen(pVfs, zPath);
20939 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
20940 pVfs->xDlError(pVfs, nByte, zBufOut);
20942 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
20943 return pVfs->xDlSym(pVfs, pHdle, zSym);
20945 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
20946 pVfs->xDlClose(pVfs, pHandle);
20948 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
20949 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
20950 return pVfs->xRandomness(pVfs, nByte, zBufOut);
20952 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
20953 return pVfs->xSleep(pVfs, nMicro);
20955 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
20956 return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
20958 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
20959 int rc;
20960 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
20961 ** method to get the current date and time if that method is available
20962 ** (if iVersion is 2 or greater and the function pointer is not NULL) and
20963 ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
20964 ** unavailable.
20966 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
20967 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
20968 }else{
20969 double r;
20970 rc = pVfs->xCurrentTime(pVfs, &r);
20971 *pTimeOut = (sqlite3_int64)(r*86400000.0);
20973 return rc;
20976 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
20977 sqlite3_vfs *pVfs,
20978 const char *zFile,
20979 sqlite3_file **ppFile,
20980 int flags,
20981 int *pOutFlags
20983 int rc;
20984 sqlite3_file *pFile;
20985 pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
20986 if( pFile ){
20987 rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
20988 if( rc!=SQLITE_OK ){
20989 sqlite3_free(pFile);
20990 }else{
20991 *ppFile = pFile;
20993 }else{
20994 rc = SQLITE_NOMEM_BKPT;
20996 return rc;
20998 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
20999 assert( pFile );
21000 sqlite3OsClose(pFile);
21001 sqlite3_free(pFile);
21005 ** This function is a wrapper around the OS specific implementation of
21006 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
21007 ** ability to simulate a malloc failure, so that the handling of an
21008 ** error in sqlite3_os_init() by the upper layers can be tested.
21010 SQLITE_PRIVATE int sqlite3OsInit(void){
21011 void *p = sqlite3_malloc(10);
21012 if( p==0 ) return SQLITE_NOMEM_BKPT;
21013 sqlite3_free(p);
21014 return sqlite3_os_init();
21018 ** The list of all registered VFS implementations.
21020 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
21021 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
21024 ** Locate a VFS by name. If no name is given, simply return the
21025 ** first VFS on the list.
21027 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
21028 sqlite3_vfs *pVfs = 0;
21029 #if SQLITE_THREADSAFE
21030 sqlite3_mutex *mutex;
21031 #endif
21032 #ifndef SQLITE_OMIT_AUTOINIT
21033 int rc = sqlite3_initialize();
21034 if( rc ) return 0;
21035 #endif
21036 #if SQLITE_THREADSAFE
21037 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
21038 #endif
21039 sqlite3_mutex_enter(mutex);
21040 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
21041 if( zVfs==0 ) break;
21042 if( strcmp(zVfs, pVfs->zName)==0 ) break;
21044 sqlite3_mutex_leave(mutex);
21045 return pVfs;
21049 ** Unlink a VFS from the linked list
21051 static void vfsUnlink(sqlite3_vfs *pVfs){
21052 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
21053 if( pVfs==0 ){
21054 /* No-op */
21055 }else if( vfsList==pVfs ){
21056 vfsList = pVfs->pNext;
21057 }else if( vfsList ){
21058 sqlite3_vfs *p = vfsList;
21059 while( p->pNext && p->pNext!=pVfs ){
21060 p = p->pNext;
21062 if( p->pNext==pVfs ){
21063 p->pNext = pVfs->pNext;
21069 ** Register a VFS with the system. It is harmless to register the same
21070 ** VFS multiple times. The new VFS becomes the default if makeDflt is
21071 ** true.
21073 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
21074 MUTEX_LOGIC(sqlite3_mutex *mutex;)
21075 #ifndef SQLITE_OMIT_AUTOINIT
21076 int rc = sqlite3_initialize();
21077 if( rc ) return rc;
21078 #endif
21079 #ifdef SQLITE_ENABLE_API_ARMOR
21080 if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
21081 #endif
21083 MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
21084 sqlite3_mutex_enter(mutex);
21085 vfsUnlink(pVfs);
21086 if( makeDflt || vfsList==0 ){
21087 pVfs->pNext = vfsList;
21088 vfsList = pVfs;
21089 }else{
21090 pVfs->pNext = vfsList->pNext;
21091 vfsList->pNext = pVfs;
21093 assert(vfsList);
21094 sqlite3_mutex_leave(mutex);
21095 return SQLITE_OK;
21099 ** Unregister a VFS so that it is no longer accessible.
21101 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
21102 #if SQLITE_THREADSAFE
21103 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
21104 #endif
21105 sqlite3_mutex_enter(mutex);
21106 vfsUnlink(pVfs);
21107 sqlite3_mutex_leave(mutex);
21108 return SQLITE_OK;
21111 /************** End of os.c **************************************************/
21112 /************** Begin file fault.c *******************************************/
21114 ** 2008 Jan 22
21116 ** The author disclaims copyright to this source code. In place of
21117 ** a legal notice, here is a blessing:
21119 ** May you do good and not evil.
21120 ** May you find forgiveness for yourself and forgive others.
21121 ** May you share freely, never taking more than you give.
21123 *************************************************************************
21125 ** This file contains code to support the concept of "benign"
21126 ** malloc failures (when the xMalloc() or xRealloc() method of the
21127 ** sqlite3_mem_methods structure fails to allocate a block of memory
21128 ** and returns 0).
21130 ** Most malloc failures are non-benign. After they occur, SQLite
21131 ** abandons the current operation and returns an error code (usually
21132 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
21133 ** fatal. For example, if a malloc fails while resizing a hash table, this
21134 ** is completely recoverable simply by not carrying out the resize. The
21135 ** hash table will continue to function normally. So a malloc failure
21136 ** during a hash table resize is a benign fault.
21139 /* #include "sqliteInt.h" */
21141 #ifndef SQLITE_UNTESTABLE
21144 ** Global variables.
21146 typedef struct BenignMallocHooks BenignMallocHooks;
21147 static SQLITE_WSD struct BenignMallocHooks {
21148 void (*xBenignBegin)(void);
21149 void (*xBenignEnd)(void);
21150 } sqlite3Hooks = { 0, 0 };
21152 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
21153 ** structure. If writable static data is unsupported on the target,
21154 ** we have to locate the state vector at run-time. In the more common
21155 ** case where writable static data is supported, wsdHooks can refer directly
21156 ** to the "sqlite3Hooks" state vector declared above.
21158 #ifdef SQLITE_OMIT_WSD
21159 # define wsdHooksInit \
21160 BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
21161 # define wsdHooks x[0]
21162 #else
21163 # define wsdHooksInit
21164 # define wsdHooks sqlite3Hooks
21165 #endif
21169 ** Register hooks to call when sqlite3BeginBenignMalloc() and
21170 ** sqlite3EndBenignMalloc() are called, respectively.
21172 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
21173 void (*xBenignBegin)(void),
21174 void (*xBenignEnd)(void)
21176 wsdHooksInit;
21177 wsdHooks.xBenignBegin = xBenignBegin;
21178 wsdHooks.xBenignEnd = xBenignEnd;
21182 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
21183 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
21184 ** indicates that subsequent malloc failures are non-benign.
21186 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
21187 wsdHooksInit;
21188 if( wsdHooks.xBenignBegin ){
21189 wsdHooks.xBenignBegin();
21192 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
21193 wsdHooksInit;
21194 if( wsdHooks.xBenignEnd ){
21195 wsdHooks.xBenignEnd();
21199 #endif /* #ifndef SQLITE_UNTESTABLE */
21201 /************** End of fault.c ***********************************************/
21202 /************** Begin file mem0.c ********************************************/
21204 ** 2008 October 28
21206 ** The author disclaims copyright to this source code. In place of
21207 ** a legal notice, here is a blessing:
21209 ** May you do good and not evil.
21210 ** May you find forgiveness for yourself and forgive others.
21211 ** May you share freely, never taking more than you give.
21213 *************************************************************************
21215 ** This file contains a no-op memory allocation drivers for use when
21216 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
21217 ** here always fail. SQLite will not operate with these drivers. These
21218 ** are merely placeholders. Real drivers must be substituted using
21219 ** sqlite3_config() before SQLite will operate.
21221 /* #include "sqliteInt.h" */
21224 ** This version of the memory allocator is the default. It is
21225 ** used when no other memory allocator is specified using compile-time
21226 ** macros.
21228 #ifdef SQLITE_ZERO_MALLOC
21231 ** No-op versions of all memory allocation routines
21233 static void *sqlite3MemMalloc(int nByte){ return 0; }
21234 static void sqlite3MemFree(void *pPrior){ return; }
21235 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
21236 static int sqlite3MemSize(void *pPrior){ return 0; }
21237 static int sqlite3MemRoundup(int n){ return n; }
21238 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
21239 static void sqlite3MemShutdown(void *NotUsed){ return; }
21242 ** This routine is the only routine in this file with external linkage.
21244 ** Populate the low-level memory allocation function pointers in
21245 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
21247 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
21248 static const sqlite3_mem_methods defaultMethods = {
21249 sqlite3MemMalloc,
21250 sqlite3MemFree,
21251 sqlite3MemRealloc,
21252 sqlite3MemSize,
21253 sqlite3MemRoundup,
21254 sqlite3MemInit,
21255 sqlite3MemShutdown,
21258 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
21261 #endif /* SQLITE_ZERO_MALLOC */
21263 /************** End of mem0.c ************************************************/
21264 /************** Begin file mem1.c ********************************************/
21266 ** 2007 August 14
21268 ** The author disclaims copyright to this source code. In place of
21269 ** a legal notice, here is a blessing:
21271 ** May you do good and not evil.
21272 ** May you find forgiveness for yourself and forgive others.
21273 ** May you share freely, never taking more than you give.
21275 *************************************************************************
21277 ** This file contains low-level memory allocation drivers for when
21278 ** SQLite will use the standard C-library malloc/realloc/free interface
21279 ** to obtain the memory it needs.
21281 ** This file contains implementations of the low-level memory allocation
21282 ** routines specified in the sqlite3_mem_methods object. The content of
21283 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
21284 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
21285 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
21286 ** default configuration is to use memory allocation routines in this
21287 ** file.
21289 ** C-preprocessor macro summary:
21291 ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
21292 ** the malloc_usable_size() interface exists
21293 ** on the target platform. Or, this symbol
21294 ** can be set manually, if desired.
21295 ** If an equivalent interface exists by
21296 ** a different name, using a separate -D
21297 ** option to rename it.
21299 ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
21300 ** memory allocator. Set this symbol to enable
21301 ** building on older macs.
21303 ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
21304 ** _msize() on windows systems. This might
21305 ** be necessary when compiling for Delphi,
21306 ** for example.
21308 /* #include "sqliteInt.h" */
21311 ** This version of the memory allocator is the default. It is
21312 ** used when no other memory allocator is specified using compile-time
21313 ** macros.
21315 #ifdef SQLITE_SYSTEM_MALLOC
21316 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
21319 ** Use the zone allocator available on apple products unless the
21320 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
21322 #include <sys/sysctl.h>
21323 #include <malloc/malloc.h>
21324 #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
21325 #include <libkern/OSAtomic.h>
21326 #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
21327 static malloc_zone_t* _sqliteZone_;
21328 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
21329 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
21330 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
21331 #define SQLITE_MALLOCSIZE(x) \
21332 (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
21334 #else /* if not __APPLE__ */
21337 ** Use standard C library malloc and free on non-Apple systems.
21338 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
21340 #define SQLITE_MALLOC(x) malloc(x)
21341 #define SQLITE_FREE(x) free(x)
21342 #define SQLITE_REALLOC(x,y) realloc((x),(y))
21345 ** The malloc.h header file is needed for malloc_usable_size() function
21346 ** on some systems (e.g. Linux).
21348 #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
21349 # define SQLITE_USE_MALLOC_H 1
21350 # define SQLITE_USE_MALLOC_USABLE_SIZE 1
21352 ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
21353 ** use of _msize() is automatic, but can be disabled by compiling with
21354 ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
21355 ** the malloc.h header file.
21357 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
21358 # define SQLITE_USE_MALLOC_H
21359 # define SQLITE_USE_MSIZE
21360 #endif
21363 ** Include the malloc.h header file, if necessary. Also set define macro
21364 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
21365 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
21366 ** The memory size function can always be overridden manually by defining
21367 ** the macro SQLITE_MALLOCSIZE to the desired function name.
21369 #if defined(SQLITE_USE_MALLOC_H)
21370 # include <malloc.h>
21371 # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
21372 # if !defined(SQLITE_MALLOCSIZE)
21373 # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
21374 # endif
21375 # elif defined(SQLITE_USE_MSIZE)
21376 # if !defined(SQLITE_MALLOCSIZE)
21377 # define SQLITE_MALLOCSIZE _msize
21378 # endif
21379 # endif
21380 #endif /* defined(SQLITE_USE_MALLOC_H) */
21382 #endif /* __APPLE__ or not __APPLE__ */
21385 ** Like malloc(), but remember the size of the allocation
21386 ** so that we can find it later using sqlite3MemSize().
21388 ** For this low-level routine, we are guaranteed that nByte>0 because
21389 ** cases of nByte<=0 will be intercepted and dealt with by higher level
21390 ** routines.
21392 static void *sqlite3MemMalloc(int nByte){
21393 #ifdef SQLITE_MALLOCSIZE
21394 void *p;
21395 testcase( ROUND8(nByte)==nByte );
21396 p = SQLITE_MALLOC( nByte );
21397 if( p==0 ){
21398 testcase( sqlite3GlobalConfig.xLog!=0 );
21399 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
21401 return p;
21402 #else
21403 sqlite3_int64 *p;
21404 assert( nByte>0 );
21405 testcase( ROUND8(nByte)!=nByte );
21406 p = SQLITE_MALLOC( nByte+8 );
21407 if( p ){
21408 p[0] = nByte;
21409 p++;
21410 }else{
21411 testcase( sqlite3GlobalConfig.xLog!=0 );
21412 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
21414 return (void *)p;
21415 #endif
21419 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
21420 ** or sqlite3MemRealloc().
21422 ** For this low-level routine, we already know that pPrior!=0 since
21423 ** cases where pPrior==0 will have been intecepted and dealt with
21424 ** by higher-level routines.
21426 static void sqlite3MemFree(void *pPrior){
21427 #ifdef SQLITE_MALLOCSIZE
21428 SQLITE_FREE(pPrior);
21429 #else
21430 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
21431 assert( pPrior!=0 );
21432 p--;
21433 SQLITE_FREE(p);
21434 #endif
21438 ** Report the allocated size of a prior return from xMalloc()
21439 ** or xRealloc().
21441 static int sqlite3MemSize(void *pPrior){
21442 #ifdef SQLITE_MALLOCSIZE
21443 assert( pPrior!=0 );
21444 return (int)SQLITE_MALLOCSIZE(pPrior);
21445 #else
21446 sqlite3_int64 *p;
21447 assert( pPrior!=0 );
21448 p = (sqlite3_int64*)pPrior;
21449 p--;
21450 return (int)p[0];
21451 #endif
21455 ** Like realloc(). Resize an allocation previously obtained from
21456 ** sqlite3MemMalloc().
21458 ** For this low-level interface, we know that pPrior!=0. Cases where
21459 ** pPrior==0 while have been intercepted by higher-level routine and
21460 ** redirected to xMalloc. Similarly, we know that nByte>0 because
21461 ** cases where nByte<=0 will have been intercepted by higher-level
21462 ** routines and redirected to xFree.
21464 static void *sqlite3MemRealloc(void *pPrior, int nByte){
21465 #ifdef SQLITE_MALLOCSIZE
21466 void *p = SQLITE_REALLOC(pPrior, nByte);
21467 if( p==0 ){
21468 testcase( sqlite3GlobalConfig.xLog!=0 );
21469 sqlite3_log(SQLITE_NOMEM,
21470 "failed memory resize %u to %u bytes",
21471 SQLITE_MALLOCSIZE(pPrior), nByte);
21473 return p;
21474 #else
21475 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
21476 assert( pPrior!=0 && nByte>0 );
21477 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
21478 p--;
21479 p = SQLITE_REALLOC(p, nByte+8 );
21480 if( p ){
21481 p[0] = nByte;
21482 p++;
21483 }else{
21484 testcase( sqlite3GlobalConfig.xLog!=0 );
21485 sqlite3_log(SQLITE_NOMEM,
21486 "failed memory resize %u to %u bytes",
21487 sqlite3MemSize(pPrior), nByte);
21489 return (void*)p;
21490 #endif
21494 ** Round up a request size to the next valid allocation size.
21496 static int sqlite3MemRoundup(int n){
21497 return ROUND8(n);
21501 ** Initialize this module.
21503 static int sqlite3MemInit(void *NotUsed){
21504 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
21505 int cpuCount;
21506 size_t len;
21507 if( _sqliteZone_ ){
21508 return SQLITE_OK;
21510 len = sizeof(cpuCount);
21511 /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
21512 sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
21513 if( cpuCount>1 ){
21514 /* defer MT decisions to system malloc */
21515 _sqliteZone_ = malloc_default_zone();
21516 }else{
21517 /* only 1 core, use our own zone to contention over global locks,
21518 ** e.g. we have our own dedicated locks */
21519 _sqliteZone_ = malloc_create_zone(4096, 0);
21520 malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
21522 #endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
21523 UNUSED_PARAMETER(NotUsed);
21524 return SQLITE_OK;
21528 ** Deinitialize this module.
21530 static void sqlite3MemShutdown(void *NotUsed){
21531 UNUSED_PARAMETER(NotUsed);
21532 return;
21536 ** This routine is the only routine in this file with external linkage.
21538 ** Populate the low-level memory allocation function pointers in
21539 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
21541 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
21542 static const sqlite3_mem_methods defaultMethods = {
21543 sqlite3MemMalloc,
21544 sqlite3MemFree,
21545 sqlite3MemRealloc,
21546 sqlite3MemSize,
21547 sqlite3MemRoundup,
21548 sqlite3MemInit,
21549 sqlite3MemShutdown,
21552 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
21555 #endif /* SQLITE_SYSTEM_MALLOC */
21557 /************** End of mem1.c ************************************************/
21558 /************** Begin file mem2.c ********************************************/
21560 ** 2007 August 15
21562 ** The author disclaims copyright to this source code. In place of
21563 ** a legal notice, here is a blessing:
21565 ** May you do good and not evil.
21566 ** May you find forgiveness for yourself and forgive others.
21567 ** May you share freely, never taking more than you give.
21569 *************************************************************************
21571 ** This file contains low-level memory allocation drivers for when
21572 ** SQLite will use the standard C-library malloc/realloc/free interface
21573 ** to obtain the memory it needs while adding lots of additional debugging
21574 ** information to each allocation in order to help detect and fix memory
21575 ** leaks and memory usage errors.
21577 ** This file contains implementations of the low-level memory allocation
21578 ** routines specified in the sqlite3_mem_methods object.
21580 /* #include "sqliteInt.h" */
21583 ** This version of the memory allocator is used only if the
21584 ** SQLITE_MEMDEBUG macro is defined
21586 #ifdef SQLITE_MEMDEBUG
21589 ** The backtrace functionality is only available with GLIBC
21591 #ifdef __GLIBC__
21592 extern int backtrace(void**,int);
21593 extern void backtrace_symbols_fd(void*const*,int,int);
21594 #else
21595 # define backtrace(A,B) 1
21596 # define backtrace_symbols_fd(A,B,C)
21597 #endif
21598 /* #include <stdio.h> */
21601 ** Each memory allocation looks like this:
21603 ** ------------------------------------------------------------------------
21604 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
21605 ** ------------------------------------------------------------------------
21607 ** The application code sees only a pointer to the allocation. We have
21608 ** to back up from the allocation pointer to find the MemBlockHdr. The
21609 ** MemBlockHdr tells us the size of the allocation and the number of
21610 ** backtrace pointers. There is also a guard word at the end of the
21611 ** MemBlockHdr.
21613 struct MemBlockHdr {
21614 i64 iSize; /* Size of this allocation */
21615 struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
21616 char nBacktrace; /* Number of backtraces on this alloc */
21617 char nBacktraceSlots; /* Available backtrace slots */
21618 u8 nTitle; /* Bytes of title; includes '\0' */
21619 u8 eType; /* Allocation type code */
21620 int iForeGuard; /* Guard word for sanity */
21624 ** Guard words
21626 #define FOREGUARD 0x80F5E153
21627 #define REARGUARD 0xE4676B53
21630 ** Number of malloc size increments to track.
21632 #define NCSIZE 1000
21635 ** All of the static variables used by this module are collected
21636 ** into a single structure named "mem". This is to keep the
21637 ** static variables organized and to reduce namespace pollution
21638 ** when this module is combined with other in the amalgamation.
21640 static struct {
21643 ** Mutex to control access to the memory allocation subsystem.
21645 sqlite3_mutex *mutex;
21648 ** Head and tail of a linked list of all outstanding allocations
21650 struct MemBlockHdr *pFirst;
21651 struct MemBlockHdr *pLast;
21654 ** The number of levels of backtrace to save in new allocations.
21656 int nBacktrace;
21657 void (*xBacktrace)(int, int, void **);
21660 ** Title text to insert in front of each block
21662 int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
21663 char zTitle[100]; /* The title text */
21666 ** sqlite3MallocDisallow() increments the following counter.
21667 ** sqlite3MallocAllow() decrements it.
21669 int disallow; /* Do not allow memory allocation */
21672 ** Gather statistics on the sizes of memory allocations.
21673 ** nAlloc[i] is the number of allocation attempts of i*8
21674 ** bytes. i==NCSIZE is the number of allocation attempts for
21675 ** sizes more than NCSIZE*8 bytes.
21677 int nAlloc[NCSIZE]; /* Total number of allocations */
21678 int nCurrent[NCSIZE]; /* Current number of allocations */
21679 int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
21681 } mem;
21685 ** Adjust memory usage statistics
21687 static void adjustStats(int iSize, int increment){
21688 int i = ROUND8(iSize)/8;
21689 if( i>NCSIZE-1 ){
21690 i = NCSIZE - 1;
21692 if( increment>0 ){
21693 mem.nAlloc[i]++;
21694 mem.nCurrent[i]++;
21695 if( mem.nCurrent[i]>mem.mxCurrent[i] ){
21696 mem.mxCurrent[i] = mem.nCurrent[i];
21698 }else{
21699 mem.nCurrent[i]--;
21700 assert( mem.nCurrent[i]>=0 );
21705 ** Given an allocation, find the MemBlockHdr for that allocation.
21707 ** This routine checks the guards at either end of the allocation and
21708 ** if they are incorrect it asserts.
21710 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
21711 struct MemBlockHdr *p;
21712 int *pInt;
21713 u8 *pU8;
21714 int nReserve;
21716 p = (struct MemBlockHdr*)pAllocation;
21717 p--;
21718 assert( p->iForeGuard==(int)FOREGUARD );
21719 nReserve = ROUND8(p->iSize);
21720 pInt = (int*)pAllocation;
21721 pU8 = (u8*)pAllocation;
21722 assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
21723 /* This checks any of the "extra" bytes allocated due
21724 ** to rounding up to an 8 byte boundary to ensure
21725 ** they haven't been overwritten.
21727 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
21728 return p;
21732 ** Return the number of bytes currently allocated at address p.
21734 static int sqlite3MemSize(void *p){
21735 struct MemBlockHdr *pHdr;
21736 if( !p ){
21737 return 0;
21739 pHdr = sqlite3MemsysGetHeader(p);
21740 return (int)pHdr->iSize;
21744 ** Initialize the memory allocation subsystem.
21746 static int sqlite3MemInit(void *NotUsed){
21747 UNUSED_PARAMETER(NotUsed);
21748 assert( (sizeof(struct MemBlockHdr)&7) == 0 );
21749 if( !sqlite3GlobalConfig.bMemstat ){
21750 /* If memory status is enabled, then the malloc.c wrapper will already
21751 ** hold the STATIC_MEM mutex when the routines here are invoked. */
21752 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
21754 return SQLITE_OK;
21758 ** Deinitialize the memory allocation subsystem.
21760 static void sqlite3MemShutdown(void *NotUsed){
21761 UNUSED_PARAMETER(NotUsed);
21762 mem.mutex = 0;
21766 ** Round up a request size to the next valid allocation size.
21768 static int sqlite3MemRoundup(int n){
21769 return ROUND8(n);
21773 ** Fill a buffer with pseudo-random bytes. This is used to preset
21774 ** the content of a new memory allocation to unpredictable values and
21775 ** to clear the content of a freed allocation to unpredictable values.
21777 static void randomFill(char *pBuf, int nByte){
21778 unsigned int x, y, r;
21779 x = SQLITE_PTR_TO_INT(pBuf);
21780 y = nByte | 1;
21781 while( nByte >= 4 ){
21782 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
21783 y = y*1103515245 + 12345;
21784 r = x ^ y;
21785 *(int*)pBuf = r;
21786 pBuf += 4;
21787 nByte -= 4;
21789 while( nByte-- > 0 ){
21790 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
21791 y = y*1103515245 + 12345;
21792 r = x ^ y;
21793 *(pBuf++) = r & 0xff;
21798 ** Allocate nByte bytes of memory.
21800 static void *sqlite3MemMalloc(int nByte){
21801 struct MemBlockHdr *pHdr;
21802 void **pBt;
21803 char *z;
21804 int *pInt;
21805 void *p = 0;
21806 int totalSize;
21807 int nReserve;
21808 sqlite3_mutex_enter(mem.mutex);
21809 assert( mem.disallow==0 );
21810 nReserve = ROUND8(nByte);
21811 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
21812 mem.nBacktrace*sizeof(void*) + mem.nTitle;
21813 p = malloc(totalSize);
21814 if( p ){
21815 z = p;
21816 pBt = (void**)&z[mem.nTitle];
21817 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
21818 pHdr->pNext = 0;
21819 pHdr->pPrev = mem.pLast;
21820 if( mem.pLast ){
21821 mem.pLast->pNext = pHdr;
21822 }else{
21823 mem.pFirst = pHdr;
21825 mem.pLast = pHdr;
21826 pHdr->iForeGuard = FOREGUARD;
21827 pHdr->eType = MEMTYPE_HEAP;
21828 pHdr->nBacktraceSlots = mem.nBacktrace;
21829 pHdr->nTitle = mem.nTitle;
21830 if( mem.nBacktrace ){
21831 void *aAddr[40];
21832 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
21833 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
21834 assert(pBt[0]);
21835 if( mem.xBacktrace ){
21836 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
21838 }else{
21839 pHdr->nBacktrace = 0;
21841 if( mem.nTitle ){
21842 memcpy(z, mem.zTitle, mem.nTitle);
21844 pHdr->iSize = nByte;
21845 adjustStats(nByte, +1);
21846 pInt = (int*)&pHdr[1];
21847 pInt[nReserve/sizeof(int)] = REARGUARD;
21848 randomFill((char*)pInt, nByte);
21849 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
21850 p = (void*)pInt;
21852 sqlite3_mutex_leave(mem.mutex);
21853 return p;
21857 ** Free memory.
21859 static void sqlite3MemFree(void *pPrior){
21860 struct MemBlockHdr *pHdr;
21861 void **pBt;
21862 char *z;
21863 assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
21864 || mem.mutex!=0 );
21865 pHdr = sqlite3MemsysGetHeader(pPrior);
21866 pBt = (void**)pHdr;
21867 pBt -= pHdr->nBacktraceSlots;
21868 sqlite3_mutex_enter(mem.mutex);
21869 if( pHdr->pPrev ){
21870 assert( pHdr->pPrev->pNext==pHdr );
21871 pHdr->pPrev->pNext = pHdr->pNext;
21872 }else{
21873 assert( mem.pFirst==pHdr );
21874 mem.pFirst = pHdr->pNext;
21876 if( pHdr->pNext ){
21877 assert( pHdr->pNext->pPrev==pHdr );
21878 pHdr->pNext->pPrev = pHdr->pPrev;
21879 }else{
21880 assert( mem.pLast==pHdr );
21881 mem.pLast = pHdr->pPrev;
21883 z = (char*)pBt;
21884 z -= pHdr->nTitle;
21885 adjustStats((int)pHdr->iSize, -1);
21886 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
21887 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
21888 free(z);
21889 sqlite3_mutex_leave(mem.mutex);
21893 ** Change the size of an existing memory allocation.
21895 ** For this debugging implementation, we *always* make a copy of the
21896 ** allocation into a new place in memory. In this way, if the
21897 ** higher level code is using pointer to the old allocation, it is
21898 ** much more likely to break and we are much more liking to find
21899 ** the error.
21901 static void *sqlite3MemRealloc(void *pPrior, int nByte){
21902 struct MemBlockHdr *pOldHdr;
21903 void *pNew;
21904 assert( mem.disallow==0 );
21905 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
21906 pOldHdr = sqlite3MemsysGetHeader(pPrior);
21907 pNew = sqlite3MemMalloc(nByte);
21908 if( pNew ){
21909 memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
21910 if( nByte>pOldHdr->iSize ){
21911 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
21913 sqlite3MemFree(pPrior);
21915 return pNew;
21919 ** Populate the low-level memory allocation function pointers in
21920 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
21922 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
21923 static const sqlite3_mem_methods defaultMethods = {
21924 sqlite3MemMalloc,
21925 sqlite3MemFree,
21926 sqlite3MemRealloc,
21927 sqlite3MemSize,
21928 sqlite3MemRoundup,
21929 sqlite3MemInit,
21930 sqlite3MemShutdown,
21933 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
21937 ** Set the "type" of an allocation.
21939 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
21940 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21941 struct MemBlockHdr *pHdr;
21942 pHdr = sqlite3MemsysGetHeader(p);
21943 assert( pHdr->iForeGuard==FOREGUARD );
21944 pHdr->eType = eType;
21949 ** Return TRUE if the mask of type in eType matches the type of the
21950 ** allocation p. Also return true if p==NULL.
21952 ** This routine is designed for use within an assert() statement, to
21953 ** verify the type of an allocation. For example:
21955 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21957 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
21958 int rc = 1;
21959 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21960 struct MemBlockHdr *pHdr;
21961 pHdr = sqlite3MemsysGetHeader(p);
21962 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
21963 if( (pHdr->eType&eType)==0 ){
21964 rc = 0;
21967 return rc;
21971 ** Return TRUE if the mask of type in eType matches no bits of the type of the
21972 ** allocation p. Also return true if p==NULL.
21974 ** This routine is designed for use within an assert() statement, to
21975 ** verify the type of an allocation. For example:
21977 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
21979 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
21980 int rc = 1;
21981 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21982 struct MemBlockHdr *pHdr;
21983 pHdr = sqlite3MemsysGetHeader(p);
21984 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
21985 if( (pHdr->eType&eType)!=0 ){
21986 rc = 0;
21989 return rc;
21993 ** Set the number of backtrace levels kept for each allocation.
21994 ** A value of zero turns off backtracing. The number is always rounded
21995 ** up to a multiple of 2.
21997 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
21998 if( depth<0 ){ depth = 0; }
21999 if( depth>20 ){ depth = 20; }
22000 depth = (depth+1)&0xfe;
22001 mem.nBacktrace = depth;
22004 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
22005 mem.xBacktrace = xBacktrace;
22009 ** Set the title string for subsequent allocations.
22011 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
22012 unsigned int n = sqlite3Strlen30(zTitle) + 1;
22013 sqlite3_mutex_enter(mem.mutex);
22014 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
22015 memcpy(mem.zTitle, zTitle, n);
22016 mem.zTitle[n] = 0;
22017 mem.nTitle = ROUND8(n);
22018 sqlite3_mutex_leave(mem.mutex);
22021 SQLITE_PRIVATE void sqlite3MemdebugSync(){
22022 struct MemBlockHdr *pHdr;
22023 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
22024 void **pBt = (void**)pHdr;
22025 pBt -= pHdr->nBacktraceSlots;
22026 mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
22031 ** Open the file indicated and write a log of all unfreed memory
22032 ** allocations into that log.
22034 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
22035 FILE *out;
22036 struct MemBlockHdr *pHdr;
22037 void **pBt;
22038 int i;
22039 out = fopen(zFilename, "w");
22040 if( out==0 ){
22041 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
22042 zFilename);
22043 return;
22045 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
22046 char *z = (char*)pHdr;
22047 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
22048 fprintf(out, "**** %lld bytes at %p from %s ****\n",
22049 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
22050 if( pHdr->nBacktrace ){
22051 fflush(out);
22052 pBt = (void**)pHdr;
22053 pBt -= pHdr->nBacktraceSlots;
22054 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
22055 fprintf(out, "\n");
22058 fprintf(out, "COUNTS:\n");
22059 for(i=0; i<NCSIZE-1; i++){
22060 if( mem.nAlloc[i] ){
22061 fprintf(out, " %5d: %10d %10d %10d\n",
22062 i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
22065 if( mem.nAlloc[NCSIZE-1] ){
22066 fprintf(out, " %5d: %10d %10d %10d\n",
22067 NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
22068 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
22070 fclose(out);
22074 ** Return the number of times sqlite3MemMalloc() has been called.
22076 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
22077 int i;
22078 int nTotal = 0;
22079 for(i=0; i<NCSIZE; i++){
22080 nTotal += mem.nAlloc[i];
22082 return nTotal;
22086 #endif /* SQLITE_MEMDEBUG */
22088 /************** End of mem2.c ************************************************/
22089 /************** Begin file mem3.c ********************************************/
22091 ** 2007 October 14
22093 ** The author disclaims copyright to this source code. In place of
22094 ** a legal notice, here is a blessing:
22096 ** May you do good and not evil.
22097 ** May you find forgiveness for yourself and forgive others.
22098 ** May you share freely, never taking more than you give.
22100 *************************************************************************
22101 ** This file contains the C functions that implement a memory
22102 ** allocation subsystem for use by SQLite.
22104 ** This version of the memory allocation subsystem omits all
22105 ** use of malloc(). The SQLite user supplies a block of memory
22106 ** before calling sqlite3_initialize() from which allocations
22107 ** are made and returned by the xMalloc() and xRealloc()
22108 ** implementations. Once sqlite3_initialize() has been called,
22109 ** the amount of memory available to SQLite is fixed and cannot
22110 ** be changed.
22112 ** This version of the memory allocation subsystem is included
22113 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
22115 /* #include "sqliteInt.h" */
22118 ** This version of the memory allocator is only built into the library
22119 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
22120 ** mean that the library will use a memory-pool by default, just that
22121 ** it is available. The mempool allocator is activated by calling
22122 ** sqlite3_config().
22124 #ifdef SQLITE_ENABLE_MEMSYS3
22127 ** Maximum size (in Mem3Blocks) of a "small" chunk.
22129 #define MX_SMALL 10
22133 ** Number of freelist hash slots
22135 #define N_HASH 61
22138 ** A memory allocation (also called a "chunk") consists of two or
22139 ** more blocks where each block is 8 bytes. The first 8 bytes are
22140 ** a header that is not returned to the user.
22142 ** A chunk is two or more blocks that is either checked out or
22143 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
22144 ** size of the allocation in blocks if the allocation is free.
22145 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
22146 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
22147 ** is true if the previous chunk is checked out and false if the
22148 ** previous chunk is free. The u.hdr.prevSize field is the size of
22149 ** the previous chunk in blocks if the previous chunk is on the
22150 ** freelist. If the previous chunk is checked out, then
22151 ** u.hdr.prevSize can be part of the data for that chunk and should
22152 ** not be read or written.
22154 ** We often identify a chunk by its index in mem3.aPool[]. When
22155 ** this is done, the chunk index refers to the second block of
22156 ** the chunk. In this way, the first chunk has an index of 1.
22157 ** A chunk index of 0 means "no such chunk" and is the equivalent
22158 ** of a NULL pointer.
22160 ** The second block of free chunks is of the form u.list. The
22161 ** two fields form a double-linked list of chunks of related sizes.
22162 ** Pointers to the head of the list are stored in mem3.aiSmall[]
22163 ** for smaller chunks and mem3.aiHash[] for larger chunks.
22165 ** The second block of a chunk is user data if the chunk is checked
22166 ** out. If a chunk is checked out, the user data may extend into
22167 ** the u.hdr.prevSize value of the following chunk.
22169 typedef struct Mem3Block Mem3Block;
22170 struct Mem3Block {
22171 union {
22172 struct {
22173 u32 prevSize; /* Size of previous chunk in Mem3Block elements */
22174 u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
22175 } hdr;
22176 struct {
22177 u32 next; /* Index in mem3.aPool[] of next free chunk */
22178 u32 prev; /* Index in mem3.aPool[] of previous free chunk */
22179 } list;
22180 } u;
22184 ** All of the static variables used by this module are collected
22185 ** into a single structure named "mem3". This is to keep the
22186 ** static variables organized and to reduce namespace pollution
22187 ** when this module is combined with other in the amalgamation.
22189 static SQLITE_WSD struct Mem3Global {
22191 ** Memory available for allocation. nPool is the size of the array
22192 ** (in Mem3Blocks) pointed to by aPool less 2.
22194 u32 nPool;
22195 Mem3Block *aPool;
22198 ** True if we are evaluating an out-of-memory callback.
22200 int alarmBusy;
22203 ** Mutex to control access to the memory allocation subsystem.
22205 sqlite3_mutex *mutex;
22208 ** The minimum amount of free space that we have seen.
22210 u32 mnMaster;
22213 ** iMaster is the index of the master chunk. Most new allocations
22214 ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
22215 ** of the current master. iMaster is 0 if there is not master chunk.
22216 ** The master chunk is not in either the aiHash[] or aiSmall[].
22218 u32 iMaster;
22219 u32 szMaster;
22222 ** Array of lists of free blocks according to the block size
22223 ** for smaller chunks, or a hash on the block size for larger
22224 ** chunks.
22226 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
22227 u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
22228 } mem3 = { 97535575 };
22230 #define mem3 GLOBAL(struct Mem3Global, mem3)
22233 ** Unlink the chunk at mem3.aPool[i] from list it is currently
22234 ** on. *pRoot is the list that i is a member of.
22236 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
22237 u32 next = mem3.aPool[i].u.list.next;
22238 u32 prev = mem3.aPool[i].u.list.prev;
22239 assert( sqlite3_mutex_held(mem3.mutex) );
22240 if( prev==0 ){
22241 *pRoot = next;
22242 }else{
22243 mem3.aPool[prev].u.list.next = next;
22245 if( next ){
22246 mem3.aPool[next].u.list.prev = prev;
22248 mem3.aPool[i].u.list.next = 0;
22249 mem3.aPool[i].u.list.prev = 0;
22253 ** Unlink the chunk at index i from
22254 ** whatever list is currently a member of.
22256 static void memsys3Unlink(u32 i){
22257 u32 size, hash;
22258 assert( sqlite3_mutex_held(mem3.mutex) );
22259 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
22260 assert( i>=1 );
22261 size = mem3.aPool[i-1].u.hdr.size4x/4;
22262 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
22263 assert( size>=2 );
22264 if( size <= MX_SMALL ){
22265 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
22266 }else{
22267 hash = size % N_HASH;
22268 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
22273 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
22274 ** at *pRoot.
22276 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
22277 assert( sqlite3_mutex_held(mem3.mutex) );
22278 mem3.aPool[i].u.list.next = *pRoot;
22279 mem3.aPool[i].u.list.prev = 0;
22280 if( *pRoot ){
22281 mem3.aPool[*pRoot].u.list.prev = i;
22283 *pRoot = i;
22287 ** Link the chunk at index i into either the appropriate
22288 ** small chunk list, or into the large chunk hash table.
22290 static void memsys3Link(u32 i){
22291 u32 size, hash;
22292 assert( sqlite3_mutex_held(mem3.mutex) );
22293 assert( i>=1 );
22294 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
22295 size = mem3.aPool[i-1].u.hdr.size4x/4;
22296 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
22297 assert( size>=2 );
22298 if( size <= MX_SMALL ){
22299 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
22300 }else{
22301 hash = size % N_HASH;
22302 memsys3LinkIntoList(i, &mem3.aiHash[hash]);
22307 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
22308 ** will already be held (obtained by code in malloc.c) if
22309 ** sqlite3GlobalConfig.bMemStat is true.
22311 static void memsys3Enter(void){
22312 if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
22313 mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
22315 sqlite3_mutex_enter(mem3.mutex);
22317 static void memsys3Leave(void){
22318 sqlite3_mutex_leave(mem3.mutex);
22322 ** Called when we are unable to satisfy an allocation of nBytes.
22324 static void memsys3OutOfMemory(int nByte){
22325 if( !mem3.alarmBusy ){
22326 mem3.alarmBusy = 1;
22327 assert( sqlite3_mutex_held(mem3.mutex) );
22328 sqlite3_mutex_leave(mem3.mutex);
22329 sqlite3_release_memory(nByte);
22330 sqlite3_mutex_enter(mem3.mutex);
22331 mem3.alarmBusy = 0;
22337 ** Chunk i is a free chunk that has been unlinked. Adjust its
22338 ** size parameters for check-out and return a pointer to the
22339 ** user portion of the chunk.
22341 static void *memsys3Checkout(u32 i, u32 nBlock){
22342 u32 x;
22343 assert( sqlite3_mutex_held(mem3.mutex) );
22344 assert( i>=1 );
22345 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
22346 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
22347 x = mem3.aPool[i-1].u.hdr.size4x;
22348 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
22349 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
22350 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
22351 return &mem3.aPool[i];
22355 ** Carve a piece off of the end of the mem3.iMaster free chunk.
22356 ** Return a pointer to the new allocation. Or, if the master chunk
22357 ** is not large enough, return 0.
22359 static void *memsys3FromMaster(u32 nBlock){
22360 assert( sqlite3_mutex_held(mem3.mutex) );
22361 assert( mem3.szMaster>=nBlock );
22362 if( nBlock>=mem3.szMaster-1 ){
22363 /* Use the entire master */
22364 void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
22365 mem3.iMaster = 0;
22366 mem3.szMaster = 0;
22367 mem3.mnMaster = 0;
22368 return p;
22369 }else{
22370 /* Split the master block. Return the tail. */
22371 u32 newi, x;
22372 newi = mem3.iMaster + mem3.szMaster - nBlock;
22373 assert( newi > mem3.iMaster+1 );
22374 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
22375 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
22376 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
22377 mem3.szMaster -= nBlock;
22378 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
22379 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
22380 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
22381 if( mem3.szMaster < mem3.mnMaster ){
22382 mem3.mnMaster = mem3.szMaster;
22384 return (void*)&mem3.aPool[newi];
22389 ** *pRoot is the head of a list of free chunks of the same size
22390 ** or same size hash. In other words, *pRoot is an entry in either
22391 ** mem3.aiSmall[] or mem3.aiHash[].
22393 ** This routine examines all entries on the given list and tries
22394 ** to coalesce each entries with adjacent free chunks.
22396 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
22397 ** the current mem3.iMaster with the new larger chunk. In order for
22398 ** this mem3.iMaster replacement to work, the master chunk must be
22399 ** linked into the hash tables. That is not the normal state of
22400 ** affairs, of course. The calling routine must link the master
22401 ** chunk before invoking this routine, then must unlink the (possibly
22402 ** changed) master chunk once this routine has finished.
22404 static void memsys3Merge(u32 *pRoot){
22405 u32 iNext, prev, size, i, x;
22407 assert( sqlite3_mutex_held(mem3.mutex) );
22408 for(i=*pRoot; i>0; i=iNext){
22409 iNext = mem3.aPool[i].u.list.next;
22410 size = mem3.aPool[i-1].u.hdr.size4x;
22411 assert( (size&1)==0 );
22412 if( (size&2)==0 ){
22413 memsys3UnlinkFromList(i, pRoot);
22414 assert( i > mem3.aPool[i-1].u.hdr.prevSize );
22415 prev = i - mem3.aPool[i-1].u.hdr.prevSize;
22416 if( prev==iNext ){
22417 iNext = mem3.aPool[prev].u.list.next;
22419 memsys3Unlink(prev);
22420 size = i + size/4 - prev;
22421 x = mem3.aPool[prev-1].u.hdr.size4x & 2;
22422 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
22423 mem3.aPool[prev+size-1].u.hdr.prevSize = size;
22424 memsys3Link(prev);
22425 i = prev;
22426 }else{
22427 size /= 4;
22429 if( size>mem3.szMaster ){
22430 mem3.iMaster = i;
22431 mem3.szMaster = size;
22437 ** Return a block of memory of at least nBytes in size.
22438 ** Return NULL if unable.
22440 ** This function assumes that the necessary mutexes, if any, are
22441 ** already held by the caller. Hence "Unsafe".
22443 static void *memsys3MallocUnsafe(int nByte){
22444 u32 i;
22445 u32 nBlock;
22446 u32 toFree;
22448 assert( sqlite3_mutex_held(mem3.mutex) );
22449 assert( sizeof(Mem3Block)==8 );
22450 if( nByte<=12 ){
22451 nBlock = 2;
22452 }else{
22453 nBlock = (nByte + 11)/8;
22455 assert( nBlock>=2 );
22457 /* STEP 1:
22458 ** Look for an entry of the correct size in either the small
22459 ** chunk table or in the large chunk hash table. This is
22460 ** successful most of the time (about 9 times out of 10).
22462 if( nBlock <= MX_SMALL ){
22463 i = mem3.aiSmall[nBlock-2];
22464 if( i>0 ){
22465 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
22466 return memsys3Checkout(i, nBlock);
22468 }else{
22469 int hash = nBlock % N_HASH;
22470 for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
22471 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
22472 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
22473 return memsys3Checkout(i, nBlock);
22478 /* STEP 2:
22479 ** Try to satisfy the allocation by carving a piece off of the end
22480 ** of the master chunk. This step usually works if step 1 fails.
22482 if( mem3.szMaster>=nBlock ){
22483 return memsys3FromMaster(nBlock);
22487 /* STEP 3:
22488 ** Loop through the entire memory pool. Coalesce adjacent free
22489 ** chunks. Recompute the master chunk as the largest free chunk.
22490 ** Then try again to satisfy the allocation by carving a piece off
22491 ** of the end of the master chunk. This step happens very
22492 ** rarely (we hope!)
22494 for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
22495 memsys3OutOfMemory(toFree);
22496 if( mem3.iMaster ){
22497 memsys3Link(mem3.iMaster);
22498 mem3.iMaster = 0;
22499 mem3.szMaster = 0;
22501 for(i=0; i<N_HASH; i++){
22502 memsys3Merge(&mem3.aiHash[i]);
22504 for(i=0; i<MX_SMALL-1; i++){
22505 memsys3Merge(&mem3.aiSmall[i]);
22507 if( mem3.szMaster ){
22508 memsys3Unlink(mem3.iMaster);
22509 if( mem3.szMaster>=nBlock ){
22510 return memsys3FromMaster(nBlock);
22515 /* If none of the above worked, then we fail. */
22516 return 0;
22520 ** Free an outstanding memory allocation.
22522 ** This function assumes that the necessary mutexes, if any, are
22523 ** already held by the caller. Hence "Unsafe".
22525 static void memsys3FreeUnsafe(void *pOld){
22526 Mem3Block *p = (Mem3Block*)pOld;
22527 int i;
22528 u32 size, x;
22529 assert( sqlite3_mutex_held(mem3.mutex) );
22530 assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
22531 i = p - mem3.aPool;
22532 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
22533 size = mem3.aPool[i-1].u.hdr.size4x/4;
22534 assert( i+size<=mem3.nPool+1 );
22535 mem3.aPool[i-1].u.hdr.size4x &= ~1;
22536 mem3.aPool[i+size-1].u.hdr.prevSize = size;
22537 mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
22538 memsys3Link(i);
22540 /* Try to expand the master using the newly freed chunk */
22541 if( mem3.iMaster ){
22542 while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
22543 size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
22544 mem3.iMaster -= size;
22545 mem3.szMaster += size;
22546 memsys3Unlink(mem3.iMaster);
22547 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
22548 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
22549 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
22551 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
22552 while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
22553 memsys3Unlink(mem3.iMaster+mem3.szMaster);
22554 mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
22555 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
22556 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
22562 ** Return the size of an outstanding allocation, in bytes. The
22563 ** size returned omits the 8-byte header overhead. This only
22564 ** works for chunks that are currently checked out.
22566 static int memsys3Size(void *p){
22567 Mem3Block *pBlock;
22568 assert( p!=0 );
22569 pBlock = (Mem3Block*)p;
22570 assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
22571 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
22575 ** Round up a request size to the next valid allocation size.
22577 static int memsys3Roundup(int n){
22578 if( n<=12 ){
22579 return 12;
22580 }else{
22581 return ((n+11)&~7) - 4;
22586 ** Allocate nBytes of memory.
22588 static void *memsys3Malloc(int nBytes){
22589 sqlite3_int64 *p;
22590 assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
22591 memsys3Enter();
22592 p = memsys3MallocUnsafe(nBytes);
22593 memsys3Leave();
22594 return (void*)p;
22598 ** Free memory.
22600 static void memsys3Free(void *pPrior){
22601 assert( pPrior );
22602 memsys3Enter();
22603 memsys3FreeUnsafe(pPrior);
22604 memsys3Leave();
22608 ** Change the size of an existing memory allocation
22610 static void *memsys3Realloc(void *pPrior, int nBytes){
22611 int nOld;
22612 void *p;
22613 if( pPrior==0 ){
22614 return sqlite3_malloc(nBytes);
22616 if( nBytes<=0 ){
22617 sqlite3_free(pPrior);
22618 return 0;
22620 nOld = memsys3Size(pPrior);
22621 if( nBytes<=nOld && nBytes>=nOld-128 ){
22622 return pPrior;
22624 memsys3Enter();
22625 p = memsys3MallocUnsafe(nBytes);
22626 if( p ){
22627 if( nOld<nBytes ){
22628 memcpy(p, pPrior, nOld);
22629 }else{
22630 memcpy(p, pPrior, nBytes);
22632 memsys3FreeUnsafe(pPrior);
22634 memsys3Leave();
22635 return p;
22639 ** Initialize this module.
22641 static int memsys3Init(void *NotUsed){
22642 UNUSED_PARAMETER(NotUsed);
22643 if( !sqlite3GlobalConfig.pHeap ){
22644 return SQLITE_ERROR;
22647 /* Store a pointer to the memory block in global structure mem3. */
22648 assert( sizeof(Mem3Block)==8 );
22649 mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
22650 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
22652 /* Initialize the master block. */
22653 mem3.szMaster = mem3.nPool;
22654 mem3.mnMaster = mem3.szMaster;
22655 mem3.iMaster = 1;
22656 mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
22657 mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
22658 mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
22660 return SQLITE_OK;
22664 ** Deinitialize this module.
22666 static void memsys3Shutdown(void *NotUsed){
22667 UNUSED_PARAMETER(NotUsed);
22668 mem3.mutex = 0;
22669 return;
22675 ** Open the file indicated and write a log of all unfreed memory
22676 ** allocations into that log.
22678 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
22679 #ifdef SQLITE_DEBUG
22680 FILE *out;
22681 u32 i, j;
22682 u32 size;
22683 if( zFilename==0 || zFilename[0]==0 ){
22684 out = stdout;
22685 }else{
22686 out = fopen(zFilename, "w");
22687 if( out==0 ){
22688 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
22689 zFilename);
22690 return;
22693 memsys3Enter();
22694 fprintf(out, "CHUNKS:\n");
22695 for(i=1; i<=mem3.nPool; i+=size/4){
22696 size = mem3.aPool[i-1].u.hdr.size4x;
22697 if( size/4<=1 ){
22698 fprintf(out, "%p size error\n", &mem3.aPool[i]);
22699 assert( 0 );
22700 break;
22702 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
22703 fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
22704 assert( 0 );
22705 break;
22707 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
22708 fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
22709 assert( 0 );
22710 break;
22712 if( size&1 ){
22713 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
22714 }else{
22715 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
22716 i==mem3.iMaster ? " **master**" : "");
22719 for(i=0; i<MX_SMALL-1; i++){
22720 if( mem3.aiSmall[i]==0 ) continue;
22721 fprintf(out, "small(%2d):", i);
22722 for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
22723 fprintf(out, " %p(%d)", &mem3.aPool[j],
22724 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
22726 fprintf(out, "\n");
22728 for(i=0; i<N_HASH; i++){
22729 if( mem3.aiHash[i]==0 ) continue;
22730 fprintf(out, "hash(%2d):", i);
22731 for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
22732 fprintf(out, " %p(%d)", &mem3.aPool[j],
22733 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
22735 fprintf(out, "\n");
22737 fprintf(out, "master=%d\n", mem3.iMaster);
22738 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
22739 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
22740 sqlite3_mutex_leave(mem3.mutex);
22741 if( out==stdout ){
22742 fflush(stdout);
22743 }else{
22744 fclose(out);
22746 #else
22747 UNUSED_PARAMETER(zFilename);
22748 #endif
22752 ** This routine is the only routine in this file with external
22753 ** linkage.
22755 ** Populate the low-level memory allocation function pointers in
22756 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
22757 ** arguments specify the block of memory to manage.
22759 ** This routine is only called by sqlite3_config(), and therefore
22760 ** is not required to be threadsafe (it is not).
22762 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
22763 static const sqlite3_mem_methods mempoolMethods = {
22764 memsys3Malloc,
22765 memsys3Free,
22766 memsys3Realloc,
22767 memsys3Size,
22768 memsys3Roundup,
22769 memsys3Init,
22770 memsys3Shutdown,
22773 return &mempoolMethods;
22776 #endif /* SQLITE_ENABLE_MEMSYS3 */
22778 /************** End of mem3.c ************************************************/
22779 /************** Begin file mem5.c ********************************************/
22781 ** 2007 October 14
22783 ** The author disclaims copyright to this source code. In place of
22784 ** a legal notice, here is a blessing:
22786 ** May you do good and not evil.
22787 ** May you find forgiveness for yourself and forgive others.
22788 ** May you share freely, never taking more than you give.
22790 *************************************************************************
22791 ** This file contains the C functions that implement a memory
22792 ** allocation subsystem for use by SQLite.
22794 ** This version of the memory allocation subsystem omits all
22795 ** use of malloc(). The application gives SQLite a block of memory
22796 ** before calling sqlite3_initialize() from which allocations
22797 ** are made and returned by the xMalloc() and xRealloc()
22798 ** implementations. Once sqlite3_initialize() has been called,
22799 ** the amount of memory available to SQLite is fixed and cannot
22800 ** be changed.
22802 ** This version of the memory allocation subsystem is included
22803 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
22805 ** This memory allocator uses the following algorithm:
22807 ** 1. All memory allocation sizes are rounded up to a power of 2.
22809 ** 2. If two adjacent free blocks are the halves of a larger block,
22810 ** then the two blocks are coalesced into the single larger block.
22812 ** 3. New memory is allocated from the first available free block.
22814 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
22815 ** Concerning Dynamic Storage Allocation". Journal of the Association for
22816 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
22818 ** Let n be the size of the largest allocation divided by the minimum
22819 ** allocation size (after rounding all sizes up to a power of 2.) Let M
22820 ** be the maximum amount of memory ever outstanding at one time. Let
22821 ** N be the total amount of memory available for allocation. Robson
22822 ** proved that this memory allocator will never breakdown due to
22823 ** fragmentation as long as the following constraint holds:
22825 ** N >= M*(1 + log2(n)/2) - n + 1
22827 ** The sqlite3_status() logic tracks the maximum values of n and M so
22828 ** that an application can, at any time, verify this constraint.
22830 /* #include "sqliteInt.h" */
22833 ** This version of the memory allocator is used only when
22834 ** SQLITE_ENABLE_MEMSYS5 is defined.
22836 #ifdef SQLITE_ENABLE_MEMSYS5
22839 ** A minimum allocation is an instance of the following structure.
22840 ** Larger allocations are an array of these structures where the
22841 ** size of the array is a power of 2.
22843 ** The size of this object must be a power of two. That fact is
22844 ** verified in memsys5Init().
22846 typedef struct Mem5Link Mem5Link;
22847 struct Mem5Link {
22848 int next; /* Index of next free chunk */
22849 int prev; /* Index of previous free chunk */
22853 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
22854 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
22855 ** it is not actually possible to reach this limit.
22857 #define LOGMAX 30
22860 ** Masks used for mem5.aCtrl[] elements.
22862 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
22863 #define CTRL_FREE 0x20 /* True if not checked out */
22866 ** All of the static variables used by this module are collected
22867 ** into a single structure named "mem5". This is to keep the
22868 ** static variables organized and to reduce namespace pollution
22869 ** when this module is combined with other in the amalgamation.
22871 static SQLITE_WSD struct Mem5Global {
22873 ** Memory available for allocation
22875 int szAtom; /* Smallest possible allocation in bytes */
22876 int nBlock; /* Number of szAtom sized blocks in zPool */
22877 u8 *zPool; /* Memory available to be allocated */
22880 ** Mutex to control access to the memory allocation subsystem.
22882 sqlite3_mutex *mutex;
22884 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22886 ** Performance statistics
22888 u64 nAlloc; /* Total number of calls to malloc */
22889 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
22890 u64 totalExcess; /* Total internal fragmentation */
22891 u32 currentOut; /* Current checkout, including internal fragmentation */
22892 u32 currentCount; /* Current number of distinct checkouts */
22893 u32 maxOut; /* Maximum instantaneous currentOut */
22894 u32 maxCount; /* Maximum instantaneous currentCount */
22895 u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
22896 #endif
22899 ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
22900 ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
22901 ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
22903 int aiFreelist[LOGMAX+1];
22906 ** Space for tracking which blocks are checked out and the size
22907 ** of each block. One byte per block.
22909 u8 *aCtrl;
22911 } mem5;
22914 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
22916 #define mem5 GLOBAL(struct Mem5Global, mem5)
22919 ** Assuming mem5.zPool is divided up into an array of Mem5Link
22920 ** structures, return a pointer to the idx-th such link.
22922 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
22925 ** Unlink the chunk at mem5.aPool[i] from list it is currently
22926 ** on. It should be found on mem5.aiFreelist[iLogsize].
22928 static void memsys5Unlink(int i, int iLogsize){
22929 int next, prev;
22930 assert( i>=0 && i<mem5.nBlock );
22931 assert( iLogsize>=0 && iLogsize<=LOGMAX );
22932 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
22934 next = MEM5LINK(i)->next;
22935 prev = MEM5LINK(i)->prev;
22936 if( prev<0 ){
22937 mem5.aiFreelist[iLogsize] = next;
22938 }else{
22939 MEM5LINK(prev)->next = next;
22941 if( next>=0 ){
22942 MEM5LINK(next)->prev = prev;
22947 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
22948 ** free list.
22950 static void memsys5Link(int i, int iLogsize){
22951 int x;
22952 assert( sqlite3_mutex_held(mem5.mutex) );
22953 assert( i>=0 && i<mem5.nBlock );
22954 assert( iLogsize>=0 && iLogsize<=LOGMAX );
22955 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
22957 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
22958 MEM5LINK(i)->prev = -1;
22959 if( x>=0 ){
22960 assert( x<mem5.nBlock );
22961 MEM5LINK(x)->prev = i;
22963 mem5.aiFreelist[iLogsize] = i;
22967 ** Obtain or release the mutex needed to access global data structures.
22969 static void memsys5Enter(void){
22970 sqlite3_mutex_enter(mem5.mutex);
22972 static void memsys5Leave(void){
22973 sqlite3_mutex_leave(mem5.mutex);
22977 ** Return the size of an outstanding allocation, in bytes.
22978 ** This only works for chunks that are currently checked out.
22980 static int memsys5Size(void *p){
22981 int iSize, i;
22982 assert( p!=0 );
22983 i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
22984 assert( i>=0 && i<mem5.nBlock );
22985 iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
22986 return iSize;
22990 ** Return a block of memory of at least nBytes in size.
22991 ** Return NULL if unable. Return NULL if nBytes==0.
22993 ** The caller guarantees that nByte is positive.
22995 ** The caller has obtained a mutex prior to invoking this
22996 ** routine so there is never any chance that two or more
22997 ** threads can be in this routine at the same time.
22999 static void *memsys5MallocUnsafe(int nByte){
23000 int i; /* Index of a mem5.aPool[] slot */
23001 int iBin; /* Index into mem5.aiFreelist[] */
23002 int iFullSz; /* Size of allocation rounded up to power of 2 */
23003 int iLogsize; /* Log2 of iFullSz/POW2_MIN */
23005 /* nByte must be a positive */
23006 assert( nByte>0 );
23008 /* No more than 1GiB per allocation */
23009 if( nByte > 0x40000000 ) return 0;
23011 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23012 /* Keep track of the maximum allocation request. Even unfulfilled
23013 ** requests are counted */
23014 if( (u32)nByte>mem5.maxRequest ){
23015 mem5.maxRequest = nByte;
23017 #endif
23020 /* Round nByte up to the next valid power of two */
23021 for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
23023 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
23024 ** block. If not, then split a block of the next larger power of
23025 ** two in order to create a new free block of size iLogsize.
23027 for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
23028 if( iBin>LOGMAX ){
23029 testcase( sqlite3GlobalConfig.xLog!=0 );
23030 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
23031 return 0;
23033 i = mem5.aiFreelist[iBin];
23034 memsys5Unlink(i, iBin);
23035 while( iBin>iLogsize ){
23036 int newSize;
23038 iBin--;
23039 newSize = 1 << iBin;
23040 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
23041 memsys5Link(i+newSize, iBin);
23043 mem5.aCtrl[i] = iLogsize;
23045 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23046 /* Update allocator performance statistics. */
23047 mem5.nAlloc++;
23048 mem5.totalAlloc += iFullSz;
23049 mem5.totalExcess += iFullSz - nByte;
23050 mem5.currentCount++;
23051 mem5.currentOut += iFullSz;
23052 if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
23053 if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
23054 #endif
23056 #ifdef SQLITE_DEBUG
23057 /* Make sure the allocated memory does not assume that it is set to zero
23058 ** or retains a value from a previous allocation */
23059 memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
23060 #endif
23062 /* Return a pointer to the allocated memory. */
23063 return (void*)&mem5.zPool[i*mem5.szAtom];
23067 ** Free an outstanding memory allocation.
23069 static void memsys5FreeUnsafe(void *pOld){
23070 u32 size, iLogsize;
23071 int iBlock;
23073 /* Set iBlock to the index of the block pointed to by pOld in
23074 ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
23076 iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
23078 /* Check that the pointer pOld points to a valid, non-free block. */
23079 assert( iBlock>=0 && iBlock<mem5.nBlock );
23080 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
23081 assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
23083 iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
23084 size = 1<<iLogsize;
23085 assert( iBlock+size-1<(u32)mem5.nBlock );
23087 mem5.aCtrl[iBlock] |= CTRL_FREE;
23088 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
23090 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23091 assert( mem5.currentCount>0 );
23092 assert( mem5.currentOut>=(size*mem5.szAtom) );
23093 mem5.currentCount--;
23094 mem5.currentOut -= size*mem5.szAtom;
23095 assert( mem5.currentOut>0 || mem5.currentCount==0 );
23096 assert( mem5.currentCount>0 || mem5.currentOut==0 );
23097 #endif
23099 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
23100 while( ALWAYS(iLogsize<LOGMAX) ){
23101 int iBuddy;
23102 if( (iBlock>>iLogsize) & 1 ){
23103 iBuddy = iBlock - size;
23104 assert( iBuddy>=0 );
23105 }else{
23106 iBuddy = iBlock + size;
23107 if( iBuddy>=mem5.nBlock ) break;
23109 if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
23110 memsys5Unlink(iBuddy, iLogsize);
23111 iLogsize++;
23112 if( iBuddy<iBlock ){
23113 mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
23114 mem5.aCtrl[iBlock] = 0;
23115 iBlock = iBuddy;
23116 }else{
23117 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
23118 mem5.aCtrl[iBuddy] = 0;
23120 size *= 2;
23123 #ifdef SQLITE_DEBUG
23124 /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
23125 ** not used after being freed */
23126 memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
23127 #endif
23129 memsys5Link(iBlock, iLogsize);
23133 ** Allocate nBytes of memory.
23135 static void *memsys5Malloc(int nBytes){
23136 sqlite3_int64 *p = 0;
23137 if( nBytes>0 ){
23138 memsys5Enter();
23139 p = memsys5MallocUnsafe(nBytes);
23140 memsys5Leave();
23142 return (void*)p;
23146 ** Free memory.
23148 ** The outer layer memory allocator prevents this routine from
23149 ** being called with pPrior==0.
23151 static void memsys5Free(void *pPrior){
23152 assert( pPrior!=0 );
23153 memsys5Enter();
23154 memsys5FreeUnsafe(pPrior);
23155 memsys5Leave();
23159 ** Change the size of an existing memory allocation.
23161 ** The outer layer memory allocator prevents this routine from
23162 ** being called with pPrior==0.
23164 ** nBytes is always a value obtained from a prior call to
23165 ** memsys5Round(). Hence nBytes is always a non-negative power
23166 ** of two. If nBytes==0 that means that an oversize allocation
23167 ** (an allocation larger than 0x40000000) was requested and this
23168 ** routine should return 0 without freeing pPrior.
23170 static void *memsys5Realloc(void *pPrior, int nBytes){
23171 int nOld;
23172 void *p;
23173 assert( pPrior!=0 );
23174 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
23175 assert( nBytes>=0 );
23176 if( nBytes==0 ){
23177 return 0;
23179 nOld = memsys5Size(pPrior);
23180 if( nBytes<=nOld ){
23181 return pPrior;
23183 p = memsys5Malloc(nBytes);
23184 if( p ){
23185 memcpy(p, pPrior, nOld);
23186 memsys5Free(pPrior);
23188 return p;
23192 ** Round up a request size to the next valid allocation size. If
23193 ** the allocation is too large to be handled by this allocation system,
23194 ** return 0.
23196 ** All allocations must be a power of two and must be expressed by a
23197 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
23198 ** or 1073741824 bytes.
23200 static int memsys5Roundup(int n){
23201 int iFullSz;
23202 if( n > 0x40000000 ) return 0;
23203 for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
23204 return iFullSz;
23208 ** Return the ceiling of the logarithm base 2 of iValue.
23210 ** Examples: memsys5Log(1) -> 0
23211 ** memsys5Log(2) -> 1
23212 ** memsys5Log(4) -> 2
23213 ** memsys5Log(5) -> 3
23214 ** memsys5Log(8) -> 3
23215 ** memsys5Log(9) -> 4
23217 static int memsys5Log(int iValue){
23218 int iLog;
23219 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
23220 return iLog;
23224 ** Initialize the memory allocator.
23226 ** This routine is not threadsafe. The caller must be holding a mutex
23227 ** to prevent multiple threads from entering at the same time.
23229 static int memsys5Init(void *NotUsed){
23230 int ii; /* Loop counter */
23231 int nByte; /* Number of bytes of memory available to this allocator */
23232 u8 *zByte; /* Memory usable by this allocator */
23233 int nMinLog; /* Log base 2 of minimum allocation size in bytes */
23234 int iOffset; /* An offset into mem5.aCtrl[] */
23236 UNUSED_PARAMETER(NotUsed);
23238 /* For the purposes of this routine, disable the mutex */
23239 mem5.mutex = 0;
23241 /* The size of a Mem5Link object must be a power of two. Verify that
23242 ** this is case.
23244 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
23246 nByte = sqlite3GlobalConfig.nHeap;
23247 zByte = (u8*)sqlite3GlobalConfig.pHeap;
23248 assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
23250 /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
23251 nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
23252 mem5.szAtom = (1<<nMinLog);
23253 while( (int)sizeof(Mem5Link)>mem5.szAtom ){
23254 mem5.szAtom = mem5.szAtom << 1;
23257 mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
23258 mem5.zPool = zByte;
23259 mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
23261 for(ii=0; ii<=LOGMAX; ii++){
23262 mem5.aiFreelist[ii] = -1;
23265 iOffset = 0;
23266 for(ii=LOGMAX; ii>=0; ii--){
23267 int nAlloc = (1<<ii);
23268 if( (iOffset+nAlloc)<=mem5.nBlock ){
23269 mem5.aCtrl[iOffset] = ii | CTRL_FREE;
23270 memsys5Link(iOffset, ii);
23271 iOffset += nAlloc;
23273 assert((iOffset+nAlloc)>mem5.nBlock);
23276 /* If a mutex is required for normal operation, allocate one */
23277 if( sqlite3GlobalConfig.bMemstat==0 ){
23278 mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
23281 return SQLITE_OK;
23285 ** Deinitialize this module.
23287 static void memsys5Shutdown(void *NotUsed){
23288 UNUSED_PARAMETER(NotUsed);
23289 mem5.mutex = 0;
23290 return;
23293 #ifdef SQLITE_TEST
23295 ** Open the file indicated and write a log of all unfreed memory
23296 ** allocations into that log.
23298 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
23299 FILE *out;
23300 int i, j, n;
23301 int nMinLog;
23303 if( zFilename==0 || zFilename[0]==0 ){
23304 out = stdout;
23305 }else{
23306 out = fopen(zFilename, "w");
23307 if( out==0 ){
23308 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
23309 zFilename);
23310 return;
23313 memsys5Enter();
23314 nMinLog = memsys5Log(mem5.szAtom);
23315 for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
23316 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
23317 fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
23319 fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
23320 fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
23321 fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
23322 fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
23323 fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
23324 fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
23325 fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
23326 fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
23327 memsys5Leave();
23328 if( out==stdout ){
23329 fflush(stdout);
23330 }else{
23331 fclose(out);
23334 #endif
23337 ** This routine is the only routine in this file with external
23338 ** linkage. It returns a pointer to a static sqlite3_mem_methods
23339 ** struct populated with the memsys5 methods.
23341 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
23342 static const sqlite3_mem_methods memsys5Methods = {
23343 memsys5Malloc,
23344 memsys5Free,
23345 memsys5Realloc,
23346 memsys5Size,
23347 memsys5Roundup,
23348 memsys5Init,
23349 memsys5Shutdown,
23352 return &memsys5Methods;
23355 #endif /* SQLITE_ENABLE_MEMSYS5 */
23357 /************** End of mem5.c ************************************************/
23358 /************** Begin file mutex.c *******************************************/
23360 ** 2007 August 14
23362 ** The author disclaims copyright to this source code. In place of
23363 ** a legal notice, here is a blessing:
23365 ** May you do good and not evil.
23366 ** May you find forgiveness for yourself and forgive others.
23367 ** May you share freely, never taking more than you give.
23369 *************************************************************************
23370 ** This file contains the C functions that implement mutexes.
23372 ** This file contains code that is common across all mutex implementations.
23374 /* #include "sqliteInt.h" */
23376 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
23378 ** For debugging purposes, record when the mutex subsystem is initialized
23379 ** and uninitialized so that we can assert() if there is an attempt to
23380 ** allocate a mutex while the system is uninitialized.
23382 static SQLITE_WSD int mutexIsInit = 0;
23383 #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
23386 #ifndef SQLITE_MUTEX_OMIT
23388 ** Initialize the mutex system.
23390 SQLITE_PRIVATE int sqlite3MutexInit(void){
23391 int rc = SQLITE_OK;
23392 if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
23393 /* If the xMutexAlloc method has not been set, then the user did not
23394 ** install a mutex implementation via sqlite3_config() prior to
23395 ** sqlite3_initialize() being called. This block copies pointers to
23396 ** the default implementation into the sqlite3GlobalConfig structure.
23398 sqlite3_mutex_methods const *pFrom;
23399 sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
23401 if( sqlite3GlobalConfig.bCoreMutex ){
23402 pFrom = sqlite3DefaultMutex();
23403 }else{
23404 pFrom = sqlite3NoopMutex();
23406 pTo->xMutexInit = pFrom->xMutexInit;
23407 pTo->xMutexEnd = pFrom->xMutexEnd;
23408 pTo->xMutexFree = pFrom->xMutexFree;
23409 pTo->xMutexEnter = pFrom->xMutexEnter;
23410 pTo->xMutexTry = pFrom->xMutexTry;
23411 pTo->xMutexLeave = pFrom->xMutexLeave;
23412 pTo->xMutexHeld = pFrom->xMutexHeld;
23413 pTo->xMutexNotheld = pFrom->xMutexNotheld;
23414 sqlite3MemoryBarrier();
23415 pTo->xMutexAlloc = pFrom->xMutexAlloc;
23417 assert( sqlite3GlobalConfig.mutex.xMutexInit );
23418 rc = sqlite3GlobalConfig.mutex.xMutexInit();
23420 #ifdef SQLITE_DEBUG
23421 GLOBAL(int, mutexIsInit) = 1;
23422 #endif
23424 return rc;
23428 ** Shutdown the mutex system. This call frees resources allocated by
23429 ** sqlite3MutexInit().
23431 SQLITE_PRIVATE int sqlite3MutexEnd(void){
23432 int rc = SQLITE_OK;
23433 if( sqlite3GlobalConfig.mutex.xMutexEnd ){
23434 rc = sqlite3GlobalConfig.mutex.xMutexEnd();
23437 #ifdef SQLITE_DEBUG
23438 GLOBAL(int, mutexIsInit) = 0;
23439 #endif
23441 return rc;
23445 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
23447 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
23448 #ifndef SQLITE_OMIT_AUTOINIT
23449 if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
23450 if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
23451 #endif
23452 assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
23453 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
23456 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
23457 if( !sqlite3GlobalConfig.bCoreMutex ){
23458 return 0;
23460 assert( GLOBAL(int, mutexIsInit) );
23461 assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
23462 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
23466 ** Free a dynamic mutex.
23468 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
23469 if( p ){
23470 assert( sqlite3GlobalConfig.mutex.xMutexFree );
23471 sqlite3GlobalConfig.mutex.xMutexFree(p);
23476 ** Obtain the mutex p. If some other thread already has the mutex, block
23477 ** until it can be obtained.
23479 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
23480 if( p ){
23481 assert( sqlite3GlobalConfig.mutex.xMutexEnter );
23482 sqlite3GlobalConfig.mutex.xMutexEnter(p);
23487 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
23488 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
23490 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
23491 int rc = SQLITE_OK;
23492 if( p ){
23493 assert( sqlite3GlobalConfig.mutex.xMutexTry );
23494 return sqlite3GlobalConfig.mutex.xMutexTry(p);
23496 return rc;
23500 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
23501 ** entered by the same thread. The behavior is undefined if the mutex
23502 ** is not currently entered. If a NULL pointer is passed as an argument
23503 ** this function is a no-op.
23505 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
23506 if( p ){
23507 assert( sqlite3GlobalConfig.mutex.xMutexLeave );
23508 sqlite3GlobalConfig.mutex.xMutexLeave(p);
23512 #ifndef NDEBUG
23514 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23515 ** intended for use inside assert() statements.
23517 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
23518 assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
23519 return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
23521 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
23522 assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
23523 return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
23525 #endif
23527 #endif /* !defined(SQLITE_MUTEX_OMIT) */
23529 /************** End of mutex.c ***********************************************/
23530 /************** Begin file mutex_noop.c **************************************/
23532 ** 2008 October 07
23534 ** The author disclaims copyright to this source code. In place of
23535 ** a legal notice, here is a blessing:
23537 ** May you do good and not evil.
23538 ** May you find forgiveness for yourself and forgive others.
23539 ** May you share freely, never taking more than you give.
23541 *************************************************************************
23542 ** This file contains the C functions that implement mutexes.
23544 ** This implementation in this file does not provide any mutual
23545 ** exclusion and is thus suitable for use only in applications
23546 ** that use SQLite in a single thread. The routines defined
23547 ** here are place-holders. Applications can substitute working
23548 ** mutex routines at start-time using the
23550 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
23552 ** interface.
23554 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
23555 ** that does error checking on mutexes to make sure they are being
23556 ** called correctly.
23558 /* #include "sqliteInt.h" */
23560 #ifndef SQLITE_MUTEX_OMIT
23562 #ifndef SQLITE_DEBUG
23564 ** Stub routines for all mutex methods.
23566 ** This routines provide no mutual exclusion or error checking.
23568 static int noopMutexInit(void){ return SQLITE_OK; }
23569 static int noopMutexEnd(void){ return SQLITE_OK; }
23570 static sqlite3_mutex *noopMutexAlloc(int id){
23571 UNUSED_PARAMETER(id);
23572 return (sqlite3_mutex*)8;
23574 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
23575 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
23576 static int noopMutexTry(sqlite3_mutex *p){
23577 UNUSED_PARAMETER(p);
23578 return SQLITE_OK;
23580 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
23582 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
23583 static const sqlite3_mutex_methods sMutex = {
23584 noopMutexInit,
23585 noopMutexEnd,
23586 noopMutexAlloc,
23587 noopMutexFree,
23588 noopMutexEnter,
23589 noopMutexTry,
23590 noopMutexLeave,
23596 return &sMutex;
23598 #endif /* !SQLITE_DEBUG */
23600 #ifdef SQLITE_DEBUG
23602 ** In this implementation, error checking is provided for testing
23603 ** and debugging purposes. The mutexes still do not provide any
23604 ** mutual exclusion.
23608 ** The mutex object
23610 typedef struct sqlite3_debug_mutex {
23611 int id; /* The mutex type */
23612 int cnt; /* Number of entries without a matching leave */
23613 } sqlite3_debug_mutex;
23616 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23617 ** intended for use inside assert() statements.
23619 static int debugMutexHeld(sqlite3_mutex *pX){
23620 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23621 return p==0 || p->cnt>0;
23623 static int debugMutexNotheld(sqlite3_mutex *pX){
23624 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23625 return p==0 || p->cnt==0;
23629 ** Initialize and deinitialize the mutex subsystem.
23631 static int debugMutexInit(void){ return SQLITE_OK; }
23632 static int debugMutexEnd(void){ return SQLITE_OK; }
23635 ** The sqlite3_mutex_alloc() routine allocates a new
23636 ** mutex and returns a pointer to it. If it returns NULL
23637 ** that means that a mutex could not be allocated.
23639 static sqlite3_mutex *debugMutexAlloc(int id){
23640 static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
23641 sqlite3_debug_mutex *pNew = 0;
23642 switch( id ){
23643 case SQLITE_MUTEX_FAST:
23644 case SQLITE_MUTEX_RECURSIVE: {
23645 pNew = sqlite3Malloc(sizeof(*pNew));
23646 if( pNew ){
23647 pNew->id = id;
23648 pNew->cnt = 0;
23650 break;
23652 default: {
23653 #ifdef SQLITE_ENABLE_API_ARMOR
23654 if( id-2<0 || id-2>=ArraySize(aStatic) ){
23655 (void)SQLITE_MISUSE_BKPT;
23656 return 0;
23658 #endif
23659 pNew = &aStatic[id-2];
23660 pNew->id = id;
23661 break;
23664 return (sqlite3_mutex*)pNew;
23668 ** This routine deallocates a previously allocated mutex.
23670 static void debugMutexFree(sqlite3_mutex *pX){
23671 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23672 assert( p->cnt==0 );
23673 if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
23674 sqlite3_free(p);
23675 }else{
23676 #ifdef SQLITE_ENABLE_API_ARMOR
23677 (void)SQLITE_MISUSE_BKPT;
23678 #endif
23683 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23684 ** to enter a mutex. If another thread is already within the mutex,
23685 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23686 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
23687 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
23688 ** be entered multiple times by the same thread. In such cases the,
23689 ** mutex must be exited an equal number of times before another thread
23690 ** can enter. If the same thread tries to enter any other kind of mutex
23691 ** more than once, the behavior is undefined.
23693 static void debugMutexEnter(sqlite3_mutex *pX){
23694 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23695 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
23696 p->cnt++;
23698 static int debugMutexTry(sqlite3_mutex *pX){
23699 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23700 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
23701 p->cnt++;
23702 return SQLITE_OK;
23706 ** The sqlite3_mutex_leave() routine exits a mutex that was
23707 ** previously entered by the same thread. The behavior
23708 ** is undefined if the mutex is not currently entered or
23709 ** is not currently allocated. SQLite will never do either.
23711 static void debugMutexLeave(sqlite3_mutex *pX){
23712 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23713 assert( debugMutexHeld(pX) );
23714 p->cnt--;
23715 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
23718 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
23719 static const sqlite3_mutex_methods sMutex = {
23720 debugMutexInit,
23721 debugMutexEnd,
23722 debugMutexAlloc,
23723 debugMutexFree,
23724 debugMutexEnter,
23725 debugMutexTry,
23726 debugMutexLeave,
23728 debugMutexHeld,
23729 debugMutexNotheld
23732 return &sMutex;
23734 #endif /* SQLITE_DEBUG */
23737 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
23738 ** is used regardless of the run-time threadsafety setting.
23740 #ifdef SQLITE_MUTEX_NOOP
23741 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23742 return sqlite3NoopMutex();
23744 #endif /* defined(SQLITE_MUTEX_NOOP) */
23745 #endif /* !defined(SQLITE_MUTEX_OMIT) */
23747 /************** End of mutex_noop.c ******************************************/
23748 /************** Begin file mutex_unix.c **************************************/
23750 ** 2007 August 28
23752 ** The author disclaims copyright to this source code. In place of
23753 ** a legal notice, here is a blessing:
23755 ** May you do good and not evil.
23756 ** May you find forgiveness for yourself and forgive others.
23757 ** May you share freely, never taking more than you give.
23759 *************************************************************************
23760 ** This file contains the C functions that implement mutexes for pthreads
23762 /* #include "sqliteInt.h" */
23765 ** The code in this file is only used if we are compiling threadsafe
23766 ** under unix with pthreads.
23768 ** Note that this implementation requires a version of pthreads that
23769 ** supports recursive mutexes.
23771 #ifdef SQLITE_MUTEX_PTHREADS
23773 #include <pthread.h>
23776 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
23777 ** are necessary under two condidtions: (1) Debug builds and (2) using
23778 ** home-grown mutexes. Encapsulate these conditions into a single #define.
23780 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
23781 # define SQLITE_MUTEX_NREF 1
23782 #else
23783 # define SQLITE_MUTEX_NREF 0
23784 #endif
23787 ** Each recursive mutex is an instance of the following structure.
23789 struct sqlite3_mutex {
23790 pthread_mutex_t mutex; /* Mutex controlling the lock */
23791 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
23792 int id; /* Mutex type */
23793 #endif
23794 #if SQLITE_MUTEX_NREF
23795 volatile int nRef; /* Number of entrances */
23796 volatile pthread_t owner; /* Thread that is within this mutex */
23797 int trace; /* True to trace changes */
23798 #endif
23800 #if SQLITE_MUTEX_NREF
23801 #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
23802 #elif defined(SQLITE_ENABLE_API_ARMOR)
23803 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
23804 #else
23805 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
23806 #endif
23809 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23810 ** intended for use only inside assert() statements. On some platforms,
23811 ** there might be race conditions that can cause these routines to
23812 ** deliver incorrect results. In particular, if pthread_equal() is
23813 ** not an atomic operation, then these routines might delivery
23814 ** incorrect results. On most platforms, pthread_equal() is a
23815 ** comparison of two integers and is therefore atomic. But we are
23816 ** told that HPUX is not such a platform. If so, then these routines
23817 ** will not always work correctly on HPUX.
23819 ** On those platforms where pthread_equal() is not atomic, SQLite
23820 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
23821 ** make sure no assert() statements are evaluated and hence these
23822 ** routines are never called.
23824 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
23825 static int pthreadMutexHeld(sqlite3_mutex *p){
23826 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
23828 static int pthreadMutexNotheld(sqlite3_mutex *p){
23829 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
23831 #endif
23834 ** Try to provide a memory barrier operation, needed for initialization
23835 ** and also for the implementation of xShmBarrier in the VFS in cases
23836 ** where SQLite is compiled without mutexes.
23838 SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
23839 #if defined(SQLITE_MEMORY_BARRIER)
23840 SQLITE_MEMORY_BARRIER;
23841 #elif defined(__GNUC__) && GCC_VERSION>=4001000
23842 __sync_synchronize();
23843 #endif
23847 ** Initialize and deinitialize the mutex subsystem.
23849 static int pthreadMutexInit(void){ return SQLITE_OK; }
23850 static int pthreadMutexEnd(void){ return SQLITE_OK; }
23853 ** The sqlite3_mutex_alloc() routine allocates a new
23854 ** mutex and returns a pointer to it. If it returns NULL
23855 ** that means that a mutex could not be allocated. SQLite
23856 ** will unwind its stack and return an error. The argument
23857 ** to sqlite3_mutex_alloc() is one of these integer constants:
23859 ** <ul>
23860 ** <li> SQLITE_MUTEX_FAST
23861 ** <li> SQLITE_MUTEX_RECURSIVE
23862 ** <li> SQLITE_MUTEX_STATIC_MASTER
23863 ** <li> SQLITE_MUTEX_STATIC_MEM
23864 ** <li> SQLITE_MUTEX_STATIC_OPEN
23865 ** <li> SQLITE_MUTEX_STATIC_PRNG
23866 ** <li> SQLITE_MUTEX_STATIC_LRU
23867 ** <li> SQLITE_MUTEX_STATIC_PMEM
23868 ** <li> SQLITE_MUTEX_STATIC_APP1
23869 ** <li> SQLITE_MUTEX_STATIC_APP2
23870 ** <li> SQLITE_MUTEX_STATIC_APP3
23871 ** <li> SQLITE_MUTEX_STATIC_VFS1
23872 ** <li> SQLITE_MUTEX_STATIC_VFS2
23873 ** <li> SQLITE_MUTEX_STATIC_VFS3
23874 ** </ul>
23876 ** The first two constants cause sqlite3_mutex_alloc() to create
23877 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
23878 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
23879 ** The mutex implementation does not need to make a distinction
23880 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
23881 ** not want to. But SQLite will only request a recursive mutex in
23882 ** cases where it really needs one. If a faster non-recursive mutex
23883 ** implementation is available on the host platform, the mutex subsystem
23884 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
23886 ** The other allowed parameters to sqlite3_mutex_alloc() each return
23887 ** a pointer to a static preexisting mutex. Six static mutexes are
23888 ** used by the current version of SQLite. Future versions of SQLite
23889 ** may add additional static mutexes. Static mutexes are for internal
23890 ** use by SQLite only. Applications that use SQLite mutexes should
23891 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
23892 ** SQLITE_MUTEX_RECURSIVE.
23894 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
23895 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
23896 ** returns a different mutex on every call. But for the static
23897 ** mutex types, the same mutex is returned on every call that has
23898 ** the same type number.
23900 static sqlite3_mutex *pthreadMutexAlloc(int iType){
23901 static sqlite3_mutex staticMutexes[] = {
23902 SQLITE3_MUTEX_INITIALIZER,
23903 SQLITE3_MUTEX_INITIALIZER,
23904 SQLITE3_MUTEX_INITIALIZER,
23905 SQLITE3_MUTEX_INITIALIZER,
23906 SQLITE3_MUTEX_INITIALIZER,
23907 SQLITE3_MUTEX_INITIALIZER,
23908 SQLITE3_MUTEX_INITIALIZER,
23909 SQLITE3_MUTEX_INITIALIZER,
23910 SQLITE3_MUTEX_INITIALIZER,
23911 SQLITE3_MUTEX_INITIALIZER,
23912 SQLITE3_MUTEX_INITIALIZER,
23913 SQLITE3_MUTEX_INITIALIZER
23915 sqlite3_mutex *p;
23916 switch( iType ){
23917 case SQLITE_MUTEX_RECURSIVE: {
23918 p = sqlite3MallocZero( sizeof(*p) );
23919 if( p ){
23920 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23921 /* If recursive mutexes are not available, we will have to
23922 ** build our own. See below. */
23923 pthread_mutex_init(&p->mutex, 0);
23924 #else
23925 /* Use a recursive mutex if it is available */
23926 pthread_mutexattr_t recursiveAttr;
23927 pthread_mutexattr_init(&recursiveAttr);
23928 pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
23929 pthread_mutex_init(&p->mutex, &recursiveAttr);
23930 pthread_mutexattr_destroy(&recursiveAttr);
23931 #endif
23933 break;
23935 case SQLITE_MUTEX_FAST: {
23936 p = sqlite3MallocZero( sizeof(*p) );
23937 if( p ){
23938 pthread_mutex_init(&p->mutex, 0);
23940 break;
23942 default: {
23943 #ifdef SQLITE_ENABLE_API_ARMOR
23944 if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
23945 (void)SQLITE_MISUSE_BKPT;
23946 return 0;
23948 #endif
23949 p = &staticMutexes[iType-2];
23950 break;
23953 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
23954 if( p ) p->id = iType;
23955 #endif
23956 return p;
23961 ** This routine deallocates a previously
23962 ** allocated mutex. SQLite is careful to deallocate every
23963 ** mutex that it allocates.
23965 static void pthreadMutexFree(sqlite3_mutex *p){
23966 assert( p->nRef==0 );
23967 #if SQLITE_ENABLE_API_ARMOR
23968 if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
23969 #endif
23971 pthread_mutex_destroy(&p->mutex);
23972 sqlite3_free(p);
23974 #ifdef SQLITE_ENABLE_API_ARMOR
23975 else{
23976 (void)SQLITE_MISUSE_BKPT;
23978 #endif
23982 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23983 ** to enter a mutex. If another thread is already within the mutex,
23984 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23985 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
23986 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
23987 ** be entered multiple times by the same thread. In such cases the,
23988 ** mutex must be exited an equal number of times before another thread
23989 ** can enter. If the same thread tries to enter any other kind of mutex
23990 ** more than once, the behavior is undefined.
23992 static void pthreadMutexEnter(sqlite3_mutex *p){
23993 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23995 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23996 /* If recursive mutexes are not available, then we have to grow
23997 ** our own. This implementation assumes that pthread_equal()
23998 ** is atomic - that it cannot be deceived into thinking self
23999 ** and p->owner are equal if p->owner changes between two values
24000 ** that are not equal to self while the comparison is taking place.
24001 ** This implementation also assumes a coherent cache - that
24002 ** separate processes cannot read different values from the same
24003 ** address at the same time. If either of these two conditions
24004 ** are not met, then the mutexes will fail and problems will result.
24007 pthread_t self = pthread_self();
24008 if( p->nRef>0 && pthread_equal(p->owner, self) ){
24009 p->nRef++;
24010 }else{
24011 pthread_mutex_lock(&p->mutex);
24012 assert( p->nRef==0 );
24013 p->owner = self;
24014 p->nRef = 1;
24017 #else
24018 /* Use the built-in recursive mutexes if they are available.
24020 pthread_mutex_lock(&p->mutex);
24021 #if SQLITE_MUTEX_NREF
24022 assert( p->nRef>0 || p->owner==0 );
24023 p->owner = pthread_self();
24024 p->nRef++;
24025 #endif
24026 #endif
24028 #ifdef SQLITE_DEBUG
24029 if( p->trace ){
24030 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
24032 #endif
24034 static int pthreadMutexTry(sqlite3_mutex *p){
24035 int rc;
24036 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
24038 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
24039 /* If recursive mutexes are not available, then we have to grow
24040 ** our own. This implementation assumes that pthread_equal()
24041 ** is atomic - that it cannot be deceived into thinking self
24042 ** and p->owner are equal if p->owner changes between two values
24043 ** that are not equal to self while the comparison is taking place.
24044 ** This implementation also assumes a coherent cache - that
24045 ** separate processes cannot read different values from the same
24046 ** address at the same time. If either of these two conditions
24047 ** are not met, then the mutexes will fail and problems will result.
24050 pthread_t self = pthread_self();
24051 if( p->nRef>0 && pthread_equal(p->owner, self) ){
24052 p->nRef++;
24053 rc = SQLITE_OK;
24054 }else if( pthread_mutex_trylock(&p->mutex)==0 ){
24055 assert( p->nRef==0 );
24056 p->owner = self;
24057 p->nRef = 1;
24058 rc = SQLITE_OK;
24059 }else{
24060 rc = SQLITE_BUSY;
24063 #else
24064 /* Use the built-in recursive mutexes if they are available.
24066 if( pthread_mutex_trylock(&p->mutex)==0 ){
24067 #if SQLITE_MUTEX_NREF
24068 p->owner = pthread_self();
24069 p->nRef++;
24070 #endif
24071 rc = SQLITE_OK;
24072 }else{
24073 rc = SQLITE_BUSY;
24075 #endif
24077 #ifdef SQLITE_DEBUG
24078 if( rc==SQLITE_OK && p->trace ){
24079 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
24081 #endif
24082 return rc;
24086 ** The sqlite3_mutex_leave() routine exits a mutex that was
24087 ** previously entered by the same thread. The behavior
24088 ** is undefined if the mutex is not currently entered or
24089 ** is not currently allocated. SQLite will never do either.
24091 static void pthreadMutexLeave(sqlite3_mutex *p){
24092 assert( pthreadMutexHeld(p) );
24093 #if SQLITE_MUTEX_NREF
24094 p->nRef--;
24095 if( p->nRef==0 ) p->owner = 0;
24096 #endif
24097 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
24099 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
24100 if( p->nRef==0 ){
24101 pthread_mutex_unlock(&p->mutex);
24103 #else
24104 pthread_mutex_unlock(&p->mutex);
24105 #endif
24107 #ifdef SQLITE_DEBUG
24108 if( p->trace ){
24109 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
24111 #endif
24114 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
24115 static const sqlite3_mutex_methods sMutex = {
24116 pthreadMutexInit,
24117 pthreadMutexEnd,
24118 pthreadMutexAlloc,
24119 pthreadMutexFree,
24120 pthreadMutexEnter,
24121 pthreadMutexTry,
24122 pthreadMutexLeave,
24123 #ifdef SQLITE_DEBUG
24124 pthreadMutexHeld,
24125 pthreadMutexNotheld
24126 #else
24129 #endif
24132 return &sMutex;
24135 #endif /* SQLITE_MUTEX_PTHREADS */
24137 /************** End of mutex_unix.c ******************************************/
24138 /************** Begin file mutex_w32.c ***************************************/
24140 ** 2007 August 14
24142 ** The author disclaims copyright to this source code. In place of
24143 ** a legal notice, here is a blessing:
24145 ** May you do good and not evil.
24146 ** May you find forgiveness for yourself and forgive others.
24147 ** May you share freely, never taking more than you give.
24149 *************************************************************************
24150 ** This file contains the C functions that implement mutexes for Win32.
24152 /* #include "sqliteInt.h" */
24154 #if SQLITE_OS_WIN
24156 ** Include code that is common to all os_*.c files
24158 /************** Include os_common.h in the middle of mutex_w32.c *************/
24159 /************** Begin file os_common.h ***************************************/
24161 ** 2004 May 22
24163 ** The author disclaims copyright to this source code. In place of
24164 ** a legal notice, here is a blessing:
24166 ** May you do good and not evil.
24167 ** May you find forgiveness for yourself and forgive others.
24168 ** May you share freely, never taking more than you give.
24170 ******************************************************************************
24172 ** This file contains macros and a little bit of code that is common to
24173 ** all of the platform-specific files (os_*.c) and is #included into those
24174 ** files.
24176 ** This file should be #included by the os_*.c files only. It is not a
24177 ** general purpose header file.
24179 #ifndef _OS_COMMON_H_
24180 #define _OS_COMMON_H_
24183 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24184 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24185 ** switch. The following code should catch this problem at compile-time.
24187 #ifdef MEMORY_DEBUG
24188 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
24189 #endif
24192 ** Macros for performance tracing. Normally turned off. Only works
24193 ** on i486 hardware.
24195 #ifdef SQLITE_PERFORMANCE_TRACE
24198 ** hwtime.h contains inline assembler code for implementing
24199 ** high-performance timing routines.
24201 /************** Include hwtime.h in the middle of os_common.h ****************/
24202 /************** Begin file hwtime.h ******************************************/
24204 ** 2008 May 27
24206 ** The author disclaims copyright to this source code. In place of
24207 ** a legal notice, here is a blessing:
24209 ** May you do good and not evil.
24210 ** May you find forgiveness for yourself and forgive others.
24211 ** May you share freely, never taking more than you give.
24213 ******************************************************************************
24215 ** This file contains inline asm code for retrieving "high-performance"
24216 ** counters for x86 class CPUs.
24218 #ifndef SQLITE_HWTIME_H
24219 #define SQLITE_HWTIME_H
24222 ** The following routine only works on pentium-class (or newer) processors.
24223 ** It uses the RDTSC opcode to read the cycle count value out of the
24224 ** processor and returns that value. This can be used for high-res
24225 ** profiling.
24227 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24228 (defined(i386) || defined(__i386__) || defined(_M_IX86))
24230 #if defined(__GNUC__)
24232 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24233 unsigned int lo, hi;
24234 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24235 return (sqlite_uint64)hi << 32 | lo;
24238 #elif defined(_MSC_VER)
24240 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24241 __asm {
24242 rdtsc
24243 ret ; return value at EDX:EAX
24247 #endif
24249 #elif (defined(__GNUC__) && defined(__x86_64__))
24251 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24252 unsigned long val;
24253 __asm__ __volatile__ ("rdtsc" : "=A" (val));
24254 return val;
24257 #elif (defined(__GNUC__) && defined(__ppc__))
24259 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24260 unsigned long long retval;
24261 unsigned long junk;
24262 __asm__ __volatile__ ("\n\
24263 1: mftbu %1\n\
24264 mftb %L0\n\
24265 mftbu %0\n\
24266 cmpw %0,%1\n\
24267 bne 1b"
24268 : "=r" (retval), "=r" (junk));
24269 return retval;
24272 #else
24274 #error Need implementation of sqlite3Hwtime() for your platform.
24277 ** To compile without implementing sqlite3Hwtime() for your platform,
24278 ** you can remove the above #error and use the following
24279 ** stub function. You will lose timing support for many
24280 ** of the debugging and testing utilities, but it should at
24281 ** least compile and run.
24283 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24285 #endif
24287 #endif /* !defined(SQLITE_HWTIME_H) */
24289 /************** End of hwtime.h **********************************************/
24290 /************** Continuing where we left off in os_common.h ******************/
24292 static sqlite_uint64 g_start;
24293 static sqlite_uint64 g_elapsed;
24294 #define TIMER_START g_start=sqlite3Hwtime()
24295 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
24296 #define TIMER_ELAPSED g_elapsed
24297 #else
24298 #define TIMER_START
24299 #define TIMER_END
24300 #define TIMER_ELAPSED ((sqlite_uint64)0)
24301 #endif
24304 ** If we compile with the SQLITE_TEST macro set, then the following block
24305 ** of code will give us the ability to simulate a disk I/O error. This
24306 ** is used for testing the I/O recovery logic.
24308 #if defined(SQLITE_TEST)
24309 SQLITE_API extern int sqlite3_io_error_hit;
24310 SQLITE_API extern int sqlite3_io_error_hardhit;
24311 SQLITE_API extern int sqlite3_io_error_pending;
24312 SQLITE_API extern int sqlite3_io_error_persist;
24313 SQLITE_API extern int sqlite3_io_error_benign;
24314 SQLITE_API extern int sqlite3_diskfull_pending;
24315 SQLITE_API extern int sqlite3_diskfull;
24316 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24317 #define SimulateIOError(CODE) \
24318 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24319 || sqlite3_io_error_pending-- == 1 ) \
24320 { local_ioerr(); CODE; }
24321 static void local_ioerr(){
24322 IOTRACE(("IOERR\n"));
24323 sqlite3_io_error_hit++;
24324 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24326 #define SimulateDiskfullError(CODE) \
24327 if( sqlite3_diskfull_pending ){ \
24328 if( sqlite3_diskfull_pending == 1 ){ \
24329 local_ioerr(); \
24330 sqlite3_diskfull = 1; \
24331 sqlite3_io_error_hit = 1; \
24332 CODE; \
24333 }else{ \
24334 sqlite3_diskfull_pending--; \
24337 #else
24338 #define SimulateIOErrorBenign(X)
24339 #define SimulateIOError(A)
24340 #define SimulateDiskfullError(A)
24341 #endif /* defined(SQLITE_TEST) */
24344 ** When testing, keep a count of the number of open files.
24346 #if defined(SQLITE_TEST)
24347 SQLITE_API extern int sqlite3_open_file_count;
24348 #define OpenCounter(X) sqlite3_open_file_count+=(X)
24349 #else
24350 #define OpenCounter(X)
24351 #endif /* defined(SQLITE_TEST) */
24353 #endif /* !defined(_OS_COMMON_H_) */
24355 /************** End of os_common.h *******************************************/
24356 /************** Continuing where we left off in mutex_w32.c ******************/
24359 ** Include the header file for the Windows VFS.
24361 /************** Include os_win.h in the middle of mutex_w32.c ****************/
24362 /************** Begin file os_win.h ******************************************/
24364 ** 2013 November 25
24366 ** The author disclaims copyright to this source code. In place of
24367 ** a legal notice, here is a blessing:
24369 ** May you do good and not evil.
24370 ** May you find forgiveness for yourself and forgive others.
24371 ** May you share freely, never taking more than you give.
24373 ******************************************************************************
24375 ** This file contains code that is specific to Windows.
24377 #ifndef SQLITE_OS_WIN_H
24378 #define SQLITE_OS_WIN_H
24381 ** Include the primary Windows SDK header file.
24383 #include "windows.h"
24385 #ifdef __CYGWIN__
24386 # include <sys/cygwin.h>
24387 # include <errno.h> /* amalgamator: dontcache */
24388 #endif
24391 ** Determine if we are dealing with Windows NT.
24393 ** We ought to be able to determine if we are compiling for Windows 9x or
24394 ** Windows NT using the _WIN32_WINNT macro as follows:
24396 ** #if defined(_WIN32_WINNT)
24397 ** # define SQLITE_OS_WINNT 1
24398 ** #else
24399 ** # define SQLITE_OS_WINNT 0
24400 ** #endif
24402 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
24403 ** it ought to, so the above test does not work. We'll just assume that
24404 ** everything is Windows NT unless the programmer explicitly says otherwise
24405 ** by setting SQLITE_OS_WINNT to 0.
24407 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
24408 # define SQLITE_OS_WINNT 1
24409 #endif
24412 ** Determine if we are dealing with Windows CE - which has a much reduced
24413 ** API.
24415 #if defined(_WIN32_WCE)
24416 # define SQLITE_OS_WINCE 1
24417 #else
24418 # define SQLITE_OS_WINCE 0
24419 #endif
24422 ** Determine if we are dealing with WinRT, which provides only a subset of
24423 ** the full Win32 API.
24425 #if !defined(SQLITE_OS_WINRT)
24426 # define SQLITE_OS_WINRT 0
24427 #endif
24430 ** For WinCE, some API function parameters do not appear to be declared as
24431 ** volatile.
24433 #if SQLITE_OS_WINCE
24434 # define SQLITE_WIN32_VOLATILE
24435 #else
24436 # define SQLITE_WIN32_VOLATILE volatile
24437 #endif
24440 ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
24441 ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
24443 #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
24444 SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
24445 # define SQLITE_OS_WIN_THREADS 1
24446 #else
24447 # define SQLITE_OS_WIN_THREADS 0
24448 #endif
24450 #endif /* SQLITE_OS_WIN_H */
24452 /************** End of os_win.h **********************************************/
24453 /************** Continuing where we left off in mutex_w32.c ******************/
24454 #endif
24457 ** The code in this file is only used if we are compiling multithreaded
24458 ** on a Win32 system.
24460 #ifdef SQLITE_MUTEX_W32
24463 ** Each recursive mutex is an instance of the following structure.
24465 struct sqlite3_mutex {
24466 CRITICAL_SECTION mutex; /* Mutex controlling the lock */
24467 int id; /* Mutex type */
24468 #ifdef SQLITE_DEBUG
24469 volatile int nRef; /* Number of enterances */
24470 volatile DWORD owner; /* Thread holding this mutex */
24471 volatile int trace; /* True to trace changes */
24472 #endif
24476 ** These are the initializer values used when declaring a "static" mutex
24477 ** on Win32. It should be noted that all mutexes require initialization
24478 ** on the Win32 platform.
24480 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
24482 #ifdef SQLITE_DEBUG
24483 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
24484 0L, (DWORD)0, 0 }
24485 #else
24486 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
24487 #endif
24489 #ifdef SQLITE_DEBUG
24491 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
24492 ** intended for use only inside assert() statements.
24494 static int winMutexHeld(sqlite3_mutex *p){
24495 return p->nRef!=0 && p->owner==GetCurrentThreadId();
24498 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
24499 return p->nRef==0 || p->owner!=tid;
24502 static int winMutexNotheld(sqlite3_mutex *p){
24503 DWORD tid = GetCurrentThreadId();
24504 return winMutexNotheld2(p, tid);
24506 #endif
24509 ** Try to provide a memory barrier operation, needed for initialization
24510 ** and also for the xShmBarrier method of the VFS in cases when SQLite is
24511 ** compiled without mutexes (SQLITE_THREADSAFE=0).
24513 SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
24514 #if defined(SQLITE_MEMORY_BARRIER)
24515 SQLITE_MEMORY_BARRIER;
24516 #elif defined(__GNUC__)
24517 __sync_synchronize();
24518 #elif MSVC_VERSION>=1300
24519 _ReadWriteBarrier();
24520 #elif defined(MemoryBarrier)
24521 MemoryBarrier();
24522 #endif
24526 ** Initialize and deinitialize the mutex subsystem.
24528 static sqlite3_mutex winMutex_staticMutexes[] = {
24529 SQLITE3_MUTEX_INITIALIZER,
24530 SQLITE3_MUTEX_INITIALIZER,
24531 SQLITE3_MUTEX_INITIALIZER,
24532 SQLITE3_MUTEX_INITIALIZER,
24533 SQLITE3_MUTEX_INITIALIZER,
24534 SQLITE3_MUTEX_INITIALIZER,
24535 SQLITE3_MUTEX_INITIALIZER,
24536 SQLITE3_MUTEX_INITIALIZER,
24537 SQLITE3_MUTEX_INITIALIZER,
24538 SQLITE3_MUTEX_INITIALIZER,
24539 SQLITE3_MUTEX_INITIALIZER,
24540 SQLITE3_MUTEX_INITIALIZER
24543 static int winMutex_isInit = 0;
24544 static int winMutex_isNt = -1; /* <0 means "need to query" */
24546 /* As the winMutexInit() and winMutexEnd() functions are called as part
24547 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
24548 ** "interlocked" magic used here is probably not strictly necessary.
24550 static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
24552 SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
24553 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
24555 static int winMutexInit(void){
24556 /* The first to increment to 1 does actual initialization */
24557 if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
24558 int i;
24559 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
24560 #if SQLITE_OS_WINRT
24561 InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
24562 #else
24563 InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
24564 #endif
24566 winMutex_isInit = 1;
24567 }else{
24568 /* Another thread is (in the process of) initializing the static
24569 ** mutexes */
24570 while( !winMutex_isInit ){
24571 sqlite3_win32_sleep(1);
24574 return SQLITE_OK;
24577 static int winMutexEnd(void){
24578 /* The first to decrement to 0 does actual shutdown
24579 ** (which should be the last to shutdown.) */
24580 if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
24581 if( winMutex_isInit==1 ){
24582 int i;
24583 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
24584 DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
24586 winMutex_isInit = 0;
24589 return SQLITE_OK;
24593 ** The sqlite3_mutex_alloc() routine allocates a new
24594 ** mutex and returns a pointer to it. If it returns NULL
24595 ** that means that a mutex could not be allocated. SQLite
24596 ** will unwind its stack and return an error. The argument
24597 ** to sqlite3_mutex_alloc() is one of these integer constants:
24599 ** <ul>
24600 ** <li> SQLITE_MUTEX_FAST
24601 ** <li> SQLITE_MUTEX_RECURSIVE
24602 ** <li> SQLITE_MUTEX_STATIC_MASTER
24603 ** <li> SQLITE_MUTEX_STATIC_MEM
24604 ** <li> SQLITE_MUTEX_STATIC_OPEN
24605 ** <li> SQLITE_MUTEX_STATIC_PRNG
24606 ** <li> SQLITE_MUTEX_STATIC_LRU
24607 ** <li> SQLITE_MUTEX_STATIC_PMEM
24608 ** <li> SQLITE_MUTEX_STATIC_APP1
24609 ** <li> SQLITE_MUTEX_STATIC_APP2
24610 ** <li> SQLITE_MUTEX_STATIC_APP3
24611 ** <li> SQLITE_MUTEX_STATIC_VFS1
24612 ** <li> SQLITE_MUTEX_STATIC_VFS2
24613 ** <li> SQLITE_MUTEX_STATIC_VFS3
24614 ** </ul>
24616 ** The first two constants cause sqlite3_mutex_alloc() to create
24617 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
24618 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
24619 ** The mutex implementation does not need to make a distinction
24620 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
24621 ** not want to. But SQLite will only request a recursive mutex in
24622 ** cases where it really needs one. If a faster non-recursive mutex
24623 ** implementation is available on the host platform, the mutex subsystem
24624 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
24626 ** The other allowed parameters to sqlite3_mutex_alloc() each return
24627 ** a pointer to a static preexisting mutex. Six static mutexes are
24628 ** used by the current version of SQLite. Future versions of SQLite
24629 ** may add additional static mutexes. Static mutexes are for internal
24630 ** use by SQLite only. Applications that use SQLite mutexes should
24631 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
24632 ** SQLITE_MUTEX_RECURSIVE.
24634 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
24635 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
24636 ** returns a different mutex on every call. But for the static
24637 ** mutex types, the same mutex is returned on every call that has
24638 ** the same type number.
24640 static sqlite3_mutex *winMutexAlloc(int iType){
24641 sqlite3_mutex *p;
24643 switch( iType ){
24644 case SQLITE_MUTEX_FAST:
24645 case SQLITE_MUTEX_RECURSIVE: {
24646 p = sqlite3MallocZero( sizeof(*p) );
24647 if( p ){
24648 p->id = iType;
24649 #ifdef SQLITE_DEBUG
24650 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
24651 p->trace = 1;
24652 #endif
24653 #endif
24654 #if SQLITE_OS_WINRT
24655 InitializeCriticalSectionEx(&p->mutex, 0, 0);
24656 #else
24657 InitializeCriticalSection(&p->mutex);
24658 #endif
24660 break;
24662 default: {
24663 #ifdef SQLITE_ENABLE_API_ARMOR
24664 if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
24665 (void)SQLITE_MISUSE_BKPT;
24666 return 0;
24668 #endif
24669 p = &winMutex_staticMutexes[iType-2];
24670 p->id = iType;
24671 #ifdef SQLITE_DEBUG
24672 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
24673 p->trace = 1;
24674 #endif
24675 #endif
24676 break;
24679 return p;
24684 ** This routine deallocates a previously
24685 ** allocated mutex. SQLite is careful to deallocate every
24686 ** mutex that it allocates.
24688 static void winMutexFree(sqlite3_mutex *p){
24689 assert( p );
24690 assert( p->nRef==0 && p->owner==0 );
24691 if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
24692 DeleteCriticalSection(&p->mutex);
24693 sqlite3_free(p);
24694 }else{
24695 #ifdef SQLITE_ENABLE_API_ARMOR
24696 (void)SQLITE_MISUSE_BKPT;
24697 #endif
24702 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
24703 ** to enter a mutex. If another thread is already within the mutex,
24704 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
24705 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
24706 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
24707 ** be entered multiple times by the same thread. In such cases the,
24708 ** mutex must be exited an equal number of times before another thread
24709 ** can enter. If the same thread tries to enter any other kind of mutex
24710 ** more than once, the behavior is undefined.
24712 static void winMutexEnter(sqlite3_mutex *p){
24713 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
24714 DWORD tid = GetCurrentThreadId();
24715 #endif
24716 #ifdef SQLITE_DEBUG
24717 assert( p );
24718 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
24719 #else
24720 assert( p );
24721 #endif
24722 assert( winMutex_isInit==1 );
24723 EnterCriticalSection(&p->mutex);
24724 #ifdef SQLITE_DEBUG
24725 assert( p->nRef>0 || p->owner==0 );
24726 p->owner = tid;
24727 p->nRef++;
24728 if( p->trace ){
24729 OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
24730 tid, p->id, p, p->trace, p->nRef));
24732 #endif
24735 static int winMutexTry(sqlite3_mutex *p){
24736 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
24737 DWORD tid = GetCurrentThreadId();
24738 #endif
24739 int rc = SQLITE_BUSY;
24740 assert( p );
24741 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
24743 ** The sqlite3_mutex_try() routine is very rarely used, and when it
24744 ** is used it is merely an optimization. So it is OK for it to always
24745 ** fail.
24747 ** The TryEnterCriticalSection() interface is only available on WinNT.
24748 ** And some windows compilers complain if you try to use it without
24749 ** first doing some #defines that prevent SQLite from building on Win98.
24750 ** For that reason, we will omit this optimization for now. See
24751 ** ticket #2685.
24753 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
24754 assert( winMutex_isInit==1 );
24755 assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
24756 if( winMutex_isNt<0 ){
24757 winMutex_isNt = sqlite3_win32_is_nt();
24759 assert( winMutex_isNt==0 || winMutex_isNt==1 );
24760 if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
24761 #ifdef SQLITE_DEBUG
24762 p->owner = tid;
24763 p->nRef++;
24764 #endif
24765 rc = SQLITE_OK;
24767 #else
24768 UNUSED_PARAMETER(p);
24769 #endif
24770 #ifdef SQLITE_DEBUG
24771 if( p->trace ){
24772 OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
24773 tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
24775 #endif
24776 return rc;
24780 ** The sqlite3_mutex_leave() routine exits a mutex that was
24781 ** previously entered by the same thread. The behavior
24782 ** is undefined if the mutex is not currently entered or
24783 ** is not currently allocated. SQLite will never do either.
24785 static void winMutexLeave(sqlite3_mutex *p){
24786 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
24787 DWORD tid = GetCurrentThreadId();
24788 #endif
24789 assert( p );
24790 #ifdef SQLITE_DEBUG
24791 assert( p->nRef>0 );
24792 assert( p->owner==tid );
24793 p->nRef--;
24794 if( p->nRef==0 ) p->owner = 0;
24795 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
24796 #endif
24797 assert( winMutex_isInit==1 );
24798 LeaveCriticalSection(&p->mutex);
24799 #ifdef SQLITE_DEBUG
24800 if( p->trace ){
24801 OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
24802 tid, p->id, p, p->trace, p->nRef));
24804 #endif
24807 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
24808 static const sqlite3_mutex_methods sMutex = {
24809 winMutexInit,
24810 winMutexEnd,
24811 winMutexAlloc,
24812 winMutexFree,
24813 winMutexEnter,
24814 winMutexTry,
24815 winMutexLeave,
24816 #ifdef SQLITE_DEBUG
24817 winMutexHeld,
24818 winMutexNotheld
24819 #else
24822 #endif
24824 return &sMutex;
24827 #endif /* SQLITE_MUTEX_W32 */
24829 /************** End of mutex_w32.c *******************************************/
24830 /************** Begin file malloc.c ******************************************/
24832 ** 2001 September 15
24834 ** The author disclaims copyright to this source code. In place of
24835 ** a legal notice, here is a blessing:
24837 ** May you do good and not evil.
24838 ** May you find forgiveness for yourself and forgive others.
24839 ** May you share freely, never taking more than you give.
24841 *************************************************************************
24843 ** Memory allocation functions used throughout sqlite.
24845 /* #include "sqliteInt.h" */
24846 /* #include <stdarg.h> */
24849 ** Attempt to release up to n bytes of non-essential memory currently
24850 ** held by SQLite. An example of non-essential memory is memory used to
24851 ** cache database pages that are not currently in use.
24853 SQLITE_API int sqlite3_release_memory(int n){
24854 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24855 return sqlite3PcacheReleaseMemory(n);
24856 #else
24857 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
24858 ** is a no-op returning zero if SQLite is not compiled with
24859 ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
24860 UNUSED_PARAMETER(n);
24861 return 0;
24862 #endif
24866 ** State information local to the memory allocation subsystem.
24868 static SQLITE_WSD struct Mem0Global {
24869 sqlite3_mutex *mutex; /* Mutex to serialize access */
24870 sqlite3_int64 alarmThreshold; /* The soft heap limit */
24873 ** True if heap is nearly "full" where "full" is defined by the
24874 ** sqlite3_soft_heap_limit() setting.
24876 int nearlyFull;
24877 } mem0 = { 0, 0, 0 };
24879 #define mem0 GLOBAL(struct Mem0Global, mem0)
24882 ** Return the memory allocator mutex. sqlite3_status() needs it.
24884 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
24885 return mem0.mutex;
24888 #ifndef SQLITE_OMIT_DEPRECATED
24890 ** Deprecated external interface. It used to set an alarm callback
24891 ** that was invoked when memory usage grew too large. Now it is a
24892 ** no-op.
24894 SQLITE_API int sqlite3_memory_alarm(
24895 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
24896 void *pArg,
24897 sqlite3_int64 iThreshold
24899 (void)xCallback;
24900 (void)pArg;
24901 (void)iThreshold;
24902 return SQLITE_OK;
24904 #endif
24907 ** Set the soft heap-size limit for the library. Passing a zero or
24908 ** negative value indicates no limit.
24910 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
24911 sqlite3_int64 priorLimit;
24912 sqlite3_int64 excess;
24913 sqlite3_int64 nUsed;
24914 #ifndef SQLITE_OMIT_AUTOINIT
24915 int rc = sqlite3_initialize();
24916 if( rc ) return -1;
24917 #endif
24918 sqlite3_mutex_enter(mem0.mutex);
24919 priorLimit = mem0.alarmThreshold;
24920 if( n<0 ){
24921 sqlite3_mutex_leave(mem0.mutex);
24922 return priorLimit;
24924 mem0.alarmThreshold = n;
24925 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24926 mem0.nearlyFull = (n>0 && n<=nUsed);
24927 sqlite3_mutex_leave(mem0.mutex);
24928 excess = sqlite3_memory_used() - n;
24929 if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
24930 return priorLimit;
24932 SQLITE_API void sqlite3_soft_heap_limit(int n){
24933 if( n<0 ) n = 0;
24934 sqlite3_soft_heap_limit64(n);
24938 ** Initialize the memory allocation subsystem.
24940 SQLITE_PRIVATE int sqlite3MallocInit(void){
24941 int rc;
24942 if( sqlite3GlobalConfig.m.xMalloc==0 ){
24943 sqlite3MemSetDefault();
24945 memset(&mem0, 0, sizeof(mem0));
24946 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
24947 if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
24948 || sqlite3GlobalConfig.nPage<=0 ){
24949 sqlite3GlobalConfig.pPage = 0;
24950 sqlite3GlobalConfig.szPage = 0;
24952 rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
24953 if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
24954 return rc;
24958 ** Return true if the heap is currently under memory pressure - in other
24959 ** words if the amount of heap used is close to the limit set by
24960 ** sqlite3_soft_heap_limit().
24962 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
24963 return mem0.nearlyFull;
24967 ** Deinitialize the memory allocation subsystem.
24969 SQLITE_PRIVATE void sqlite3MallocEnd(void){
24970 if( sqlite3GlobalConfig.m.xShutdown ){
24971 sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
24973 memset(&mem0, 0, sizeof(mem0));
24977 ** Return the amount of memory currently checked out.
24979 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
24980 sqlite3_int64 res, mx;
24981 sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
24982 return res;
24986 ** Return the maximum amount of memory that has ever been
24987 ** checked out since either the beginning of this process
24988 ** or since the most recent reset.
24990 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
24991 sqlite3_int64 res, mx;
24992 sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
24993 return mx;
24997 ** Trigger the alarm
24999 static void sqlite3MallocAlarm(int nByte){
25000 if( mem0.alarmThreshold<=0 ) return;
25001 sqlite3_mutex_leave(mem0.mutex);
25002 sqlite3_release_memory(nByte);
25003 sqlite3_mutex_enter(mem0.mutex);
25007 ** Do a memory allocation with statistics and alarms. Assume the
25008 ** lock is already held.
25010 static void mallocWithAlarm(int n, void **pp){
25011 void *p;
25012 int nFull;
25013 assert( sqlite3_mutex_held(mem0.mutex) );
25014 assert( n>0 );
25016 /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
25017 ** implementation of malloc_good_size(), which must be called in debug
25018 ** mode and specifically when the DMD "Dark Matter Detector" is enabled
25019 ** or else a crash results. Hence, do not attempt to optimize out the
25020 ** following xRoundup() call. */
25021 nFull = sqlite3GlobalConfig.m.xRoundup(n);
25023 #ifdef SQLITE_MAX_MEMORY
25024 if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
25025 *pp = 0;
25026 return;
25028 #endif
25030 sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
25031 if( mem0.alarmThreshold>0 ){
25032 sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
25033 if( nUsed >= mem0.alarmThreshold - nFull ){
25034 mem0.nearlyFull = 1;
25035 sqlite3MallocAlarm(nFull);
25036 }else{
25037 mem0.nearlyFull = 0;
25040 p = sqlite3GlobalConfig.m.xMalloc(nFull);
25041 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
25042 if( p==0 && mem0.alarmThreshold>0 ){
25043 sqlite3MallocAlarm(nFull);
25044 p = sqlite3GlobalConfig.m.xMalloc(nFull);
25046 #endif
25047 if( p ){
25048 nFull = sqlite3MallocSize(p);
25049 sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
25050 sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
25052 *pp = p;
25056 ** Allocate memory. This routine is like sqlite3_malloc() except that it
25057 ** assumes the memory subsystem has already been initialized.
25059 SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
25060 void *p;
25061 if( n==0 || n>=0x7fffff00 ){
25062 /* A memory allocation of a number of bytes which is near the maximum
25063 ** signed integer value might cause an integer overflow inside of the
25064 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
25065 ** 255 bytes of overhead. SQLite itself will never use anything near
25066 ** this amount. The only way to reach the limit is with sqlite3_malloc() */
25067 p = 0;
25068 }else if( sqlite3GlobalConfig.bMemstat ){
25069 sqlite3_mutex_enter(mem0.mutex);
25070 mallocWithAlarm((int)n, &p);
25071 sqlite3_mutex_leave(mem0.mutex);
25072 }else{
25073 p = sqlite3GlobalConfig.m.xMalloc((int)n);
25075 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
25076 return p;
25080 ** This version of the memory allocation is for use by the application.
25081 ** First make sure the memory subsystem is initialized, then do the
25082 ** allocation.
25084 SQLITE_API void *sqlite3_malloc(int n){
25085 #ifndef SQLITE_OMIT_AUTOINIT
25086 if( sqlite3_initialize() ) return 0;
25087 #endif
25088 return n<=0 ? 0 : sqlite3Malloc(n);
25090 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
25091 #ifndef SQLITE_OMIT_AUTOINIT
25092 if( sqlite3_initialize() ) return 0;
25093 #endif
25094 return sqlite3Malloc(n);
25098 ** TRUE if p is a lookaside memory allocation from db
25100 #ifndef SQLITE_OMIT_LOOKASIDE
25101 static int isLookaside(sqlite3 *db, void *p){
25102 return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
25104 #else
25105 #define isLookaside(A,B) 0
25106 #endif
25109 ** Return the size of a memory allocation previously obtained from
25110 ** sqlite3Malloc() or sqlite3_malloc().
25112 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
25113 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
25114 return sqlite3GlobalConfig.m.xSize(p);
25116 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
25117 assert( p!=0 );
25118 if( db==0 || !isLookaside(db,p) ){
25119 #ifdef SQLITE_DEBUG
25120 if( db==0 ){
25121 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
25122 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
25123 }else{
25124 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25125 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25127 #endif
25128 return sqlite3GlobalConfig.m.xSize(p);
25129 }else{
25130 assert( sqlite3_mutex_held(db->mutex) );
25131 return db->lookaside.sz;
25134 SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
25135 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
25136 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
25137 return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
25141 ** Free memory previously obtained from sqlite3Malloc().
25143 SQLITE_API void sqlite3_free(void *p){
25144 if( p==0 ) return; /* IMP: R-49053-54554 */
25145 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
25146 assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
25147 if( sqlite3GlobalConfig.bMemstat ){
25148 sqlite3_mutex_enter(mem0.mutex);
25149 sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
25150 sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
25151 sqlite3GlobalConfig.m.xFree(p);
25152 sqlite3_mutex_leave(mem0.mutex);
25153 }else{
25154 sqlite3GlobalConfig.m.xFree(p);
25159 ** Add the size of memory allocation "p" to the count in
25160 ** *db->pnBytesFreed.
25162 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
25163 *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
25167 ** Free memory that might be associated with a particular database
25168 ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
25169 ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
25171 SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
25172 assert( db==0 || sqlite3_mutex_held(db->mutex) );
25173 assert( p!=0 );
25174 if( db ){
25175 if( db->pnBytesFreed ){
25176 measureAllocationSize(db, p);
25177 return;
25179 if( isLookaside(db, p) ){
25180 LookasideSlot *pBuf = (LookasideSlot*)p;
25181 #ifdef SQLITE_DEBUG
25182 /* Trash all content in the buffer being freed */
25183 memset(p, 0xaa, db->lookaside.sz);
25184 #endif
25185 pBuf->pNext = db->lookaside.pFree;
25186 db->lookaside.pFree = pBuf;
25187 return;
25190 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25191 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25192 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
25193 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
25194 sqlite3_free(p);
25196 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
25197 assert( db==0 || sqlite3_mutex_held(db->mutex) );
25198 if( p ) sqlite3DbFreeNN(db, p);
25202 ** Change the size of an existing memory allocation
25204 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
25205 int nOld, nNew, nDiff;
25206 void *pNew;
25207 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
25208 assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
25209 if( pOld==0 ){
25210 return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
25212 if( nBytes==0 ){
25213 sqlite3_free(pOld); /* IMP: R-26507-47431 */
25214 return 0;
25216 if( nBytes>=0x7fffff00 ){
25217 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
25218 return 0;
25220 nOld = sqlite3MallocSize(pOld);
25221 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
25222 ** argument to xRealloc is always a value returned by a prior call to
25223 ** xRoundup. */
25224 nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
25225 if( nOld==nNew ){
25226 pNew = pOld;
25227 }else if( sqlite3GlobalConfig.bMemstat ){
25228 sqlite3_mutex_enter(mem0.mutex);
25229 sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
25230 nDiff = nNew - nOld;
25231 if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
25232 mem0.alarmThreshold-nDiff ){
25233 sqlite3MallocAlarm(nDiff);
25235 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
25236 if( pNew==0 && mem0.alarmThreshold>0 ){
25237 sqlite3MallocAlarm((int)nBytes);
25238 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
25240 if( pNew ){
25241 nNew = sqlite3MallocSize(pNew);
25242 sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
25244 sqlite3_mutex_leave(mem0.mutex);
25245 }else{
25246 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
25248 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
25249 return pNew;
25253 ** The public interface to sqlite3Realloc. Make sure that the memory
25254 ** subsystem is initialized prior to invoking sqliteRealloc.
25256 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
25257 #ifndef SQLITE_OMIT_AUTOINIT
25258 if( sqlite3_initialize() ) return 0;
25259 #endif
25260 if( n<0 ) n = 0; /* IMP: R-26507-47431 */
25261 return sqlite3Realloc(pOld, n);
25263 SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
25264 #ifndef SQLITE_OMIT_AUTOINIT
25265 if( sqlite3_initialize() ) return 0;
25266 #endif
25267 return sqlite3Realloc(pOld, n);
25272 ** Allocate and zero memory.
25274 SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
25275 void *p = sqlite3Malloc(n);
25276 if( p ){
25277 memset(p, 0, (size_t)n);
25279 return p;
25283 ** Allocate and zero memory. If the allocation fails, make
25284 ** the mallocFailed flag in the connection pointer.
25286 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
25287 void *p;
25288 testcase( db==0 );
25289 p = sqlite3DbMallocRaw(db, n);
25290 if( p ) memset(p, 0, (size_t)n);
25291 return p;
25295 /* Finish the work of sqlite3DbMallocRawNN for the unusual and
25296 ** slower case when the allocation cannot be fulfilled using lookaside.
25298 static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
25299 void *p;
25300 assert( db!=0 );
25301 p = sqlite3Malloc(n);
25302 if( !p ) sqlite3OomFault(db);
25303 sqlite3MemdebugSetType(p,
25304 (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
25305 return p;
25309 ** Allocate memory, either lookaside (if possible) or heap.
25310 ** If the allocation fails, set the mallocFailed flag in
25311 ** the connection pointer.
25313 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
25314 ** failure on the same database connection) then always return 0.
25315 ** Hence for a particular database connection, once malloc starts
25316 ** failing, it fails consistently until mallocFailed is reset.
25317 ** This is an important assumption. There are many places in the
25318 ** code that do things like this:
25320 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
25321 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
25322 ** if( b ) a[10] = 9;
25324 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
25325 ** that all prior mallocs (ex: "a") worked too.
25327 ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
25328 ** not a NULL pointer.
25330 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
25331 void *p;
25332 if( db ) return sqlite3DbMallocRawNN(db, n);
25333 p = sqlite3Malloc(n);
25334 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
25335 return p;
25337 SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
25338 #ifndef SQLITE_OMIT_LOOKASIDE
25339 LookasideSlot *pBuf;
25340 assert( db!=0 );
25341 assert( sqlite3_mutex_held(db->mutex) );
25342 assert( db->pnBytesFreed==0 );
25343 if( db->lookaside.bDisable==0 ){
25344 assert( db->mallocFailed==0 );
25345 if( n>db->lookaside.sz ){
25346 db->lookaside.anStat[1]++;
25347 }else if( (pBuf = db->lookaside.pFree)!=0 ){
25348 db->lookaside.pFree = pBuf->pNext;
25349 db->lookaside.anStat[0]++;
25350 return (void*)pBuf;
25351 }else if( (pBuf = db->lookaside.pInit)!=0 ){
25352 db->lookaside.pInit = pBuf->pNext;
25353 db->lookaside.anStat[0]++;
25354 return (void*)pBuf;
25355 }else{
25356 db->lookaside.anStat[2]++;
25358 }else if( db->mallocFailed ){
25359 return 0;
25361 #else
25362 assert( db!=0 );
25363 assert( sqlite3_mutex_held(db->mutex) );
25364 assert( db->pnBytesFreed==0 );
25365 if( db->mallocFailed ){
25366 return 0;
25368 #endif
25369 return dbMallocRawFinish(db, n);
25372 /* Forward declaration */
25373 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
25376 ** Resize the block of memory pointed to by p to n bytes. If the
25377 ** resize fails, set the mallocFailed flag in the connection object.
25379 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
25380 assert( db!=0 );
25381 if( p==0 ) return sqlite3DbMallocRawNN(db, n);
25382 assert( sqlite3_mutex_held(db->mutex) );
25383 if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
25384 return dbReallocFinish(db, p, n);
25386 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
25387 void *pNew = 0;
25388 assert( db!=0 );
25389 assert( p!=0 );
25390 if( db->mallocFailed==0 ){
25391 if( isLookaside(db, p) ){
25392 pNew = sqlite3DbMallocRawNN(db, n);
25393 if( pNew ){
25394 memcpy(pNew, p, db->lookaside.sz);
25395 sqlite3DbFree(db, p);
25397 }else{
25398 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25399 assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25400 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
25401 pNew = sqlite3_realloc64(p, n);
25402 if( !pNew ){
25403 sqlite3OomFault(db);
25405 sqlite3MemdebugSetType(pNew,
25406 (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
25409 return pNew;
25413 ** Attempt to reallocate p. If the reallocation fails, then free p
25414 ** and set the mallocFailed flag in the database connection.
25416 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
25417 void *pNew;
25418 pNew = sqlite3DbRealloc(db, p, n);
25419 if( !pNew ){
25420 sqlite3DbFree(db, p);
25422 return pNew;
25426 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
25427 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
25428 ** is because when memory debugging is turned on, these two functions are
25429 ** called via macros that record the current file and line number in the
25430 ** ThreadData structure.
25432 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
25433 char *zNew;
25434 size_t n;
25435 if( z==0 ){
25436 return 0;
25438 n = strlen(z) + 1;
25439 zNew = sqlite3DbMallocRaw(db, n);
25440 if( zNew ){
25441 memcpy(zNew, z, n);
25443 return zNew;
25445 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
25446 char *zNew;
25447 assert( db!=0 );
25448 if( z==0 ){
25449 return 0;
25451 assert( (n&0x7fffffff)==n );
25452 zNew = sqlite3DbMallocRawNN(db, n+1);
25453 if( zNew ){
25454 memcpy(zNew, z, (size_t)n);
25455 zNew[n] = 0;
25457 return zNew;
25461 ** Free any prior content in *pz and replace it with a copy of zNew.
25463 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
25464 sqlite3DbFree(db, *pz);
25465 *pz = sqlite3DbStrDup(db, zNew);
25469 ** Call this routine to record the fact that an OOM (out-of-memory) error
25470 ** has happened. This routine will set db->mallocFailed, and also
25471 ** temporarily disable the lookaside memory allocator and interrupt
25472 ** any running VDBEs.
25474 SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
25475 if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
25476 db->mallocFailed = 1;
25477 if( db->nVdbeExec>0 ){
25478 db->u1.isInterrupted = 1;
25480 db->lookaside.bDisable++;
25485 ** This routine reactivates the memory allocator and clears the
25486 ** db->mallocFailed flag as necessary.
25488 ** The memory allocator is not restarted if there are running
25489 ** VDBEs.
25491 SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
25492 if( db->mallocFailed && db->nVdbeExec==0 ){
25493 db->mallocFailed = 0;
25494 db->u1.isInterrupted = 0;
25495 assert( db->lookaside.bDisable>0 );
25496 db->lookaside.bDisable--;
25501 ** Take actions at the end of an API call to indicate an OOM error
25503 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
25504 sqlite3OomClear(db);
25505 sqlite3Error(db, SQLITE_NOMEM);
25506 return SQLITE_NOMEM_BKPT;
25510 ** This function must be called before exiting any API function (i.e.
25511 ** returning control to the user) that has called sqlite3_malloc or
25512 ** sqlite3_realloc.
25514 ** The returned value is normally a copy of the second argument to this
25515 ** function. However, if a malloc() failure has occurred since the previous
25516 ** invocation SQLITE_NOMEM is returned instead.
25518 ** If an OOM as occurred, then the connection error-code (the value
25519 ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
25521 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
25522 /* If the db handle must hold the connection handle mutex here.
25523 ** Otherwise the read (and possible write) of db->mallocFailed
25524 ** is unsafe, as is the call to sqlite3Error().
25526 assert( db!=0 );
25527 assert( sqlite3_mutex_held(db->mutex) );
25528 if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
25529 return apiOomError(db);
25531 return rc & db->errMask;
25534 /************** End of malloc.c **********************************************/
25535 /************** Begin file printf.c ******************************************/
25537 ** The "printf" code that follows dates from the 1980's. It is in
25538 ** the public domain.
25540 **************************************************************************
25542 ** This file contains code for a set of "printf"-like routines. These
25543 ** routines format strings much like the printf() from the standard C
25544 ** library, though the implementation here has enhancements to support
25545 ** SQLite.
25547 /* #include "sqliteInt.h" */
25550 ** Conversion types fall into various categories as defined by the
25551 ** following enumeration.
25553 #define etRADIX 0 /* non-decimal integer types. %x %o */
25554 #define etFLOAT 1 /* Floating point. %f */
25555 #define etEXP 2 /* Exponentional notation. %e and %E */
25556 #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
25557 #define etSIZE 4 /* Return number of characters processed so far. %n */
25558 #define etSTRING 5 /* Strings. %s */
25559 #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
25560 #define etPERCENT 7 /* Percent symbol. %% */
25561 #define etCHARX 8 /* Characters. %c */
25562 /* The rest are extensions, not normally found in printf() */
25563 #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
25564 #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
25565 NULL pointers replaced by SQL NULL. %Q */
25566 #define etTOKEN 11 /* a pointer to a Token structure */
25567 #define etSRCLIST 12 /* a pointer to a SrcList */
25568 #define etPOINTER 13 /* The %p conversion */
25569 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
25570 #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
25571 #define etDECIMAL 16 /* %d or %u, but not %x, %o */
25573 #define etINVALID 17 /* Any unrecognized conversion type */
25577 ** An "etByte" is an 8-bit unsigned value.
25579 typedef unsigned char etByte;
25582 ** Each builtin conversion character (ex: the 'd' in "%d") is described
25583 ** by an instance of the following structure
25585 typedef struct et_info { /* Information about each format field */
25586 char fmttype; /* The format field code letter */
25587 etByte base; /* The base for radix conversion */
25588 etByte flags; /* One or more of FLAG_ constants below */
25589 etByte type; /* Conversion paradigm */
25590 etByte charset; /* Offset into aDigits[] of the digits string */
25591 etByte prefix; /* Offset into aPrefix[] of the prefix string */
25592 } et_info;
25595 ** Allowed values for et_info.flags
25597 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
25598 #define FLAG_STRING 4 /* Allow infinite precision */
25602 ** The following table is searched linearly, so it is good to put the
25603 ** most frequently used conversion types first.
25605 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
25606 static const char aPrefix[] = "-x0\000X0";
25607 static const et_info fmtinfo[] = {
25608 { 'd', 10, 1, etDECIMAL, 0, 0 },
25609 { 's', 0, 4, etSTRING, 0, 0 },
25610 { 'g', 0, 1, etGENERIC, 30, 0 },
25611 { 'z', 0, 4, etDYNSTRING, 0, 0 },
25612 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
25613 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
25614 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
25615 { 'c', 0, 0, etCHARX, 0, 0 },
25616 { 'o', 8, 0, etRADIX, 0, 2 },
25617 { 'u', 10, 0, etDECIMAL, 0, 0 },
25618 { 'x', 16, 0, etRADIX, 16, 1 },
25619 { 'X', 16, 0, etRADIX, 0, 4 },
25620 #ifndef SQLITE_OMIT_FLOATING_POINT
25621 { 'f', 0, 1, etFLOAT, 0, 0 },
25622 { 'e', 0, 1, etEXP, 30, 0 },
25623 { 'E', 0, 1, etEXP, 14, 0 },
25624 { 'G', 0, 1, etGENERIC, 14, 0 },
25625 #endif
25626 { 'i', 10, 1, etDECIMAL, 0, 0 },
25627 { 'n', 0, 0, etSIZE, 0, 0 },
25628 { '%', 0, 0, etPERCENT, 0, 0 },
25629 { 'p', 16, 0, etPOINTER, 0, 1 },
25631 /* All the rest are undocumented and are for internal use only */
25632 { 'T', 0, 0, etTOKEN, 0, 0 },
25633 { 'S', 0, 0, etSRCLIST, 0, 0 },
25634 { 'r', 10, 1, etORDINAL, 0, 0 },
25638 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
25639 ** conversions will work.
25641 #ifndef SQLITE_OMIT_FLOATING_POINT
25643 ** "*val" is a double such that 0.1 <= *val < 10.0
25644 ** Return the ascii code for the leading digit of *val, then
25645 ** multiply "*val" by 10.0 to renormalize.
25647 ** Example:
25648 ** input: *val = 3.14159
25649 ** output: *val = 1.4159 function return = '3'
25651 ** The counter *cnt is incremented each time. After counter exceeds
25652 ** 16 (the number of significant digits in a 64-bit float) '0' is
25653 ** always returned.
25655 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
25656 int digit;
25657 LONGDOUBLE_TYPE d;
25658 if( (*cnt)<=0 ) return '0';
25659 (*cnt)--;
25660 digit = (int)*val;
25661 d = digit;
25662 digit += '0';
25663 *val = (*val - d)*10.0;
25664 return (char)digit;
25666 #endif /* SQLITE_OMIT_FLOATING_POINT */
25669 ** Set the StrAccum object to an error mode.
25671 static void setStrAccumError(StrAccum *p, u8 eError){
25672 assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
25673 p->accError = eError;
25674 p->nAlloc = 0;
25678 ** Extra argument values from a PrintfArguments object
25680 static sqlite3_int64 getIntArg(PrintfArguments *p){
25681 if( p->nArg<=p->nUsed ) return 0;
25682 return sqlite3_value_int64(p->apArg[p->nUsed++]);
25684 static double getDoubleArg(PrintfArguments *p){
25685 if( p->nArg<=p->nUsed ) return 0.0;
25686 return sqlite3_value_double(p->apArg[p->nUsed++]);
25688 static char *getTextArg(PrintfArguments *p){
25689 if( p->nArg<=p->nUsed ) return 0;
25690 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
25695 ** On machines with a small stack size, you can redefine the
25696 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
25698 #ifndef SQLITE_PRINT_BUF_SIZE
25699 # define SQLITE_PRINT_BUF_SIZE 70
25700 #endif
25701 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
25704 ** Render a string given by "fmt" into the StrAccum object.
25706 SQLITE_PRIVATE void sqlite3VXPrintf(
25707 StrAccum *pAccum, /* Accumulate results here */
25708 const char *fmt, /* Format string */
25709 va_list ap /* arguments */
25711 int c; /* Next character in the format string */
25712 char *bufpt; /* Pointer to the conversion buffer */
25713 int precision; /* Precision of the current field */
25714 int length; /* Length of the field */
25715 int idx; /* A general purpose loop counter */
25716 int width; /* Width of the current field */
25717 etByte flag_leftjustify; /* True if "-" flag is present */
25718 etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
25719 etByte flag_alternateform; /* True if "#" flag is present */
25720 etByte flag_altform2; /* True if "!" flag is present */
25721 etByte flag_zeropad; /* True if field width constant starts with zero */
25722 etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
25723 etByte done; /* Loop termination flag */
25724 etByte cThousand; /* Thousands separator for %d and %u */
25725 etByte xtype = etINVALID; /* Conversion paradigm */
25726 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
25727 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
25728 sqlite_uint64 longvalue; /* Value for integer types */
25729 LONGDOUBLE_TYPE realvalue; /* Value for real types */
25730 const et_info *infop; /* Pointer to the appropriate info structure */
25731 char *zOut; /* Rendering buffer */
25732 int nOut; /* Size of the rendering buffer */
25733 char *zExtra = 0; /* Malloced memory used by some conversion */
25734 #ifndef SQLITE_OMIT_FLOATING_POINT
25735 int exp, e2; /* exponent of real numbers */
25736 int nsd; /* Number of significant digits returned */
25737 double rounder; /* Used for rounding floating point values */
25738 etByte flag_dp; /* True if decimal point should be shown */
25739 etByte flag_rtz; /* True if trailing zeros should be removed */
25740 #endif
25741 PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
25742 char buf[etBUFSIZE]; /* Conversion buffer */
25744 bufpt = 0;
25745 if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
25746 pArgList = va_arg(ap, PrintfArguments*);
25747 bArgList = 1;
25748 }else{
25749 bArgList = 0;
25751 for(; (c=(*fmt))!=0; ++fmt){
25752 if( c!='%' ){
25753 bufpt = (char *)fmt;
25754 #if HAVE_STRCHRNUL
25755 fmt = strchrnul(fmt, '%');
25756 #else
25757 do{ fmt++; }while( *fmt && *fmt != '%' );
25758 #endif
25759 sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
25760 if( *fmt==0 ) break;
25762 if( (c=(*++fmt))==0 ){
25763 sqlite3StrAccumAppend(pAccum, "%", 1);
25764 break;
25766 /* Find out what flags are present */
25767 flag_leftjustify = flag_prefix = cThousand =
25768 flag_alternateform = flag_altform2 = flag_zeropad = 0;
25769 done = 0;
25771 switch( c ){
25772 case '-': flag_leftjustify = 1; break;
25773 case '+': flag_prefix = '+'; break;
25774 case ' ': flag_prefix = ' '; break;
25775 case '#': flag_alternateform = 1; break;
25776 case '!': flag_altform2 = 1; break;
25777 case '0': flag_zeropad = 1; break;
25778 case ',': cThousand = ','; break;
25779 default: done = 1; break;
25781 }while( !done && (c=(*++fmt))!=0 );
25782 /* Get the field width */
25783 if( c=='*' ){
25784 if( bArgList ){
25785 width = (int)getIntArg(pArgList);
25786 }else{
25787 width = va_arg(ap,int);
25789 if( width<0 ){
25790 flag_leftjustify = 1;
25791 width = width >= -2147483647 ? -width : 0;
25793 c = *++fmt;
25794 }else{
25795 unsigned wx = 0;
25796 while( c>='0' && c<='9' ){
25797 wx = wx*10 + c - '0';
25798 c = *++fmt;
25800 testcase( wx>0x7fffffff );
25801 width = wx & 0x7fffffff;
25803 assert( width>=0 );
25804 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
25805 if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
25806 width = SQLITE_PRINTF_PRECISION_LIMIT;
25808 #endif
25810 /* Get the precision */
25811 if( c=='.' ){
25812 c = *++fmt;
25813 if( c=='*' ){
25814 if( bArgList ){
25815 precision = (int)getIntArg(pArgList);
25816 }else{
25817 precision = va_arg(ap,int);
25819 c = *++fmt;
25820 if( precision<0 ){
25821 precision = precision >= -2147483647 ? -precision : -1;
25823 }else{
25824 unsigned px = 0;
25825 while( c>='0' && c<='9' ){
25826 px = px*10 + c - '0';
25827 c = *++fmt;
25829 testcase( px>0x7fffffff );
25830 precision = px & 0x7fffffff;
25832 }else{
25833 precision = -1;
25835 assert( precision>=(-1) );
25836 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
25837 if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
25838 precision = SQLITE_PRINTF_PRECISION_LIMIT;
25840 #endif
25843 /* Get the conversion type modifier */
25844 if( c=='l' ){
25845 flag_long = 1;
25846 c = *++fmt;
25847 if( c=='l' ){
25848 flag_long = 2;
25849 c = *++fmt;
25851 }else{
25852 flag_long = 0;
25854 /* Fetch the info entry for the field */
25855 infop = &fmtinfo[0];
25856 xtype = etINVALID;
25857 for(idx=0; idx<ArraySize(fmtinfo); idx++){
25858 if( c==fmtinfo[idx].fmttype ){
25859 infop = &fmtinfo[idx];
25860 xtype = infop->type;
25861 break;
25866 ** At this point, variables are initialized as follows:
25868 ** flag_alternateform TRUE if a '#' is present.
25869 ** flag_altform2 TRUE if a '!' is present.
25870 ** flag_prefix '+' or ' ' or zero
25871 ** flag_leftjustify TRUE if a '-' is present or if the
25872 ** field width was negative.
25873 ** flag_zeropad TRUE if the width began with 0.
25874 ** flag_long 1 for "l", 2 for "ll"
25875 ** width The specified field width. This is
25876 ** always non-negative. Zero is the default.
25877 ** precision The specified precision. The default
25878 ** is -1.
25879 ** xtype The class of the conversion.
25880 ** infop Pointer to the appropriate info struct.
25882 switch( xtype ){
25883 case etPOINTER:
25884 flag_long = sizeof(char*)==sizeof(i64) ? 2 :
25885 sizeof(char*)==sizeof(long int) ? 1 : 0;
25886 /* Fall through into the next case */
25887 case etORDINAL:
25888 case etRADIX:
25889 cThousand = 0;
25890 /* Fall through into the next case */
25891 case etDECIMAL:
25892 if( infop->flags & FLAG_SIGNED ){
25893 i64 v;
25894 if( bArgList ){
25895 v = getIntArg(pArgList);
25896 }else if( flag_long ){
25897 if( flag_long==2 ){
25898 v = va_arg(ap,i64) ;
25899 }else{
25900 v = va_arg(ap,long int);
25902 }else{
25903 v = va_arg(ap,int);
25905 if( v<0 ){
25906 if( v==SMALLEST_INT64 ){
25907 longvalue = ((u64)1)<<63;
25908 }else{
25909 longvalue = -v;
25911 prefix = '-';
25912 }else{
25913 longvalue = v;
25914 prefix = flag_prefix;
25916 }else{
25917 if( bArgList ){
25918 longvalue = (u64)getIntArg(pArgList);
25919 }else if( flag_long ){
25920 if( flag_long==2 ){
25921 longvalue = va_arg(ap,u64);
25922 }else{
25923 longvalue = va_arg(ap,unsigned long int);
25925 }else{
25926 longvalue = va_arg(ap,unsigned int);
25928 prefix = 0;
25930 if( longvalue==0 ) flag_alternateform = 0;
25931 if( flag_zeropad && precision<width-(prefix!=0) ){
25932 precision = width-(prefix!=0);
25934 if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
25935 nOut = etBUFSIZE;
25936 zOut = buf;
25937 }else{
25938 u64 n = (u64)precision + 10 + precision/3;
25939 zOut = zExtra = sqlite3Malloc( n );
25940 if( zOut==0 ){
25941 setStrAccumError(pAccum, STRACCUM_NOMEM);
25942 return;
25944 nOut = (int)n;
25946 bufpt = &zOut[nOut-1];
25947 if( xtype==etORDINAL ){
25948 static const char zOrd[] = "thstndrd";
25949 int x = (int)(longvalue % 10);
25950 if( x>=4 || (longvalue/10)%10==1 ){
25951 x = 0;
25953 *(--bufpt) = zOrd[x*2+1];
25954 *(--bufpt) = zOrd[x*2];
25957 const char *cset = &aDigits[infop->charset];
25958 u8 base = infop->base;
25959 do{ /* Convert to ascii */
25960 *(--bufpt) = cset[longvalue%base];
25961 longvalue = longvalue/base;
25962 }while( longvalue>0 );
25964 length = (int)(&zOut[nOut-1]-bufpt);
25965 while( precision>length ){
25966 *(--bufpt) = '0'; /* Zero pad */
25967 length++;
25969 if( cThousand ){
25970 int nn = (length - 1)/3; /* Number of "," to insert */
25971 int ix = (length - 1)%3 + 1;
25972 bufpt -= nn;
25973 for(idx=0; nn>0; idx++){
25974 bufpt[idx] = bufpt[idx+nn];
25975 ix--;
25976 if( ix==0 ){
25977 bufpt[++idx] = cThousand;
25978 nn--;
25979 ix = 3;
25983 if( prefix ) *(--bufpt) = prefix; /* Add sign */
25984 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
25985 const char *pre;
25986 char x;
25987 pre = &aPrefix[infop->prefix];
25988 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
25990 length = (int)(&zOut[nOut-1]-bufpt);
25991 break;
25992 case etFLOAT:
25993 case etEXP:
25994 case etGENERIC:
25995 if( bArgList ){
25996 realvalue = getDoubleArg(pArgList);
25997 }else{
25998 realvalue = va_arg(ap,double);
26000 #ifdef SQLITE_OMIT_FLOATING_POINT
26001 length = 0;
26002 #else
26003 if( precision<0 ) precision = 6; /* Set default precision */
26004 if( realvalue<0.0 ){
26005 realvalue = -realvalue;
26006 prefix = '-';
26007 }else{
26008 prefix = flag_prefix;
26010 if( xtype==etGENERIC && precision>0 ) precision--;
26011 testcase( precision>0xfff );
26012 for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
26013 if( xtype==etFLOAT ) realvalue += rounder;
26014 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
26015 exp = 0;
26016 if( sqlite3IsNaN((double)realvalue) ){
26017 bufpt = "NaN";
26018 length = 3;
26019 break;
26021 if( realvalue>0.0 ){
26022 LONGDOUBLE_TYPE scale = 1.0;
26023 while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
26024 while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
26025 while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
26026 realvalue /= scale;
26027 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
26028 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
26029 if( exp>350 ){
26030 bufpt = buf;
26031 buf[0] = prefix;
26032 memcpy(buf+(prefix!=0),"Inf",4);
26033 length = 3+(prefix!=0);
26034 break;
26037 bufpt = buf;
26039 ** If the field type is etGENERIC, then convert to either etEXP
26040 ** or etFLOAT, as appropriate.
26042 if( xtype!=etFLOAT ){
26043 realvalue += rounder;
26044 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
26046 if( xtype==etGENERIC ){
26047 flag_rtz = !flag_alternateform;
26048 if( exp<-4 || exp>precision ){
26049 xtype = etEXP;
26050 }else{
26051 precision = precision - exp;
26052 xtype = etFLOAT;
26054 }else{
26055 flag_rtz = flag_altform2;
26057 if( xtype==etEXP ){
26058 e2 = 0;
26059 }else{
26060 e2 = exp;
26062 if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
26063 bufpt = zExtra
26064 = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
26065 if( bufpt==0 ){
26066 setStrAccumError(pAccum, STRACCUM_NOMEM);
26067 return;
26070 zOut = bufpt;
26071 nsd = 16 + flag_altform2*10;
26072 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
26073 /* The sign in front of the number */
26074 if( prefix ){
26075 *(bufpt++) = prefix;
26077 /* Digits prior to the decimal point */
26078 if( e2<0 ){
26079 *(bufpt++) = '0';
26080 }else{
26081 for(; e2>=0; e2--){
26082 *(bufpt++) = et_getdigit(&realvalue,&nsd);
26085 /* The decimal point */
26086 if( flag_dp ){
26087 *(bufpt++) = '.';
26089 /* "0" digits after the decimal point but before the first
26090 ** significant digit of the number */
26091 for(e2++; e2<0; precision--, e2++){
26092 assert( precision>0 );
26093 *(bufpt++) = '0';
26095 /* Significant digits after the decimal point */
26096 while( (precision--)>0 ){
26097 *(bufpt++) = et_getdigit(&realvalue,&nsd);
26099 /* Remove trailing zeros and the "." if no digits follow the "." */
26100 if( flag_rtz && flag_dp ){
26101 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
26102 assert( bufpt>zOut );
26103 if( bufpt[-1]=='.' ){
26104 if( flag_altform2 ){
26105 *(bufpt++) = '0';
26106 }else{
26107 *(--bufpt) = 0;
26111 /* Add the "eNNN" suffix */
26112 if( xtype==etEXP ){
26113 *(bufpt++) = aDigits[infop->charset];
26114 if( exp<0 ){
26115 *(bufpt++) = '-'; exp = -exp;
26116 }else{
26117 *(bufpt++) = '+';
26119 if( exp>=100 ){
26120 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
26121 exp %= 100;
26123 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
26124 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
26126 *bufpt = 0;
26128 /* The converted number is in buf[] and zero terminated. Output it.
26129 ** Note that the number is in the usual order, not reversed as with
26130 ** integer conversions. */
26131 length = (int)(bufpt-zOut);
26132 bufpt = zOut;
26134 /* Special case: Add leading zeros if the flag_zeropad flag is
26135 ** set and we are not left justified */
26136 if( flag_zeropad && !flag_leftjustify && length < width){
26137 int i;
26138 int nPad = width - length;
26139 for(i=width; i>=nPad; i--){
26140 bufpt[i] = bufpt[i-nPad];
26142 i = prefix!=0;
26143 while( nPad-- ) bufpt[i++] = '0';
26144 length = width;
26146 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
26147 break;
26148 case etSIZE:
26149 if( !bArgList ){
26150 *(va_arg(ap,int*)) = pAccum->nChar;
26152 length = width = 0;
26153 break;
26154 case etPERCENT:
26155 buf[0] = '%';
26156 bufpt = buf;
26157 length = 1;
26158 break;
26159 case etCHARX:
26160 if( bArgList ){
26161 bufpt = getTextArg(pArgList);
26162 c = bufpt ? bufpt[0] : 0;
26163 }else{
26164 c = va_arg(ap,int);
26166 if( precision>1 ){
26167 width -= precision-1;
26168 if( width>1 && !flag_leftjustify ){
26169 sqlite3AppendChar(pAccum, width-1, ' ');
26170 width = 0;
26172 sqlite3AppendChar(pAccum, precision-1, c);
26174 length = 1;
26175 buf[0] = c;
26176 bufpt = buf;
26177 break;
26178 case etSTRING:
26179 case etDYNSTRING:
26180 if( bArgList ){
26181 bufpt = getTextArg(pArgList);
26182 xtype = etSTRING;
26183 }else{
26184 bufpt = va_arg(ap,char*);
26186 if( bufpt==0 ){
26187 bufpt = "";
26188 }else if( xtype==etDYNSTRING ){
26189 zExtra = bufpt;
26191 if( precision>=0 ){
26192 for(length=0; length<precision && bufpt[length]; length++){}
26193 }else{
26194 length = 0x7fffffff & (int)strlen(bufpt);
26196 break;
26197 case etSQLESCAPE: /* Escape ' characters */
26198 case etSQLESCAPE2: /* Escape ' and enclose in '...' */
26199 case etSQLESCAPE3: { /* Escape " characters */
26200 int i, j, k, n, isnull;
26201 int needQuote;
26202 char ch;
26203 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
26204 char *escarg;
26206 if( bArgList ){
26207 escarg = getTextArg(pArgList);
26208 }else{
26209 escarg = va_arg(ap,char*);
26211 isnull = escarg==0;
26212 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
26213 k = precision;
26214 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
26215 if( ch==q ) n++;
26217 needQuote = !isnull && xtype==etSQLESCAPE2;
26218 n += i + 3;
26219 if( n>etBUFSIZE ){
26220 bufpt = zExtra = sqlite3Malloc( n );
26221 if( bufpt==0 ){
26222 setStrAccumError(pAccum, STRACCUM_NOMEM);
26223 return;
26225 }else{
26226 bufpt = buf;
26228 j = 0;
26229 if( needQuote ) bufpt[j++] = q;
26230 k = i;
26231 for(i=0; i<k; i++){
26232 bufpt[j++] = ch = escarg[i];
26233 if( ch==q ) bufpt[j++] = ch;
26235 if( needQuote ) bufpt[j++] = q;
26236 bufpt[j] = 0;
26237 length = j;
26238 /* The precision in %q and %Q means how many input characters to
26239 ** consume, not the length of the output...
26240 ** if( precision>=0 && precision<length ) length = precision; */
26241 break;
26243 case etTOKEN: {
26244 Token *pToken;
26245 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
26246 pToken = va_arg(ap, Token*);
26247 assert( bArgList==0 );
26248 if( pToken && pToken->n ){
26249 sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
26251 length = width = 0;
26252 break;
26254 case etSRCLIST: {
26255 SrcList *pSrc;
26256 int k;
26257 struct SrcList_item *pItem;
26258 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
26259 pSrc = va_arg(ap, SrcList*);
26260 k = va_arg(ap, int);
26261 pItem = &pSrc->a[k];
26262 assert( bArgList==0 );
26263 assert( k>=0 && k<pSrc->nSrc );
26264 if( pItem->zDatabase ){
26265 sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
26266 sqlite3StrAccumAppend(pAccum, ".", 1);
26268 sqlite3StrAccumAppendAll(pAccum, pItem->zName);
26269 length = width = 0;
26270 break;
26272 default: {
26273 assert( xtype==etINVALID );
26274 return;
26276 }/* End switch over the format type */
26278 ** The text of the conversion is pointed to by "bufpt" and is
26279 ** "length" characters long. The field width is "width". Do
26280 ** the output.
26282 width -= length;
26283 if( width>0 ){
26284 if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
26285 sqlite3StrAccumAppend(pAccum, bufpt, length);
26286 if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
26287 }else{
26288 sqlite3StrAccumAppend(pAccum, bufpt, length);
26291 if( zExtra ){
26292 sqlite3DbFree(pAccum->db, zExtra);
26293 zExtra = 0;
26295 }/* End for loop over the format string */
26296 } /* End of function */
26299 ** Enlarge the memory allocation on a StrAccum object so that it is
26300 ** able to accept at least N more bytes of text.
26302 ** Return the number of bytes of text that StrAccum is able to accept
26303 ** after the attempted enlargement. The value returned might be zero.
26305 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
26306 char *zNew;
26307 assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
26308 if( p->accError ){
26309 testcase(p->accError==STRACCUM_TOOBIG);
26310 testcase(p->accError==STRACCUM_NOMEM);
26311 return 0;
26313 if( p->mxAlloc==0 ){
26314 N = p->nAlloc - p->nChar - 1;
26315 setStrAccumError(p, STRACCUM_TOOBIG);
26316 return N;
26317 }else{
26318 char *zOld = isMalloced(p) ? p->zText : 0;
26319 i64 szNew = p->nChar;
26320 szNew += N + 1;
26321 if( szNew+p->nChar<=p->mxAlloc ){
26322 /* Force exponential buffer size growth as long as it does not overflow,
26323 ** to avoid having to call this routine too often */
26324 szNew += p->nChar;
26326 if( szNew > p->mxAlloc ){
26327 sqlite3StrAccumReset(p);
26328 setStrAccumError(p, STRACCUM_TOOBIG);
26329 return 0;
26330 }else{
26331 p->nAlloc = (int)szNew;
26333 if( p->db ){
26334 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
26335 }else{
26336 zNew = sqlite3_realloc64(zOld, p->nAlloc);
26338 if( zNew ){
26339 assert( p->zText!=0 || p->nChar==0 );
26340 if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
26341 p->zText = zNew;
26342 p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
26343 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
26344 }else{
26345 sqlite3StrAccumReset(p);
26346 setStrAccumError(p, STRACCUM_NOMEM);
26347 return 0;
26350 return N;
26354 ** Append N copies of character c to the given string buffer.
26356 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
26357 testcase( p->nChar + (i64)N > 0x7fffffff );
26358 if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
26359 return;
26361 while( (N--)>0 ) p->zText[p->nChar++] = c;
26365 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
26366 ** So enlarge if first, then do the append.
26368 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
26369 ** work (enlarging the buffer) using tail recursion, so that the
26370 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
26372 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
26373 N = sqlite3StrAccumEnlarge(p, N);
26374 if( N>0 ){
26375 memcpy(&p->zText[p->nChar], z, N);
26376 p->nChar += N;
26381 ** Append N bytes of text from z to the StrAccum object. Increase the
26382 ** size of the memory allocation for StrAccum if necessary.
26384 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
26385 assert( z!=0 || N==0 );
26386 assert( p->zText!=0 || p->nChar==0 || p->accError );
26387 assert( N>=0 );
26388 assert( p->accError==0 || p->nAlloc==0 );
26389 if( p->nChar+N >= p->nAlloc ){
26390 enlargeAndAppend(p,z,N);
26391 }else if( N ){
26392 assert( p->zText );
26393 p->nChar += N;
26394 memcpy(&p->zText[p->nChar-N], z, N);
26399 ** Append the complete text of zero-terminated string z[] to the p string.
26401 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
26402 sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
26407 ** Finish off a string by making sure it is zero-terminated.
26408 ** Return a pointer to the resulting string. Return a NULL
26409 ** pointer if any kind of error was encountered.
26411 static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
26412 char *zText;
26413 assert( p->mxAlloc>0 && !isMalloced(p) );
26414 zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
26415 if( zText ){
26416 memcpy(zText, p->zText, p->nChar+1);
26417 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
26418 }else{
26419 setStrAccumError(p, STRACCUM_NOMEM);
26421 p->zText = zText;
26422 return zText;
26424 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
26425 if( p->zText ){
26426 p->zText[p->nChar] = 0;
26427 if( p->mxAlloc>0 && !isMalloced(p) ){
26428 return strAccumFinishRealloc(p);
26431 return p->zText;
26435 ** Reset an StrAccum string. Reclaim all malloced memory.
26437 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
26438 if( isMalloced(p) ){
26439 sqlite3DbFree(p->db, p->zText);
26440 p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
26442 p->zText = 0;
26446 ** Initialize a string accumulator.
26448 ** p: The accumulator to be initialized.
26449 ** db: Pointer to a database connection. May be NULL. Lookaside
26450 ** memory is used if not NULL. db->mallocFailed is set appropriately
26451 ** when not NULL.
26452 ** zBase: An initial buffer. May be NULL in which case the initial buffer
26453 ** is malloced.
26454 ** n: Size of zBase in bytes. If total space requirements never exceed
26455 ** n then no memory allocations ever occur.
26456 ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
26457 ** allocations will ever occur.
26459 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
26460 p->zText = zBase;
26461 p->db = db;
26462 p->nAlloc = n;
26463 p->mxAlloc = mx;
26464 p->nChar = 0;
26465 p->accError = 0;
26466 p->printfFlags = 0;
26470 ** Print into memory obtained from sqliteMalloc(). Use the internal
26471 ** %-conversion extensions.
26473 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
26474 char *z;
26475 char zBase[SQLITE_PRINT_BUF_SIZE];
26476 StrAccum acc;
26477 assert( db!=0 );
26478 sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
26479 db->aLimit[SQLITE_LIMIT_LENGTH]);
26480 acc.printfFlags = SQLITE_PRINTF_INTERNAL;
26481 sqlite3VXPrintf(&acc, zFormat, ap);
26482 z = sqlite3StrAccumFinish(&acc);
26483 if( acc.accError==STRACCUM_NOMEM ){
26484 sqlite3OomFault(db);
26486 return z;
26490 ** Print into memory obtained from sqliteMalloc(). Use the internal
26491 ** %-conversion extensions.
26493 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
26494 va_list ap;
26495 char *z;
26496 va_start(ap, zFormat);
26497 z = sqlite3VMPrintf(db, zFormat, ap);
26498 va_end(ap);
26499 return z;
26503 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
26504 ** %-conversion extensions.
26506 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
26507 char *z;
26508 char zBase[SQLITE_PRINT_BUF_SIZE];
26509 StrAccum acc;
26511 #ifdef SQLITE_ENABLE_API_ARMOR
26512 if( zFormat==0 ){
26513 (void)SQLITE_MISUSE_BKPT;
26514 return 0;
26516 #endif
26517 #ifndef SQLITE_OMIT_AUTOINIT
26518 if( sqlite3_initialize() ) return 0;
26519 #endif
26520 sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
26521 sqlite3VXPrintf(&acc, zFormat, ap);
26522 z = sqlite3StrAccumFinish(&acc);
26523 return z;
26527 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
26528 ** %-conversion extensions.
26530 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
26531 va_list ap;
26532 char *z;
26533 #ifndef SQLITE_OMIT_AUTOINIT
26534 if( sqlite3_initialize() ) return 0;
26535 #endif
26536 va_start(ap, zFormat);
26537 z = sqlite3_vmprintf(zFormat, ap);
26538 va_end(ap);
26539 return z;
26543 ** sqlite3_snprintf() works like snprintf() except that it ignores the
26544 ** current locale settings. This is important for SQLite because we
26545 ** are not able to use a "," as the decimal point in place of "." as
26546 ** specified by some locales.
26548 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
26549 ** from the snprintf() standard. Unfortunately, it is too late to change
26550 ** this without breaking compatibility, so we just have to live with the
26551 ** mistake.
26553 ** sqlite3_vsnprintf() is the varargs version.
26555 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
26556 StrAccum acc;
26557 if( n<=0 ) return zBuf;
26558 #ifdef SQLITE_ENABLE_API_ARMOR
26559 if( zBuf==0 || zFormat==0 ) {
26560 (void)SQLITE_MISUSE_BKPT;
26561 if( zBuf ) zBuf[0] = 0;
26562 return zBuf;
26564 #endif
26565 sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
26566 sqlite3VXPrintf(&acc, zFormat, ap);
26567 zBuf[acc.nChar] = 0;
26568 return zBuf;
26570 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
26571 char *z;
26572 va_list ap;
26573 va_start(ap,zFormat);
26574 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
26575 va_end(ap);
26576 return z;
26580 ** This is the routine that actually formats the sqlite3_log() message.
26581 ** We house it in a separate routine from sqlite3_log() to avoid using
26582 ** stack space on small-stack systems when logging is disabled.
26584 ** sqlite3_log() must render into a static buffer. It cannot dynamically
26585 ** allocate memory because it might be called while the memory allocator
26586 ** mutex is held.
26588 ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
26589 ** certain format characters (%q) or for very large precisions or widths.
26590 ** Care must be taken that any sqlite3_log() calls that occur while the
26591 ** memory mutex is held do not use these mechanisms.
26593 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
26594 StrAccum acc; /* String accumulator */
26595 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
26597 sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
26598 sqlite3VXPrintf(&acc, zFormat, ap);
26599 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
26600 sqlite3StrAccumFinish(&acc));
26604 ** Format and write a message to the log if logging is enabled.
26606 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
26607 va_list ap; /* Vararg list */
26608 if( sqlite3GlobalConfig.xLog ){
26609 va_start(ap, zFormat);
26610 renderLogMsg(iErrCode, zFormat, ap);
26611 va_end(ap);
26615 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
26617 ** A version of printf() that understands %lld. Used for debugging.
26618 ** The printf() built into some versions of windows does not understand %lld
26619 ** and segfaults if you give it a long long int.
26621 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
26622 va_list ap;
26623 StrAccum acc;
26624 char zBuf[500];
26625 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
26626 va_start(ap,zFormat);
26627 sqlite3VXPrintf(&acc, zFormat, ap);
26628 va_end(ap);
26629 sqlite3StrAccumFinish(&acc);
26630 fprintf(stdout,"%s", zBuf);
26631 fflush(stdout);
26633 #endif
26637 ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
26638 ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
26640 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
26641 va_list ap;
26642 va_start(ap,zFormat);
26643 sqlite3VXPrintf(p, zFormat, ap);
26644 va_end(ap);
26647 /************** End of printf.c **********************************************/
26648 /************** Begin file treeview.c ****************************************/
26650 ** 2015-06-08
26652 ** The author disclaims copyright to this source code. In place of
26653 ** a legal notice, here is a blessing:
26655 ** May you do good and not evil.
26656 ** May you find forgiveness for yourself and forgive others.
26657 ** May you share freely, never taking more than you give.
26659 *************************************************************************
26661 ** This file contains C code to implement the TreeView debugging routines.
26662 ** These routines print a parse tree to standard output for debugging and
26663 ** analysis.
26665 ** The interfaces in this file is only available when compiling
26666 ** with SQLITE_DEBUG.
26668 /* #include "sqliteInt.h" */
26669 #ifdef SQLITE_DEBUG
26672 ** Add a new subitem to the tree. The moreToFollow flag indicates that this
26673 ** is not the last item in the tree.
26675 static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
26676 if( p==0 ){
26677 p = sqlite3_malloc64( sizeof(*p) );
26678 if( p==0 ) return 0;
26679 memset(p, 0, sizeof(*p));
26680 }else{
26681 p->iLevel++;
26683 assert( moreToFollow==0 || moreToFollow==1 );
26684 if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
26685 return p;
26689 ** Finished with one layer of the tree
26691 static void sqlite3TreeViewPop(TreeView *p){
26692 if( p==0 ) return;
26693 p->iLevel--;
26694 if( p->iLevel<0 ) sqlite3_free(p);
26698 ** Generate a single line of output for the tree, with a prefix that contains
26699 ** all the appropriate tree lines
26701 static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
26702 va_list ap;
26703 int i;
26704 StrAccum acc;
26705 char zBuf[500];
26706 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
26707 if( p ){
26708 for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
26709 sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
26711 sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
26713 va_start(ap, zFormat);
26714 sqlite3VXPrintf(&acc, zFormat, ap);
26715 va_end(ap);
26716 assert( acc.nChar>0 );
26717 if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
26718 sqlite3StrAccumFinish(&acc);
26719 fprintf(stdout,"%s", zBuf);
26720 fflush(stdout);
26724 ** Shorthand for starting a new tree item that consists of a single label
26726 static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
26727 p = sqlite3TreeViewPush(p, moreFollows);
26728 sqlite3TreeViewLine(p, "%s", zLabel);
26732 ** Generate a human-readable description of a WITH clause.
26734 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
26735 int i;
26736 if( pWith==0 ) return;
26737 if( pWith->nCte==0 ) return;
26738 if( pWith->pOuter ){
26739 sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
26740 }else{
26741 sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
26743 if( pWith->nCte>0 ){
26744 pView = sqlite3TreeViewPush(pView, 1);
26745 for(i=0; i<pWith->nCte; i++){
26746 StrAccum x;
26747 char zLine[1000];
26748 const struct Cte *pCte = &pWith->a[i];
26749 sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
26750 sqlite3XPrintf(&x, "%s", pCte->zName);
26751 if( pCte->pCols && pCte->pCols->nExpr>0 ){
26752 char cSep = '(';
26753 int j;
26754 for(j=0; j<pCte->pCols->nExpr; j++){
26755 sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
26756 cSep = ',';
26758 sqlite3XPrintf(&x, ")");
26760 sqlite3XPrintf(&x, " AS");
26761 sqlite3StrAccumFinish(&x);
26762 sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
26763 sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
26764 sqlite3TreeViewPop(pView);
26766 sqlite3TreeViewPop(pView);
26772 ** Generate a human-readable description of a Select object.
26774 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
26775 int n = 0;
26776 int cnt = 0;
26777 if( p==0 ){
26778 sqlite3TreeViewLine(pView, "nil-SELECT");
26779 return;
26781 pView = sqlite3TreeViewPush(pView, moreToFollow);
26782 if( p->pWith ){
26783 sqlite3TreeViewWith(pView, p->pWith, 1);
26784 cnt = 1;
26785 sqlite3TreeViewPush(pView, 1);
26788 sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
26789 ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
26790 ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
26791 (int)p->nSelectRow
26793 if( cnt++ ) sqlite3TreeViewPop(pView);
26794 if( p->pPrior ){
26795 n = 1000;
26796 }else{
26797 n = 0;
26798 if( p->pSrc && p->pSrc->nSrc ) n++;
26799 if( p->pWhere ) n++;
26800 if( p->pGroupBy ) n++;
26801 if( p->pHaving ) n++;
26802 if( p->pOrderBy ) n++;
26803 if( p->pLimit ) n++;
26804 if( p->pOffset ) n++;
26806 sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
26807 if( p->pSrc && p->pSrc->nSrc ){
26808 int i;
26809 pView = sqlite3TreeViewPush(pView, (n--)>0);
26810 sqlite3TreeViewLine(pView, "FROM");
26811 for(i=0; i<p->pSrc->nSrc; i++){
26812 struct SrcList_item *pItem = &p->pSrc->a[i];
26813 StrAccum x;
26814 char zLine[100];
26815 sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
26816 sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
26817 if( pItem->zDatabase ){
26818 sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
26819 }else if( pItem->zName ){
26820 sqlite3XPrintf(&x, " %s", pItem->zName);
26822 if( pItem->pTab ){
26823 sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
26825 if( pItem->zAlias ){
26826 sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
26828 if( pItem->fg.jointype & JT_LEFT ){
26829 sqlite3XPrintf(&x, " LEFT-JOIN");
26831 sqlite3StrAccumFinish(&x);
26832 sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
26833 if( pItem->pSelect ){
26834 sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
26836 if( pItem->fg.isTabFunc ){
26837 sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
26839 sqlite3TreeViewPop(pView);
26841 sqlite3TreeViewPop(pView);
26843 if( p->pWhere ){
26844 sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
26845 sqlite3TreeViewExpr(pView, p->pWhere, 0);
26846 sqlite3TreeViewPop(pView);
26848 if( p->pGroupBy ){
26849 sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
26851 if( p->pHaving ){
26852 sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
26853 sqlite3TreeViewExpr(pView, p->pHaving, 0);
26854 sqlite3TreeViewPop(pView);
26856 if( p->pOrderBy ){
26857 sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
26859 if( p->pLimit ){
26860 sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
26861 sqlite3TreeViewExpr(pView, p->pLimit, 0);
26862 sqlite3TreeViewPop(pView);
26864 if( p->pOffset ){
26865 sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
26866 sqlite3TreeViewExpr(pView, p->pOffset, 0);
26867 sqlite3TreeViewPop(pView);
26869 if( p->pPrior ){
26870 const char *zOp = "UNION";
26871 switch( p->op ){
26872 case TK_ALL: zOp = "UNION ALL"; break;
26873 case TK_INTERSECT: zOp = "INTERSECT"; break;
26874 case TK_EXCEPT: zOp = "EXCEPT"; break;
26876 sqlite3TreeViewItem(pView, zOp, 1);
26878 p = p->pPrior;
26879 }while( p!=0 );
26880 sqlite3TreeViewPop(pView);
26884 ** Generate a human-readable explanation of an expression tree.
26886 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
26887 const char *zBinOp = 0; /* Binary operator */
26888 const char *zUniOp = 0; /* Unary operator */
26889 char zFlgs[60];
26890 pView = sqlite3TreeViewPush(pView, moreToFollow);
26891 if( pExpr==0 ){
26892 sqlite3TreeViewLine(pView, "nil");
26893 sqlite3TreeViewPop(pView);
26894 return;
26896 if( pExpr->flags ){
26897 if( ExprHasProperty(pExpr, EP_FromJoin) ){
26898 sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x iRJT=%d",
26899 pExpr->flags, pExpr->iRightJoinTable);
26900 }else{
26901 sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
26903 }else{
26904 zFlgs[0] = 0;
26906 switch( pExpr->op ){
26907 case TK_AGG_COLUMN: {
26908 sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
26909 pExpr->iTable, pExpr->iColumn, zFlgs);
26910 break;
26912 case TK_COLUMN: {
26913 if( pExpr->iTable<0 ){
26914 /* This only happens when coding check constraints */
26915 sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
26916 }else{
26917 sqlite3TreeViewLine(pView, "{%d:%d}%s",
26918 pExpr->iTable, pExpr->iColumn, zFlgs);
26920 break;
26922 case TK_INTEGER: {
26923 if( pExpr->flags & EP_IntValue ){
26924 sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
26925 }else{
26926 sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
26928 break;
26930 #ifndef SQLITE_OMIT_FLOATING_POINT
26931 case TK_FLOAT: {
26932 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26933 break;
26935 #endif
26936 case TK_STRING: {
26937 sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
26938 break;
26940 case TK_NULL: {
26941 sqlite3TreeViewLine(pView,"NULL");
26942 break;
26944 #ifndef SQLITE_OMIT_BLOB_LITERAL
26945 case TK_BLOB: {
26946 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26947 break;
26949 #endif
26950 case TK_VARIABLE: {
26951 sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
26952 pExpr->u.zToken, pExpr->iColumn);
26953 break;
26955 case TK_REGISTER: {
26956 sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
26957 break;
26959 case TK_ID: {
26960 sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
26961 break;
26963 #ifndef SQLITE_OMIT_CAST
26964 case TK_CAST: {
26965 /* Expressions of the form: CAST(pLeft AS token) */
26966 sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
26967 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26968 break;
26970 #endif /* SQLITE_OMIT_CAST */
26971 case TK_LT: zBinOp = "LT"; break;
26972 case TK_LE: zBinOp = "LE"; break;
26973 case TK_GT: zBinOp = "GT"; break;
26974 case TK_GE: zBinOp = "GE"; break;
26975 case TK_NE: zBinOp = "NE"; break;
26976 case TK_EQ: zBinOp = "EQ"; break;
26977 case TK_IS: zBinOp = "IS"; break;
26978 case TK_ISNOT: zBinOp = "ISNOT"; break;
26979 case TK_AND: zBinOp = "AND"; break;
26980 case TK_OR: zBinOp = "OR"; break;
26981 case TK_PLUS: zBinOp = "ADD"; break;
26982 case TK_STAR: zBinOp = "MUL"; break;
26983 case TK_MINUS: zBinOp = "SUB"; break;
26984 case TK_REM: zBinOp = "REM"; break;
26985 case TK_BITAND: zBinOp = "BITAND"; break;
26986 case TK_BITOR: zBinOp = "BITOR"; break;
26987 case TK_SLASH: zBinOp = "DIV"; break;
26988 case TK_LSHIFT: zBinOp = "LSHIFT"; break;
26989 case TK_RSHIFT: zBinOp = "RSHIFT"; break;
26990 case TK_CONCAT: zBinOp = "CONCAT"; break;
26991 case TK_DOT: zBinOp = "DOT"; break;
26993 case TK_UMINUS: zUniOp = "UMINUS"; break;
26994 case TK_UPLUS: zUniOp = "UPLUS"; break;
26995 case TK_BITNOT: zUniOp = "BITNOT"; break;
26996 case TK_NOT: zUniOp = "NOT"; break;
26997 case TK_ISNULL: zUniOp = "ISNULL"; break;
26998 case TK_NOTNULL: zUniOp = "NOTNULL"; break;
27000 case TK_SPAN: {
27001 sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
27002 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
27003 break;
27006 case TK_COLLATE: {
27007 sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
27008 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
27009 break;
27012 case TK_AGG_FUNCTION:
27013 case TK_FUNCTION: {
27014 ExprList *pFarg; /* List of function arguments */
27015 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
27016 pFarg = 0;
27017 }else{
27018 pFarg = pExpr->x.pList;
27020 if( pExpr->op==TK_AGG_FUNCTION ){
27021 sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
27022 pExpr->op2, pExpr->u.zToken);
27023 }else{
27024 sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
27026 if( pFarg ){
27027 sqlite3TreeViewExprList(pView, pFarg, 0, 0);
27029 break;
27031 #ifndef SQLITE_OMIT_SUBQUERY
27032 case TK_EXISTS: {
27033 sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
27034 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
27035 break;
27037 case TK_SELECT: {
27038 sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
27039 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
27040 break;
27042 case TK_IN: {
27043 sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
27044 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
27045 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
27046 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
27047 }else{
27048 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
27050 break;
27052 #endif /* SQLITE_OMIT_SUBQUERY */
27055 ** x BETWEEN y AND z
27057 ** This is equivalent to
27059 ** x>=y AND x<=z
27061 ** X is stored in pExpr->pLeft.
27062 ** Y is stored in pExpr->pList->a[0].pExpr.
27063 ** Z is stored in pExpr->pList->a[1].pExpr.
27065 case TK_BETWEEN: {
27066 Expr *pX = pExpr->pLeft;
27067 Expr *pY = pExpr->x.pList->a[0].pExpr;
27068 Expr *pZ = pExpr->x.pList->a[1].pExpr;
27069 sqlite3TreeViewLine(pView, "BETWEEN");
27070 sqlite3TreeViewExpr(pView, pX, 1);
27071 sqlite3TreeViewExpr(pView, pY, 1);
27072 sqlite3TreeViewExpr(pView, pZ, 0);
27073 break;
27075 case TK_TRIGGER: {
27076 /* If the opcode is TK_TRIGGER, then the expression is a reference
27077 ** to a column in the new.* or old.* pseudo-tables available to
27078 ** trigger programs. In this case Expr.iTable is set to 1 for the
27079 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
27080 ** is set to the column of the pseudo-table to read, or to -1 to
27081 ** read the rowid field.
27083 sqlite3TreeViewLine(pView, "%s(%d)",
27084 pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
27085 break;
27087 case TK_CASE: {
27088 sqlite3TreeViewLine(pView, "CASE");
27089 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
27090 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
27091 break;
27093 #ifndef SQLITE_OMIT_TRIGGER
27094 case TK_RAISE: {
27095 const char *zType = "unk";
27096 switch( pExpr->affinity ){
27097 case OE_Rollback: zType = "rollback"; break;
27098 case OE_Abort: zType = "abort"; break;
27099 case OE_Fail: zType = "fail"; break;
27100 case OE_Ignore: zType = "ignore"; break;
27102 sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
27103 break;
27105 #endif
27106 case TK_MATCH: {
27107 sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
27108 pExpr->iTable, pExpr->iColumn, zFlgs);
27109 sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
27110 break;
27112 case TK_VECTOR: {
27113 sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
27114 break;
27116 case TK_SELECT_COLUMN: {
27117 sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
27118 sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
27119 break;
27121 case TK_IF_NULL_ROW: {
27122 sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
27123 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
27124 break;
27126 default: {
27127 sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
27128 break;
27131 if( zBinOp ){
27132 sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
27133 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
27134 sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
27135 }else if( zUniOp ){
27136 sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
27137 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
27139 sqlite3TreeViewPop(pView);
27144 ** Generate a human-readable explanation of an expression list.
27146 SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
27147 TreeView *pView,
27148 const ExprList *pList,
27149 const char *zLabel
27151 if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
27152 if( pList==0 ){
27153 sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
27154 }else{
27155 int i;
27156 sqlite3TreeViewLine(pView, "%s", zLabel);
27157 for(i=0; i<pList->nExpr; i++){
27158 int j = pList->a[i].u.x.iOrderByCol;
27159 if( j ){
27160 sqlite3TreeViewPush(pView, 0);
27161 sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
27163 sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
27164 if( j ) sqlite3TreeViewPop(pView);
27168 SQLITE_PRIVATE void sqlite3TreeViewExprList(
27169 TreeView *pView,
27170 const ExprList *pList,
27171 u8 moreToFollow,
27172 const char *zLabel
27174 pView = sqlite3TreeViewPush(pView, moreToFollow);
27175 sqlite3TreeViewBareExprList(pView, pList, zLabel);
27176 sqlite3TreeViewPop(pView);
27179 #endif /* SQLITE_DEBUG */
27181 /************** End of treeview.c ********************************************/
27182 /************** Begin file random.c ******************************************/
27184 ** 2001 September 15
27186 ** The author disclaims copyright to this source code. In place of
27187 ** a legal notice, here is a blessing:
27189 ** May you do good and not evil.
27190 ** May you find forgiveness for yourself and forgive others.
27191 ** May you share freely, never taking more than you give.
27193 *************************************************************************
27194 ** This file contains code to implement a pseudo-random number
27195 ** generator (PRNG) for SQLite.
27197 ** Random numbers are used by some of the database backends in order
27198 ** to generate random integer keys for tables or random filenames.
27200 /* #include "sqliteInt.h" */
27203 /* All threads share a single random number generator.
27204 ** This structure is the current state of the generator.
27206 static SQLITE_WSD struct sqlite3PrngType {
27207 unsigned char isInit; /* True if initialized */
27208 unsigned char i, j; /* State variables */
27209 unsigned char s[256]; /* State variables */
27210 } sqlite3Prng;
27213 ** Return N random bytes.
27215 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
27216 unsigned char t;
27217 unsigned char *zBuf = pBuf;
27219 /* The "wsdPrng" macro will resolve to the pseudo-random number generator
27220 ** state vector. If writable static data is unsupported on the target,
27221 ** we have to locate the state vector at run-time. In the more common
27222 ** case where writable static data is supported, wsdPrng can refer directly
27223 ** to the "sqlite3Prng" state vector declared above.
27225 #ifdef SQLITE_OMIT_WSD
27226 struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
27227 # define wsdPrng p[0]
27228 #else
27229 # define wsdPrng sqlite3Prng
27230 #endif
27232 #if SQLITE_THREADSAFE
27233 sqlite3_mutex *mutex;
27234 #endif
27236 #ifndef SQLITE_OMIT_AUTOINIT
27237 if( sqlite3_initialize() ) return;
27238 #endif
27240 #if SQLITE_THREADSAFE
27241 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
27242 #endif
27244 sqlite3_mutex_enter(mutex);
27245 if( N<=0 || pBuf==0 ){
27246 wsdPrng.isInit = 0;
27247 sqlite3_mutex_leave(mutex);
27248 return;
27251 /* Initialize the state of the random number generator once,
27252 ** the first time this routine is called. The seed value does
27253 ** not need to contain a lot of randomness since we are not
27254 ** trying to do secure encryption or anything like that...
27256 ** Nothing in this file or anywhere else in SQLite does any kind of
27257 ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
27258 ** number generator) not as an encryption device.
27260 if( !wsdPrng.isInit ){
27261 int i;
27262 char k[256];
27263 wsdPrng.j = 0;
27264 wsdPrng.i = 0;
27265 sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
27266 for(i=0; i<256; i++){
27267 wsdPrng.s[i] = (u8)i;
27269 for(i=0; i<256; i++){
27270 wsdPrng.j += wsdPrng.s[i] + k[i];
27271 t = wsdPrng.s[wsdPrng.j];
27272 wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
27273 wsdPrng.s[i] = t;
27275 wsdPrng.isInit = 1;
27278 assert( N>0 );
27280 wsdPrng.i++;
27281 t = wsdPrng.s[wsdPrng.i];
27282 wsdPrng.j += t;
27283 wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
27284 wsdPrng.s[wsdPrng.j] = t;
27285 t += wsdPrng.s[wsdPrng.i];
27286 *(zBuf++) = wsdPrng.s[t];
27287 }while( --N );
27288 sqlite3_mutex_leave(mutex);
27291 #ifndef SQLITE_UNTESTABLE
27293 ** For testing purposes, we sometimes want to preserve the state of
27294 ** PRNG and restore the PRNG to its saved state at a later time, or
27295 ** to reset the PRNG to its initial state. These routines accomplish
27296 ** those tasks.
27298 ** The sqlite3_test_control() interface calls these routines to
27299 ** control the PRNG.
27301 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
27302 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
27303 memcpy(
27304 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
27305 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
27306 sizeof(sqlite3Prng)
27309 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
27310 memcpy(
27311 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
27312 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
27313 sizeof(sqlite3Prng)
27316 #endif /* SQLITE_UNTESTABLE */
27318 /************** End of random.c **********************************************/
27319 /************** Begin file threads.c *****************************************/
27321 ** 2012 July 21
27323 ** The author disclaims copyright to this source code. In place of
27324 ** a legal notice, here is a blessing:
27326 ** May you do good and not evil.
27327 ** May you find forgiveness for yourself and forgive others.
27328 ** May you share freely, never taking more than you give.
27330 ******************************************************************************
27332 ** This file presents a simple cross-platform threading interface for
27333 ** use internally by SQLite.
27335 ** A "thread" can be created using sqlite3ThreadCreate(). This thread
27336 ** runs independently of its creator until it is joined using
27337 ** sqlite3ThreadJoin(), at which point it terminates.
27339 ** Threads do not have to be real. It could be that the work of the
27340 ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
27341 ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
27342 ** single threaded systems. Nothing in SQLite requires multiple threads.
27343 ** This interface exists so that applications that want to take advantage
27344 ** of multiple cores can do so, while also allowing applications to stay
27345 ** single-threaded if desired.
27347 /* #include "sqliteInt.h" */
27348 #if SQLITE_OS_WIN
27349 /* # include "os_win.h" */
27350 #endif
27352 #if SQLITE_MAX_WORKER_THREADS>0
27354 /********************************* Unix Pthreads ****************************/
27355 #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
27357 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
27358 /* #include <pthread.h> */
27360 /* A running thread */
27361 struct SQLiteThread {
27362 pthread_t tid; /* Thread ID */
27363 int done; /* Set to true when thread finishes */
27364 void *pOut; /* Result returned by the thread */
27365 void *(*xTask)(void*); /* The thread routine */
27366 void *pIn; /* Argument to the thread */
27369 /* Create a new thread */
27370 SQLITE_PRIVATE int sqlite3ThreadCreate(
27371 SQLiteThread **ppThread, /* OUT: Write the thread object here */
27372 void *(*xTask)(void*), /* Routine to run in a separate thread */
27373 void *pIn /* Argument passed into xTask() */
27375 SQLiteThread *p;
27376 int rc;
27378 assert( ppThread!=0 );
27379 assert( xTask!=0 );
27380 /* This routine is never used in single-threaded mode */
27381 assert( sqlite3GlobalConfig.bCoreMutex!=0 );
27383 *ppThread = 0;
27384 p = sqlite3Malloc(sizeof(*p));
27385 if( p==0 ) return SQLITE_NOMEM_BKPT;
27386 memset(p, 0, sizeof(*p));
27387 p->xTask = xTask;
27388 p->pIn = pIn;
27389 /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
27390 ** function that returns SQLITE_ERROR when passed the argument 200, that
27391 ** forces worker threads to run sequentially and deterministically
27392 ** for testing purposes. */
27393 if( sqlite3FaultSim(200) ){
27394 rc = 1;
27395 }else{
27396 rc = pthread_create(&p->tid, 0, xTask, pIn);
27398 if( rc ){
27399 p->done = 1;
27400 p->pOut = xTask(pIn);
27402 *ppThread = p;
27403 return SQLITE_OK;
27406 /* Get the results of the thread */
27407 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
27408 int rc;
27410 assert( ppOut!=0 );
27411 if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
27412 if( p->done ){
27413 *ppOut = p->pOut;
27414 rc = SQLITE_OK;
27415 }else{
27416 rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
27418 sqlite3_free(p);
27419 return rc;
27422 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
27423 /******************************** End Unix Pthreads *************************/
27426 /********************************* Win32 Threads ****************************/
27427 #if SQLITE_OS_WIN_THREADS
27429 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
27430 #include <process.h>
27432 /* A running thread */
27433 struct SQLiteThread {
27434 void *tid; /* The thread handle */
27435 unsigned id; /* The thread identifier */
27436 void *(*xTask)(void*); /* The routine to run as a thread */
27437 void *pIn; /* Argument to xTask */
27438 void *pResult; /* Result of xTask */
27441 /* Thread procedure Win32 compatibility shim */
27442 static unsigned __stdcall sqlite3ThreadProc(
27443 void *pArg /* IN: Pointer to the SQLiteThread structure */
27445 SQLiteThread *p = (SQLiteThread *)pArg;
27447 assert( p!=0 );
27448 #if 0
27450 ** This assert appears to trigger spuriously on certain
27451 ** versions of Windows, possibly due to _beginthreadex()
27452 ** and/or CreateThread() not fully setting their thread
27453 ** ID parameter before starting the thread.
27455 assert( p->id==GetCurrentThreadId() );
27456 #endif
27457 assert( p->xTask!=0 );
27458 p->pResult = p->xTask(p->pIn);
27460 _endthreadex(0);
27461 return 0; /* NOT REACHED */
27464 /* Create a new thread */
27465 SQLITE_PRIVATE int sqlite3ThreadCreate(
27466 SQLiteThread **ppThread, /* OUT: Write the thread object here */
27467 void *(*xTask)(void*), /* Routine to run in a separate thread */
27468 void *pIn /* Argument passed into xTask() */
27470 SQLiteThread *p;
27472 assert( ppThread!=0 );
27473 assert( xTask!=0 );
27474 *ppThread = 0;
27475 p = sqlite3Malloc(sizeof(*p));
27476 if( p==0 ) return SQLITE_NOMEM_BKPT;
27477 /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
27478 ** function that returns SQLITE_ERROR when passed the argument 200, that
27479 ** forces worker threads to run sequentially and deterministically
27480 ** (via the sqlite3FaultSim() term of the conditional) for testing
27481 ** purposes. */
27482 if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
27483 memset(p, 0, sizeof(*p));
27484 }else{
27485 p->xTask = xTask;
27486 p->pIn = pIn;
27487 p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
27488 if( p->tid==0 ){
27489 memset(p, 0, sizeof(*p));
27492 if( p->xTask==0 ){
27493 p->id = GetCurrentThreadId();
27494 p->pResult = xTask(pIn);
27496 *ppThread = p;
27497 return SQLITE_OK;
27500 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
27502 /* Get the results of the thread */
27503 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
27504 DWORD rc;
27505 BOOL bRc;
27507 assert( ppOut!=0 );
27508 if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
27509 if( p->xTask==0 ){
27510 /* assert( p->id==GetCurrentThreadId() ); */
27511 rc = WAIT_OBJECT_0;
27512 assert( p->tid==0 );
27513 }else{
27514 assert( p->id!=0 && p->id!=GetCurrentThreadId() );
27515 rc = sqlite3Win32Wait((HANDLE)p->tid);
27516 assert( rc!=WAIT_IO_COMPLETION );
27517 bRc = CloseHandle((HANDLE)p->tid);
27518 assert( bRc );
27520 if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
27521 sqlite3_free(p);
27522 return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
27525 #endif /* SQLITE_OS_WIN_THREADS */
27526 /******************************** End Win32 Threads *************************/
27529 /********************************* Single-Threaded **************************/
27530 #ifndef SQLITE_THREADS_IMPLEMENTED
27532 ** This implementation does not actually create a new thread. It does the
27533 ** work of the thread in the main thread, when either the thread is created
27534 ** or when it is joined
27537 /* A running thread */
27538 struct SQLiteThread {
27539 void *(*xTask)(void*); /* The routine to run as a thread */
27540 void *pIn; /* Argument to xTask */
27541 void *pResult; /* Result of xTask */
27544 /* Create a new thread */
27545 SQLITE_PRIVATE int sqlite3ThreadCreate(
27546 SQLiteThread **ppThread, /* OUT: Write the thread object here */
27547 void *(*xTask)(void*), /* Routine to run in a separate thread */
27548 void *pIn /* Argument passed into xTask() */
27550 SQLiteThread *p;
27552 assert( ppThread!=0 );
27553 assert( xTask!=0 );
27554 *ppThread = 0;
27555 p = sqlite3Malloc(sizeof(*p));
27556 if( p==0 ) return SQLITE_NOMEM_BKPT;
27557 if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
27558 p->xTask = xTask;
27559 p->pIn = pIn;
27560 }else{
27561 p->xTask = 0;
27562 p->pResult = xTask(pIn);
27564 *ppThread = p;
27565 return SQLITE_OK;
27568 /* Get the results of the thread */
27569 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
27571 assert( ppOut!=0 );
27572 if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
27573 if( p->xTask ){
27574 *ppOut = p->xTask(p->pIn);
27575 }else{
27576 *ppOut = p->pResult;
27578 sqlite3_free(p);
27580 #if defined(SQLITE_TEST)
27582 void *pTstAlloc = sqlite3Malloc(10);
27583 if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
27584 sqlite3_free(pTstAlloc);
27586 #endif
27588 return SQLITE_OK;
27591 #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
27592 /****************************** End Single-Threaded *************************/
27593 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
27595 /************** End of threads.c *********************************************/
27596 /************** Begin file utf.c *********************************************/
27598 ** 2004 April 13
27600 ** The author disclaims copyright to this source code. In place of
27601 ** a legal notice, here is a blessing:
27603 ** May you do good and not evil.
27604 ** May you find forgiveness for yourself and forgive others.
27605 ** May you share freely, never taking more than you give.
27607 *************************************************************************
27608 ** This file contains routines used to translate between UTF-8,
27609 ** UTF-16, UTF-16BE, and UTF-16LE.
27611 ** Notes on UTF-8:
27613 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
27614 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
27615 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
27616 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
27617 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
27620 ** Notes on UTF-16: (with wwww+1==uuuuu)
27622 ** Word-0 Word-1 Value
27623 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
27624 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
27627 ** BOM or Byte Order Mark:
27628 ** 0xff 0xfe little-endian utf-16 follows
27629 ** 0xfe 0xff big-endian utf-16 follows
27632 /* #include "sqliteInt.h" */
27633 /* #include <assert.h> */
27634 /* #include "vdbeInt.h" */
27636 #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
27638 ** The following constant value is used by the SQLITE_BIGENDIAN and
27639 ** SQLITE_LITTLEENDIAN macros.
27641 SQLITE_PRIVATE const int sqlite3one = 1;
27642 #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
27645 ** This lookup table is used to help decode the first byte of
27646 ** a multi-byte UTF8 character.
27648 static const unsigned char sqlite3Utf8Trans1[] = {
27649 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
27650 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
27651 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
27652 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
27653 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
27654 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
27655 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
27656 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
27660 #define WRITE_UTF8(zOut, c) { \
27661 if( c<0x00080 ){ \
27662 *zOut++ = (u8)(c&0xFF); \
27664 else if( c<0x00800 ){ \
27665 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
27666 *zOut++ = 0x80 + (u8)(c & 0x3F); \
27668 else if( c<0x10000 ){ \
27669 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
27670 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
27671 *zOut++ = 0x80 + (u8)(c & 0x3F); \
27672 }else{ \
27673 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
27674 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
27675 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
27676 *zOut++ = 0x80 + (u8)(c & 0x3F); \
27680 #define WRITE_UTF16LE(zOut, c) { \
27681 if( c<=0xFFFF ){ \
27682 *zOut++ = (u8)(c&0x00FF); \
27683 *zOut++ = (u8)((c>>8)&0x00FF); \
27684 }else{ \
27685 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
27686 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
27687 *zOut++ = (u8)(c&0x00FF); \
27688 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
27692 #define WRITE_UTF16BE(zOut, c) { \
27693 if( c<=0xFFFF ){ \
27694 *zOut++ = (u8)((c>>8)&0x00FF); \
27695 *zOut++ = (u8)(c&0x00FF); \
27696 }else{ \
27697 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
27698 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
27699 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
27700 *zOut++ = (u8)(c&0x00FF); \
27704 #define READ_UTF16LE(zIn, TERM, c){ \
27705 c = (*zIn++); \
27706 c += ((*zIn++)<<8); \
27707 if( c>=0xD800 && c<0xE000 && TERM ){ \
27708 int c2 = (*zIn++); \
27709 c2 += ((*zIn++)<<8); \
27710 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
27714 #define READ_UTF16BE(zIn, TERM, c){ \
27715 c = ((*zIn++)<<8); \
27716 c += (*zIn++); \
27717 if( c>=0xD800 && c<0xE000 && TERM ){ \
27718 int c2 = ((*zIn++)<<8); \
27719 c2 += (*zIn++); \
27720 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
27725 ** Translate a single UTF-8 character. Return the unicode value.
27727 ** During translation, assume that the byte that zTerm points
27728 ** is a 0x00.
27730 ** Write a pointer to the next unread byte back into *pzNext.
27732 ** Notes On Invalid UTF-8:
27734 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
27735 ** be encoded as a multi-byte character. Any multi-byte character that
27736 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
27738 ** * This routine never allows a UTF16 surrogate value to be encoded.
27739 ** If a multi-byte character attempts to encode a value between
27740 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
27742 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
27743 ** byte of a character are interpreted as single-byte characters
27744 ** and rendered as themselves even though they are technically
27745 ** invalid characters.
27747 ** * This routine accepts over-length UTF8 encodings
27748 ** for unicode values 0x80 and greater. It does not change over-length
27749 ** encodings to 0xfffd as some systems recommend.
27751 #define READ_UTF8(zIn, zTerm, c) \
27752 c = *(zIn++); \
27753 if( c>=0xc0 ){ \
27754 c = sqlite3Utf8Trans1[c-0xc0]; \
27755 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
27756 c = (c<<6) + (0x3f & *(zIn++)); \
27758 if( c<0x80 \
27759 || (c&0xFFFFF800)==0xD800 \
27760 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
27762 SQLITE_PRIVATE u32 sqlite3Utf8Read(
27763 const unsigned char **pz /* Pointer to string from which to read char */
27765 unsigned int c;
27767 /* Same as READ_UTF8() above but without the zTerm parameter.
27768 ** For this routine, we assume the UTF8 string is always zero-terminated.
27770 c = *((*pz)++);
27771 if( c>=0xc0 ){
27772 c = sqlite3Utf8Trans1[c-0xc0];
27773 while( (*(*pz) & 0xc0)==0x80 ){
27774 c = (c<<6) + (0x3f & *((*pz)++));
27776 if( c<0x80
27777 || (c&0xFFFFF800)==0xD800
27778 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
27780 return c;
27787 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
27788 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
27790 /* #define TRANSLATE_TRACE 1 */
27792 #ifndef SQLITE_OMIT_UTF16
27794 ** This routine transforms the internal text encoding used by pMem to
27795 ** desiredEnc. It is an error if the string is already of the desired
27796 ** encoding, or if *pMem does not contain a string value.
27798 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
27799 int len; /* Maximum length of output string in bytes */
27800 unsigned char *zOut; /* Output buffer */
27801 unsigned char *zIn; /* Input iterator */
27802 unsigned char *zTerm; /* End of input */
27803 unsigned char *z; /* Output iterator */
27804 unsigned int c;
27806 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
27807 assert( pMem->flags&MEM_Str );
27808 assert( pMem->enc!=desiredEnc );
27809 assert( pMem->enc!=0 );
27810 assert( pMem->n>=0 );
27812 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
27814 char zBuf[100];
27815 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
27816 fprintf(stderr, "INPUT: %s\n", zBuf);
27818 #endif
27820 /* If the translation is between UTF-16 little and big endian, then
27821 ** all that is required is to swap the byte order. This case is handled
27822 ** differently from the others.
27824 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
27825 u8 temp;
27826 int rc;
27827 rc = sqlite3VdbeMemMakeWriteable(pMem);
27828 if( rc!=SQLITE_OK ){
27829 assert( rc==SQLITE_NOMEM );
27830 return SQLITE_NOMEM_BKPT;
27832 zIn = (u8*)pMem->z;
27833 zTerm = &zIn[pMem->n&~1];
27834 while( zIn<zTerm ){
27835 temp = *zIn;
27836 *zIn = *(zIn+1);
27837 zIn++;
27838 *zIn++ = temp;
27840 pMem->enc = desiredEnc;
27841 goto translate_out;
27844 /* Set len to the maximum number of bytes required in the output buffer. */
27845 if( desiredEnc==SQLITE_UTF8 ){
27846 /* When converting from UTF-16, the maximum growth results from
27847 ** translating a 2-byte character to a 4-byte UTF-8 character.
27848 ** A single byte is required for the output string
27849 ** nul-terminator.
27851 pMem->n &= ~1;
27852 len = pMem->n * 2 + 1;
27853 }else{
27854 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
27855 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
27856 ** character. Two bytes are required in the output buffer for the
27857 ** nul-terminator.
27859 len = pMem->n * 2 + 2;
27862 /* Set zIn to point at the start of the input buffer and zTerm to point 1
27863 ** byte past the end.
27865 ** Variable zOut is set to point at the output buffer, space obtained
27866 ** from sqlite3_malloc().
27868 zIn = (u8*)pMem->z;
27869 zTerm = &zIn[pMem->n];
27870 zOut = sqlite3DbMallocRaw(pMem->db, len);
27871 if( !zOut ){
27872 return SQLITE_NOMEM_BKPT;
27874 z = zOut;
27876 if( pMem->enc==SQLITE_UTF8 ){
27877 if( desiredEnc==SQLITE_UTF16LE ){
27878 /* UTF-8 -> UTF-16 Little-endian */
27879 while( zIn<zTerm ){
27880 READ_UTF8(zIn, zTerm, c);
27881 WRITE_UTF16LE(z, c);
27883 }else{
27884 assert( desiredEnc==SQLITE_UTF16BE );
27885 /* UTF-8 -> UTF-16 Big-endian */
27886 while( zIn<zTerm ){
27887 READ_UTF8(zIn, zTerm, c);
27888 WRITE_UTF16BE(z, c);
27891 pMem->n = (int)(z - zOut);
27892 *z++ = 0;
27893 }else{
27894 assert( desiredEnc==SQLITE_UTF8 );
27895 if( pMem->enc==SQLITE_UTF16LE ){
27896 /* UTF-16 Little-endian -> UTF-8 */
27897 while( zIn<zTerm ){
27898 READ_UTF16LE(zIn, zIn<zTerm, c);
27899 WRITE_UTF8(z, c);
27901 }else{
27902 /* UTF-16 Big-endian -> UTF-8 */
27903 while( zIn<zTerm ){
27904 READ_UTF16BE(zIn, zIn<zTerm, c);
27905 WRITE_UTF8(z, c);
27908 pMem->n = (int)(z - zOut);
27910 *z = 0;
27911 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
27913 c = pMem->flags;
27914 sqlite3VdbeMemRelease(pMem);
27915 pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
27916 pMem->enc = desiredEnc;
27917 pMem->z = (char*)zOut;
27918 pMem->zMalloc = pMem->z;
27919 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
27921 translate_out:
27922 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
27924 char zBuf[100];
27925 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
27926 fprintf(stderr, "OUTPUT: %s\n", zBuf);
27928 #endif
27929 return SQLITE_OK;
27931 #endif /* SQLITE_OMIT_UTF16 */
27933 #ifndef SQLITE_OMIT_UTF16
27935 ** This routine checks for a byte-order mark at the beginning of the
27936 ** UTF-16 string stored in *pMem. If one is present, it is removed and
27937 ** the encoding of the Mem adjusted. This routine does not do any
27938 ** byte-swapping, it just sets Mem.enc appropriately.
27940 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
27941 ** changed by this function.
27943 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
27944 int rc = SQLITE_OK;
27945 u8 bom = 0;
27947 assert( pMem->n>=0 );
27948 if( pMem->n>1 ){
27949 u8 b1 = *(u8 *)pMem->z;
27950 u8 b2 = *(((u8 *)pMem->z) + 1);
27951 if( b1==0xFE && b2==0xFF ){
27952 bom = SQLITE_UTF16BE;
27954 if( b1==0xFF && b2==0xFE ){
27955 bom = SQLITE_UTF16LE;
27959 if( bom ){
27960 rc = sqlite3VdbeMemMakeWriteable(pMem);
27961 if( rc==SQLITE_OK ){
27962 pMem->n -= 2;
27963 memmove(pMem->z, &pMem->z[2], pMem->n);
27964 pMem->z[pMem->n] = '\0';
27965 pMem->z[pMem->n+1] = '\0';
27966 pMem->flags |= MEM_Term;
27967 pMem->enc = bom;
27970 return rc;
27972 #endif /* SQLITE_OMIT_UTF16 */
27975 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
27976 ** return the number of unicode characters in pZ up to (but not including)
27977 ** the first 0x00 byte. If nByte is not less than zero, return the
27978 ** number of unicode characters in the first nByte of pZ (or up to
27979 ** the first 0x00, whichever comes first).
27981 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
27982 int r = 0;
27983 const u8 *z = (const u8*)zIn;
27984 const u8 *zTerm;
27985 if( nByte>=0 ){
27986 zTerm = &z[nByte];
27987 }else{
27988 zTerm = (const u8*)(-1);
27990 assert( z<=zTerm );
27991 while( *z!=0 && z<zTerm ){
27992 SQLITE_SKIP_UTF8(z);
27993 r++;
27995 return r;
27998 /* This test function is not currently used by the automated test-suite.
27999 ** Hence it is only available in debug builds.
28001 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
28003 ** Translate UTF-8 to UTF-8.
28005 ** This has the effect of making sure that the string is well-formed
28006 ** UTF-8. Miscoded characters are removed.
28008 ** The translation is done in-place and aborted if the output
28009 ** overruns the input.
28011 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
28012 unsigned char *zOut = zIn;
28013 unsigned char *zStart = zIn;
28014 u32 c;
28016 while( zIn[0] && zOut<=zIn ){
28017 c = sqlite3Utf8Read((const u8**)&zIn);
28018 if( c!=0xfffd ){
28019 WRITE_UTF8(zOut, c);
28022 *zOut = 0;
28023 return (int)(zOut - zStart);
28025 #endif
28027 #ifndef SQLITE_OMIT_UTF16
28029 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
28030 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
28031 ** be freed by the calling function.
28033 ** NULL is returned if there is an allocation error.
28035 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
28036 Mem m;
28037 memset(&m, 0, sizeof(m));
28038 m.db = db;
28039 sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
28040 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
28041 if( db->mallocFailed ){
28042 sqlite3VdbeMemRelease(&m);
28043 m.z = 0;
28045 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
28046 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
28047 assert( m.z || db->mallocFailed );
28048 return m.z;
28052 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
28053 ** Return the number of bytes in the first nChar unicode characters
28054 ** in pZ. nChar must be non-negative.
28056 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
28057 int c;
28058 unsigned char const *z = zIn;
28059 int n = 0;
28061 if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
28062 while( n<nChar ){
28063 READ_UTF16BE(z, 1, c);
28064 n++;
28066 }else{
28067 while( n<nChar ){
28068 READ_UTF16LE(z, 1, c);
28069 n++;
28072 return (int)(z-(unsigned char const *)zIn);
28075 #if defined(SQLITE_TEST)
28077 ** This routine is called from the TCL test function "translate_selftest".
28078 ** It checks that the primitives for serializing and deserializing
28079 ** characters in each encoding are inverses of each other.
28081 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
28082 unsigned int i, t;
28083 unsigned char zBuf[20];
28084 unsigned char *z;
28085 int n;
28086 unsigned int c;
28088 for(i=0; i<0x00110000; i++){
28089 z = zBuf;
28090 WRITE_UTF8(z, i);
28091 n = (int)(z-zBuf);
28092 assert( n>0 && n<=4 );
28093 z[0] = 0;
28094 z = zBuf;
28095 c = sqlite3Utf8Read((const u8**)&z);
28096 t = i;
28097 if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
28098 if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
28099 assert( c==t );
28100 assert( (z-zBuf)==n );
28102 for(i=0; i<0x00110000; i++){
28103 if( i>=0xD800 && i<0xE000 ) continue;
28104 z = zBuf;
28105 WRITE_UTF16LE(z, i);
28106 n = (int)(z-zBuf);
28107 assert( n>0 && n<=4 );
28108 z[0] = 0;
28109 z = zBuf;
28110 READ_UTF16LE(z, 1, c);
28111 assert( c==i );
28112 assert( (z-zBuf)==n );
28114 for(i=0; i<0x00110000; i++){
28115 if( i>=0xD800 && i<0xE000 ) continue;
28116 z = zBuf;
28117 WRITE_UTF16BE(z, i);
28118 n = (int)(z-zBuf);
28119 assert( n>0 && n<=4 );
28120 z[0] = 0;
28121 z = zBuf;
28122 READ_UTF16BE(z, 1, c);
28123 assert( c==i );
28124 assert( (z-zBuf)==n );
28127 #endif /* SQLITE_TEST */
28128 #endif /* SQLITE_OMIT_UTF16 */
28130 /************** End of utf.c *************************************************/
28131 /************** Begin file util.c ********************************************/
28133 ** 2001 September 15
28135 ** The author disclaims copyright to this source code. In place of
28136 ** a legal notice, here is a blessing:
28138 ** May you do good and not evil.
28139 ** May you find forgiveness for yourself and forgive others.
28140 ** May you share freely, never taking more than you give.
28142 *************************************************************************
28143 ** Utility functions used throughout sqlite.
28145 ** This file contains functions for allocating memory, comparing
28146 ** strings, and stuff like that.
28149 /* #include "sqliteInt.h" */
28150 /* #include <stdarg.h> */
28151 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
28152 # include <math.h>
28153 #endif
28156 ** Routine needed to support the testcase() macro.
28158 #ifdef SQLITE_COVERAGE_TEST
28159 SQLITE_PRIVATE void sqlite3Coverage(int x){
28160 static unsigned dummy = 0;
28161 dummy += (unsigned)x;
28163 #endif
28166 ** Give a callback to the test harness that can be used to simulate faults
28167 ** in places where it is difficult or expensive to do so purely by means
28168 ** of inputs.
28170 ** The intent of the integer argument is to let the fault simulator know
28171 ** which of multiple sqlite3FaultSim() calls has been hit.
28173 ** Return whatever integer value the test callback returns, or return
28174 ** SQLITE_OK if no test callback is installed.
28176 #ifndef SQLITE_UNTESTABLE
28177 SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
28178 int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
28179 return xCallback ? xCallback(iTest) : SQLITE_OK;
28181 #endif
28183 #ifndef SQLITE_OMIT_FLOATING_POINT
28185 ** Return true if the floating point value is Not a Number (NaN).
28187 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
28188 ** Otherwise, we have our own implementation that works on most systems.
28190 SQLITE_PRIVATE int sqlite3IsNaN(double x){
28191 int rc; /* The value return */
28192 #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
28194 ** Systems that support the isnan() library function should probably
28195 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
28196 ** found that many systems do not have a working isnan() function so
28197 ** this implementation is provided as an alternative.
28199 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
28200 ** On the other hand, the use of -ffast-math comes with the following
28201 ** warning:
28203 ** This option [-ffast-math] should never be turned on by any
28204 ** -O option since it can result in incorrect output for programs
28205 ** which depend on an exact implementation of IEEE or ISO
28206 ** rules/specifications for math functions.
28208 ** Under MSVC, this NaN test may fail if compiled with a floating-
28209 ** point precision mode other than /fp:precise. From the MSDN
28210 ** documentation:
28212 ** The compiler [with /fp:precise] will properly handle comparisons
28213 ** involving NaN. For example, x != x evaluates to true if x is NaN
28214 ** ...
28216 #ifdef __FAST_MATH__
28217 # error SQLite will not work correctly with the -ffast-math option of GCC.
28218 #endif
28219 volatile double y = x;
28220 volatile double z = y;
28221 rc = (y!=z);
28222 #else /* if HAVE_ISNAN */
28223 rc = isnan(x);
28224 #endif /* HAVE_ISNAN */
28225 testcase( rc );
28226 return rc;
28228 #endif /* SQLITE_OMIT_FLOATING_POINT */
28231 ** Compute a string length that is limited to what can be stored in
28232 ** lower 30 bits of a 32-bit signed integer.
28234 ** The value returned will never be negative. Nor will it ever be greater
28235 ** than the actual length of the string. For very long strings (greater
28236 ** than 1GiB) the value returned might be less than the true string length.
28238 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
28239 if( z==0 ) return 0;
28240 return 0x3fffffff & (int)strlen(z);
28244 ** Return the declared type of a column. Or return zDflt if the column
28245 ** has no declared type.
28247 ** The column type is an extra string stored after the zero-terminator on
28248 ** the column name if and only if the COLFLAG_HASTYPE flag is set.
28250 SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
28251 if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
28252 return pCol->zName + strlen(pCol->zName) + 1;
28256 ** Helper function for sqlite3Error() - called rarely. Broken out into
28257 ** a separate routine to avoid unnecessary register saves on entry to
28258 ** sqlite3Error().
28260 static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
28261 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
28262 sqlite3SystemError(db, err_code);
28266 ** Set the current error code to err_code and clear any prior error message.
28267 ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
28268 ** that would be appropriate.
28270 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
28271 assert( db!=0 );
28272 db->errCode = err_code;
28273 if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
28277 ** Load the sqlite3.iSysErrno field if that is an appropriate thing
28278 ** to do based on the SQLite error code in rc.
28280 SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
28281 if( rc==SQLITE_IOERR_NOMEM ) return;
28282 rc &= 0xff;
28283 if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
28284 db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
28289 ** Set the most recent error code and error string for the sqlite
28290 ** handle "db". The error code is set to "err_code".
28292 ** If it is not NULL, string zFormat specifies the format of the
28293 ** error string in the style of the printf functions: The following
28294 ** format characters are allowed:
28296 ** %s Insert a string
28297 ** %z A string that should be freed after use
28298 ** %d Insert an integer
28299 ** %T Insert a token
28300 ** %S Insert the first element of a SrcList
28302 ** zFormat and any string tokens that follow it are assumed to be
28303 ** encoded in UTF-8.
28305 ** To clear the most recent error for sqlite handle "db", sqlite3Error
28306 ** should be called with err_code set to SQLITE_OK and zFormat set
28307 ** to NULL.
28309 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
28310 assert( db!=0 );
28311 db->errCode = err_code;
28312 sqlite3SystemError(db, err_code);
28313 if( zFormat==0 ){
28314 sqlite3Error(db, err_code);
28315 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
28316 char *z;
28317 va_list ap;
28318 va_start(ap, zFormat);
28319 z = sqlite3VMPrintf(db, zFormat, ap);
28320 va_end(ap);
28321 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
28326 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
28327 ** The following formatting characters are allowed:
28329 ** %s Insert a string
28330 ** %z A string that should be freed after use
28331 ** %d Insert an integer
28332 ** %T Insert a token
28333 ** %S Insert the first element of a SrcList
28335 ** This function should be used to report any error that occurs while
28336 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
28337 ** last thing the sqlite3_prepare() function does is copy the error
28338 ** stored by this function into the database handle using sqlite3Error().
28339 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
28340 ** during statement execution (sqlite3_step() etc.).
28342 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
28343 char *zMsg;
28344 va_list ap;
28345 sqlite3 *db = pParse->db;
28346 va_start(ap, zFormat);
28347 zMsg = sqlite3VMPrintf(db, zFormat, ap);
28348 va_end(ap);
28349 if( db->suppressErr ){
28350 sqlite3DbFree(db, zMsg);
28351 }else{
28352 pParse->nErr++;
28353 sqlite3DbFree(db, pParse->zErrMsg);
28354 pParse->zErrMsg = zMsg;
28355 pParse->rc = SQLITE_ERROR;
28360 ** Convert an SQL-style quoted string into a normal string by removing
28361 ** the quote characters. The conversion is done in-place. If the
28362 ** input does not begin with a quote character, then this routine
28363 ** is a no-op.
28365 ** The input string must be zero-terminated. A new zero-terminator
28366 ** is added to the dequoted string.
28368 ** The return value is -1 if no dequoting occurs or the length of the
28369 ** dequoted string, exclusive of the zero terminator, if dequoting does
28370 ** occur.
28372 ** 2002-Feb-14: This routine is extended to remove MS-Access style
28373 ** brackets from around identifiers. For example: "[a-b-c]" becomes
28374 ** "a-b-c".
28376 SQLITE_PRIVATE void sqlite3Dequote(char *z){
28377 char quote;
28378 int i, j;
28379 if( z==0 ) return;
28380 quote = z[0];
28381 if( !sqlite3Isquote(quote) ) return;
28382 if( quote=='[' ) quote = ']';
28383 for(i=1, j=0;; i++){
28384 assert( z[i] );
28385 if( z[i]==quote ){
28386 if( z[i+1]==quote ){
28387 z[j++] = quote;
28388 i++;
28389 }else{
28390 break;
28392 }else{
28393 z[j++] = z[i];
28396 z[j] = 0;
28400 ** Generate a Token object from a string
28402 SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
28403 p->z = z;
28404 p->n = sqlite3Strlen30(z);
28407 /* Convenient short-hand */
28408 #define UpperToLower sqlite3UpperToLower
28411 ** Some systems have stricmp(). Others have strcasecmp(). Because
28412 ** there is no consistency, we will define our own.
28414 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
28415 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
28416 ** the contents of two buffers containing UTF-8 strings in a
28417 ** case-independent fashion, using the same definition of "case
28418 ** independence" that SQLite uses internally when comparing identifiers.
28420 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
28421 if( zLeft==0 ){
28422 return zRight ? -1 : 0;
28423 }else if( zRight==0 ){
28424 return 1;
28426 return sqlite3StrICmp(zLeft, zRight);
28428 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
28429 unsigned char *a, *b;
28430 int c;
28431 a = (unsigned char *)zLeft;
28432 b = (unsigned char *)zRight;
28433 for(;;){
28434 c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
28435 if( c || *a==0 ) break;
28436 a++;
28437 b++;
28439 return c;
28441 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
28442 register unsigned char *a, *b;
28443 if( zLeft==0 ){
28444 return zRight ? -1 : 0;
28445 }else if( zRight==0 ){
28446 return 1;
28448 a = (unsigned char *)zLeft;
28449 b = (unsigned char *)zRight;
28450 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
28451 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
28455 ** The string z[] is an text representation of a real number.
28456 ** Convert this string to a double and write it into *pResult.
28458 ** The string z[] is length bytes in length (bytes, not characters) and
28459 ** uses the encoding enc. The string is not necessarily zero-terminated.
28461 ** Return TRUE if the result is a valid real number (or integer) and FALSE
28462 ** if the string is empty or contains extraneous text. Valid numbers
28463 ** are in one of these formats:
28465 ** [+-]digits[E[+-]digits]
28466 ** [+-]digits.[digits][E[+-]digits]
28467 ** [+-].digits[E[+-]digits]
28469 ** Leading and trailing whitespace is ignored for the purpose of determining
28470 ** validity.
28472 ** If some prefix of the input string is a valid number, this routine
28473 ** returns FALSE but it still converts the prefix and writes the result
28474 ** into *pResult.
28476 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
28477 #ifndef SQLITE_OMIT_FLOATING_POINT
28478 int incr;
28479 const char *zEnd = z + length;
28480 /* sign * significand * (10 ^ (esign * exponent)) */
28481 int sign = 1; /* sign of significand */
28482 i64 s = 0; /* significand */
28483 int d = 0; /* adjust exponent for shifting decimal point */
28484 int esign = 1; /* sign of exponent */
28485 int e = 0; /* exponent */
28486 int eValid = 1; /* True exponent is either not used or is well-formed */
28487 double result;
28488 int nDigits = 0;
28489 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
28491 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
28492 *pResult = 0.0; /* Default return value, in case of an error */
28494 if( enc==SQLITE_UTF8 ){
28495 incr = 1;
28496 }else{
28497 int i;
28498 incr = 2;
28499 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
28500 for(i=3-enc; i<length && z[i]==0; i+=2){}
28501 nonNum = i<length;
28502 zEnd = &z[i^1];
28503 z += (enc&1);
28506 /* skip leading spaces */
28507 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
28508 if( z>=zEnd ) return 0;
28510 /* get sign of significand */
28511 if( *z=='-' ){
28512 sign = -1;
28513 z+=incr;
28514 }else if( *z=='+' ){
28515 z+=incr;
28518 /* copy max significant digits to significand */
28519 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
28520 s = s*10 + (*z - '0');
28521 z+=incr, nDigits++;
28524 /* skip non-significant significand digits
28525 ** (increase exponent by d to shift decimal left) */
28526 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
28527 if( z>=zEnd ) goto do_atof_calc;
28529 /* if decimal point is present */
28530 if( *z=='.' ){
28531 z+=incr;
28532 /* copy digits from after decimal to significand
28533 ** (decrease exponent by d to shift decimal right) */
28534 while( z<zEnd && sqlite3Isdigit(*z) ){
28535 if( s<((LARGEST_INT64-9)/10) ){
28536 s = s*10 + (*z - '0');
28537 d--;
28539 z+=incr, nDigits++;
28542 if( z>=zEnd ) goto do_atof_calc;
28544 /* if exponent is present */
28545 if( *z=='e' || *z=='E' ){
28546 z+=incr;
28547 eValid = 0;
28549 /* This branch is needed to avoid a (harmless) buffer overread. The
28550 ** special comment alerts the mutation tester that the correct answer
28551 ** is obtained even if the branch is omitted */
28552 if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
28554 /* get sign of exponent */
28555 if( *z=='-' ){
28556 esign = -1;
28557 z+=incr;
28558 }else if( *z=='+' ){
28559 z+=incr;
28561 /* copy digits to exponent */
28562 while( z<zEnd && sqlite3Isdigit(*z) ){
28563 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
28564 z+=incr;
28565 eValid = 1;
28569 /* skip trailing spaces */
28570 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
28572 do_atof_calc:
28573 /* adjust exponent by d, and update sign */
28574 e = (e*esign) + d;
28575 if( e<0 ) {
28576 esign = -1;
28577 e *= -1;
28578 } else {
28579 esign = 1;
28582 if( s==0 ) {
28583 /* In the IEEE 754 standard, zero is signed. */
28584 result = sign<0 ? -(double)0 : (double)0;
28585 } else {
28586 /* Attempt to reduce exponent.
28588 ** Branches that are not required for the correct answer but which only
28589 ** help to obtain the correct answer faster are marked with special
28590 ** comments, as a hint to the mutation tester.
28592 while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
28593 if( esign>0 ){
28594 if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
28595 s *= 10;
28596 }else{
28597 if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
28598 s /= 10;
28600 e--;
28603 /* adjust the sign of significand */
28604 s = sign<0 ? -s : s;
28606 if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
28607 result = (double)s;
28608 }else{
28609 LONGDOUBLE_TYPE scale = 1.0;
28610 /* attempt to handle extremely small/large numbers better */
28611 if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
28612 if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
28613 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
28614 if( esign<0 ){
28615 result = s / scale;
28616 result /= 1.0e+308;
28617 }else{
28618 result = s * scale;
28619 result *= 1.0e+308;
28621 }else{ assert( e>=342 );
28622 if( esign<0 ){
28623 result = 0.0*s;
28624 }else{
28625 #ifdef INFINITY
28626 result = INFINITY*s;
28627 #else
28628 result = 1e308*1e308*s; /* Infinity */
28629 #endif
28632 }else{
28633 /* 1.0e+22 is the largest power of 10 than can be
28634 ** represented exactly. */
28635 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
28636 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
28637 if( esign<0 ){
28638 result = s / scale;
28639 }else{
28640 result = s * scale;
28646 /* store the result */
28647 *pResult = result;
28649 /* return true if number and no extra non-whitespace chracters after */
28650 return z==zEnd && nDigits>0 && eValid && nonNum==0;
28651 #else
28652 return !sqlite3Atoi64(z, pResult, length, enc);
28653 #endif /* SQLITE_OMIT_FLOATING_POINT */
28657 ** Compare the 19-character string zNum against the text representation
28658 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
28659 ** if zNum is less than, equal to, or greater than the string.
28660 ** Note that zNum must contain exactly 19 characters.
28662 ** Unlike memcmp() this routine is guaranteed to return the difference
28663 ** in the values of the last digit if the only difference is in the
28664 ** last digit. So, for example,
28666 ** compare2pow63("9223372036854775800", 1)
28668 ** will return -8.
28670 static int compare2pow63(const char *zNum, int incr){
28671 int c = 0;
28672 int i;
28673 /* 012345678901234567 */
28674 const char *pow63 = "922337203685477580";
28675 for(i=0; c==0 && i<18; i++){
28676 c = (zNum[i*incr]-pow63[i])*10;
28678 if( c==0 ){
28679 c = zNum[18*incr] - '8';
28680 testcase( c==(-1) );
28681 testcase( c==0 );
28682 testcase( c==(+1) );
28684 return c;
28688 ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
28689 ** routine does *not* accept hexadecimal notation.
28691 ** Returns:
28693 ** 0 Successful transformation. Fits in a 64-bit signed integer.
28694 ** 1 Excess text after the integer value
28695 ** 2 Integer too large for a 64-bit signed integer or is malformed
28696 ** 3 Special case of 9223372036854775808
28698 ** length is the number of bytes in the string (bytes, not characters).
28699 ** The string is not necessarily zero-terminated. The encoding is
28700 ** given by enc.
28702 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
28703 int incr;
28704 u64 u = 0;
28705 int neg = 0; /* assume positive */
28706 int i;
28707 int c = 0;
28708 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
28709 int rc; /* Baseline return code */
28710 const char *zStart;
28711 const char *zEnd = zNum + length;
28712 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
28713 if( enc==SQLITE_UTF8 ){
28714 incr = 1;
28715 }else{
28716 incr = 2;
28717 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
28718 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
28719 nonNum = i<length;
28720 zEnd = &zNum[i^1];
28721 zNum += (enc&1);
28723 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
28724 if( zNum<zEnd ){
28725 if( *zNum=='-' ){
28726 neg = 1;
28727 zNum+=incr;
28728 }else if( *zNum=='+' ){
28729 zNum+=incr;
28732 zStart = zNum;
28733 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
28734 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
28735 u = u*10 + c - '0';
28737 if( u>LARGEST_INT64 ){
28738 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
28739 }else if( neg ){
28740 *pNum = -(i64)u;
28741 }else{
28742 *pNum = (i64)u;
28744 testcase( i==18 );
28745 testcase( i==19 );
28746 testcase( i==20 );
28747 if( &zNum[i]<zEnd /* Extra bytes at the end */
28748 || (i==0 && zStart==zNum) /* No digits */
28749 || nonNum /* UTF16 with high-order bytes non-zero */
28751 rc = 1;
28752 }else{
28753 rc = 0;
28755 if( i>19*incr ){ /* Too many digits */
28756 /* zNum is empty or contains non-numeric text or is longer
28757 ** than 19 digits (thus guaranteeing that it is too large) */
28758 return 2;
28759 }else if( i<19*incr ){
28760 /* Less than 19 digits, so we know that it fits in 64 bits */
28761 assert( u<=LARGEST_INT64 );
28762 return rc;
28763 }else{
28764 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
28765 c = compare2pow63(zNum, incr);
28766 if( c<0 ){
28767 /* zNum is less than 9223372036854775808 so it fits */
28768 assert( u<=LARGEST_INT64 );
28769 return rc;
28770 }else if( c>0 ){
28771 /* zNum is greater than 9223372036854775808 so it overflows */
28772 return 2;
28773 }else{
28774 /* zNum is exactly 9223372036854775808. Fits if negative. The
28775 ** special case 2 overflow if positive */
28776 assert( u-1==LARGEST_INT64 );
28777 return neg ? rc : 3;
28783 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
28784 ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
28785 ** whereas sqlite3Atoi64() does not.
28787 ** Returns:
28789 ** 0 Successful transformation. Fits in a 64-bit signed integer.
28790 ** 1 Excess text after the integer value
28791 ** 2 Integer too large for a 64-bit signed integer or is malformed
28792 ** 3 Special case of 9223372036854775808
28794 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
28795 #ifndef SQLITE_OMIT_HEX_INTEGER
28796 if( z[0]=='0'
28797 && (z[1]=='x' || z[1]=='X')
28799 u64 u = 0;
28800 int i, k;
28801 for(i=2; z[i]=='0'; i++){}
28802 for(k=i; sqlite3Isxdigit(z[k]); k++){
28803 u = u*16 + sqlite3HexToInt(z[k]);
28805 memcpy(pOut, &u, 8);
28806 return (z[k]==0 && k-i<=16) ? 0 : 2;
28807 }else
28808 #endif /* SQLITE_OMIT_HEX_INTEGER */
28810 return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
28815 ** If zNum represents an integer that will fit in 32-bits, then set
28816 ** *pValue to that integer and return true. Otherwise return false.
28818 ** This routine accepts both decimal and hexadecimal notation for integers.
28820 ** Any non-numeric characters that following zNum are ignored.
28821 ** This is different from sqlite3Atoi64() which requires the
28822 ** input number to be zero-terminated.
28824 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
28825 sqlite_int64 v = 0;
28826 int i, c;
28827 int neg = 0;
28828 if( zNum[0]=='-' ){
28829 neg = 1;
28830 zNum++;
28831 }else if( zNum[0]=='+' ){
28832 zNum++;
28834 #ifndef SQLITE_OMIT_HEX_INTEGER
28835 else if( zNum[0]=='0'
28836 && (zNum[1]=='x' || zNum[1]=='X')
28837 && sqlite3Isxdigit(zNum[2])
28839 u32 u = 0;
28840 zNum += 2;
28841 while( zNum[0]=='0' ) zNum++;
28842 for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
28843 u = u*16 + sqlite3HexToInt(zNum[i]);
28845 if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
28846 memcpy(pValue, &u, 4);
28847 return 1;
28848 }else{
28849 return 0;
28852 #endif
28853 if( !sqlite3Isdigit(zNum[0]) ) return 0;
28854 while( zNum[0]=='0' ) zNum++;
28855 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
28856 v = v*10 + c;
28859 /* The longest decimal representation of a 32 bit integer is 10 digits:
28861 ** 1234567890
28862 ** 2^31 -> 2147483648
28864 testcase( i==10 );
28865 if( i>10 ){
28866 return 0;
28868 testcase( v-neg==2147483647 );
28869 if( v-neg>2147483647 ){
28870 return 0;
28872 if( neg ){
28873 v = -v;
28875 *pValue = (int)v;
28876 return 1;
28880 ** Return a 32-bit integer value extracted from a string. If the
28881 ** string is not an integer, just return 0.
28883 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
28884 int x = 0;
28885 if( z ) sqlite3GetInt32(z, &x);
28886 return x;
28890 ** The variable-length integer encoding is as follows:
28892 ** KEY:
28893 ** A = 0xxxxxxx 7 bits of data and one flag bit
28894 ** B = 1xxxxxxx 7 bits of data and one flag bit
28895 ** C = xxxxxxxx 8 bits of data
28897 ** 7 bits - A
28898 ** 14 bits - BA
28899 ** 21 bits - BBA
28900 ** 28 bits - BBBA
28901 ** 35 bits - BBBBA
28902 ** 42 bits - BBBBBA
28903 ** 49 bits - BBBBBBA
28904 ** 56 bits - BBBBBBBA
28905 ** 64 bits - BBBBBBBBC
28909 ** Write a 64-bit variable-length integer to memory starting at p[0].
28910 ** The length of data write will be between 1 and 9 bytes. The number
28911 ** of bytes written is returned.
28913 ** A variable-length integer consists of the lower 7 bits of each byte
28914 ** for all bytes that have the 8th bit set and one byte with the 8th
28915 ** bit clear. Except, if we get to the 9th byte, it stores the full
28916 ** 8 bits and is the last byte.
28918 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
28919 int i, j, n;
28920 u8 buf[10];
28921 if( v & (((u64)0xff000000)<<32) ){
28922 p[8] = (u8)v;
28923 v >>= 8;
28924 for(i=7; i>=0; i--){
28925 p[i] = (u8)((v & 0x7f) | 0x80);
28926 v >>= 7;
28928 return 9;
28930 n = 0;
28932 buf[n++] = (u8)((v & 0x7f) | 0x80);
28933 v >>= 7;
28934 }while( v!=0 );
28935 buf[0] &= 0x7f;
28936 assert( n<=9 );
28937 for(i=0, j=n-1; j>=0; j--, i++){
28938 p[i] = buf[j];
28940 return n;
28942 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
28943 if( v<=0x7f ){
28944 p[0] = v&0x7f;
28945 return 1;
28947 if( v<=0x3fff ){
28948 p[0] = ((v>>7)&0x7f)|0x80;
28949 p[1] = v&0x7f;
28950 return 2;
28952 return putVarint64(p,v);
28956 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
28957 ** are defined here rather than simply putting the constant expressions
28958 ** inline in order to work around bugs in the RVT compiler.
28960 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
28962 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
28964 #define SLOT_2_0 0x001fc07f
28965 #define SLOT_4_2_0 0xf01fc07f
28969 ** Read a 64-bit variable-length integer from memory starting at p[0].
28970 ** Return the number of bytes read. The value is stored in *v.
28972 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
28973 u32 a,b,s;
28975 a = *p;
28976 /* a: p0 (unmasked) */
28977 if (!(a&0x80))
28979 *v = a;
28980 return 1;
28983 p++;
28984 b = *p;
28985 /* b: p1 (unmasked) */
28986 if (!(b&0x80))
28988 a &= 0x7f;
28989 a = a<<7;
28990 a |= b;
28991 *v = a;
28992 return 2;
28995 /* Verify that constants are precomputed correctly */
28996 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
28997 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
28999 p++;
29000 a = a<<14;
29001 a |= *p;
29002 /* a: p0<<14 | p2 (unmasked) */
29003 if (!(a&0x80))
29005 a &= SLOT_2_0;
29006 b &= 0x7f;
29007 b = b<<7;
29008 a |= b;
29009 *v = a;
29010 return 3;
29013 /* CSE1 from below */
29014 a &= SLOT_2_0;
29015 p++;
29016 b = b<<14;
29017 b |= *p;
29018 /* b: p1<<14 | p3 (unmasked) */
29019 if (!(b&0x80))
29021 b &= SLOT_2_0;
29022 /* moved CSE1 up */
29023 /* a &= (0x7f<<14)|(0x7f); */
29024 a = a<<7;
29025 a |= b;
29026 *v = a;
29027 return 4;
29030 /* a: p0<<14 | p2 (masked) */
29031 /* b: p1<<14 | p3 (unmasked) */
29032 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
29033 /* moved CSE1 up */
29034 /* a &= (0x7f<<14)|(0x7f); */
29035 b &= SLOT_2_0;
29036 s = a;
29037 /* s: p0<<14 | p2 (masked) */
29039 p++;
29040 a = a<<14;
29041 a |= *p;
29042 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
29043 if (!(a&0x80))
29045 /* we can skip these cause they were (effectively) done above
29046 ** while calculating s */
29047 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
29048 /* b &= (0x7f<<14)|(0x7f); */
29049 b = b<<7;
29050 a |= b;
29051 s = s>>18;
29052 *v = ((u64)s)<<32 | a;
29053 return 5;
29056 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
29057 s = s<<7;
29058 s |= b;
29059 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
29061 p++;
29062 b = b<<14;
29063 b |= *p;
29064 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
29065 if (!(b&0x80))
29067 /* we can skip this cause it was (effectively) done above in calc'ing s */
29068 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
29069 a &= SLOT_2_0;
29070 a = a<<7;
29071 a |= b;
29072 s = s>>18;
29073 *v = ((u64)s)<<32 | a;
29074 return 6;
29077 p++;
29078 a = a<<14;
29079 a |= *p;
29080 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
29081 if (!(a&0x80))
29083 a &= SLOT_4_2_0;
29084 b &= SLOT_2_0;
29085 b = b<<7;
29086 a |= b;
29087 s = s>>11;
29088 *v = ((u64)s)<<32 | a;
29089 return 7;
29092 /* CSE2 from below */
29093 a &= SLOT_2_0;
29094 p++;
29095 b = b<<14;
29096 b |= *p;
29097 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
29098 if (!(b&0x80))
29100 b &= SLOT_4_2_0;
29101 /* moved CSE2 up */
29102 /* a &= (0x7f<<14)|(0x7f); */
29103 a = a<<7;
29104 a |= b;
29105 s = s>>4;
29106 *v = ((u64)s)<<32 | a;
29107 return 8;
29110 p++;
29111 a = a<<15;
29112 a |= *p;
29113 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
29115 /* moved CSE2 up */
29116 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
29117 b &= SLOT_2_0;
29118 b = b<<8;
29119 a |= b;
29121 s = s<<4;
29122 b = p[-4];
29123 b &= 0x7f;
29124 b = b>>3;
29125 s |= b;
29127 *v = ((u64)s)<<32 | a;
29129 return 9;
29133 ** Read a 32-bit variable-length integer from memory starting at p[0].
29134 ** Return the number of bytes read. The value is stored in *v.
29136 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
29137 ** integer, then set *v to 0xffffffff.
29139 ** A MACRO version, getVarint32, is provided which inlines the
29140 ** single-byte case. All code should use the MACRO version as
29141 ** this function assumes the single-byte case has already been handled.
29143 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
29144 u32 a,b;
29146 /* The 1-byte case. Overwhelmingly the most common. Handled inline
29147 ** by the getVarin32() macro */
29148 a = *p;
29149 /* a: p0 (unmasked) */
29150 #ifndef getVarint32
29151 if (!(a&0x80))
29153 /* Values between 0 and 127 */
29154 *v = a;
29155 return 1;
29157 #endif
29159 /* The 2-byte case */
29160 p++;
29161 b = *p;
29162 /* b: p1 (unmasked) */
29163 if (!(b&0x80))
29165 /* Values between 128 and 16383 */
29166 a &= 0x7f;
29167 a = a<<7;
29168 *v = a | b;
29169 return 2;
29172 /* The 3-byte case */
29173 p++;
29174 a = a<<14;
29175 a |= *p;
29176 /* a: p0<<14 | p2 (unmasked) */
29177 if (!(a&0x80))
29179 /* Values between 16384 and 2097151 */
29180 a &= (0x7f<<14)|(0x7f);
29181 b &= 0x7f;
29182 b = b<<7;
29183 *v = a | b;
29184 return 3;
29187 /* A 32-bit varint is used to store size information in btrees.
29188 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
29189 ** A 3-byte varint is sufficient, for example, to record the size
29190 ** of a 1048569-byte BLOB or string.
29192 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
29193 ** rare larger cases can be handled by the slower 64-bit varint
29194 ** routine.
29196 #if 1
29198 u64 v64;
29199 u8 n;
29201 p -= 2;
29202 n = sqlite3GetVarint(p, &v64);
29203 assert( n>3 && n<=9 );
29204 if( (v64 & SQLITE_MAX_U32)!=v64 ){
29205 *v = 0xffffffff;
29206 }else{
29207 *v = (u32)v64;
29209 return n;
29212 #else
29213 /* For following code (kept for historical record only) shows an
29214 ** unrolling for the 3- and 4-byte varint cases. This code is
29215 ** slightly faster, but it is also larger and much harder to test.
29217 p++;
29218 b = b<<14;
29219 b |= *p;
29220 /* b: p1<<14 | p3 (unmasked) */
29221 if (!(b&0x80))
29223 /* Values between 2097152 and 268435455 */
29224 b &= (0x7f<<14)|(0x7f);
29225 a &= (0x7f<<14)|(0x7f);
29226 a = a<<7;
29227 *v = a | b;
29228 return 4;
29231 p++;
29232 a = a<<14;
29233 a |= *p;
29234 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
29235 if (!(a&0x80))
29237 /* Values between 268435456 and 34359738367 */
29238 a &= SLOT_4_2_0;
29239 b &= SLOT_4_2_0;
29240 b = b<<7;
29241 *v = a | b;
29242 return 5;
29245 /* We can only reach this point when reading a corrupt database
29246 ** file. In that case we are not in any hurry. Use the (relatively
29247 ** slow) general-purpose sqlite3GetVarint() routine to extract the
29248 ** value. */
29250 u64 v64;
29251 u8 n;
29253 p -= 4;
29254 n = sqlite3GetVarint(p, &v64);
29255 assert( n>5 && n<=9 );
29256 *v = (u32)v64;
29257 return n;
29259 #endif
29263 ** Return the number of bytes that will be needed to store the given
29264 ** 64-bit integer.
29266 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
29267 int i;
29268 for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
29269 return i;
29274 ** Read or write a four-byte big-endian integer value.
29276 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
29277 #if SQLITE_BYTEORDER==4321
29278 u32 x;
29279 memcpy(&x,p,4);
29280 return x;
29281 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
29282 u32 x;
29283 memcpy(&x,p,4);
29284 return __builtin_bswap32(x);
29285 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
29286 u32 x;
29287 memcpy(&x,p,4);
29288 return _byteswap_ulong(x);
29289 #else
29290 testcase( p[0]&0x80 );
29291 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
29292 #endif
29294 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
29295 #if SQLITE_BYTEORDER==4321
29296 memcpy(p,&v,4);
29297 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
29298 u32 x = __builtin_bswap32(v);
29299 memcpy(p,&x,4);
29300 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
29301 u32 x = _byteswap_ulong(v);
29302 memcpy(p,&x,4);
29303 #else
29304 p[0] = (u8)(v>>24);
29305 p[1] = (u8)(v>>16);
29306 p[2] = (u8)(v>>8);
29307 p[3] = (u8)v;
29308 #endif
29314 ** Translate a single byte of Hex into an integer.
29315 ** This routine only works if h really is a valid hexadecimal
29316 ** character: 0..9a..fA..F
29318 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
29319 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
29320 #ifdef SQLITE_ASCII
29321 h += 9*(1&(h>>6));
29322 #endif
29323 #ifdef SQLITE_EBCDIC
29324 h += 9*(1&~(h>>4));
29325 #endif
29326 return (u8)(h & 0xf);
29329 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
29331 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
29332 ** value. Return a pointer to its binary value. Space to hold the
29333 ** binary value has been obtained from malloc and must be freed by
29334 ** the calling routine.
29336 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
29337 char *zBlob;
29338 int i;
29340 zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
29341 n--;
29342 if( zBlob ){
29343 for(i=0; i<n; i+=2){
29344 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
29346 zBlob[i/2] = 0;
29348 return zBlob;
29350 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
29353 ** Log an error that is an API call on a connection pointer that should
29354 ** not have been used. The "type" of connection pointer is given as the
29355 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
29357 static void logBadConnection(const char *zType){
29358 sqlite3_log(SQLITE_MISUSE,
29359 "API call with %s database connection pointer",
29360 zType
29365 ** Check to make sure we have a valid db pointer. This test is not
29366 ** foolproof but it does provide some measure of protection against
29367 ** misuse of the interface such as passing in db pointers that are
29368 ** NULL or which have been previously closed. If this routine returns
29369 ** 1 it means that the db pointer is valid and 0 if it should not be
29370 ** dereferenced for any reason. The calling function should invoke
29371 ** SQLITE_MISUSE immediately.
29373 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
29374 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
29375 ** open properly and is not fit for general use but which can be
29376 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
29378 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
29379 u32 magic;
29380 if( db==0 ){
29381 logBadConnection("NULL");
29382 return 0;
29384 magic = db->magic;
29385 if( magic!=SQLITE_MAGIC_OPEN ){
29386 if( sqlite3SafetyCheckSickOrOk(db) ){
29387 testcase( sqlite3GlobalConfig.xLog!=0 );
29388 logBadConnection("unopened");
29390 return 0;
29391 }else{
29392 return 1;
29395 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
29396 u32 magic;
29397 magic = db->magic;
29398 if( magic!=SQLITE_MAGIC_SICK &&
29399 magic!=SQLITE_MAGIC_OPEN &&
29400 magic!=SQLITE_MAGIC_BUSY ){
29401 testcase( sqlite3GlobalConfig.xLog!=0 );
29402 logBadConnection("invalid");
29403 return 0;
29404 }else{
29405 return 1;
29410 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
29411 ** the other 64-bit signed integer at *pA and store the result in *pA.
29412 ** Return 0 on success. Or if the operation would have resulted in an
29413 ** overflow, leave *pA unchanged and return 1.
29415 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
29416 #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
29417 return __builtin_add_overflow(*pA, iB, pA);
29418 #else
29419 i64 iA = *pA;
29420 testcase( iA==0 ); testcase( iA==1 );
29421 testcase( iB==-1 ); testcase( iB==0 );
29422 if( iB>=0 ){
29423 testcase( iA>0 && LARGEST_INT64 - iA == iB );
29424 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
29425 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
29426 }else{
29427 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
29428 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
29429 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
29431 *pA += iB;
29432 return 0;
29433 #endif
29435 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
29436 #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
29437 return __builtin_sub_overflow(*pA, iB, pA);
29438 #else
29439 testcase( iB==SMALLEST_INT64+1 );
29440 if( iB==SMALLEST_INT64 ){
29441 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
29442 if( (*pA)>=0 ) return 1;
29443 *pA -= iB;
29444 return 0;
29445 }else{
29446 return sqlite3AddInt64(pA, -iB);
29448 #endif
29450 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
29451 #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
29452 return __builtin_mul_overflow(*pA, iB, pA);
29453 #else
29454 i64 iA = *pA;
29455 if( iB>0 ){
29456 if( iA>LARGEST_INT64/iB ) return 1;
29457 if( iA<SMALLEST_INT64/iB ) return 1;
29458 }else if( iB<0 ){
29459 if( iA>0 ){
29460 if( iB<SMALLEST_INT64/iA ) return 1;
29461 }else if( iA<0 ){
29462 if( iB==SMALLEST_INT64 ) return 1;
29463 if( iA==SMALLEST_INT64 ) return 1;
29464 if( -iA>LARGEST_INT64/-iB ) return 1;
29467 *pA = iA*iB;
29468 return 0;
29469 #endif
29473 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
29474 ** if the integer has a value of -2147483648, return +2147483647
29476 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
29477 if( x>=0 ) return x;
29478 if( x==(int)0x80000000 ) return 0x7fffffff;
29479 return -x;
29482 #ifdef SQLITE_ENABLE_8_3_NAMES
29484 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
29485 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
29486 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
29487 ** three characters, then shorten the suffix on z[] to be the last three
29488 ** characters of the original suffix.
29490 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
29491 ** do the suffix shortening regardless of URI parameter.
29493 ** Examples:
29495 ** test.db-journal => test.nal
29496 ** test.db-wal => test.wal
29497 ** test.db-shm => test.shm
29498 ** test.db-mj7f3319fa => test.9fa
29500 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
29501 #if SQLITE_ENABLE_8_3_NAMES<2
29502 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
29503 #endif
29505 int i, sz;
29506 sz = sqlite3Strlen30(z);
29507 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
29508 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
29511 #endif
29514 ** Find (an approximate) sum of two LogEst values. This computation is
29515 ** not a simple "+" operator because LogEst is stored as a logarithmic
29516 ** value.
29519 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
29520 static const unsigned char x[] = {
29521 10, 10, /* 0,1 */
29522 9, 9, /* 2,3 */
29523 8, 8, /* 4,5 */
29524 7, 7, 7, /* 6,7,8 */
29525 6, 6, 6, /* 9,10,11 */
29526 5, 5, 5, /* 12-14 */
29527 4, 4, 4, 4, /* 15-18 */
29528 3, 3, 3, 3, 3, 3, /* 19-24 */
29529 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
29531 if( a>=b ){
29532 if( a>b+49 ) return a;
29533 if( a>b+31 ) return a+1;
29534 return a+x[a-b];
29535 }else{
29536 if( b>a+49 ) return b;
29537 if( b>a+31 ) return b+1;
29538 return b+x[b-a];
29543 ** Convert an integer into a LogEst. In other words, compute an
29544 ** approximation for 10*log2(x).
29546 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
29547 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
29548 LogEst y = 40;
29549 if( x<8 ){
29550 if( x<2 ) return 0;
29551 while( x<8 ){ y -= 10; x <<= 1; }
29552 }else{
29553 #if GCC_VERSION>=5004000
29554 int i = 60 - __builtin_clzll(x);
29555 y += i*10;
29556 x >>= i;
29557 #else
29558 while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
29559 while( x>15 ){ y += 10; x >>= 1; }
29560 #endif
29562 return a[x&7] + y - 10;
29565 #ifndef SQLITE_OMIT_VIRTUALTABLE
29567 ** Convert a double into a LogEst
29568 ** In other words, compute an approximation for 10*log2(x).
29570 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
29571 u64 a;
29572 LogEst e;
29573 assert( sizeof(x)==8 && sizeof(a)==8 );
29574 if( x<=1 ) return 0;
29575 if( x<=2000000000 ) return sqlite3LogEst((u64)x);
29576 memcpy(&a, &x, 8);
29577 e = (a>>52) - 1022;
29578 return e*10;
29580 #endif /* SQLITE_OMIT_VIRTUALTABLE */
29582 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
29583 defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
29584 defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
29586 ** Convert a LogEst into an integer.
29588 ** Note that this routine is only used when one or more of various
29589 ** non-standard compile-time options is enabled.
29591 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
29592 u64 n;
29593 n = x%10;
29594 x /= 10;
29595 if( n>=5 ) n -= 2;
29596 else if( n>=1 ) n -= 1;
29597 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
29598 defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
29599 if( x>60 ) return (u64)LARGEST_INT64;
29600 #else
29601 /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
29602 ** possible to this routine is 310, resulting in a maximum x of 31 */
29603 assert( x<=60 );
29604 #endif
29605 return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
29607 #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
29610 ** Add a new name/number pair to a VList. This might require that the
29611 ** VList object be reallocated, so return the new VList. If an OOM
29612 ** error occurs, the original VList returned and the
29613 ** db->mallocFailed flag is set.
29615 ** A VList is really just an array of integers. To destroy a VList,
29616 ** simply pass it to sqlite3DbFree().
29618 ** The first integer is the number of integers allocated for the whole
29619 ** VList. The second integer is the number of integers actually used.
29620 ** Each name/number pair is encoded by subsequent groups of 3 or more
29621 ** integers.
29623 ** Each name/number pair starts with two integers which are the numeric
29624 ** value for the pair and the size of the name/number pair, respectively.
29625 ** The text name overlays one or more following integers. The text name
29626 ** is always zero-terminated.
29628 ** Conceptually:
29630 ** struct VList {
29631 ** int nAlloc; // Number of allocated slots
29632 ** int nUsed; // Number of used slots
29633 ** struct VListEntry {
29634 ** int iValue; // Value for this entry
29635 ** int nSlot; // Slots used by this entry
29636 ** // ... variable name goes here
29637 ** } a[0];
29638 ** }
29640 ** During code generation, pointers to the variable names within the
29641 ** VList are taken. When that happens, nAlloc is set to zero as an
29642 ** indication that the VList may never again be enlarged, since the
29643 ** accompanying realloc() would invalidate the pointers.
29645 SQLITE_PRIVATE VList *sqlite3VListAdd(
29646 sqlite3 *db, /* The database connection used for malloc() */
29647 VList *pIn, /* The input VList. Might be NULL */
29648 const char *zName, /* Name of symbol to add */
29649 int nName, /* Bytes of text in zName */
29650 int iVal /* Value to associate with zName */
29652 int nInt; /* number of sizeof(int) objects needed for zName */
29653 char *z; /* Pointer to where zName will be stored */
29654 int i; /* Index in pIn[] where zName is stored */
29656 nInt = nName/4 + 3;
29657 assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
29658 if( pIn==0 || pIn[1]+nInt > pIn[0] ){
29659 /* Enlarge the allocation */
29660 int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
29661 VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
29662 if( pOut==0 ) return pIn;
29663 if( pIn==0 ) pOut[1] = 2;
29664 pIn = pOut;
29665 pIn[0] = nAlloc;
29667 i = pIn[1];
29668 pIn[i] = iVal;
29669 pIn[i+1] = nInt;
29670 z = (char*)&pIn[i+2];
29671 pIn[1] = i+nInt;
29672 assert( pIn[1]<=pIn[0] );
29673 memcpy(z, zName, nName);
29674 z[nName] = 0;
29675 return pIn;
29679 ** Return a pointer to the name of a variable in the given VList that
29680 ** has the value iVal. Or return a NULL if there is no such variable in
29681 ** the list
29683 SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
29684 int i, mx;
29685 if( pIn==0 ) return 0;
29686 mx = pIn[1];
29687 i = 2;
29689 if( pIn[i]==iVal ) return (char*)&pIn[i+2];
29690 i += pIn[i+1];
29691 }while( i<mx );
29692 return 0;
29696 ** Return the number of the variable named zName, if it is in VList.
29697 ** or return 0 if there is no such variable.
29699 SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
29700 int i, mx;
29701 if( pIn==0 ) return 0;
29702 mx = pIn[1];
29703 i = 2;
29705 const char *z = (const char*)&pIn[i+2];
29706 if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
29707 i += pIn[i+1];
29708 }while( i<mx );
29709 return 0;
29712 /************** End of util.c ************************************************/
29713 /************** Begin file hash.c ********************************************/
29715 ** 2001 September 22
29717 ** The author disclaims copyright to this source code. In place of
29718 ** a legal notice, here is a blessing:
29720 ** May you do good and not evil.
29721 ** May you find forgiveness for yourself and forgive others.
29722 ** May you share freely, never taking more than you give.
29724 *************************************************************************
29725 ** This is the implementation of generic hash-tables
29726 ** used in SQLite.
29728 /* #include "sqliteInt.h" */
29729 /* #include <assert.h> */
29731 /* Turn bulk memory into a hash table object by initializing the
29732 ** fields of the Hash structure.
29734 ** "pNew" is a pointer to the hash table that is to be initialized.
29736 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
29737 assert( pNew!=0 );
29738 pNew->first = 0;
29739 pNew->count = 0;
29740 pNew->htsize = 0;
29741 pNew->ht = 0;
29744 /* Remove all entries from a hash table. Reclaim all memory.
29745 ** Call this routine to delete a hash table or to reset a hash table
29746 ** to the empty state.
29748 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
29749 HashElem *elem; /* For looping over all elements of the table */
29751 assert( pH!=0 );
29752 elem = pH->first;
29753 pH->first = 0;
29754 sqlite3_free(pH->ht);
29755 pH->ht = 0;
29756 pH->htsize = 0;
29757 while( elem ){
29758 HashElem *next_elem = elem->next;
29759 sqlite3_free(elem);
29760 elem = next_elem;
29762 pH->count = 0;
29766 ** The hashing function.
29768 static unsigned int strHash(const char *z){
29769 unsigned int h = 0;
29770 unsigned char c;
29771 while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
29772 /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
29773 ** 0x9e3779b1 is 2654435761 which is the closest prime number to
29774 ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
29775 h += sqlite3UpperToLower[c];
29776 h *= 0x9e3779b1;
29778 return h;
29782 /* Link pNew element into the hash table pH. If pEntry!=0 then also
29783 ** insert pNew into the pEntry hash bucket.
29785 static void insertElement(
29786 Hash *pH, /* The complete hash table */
29787 struct _ht *pEntry, /* The entry into which pNew is inserted */
29788 HashElem *pNew /* The element to be inserted */
29790 HashElem *pHead; /* First element already in pEntry */
29791 if( pEntry ){
29792 pHead = pEntry->count ? pEntry->chain : 0;
29793 pEntry->count++;
29794 pEntry->chain = pNew;
29795 }else{
29796 pHead = 0;
29798 if( pHead ){
29799 pNew->next = pHead;
29800 pNew->prev = pHead->prev;
29801 if( pHead->prev ){ pHead->prev->next = pNew; }
29802 else { pH->first = pNew; }
29803 pHead->prev = pNew;
29804 }else{
29805 pNew->next = pH->first;
29806 if( pH->first ){ pH->first->prev = pNew; }
29807 pNew->prev = 0;
29808 pH->first = pNew;
29813 /* Resize the hash table so that it cantains "new_size" buckets.
29815 ** The hash table might fail to resize if sqlite3_malloc() fails or
29816 ** if the new size is the same as the prior size.
29817 ** Return TRUE if the resize occurs and false if not.
29819 static int rehash(Hash *pH, unsigned int new_size){
29820 struct _ht *new_ht; /* The new hash table */
29821 HashElem *elem, *next_elem; /* For looping over existing elements */
29823 #if SQLITE_MALLOC_SOFT_LIMIT>0
29824 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
29825 new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
29827 if( new_size==pH->htsize ) return 0;
29828 #endif
29830 /* The inability to allocates space for a larger hash table is
29831 ** a performance hit but it is not a fatal error. So mark the
29832 ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
29833 ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
29834 ** only zeroes the requested number of bytes whereas this module will
29835 ** use the actual amount of space allocated for the hash table (which
29836 ** may be larger than the requested amount).
29838 sqlite3BeginBenignMalloc();
29839 new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
29840 sqlite3EndBenignMalloc();
29842 if( new_ht==0 ) return 0;
29843 sqlite3_free(pH->ht);
29844 pH->ht = new_ht;
29845 pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
29846 memset(new_ht, 0, new_size*sizeof(struct _ht));
29847 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
29848 unsigned int h = strHash(elem->pKey) % new_size;
29849 next_elem = elem->next;
29850 insertElement(pH, &new_ht[h], elem);
29852 return 1;
29855 /* This function (for internal use only) locates an element in an
29856 ** hash table that matches the given key. If no element is found,
29857 ** a pointer to a static null element with HashElem.data==0 is returned.
29858 ** If pH is not NULL, then the hash for this key is written to *pH.
29860 static HashElem *findElementWithHash(
29861 const Hash *pH, /* The pH to be searched */
29862 const char *pKey, /* The key we are searching for */
29863 unsigned int *pHash /* Write the hash value here */
29865 HashElem *elem; /* Used to loop thru the element list */
29866 int count; /* Number of elements left to test */
29867 unsigned int h; /* The computed hash */
29868 static HashElem nullElement = { 0, 0, 0, 0 };
29870 if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
29871 struct _ht *pEntry;
29872 h = strHash(pKey) % pH->htsize;
29873 pEntry = &pH->ht[h];
29874 elem = pEntry->chain;
29875 count = pEntry->count;
29876 }else{
29877 h = 0;
29878 elem = pH->first;
29879 count = pH->count;
29881 if( pHash ) *pHash = h;
29882 while( count-- ){
29883 assert( elem!=0 );
29884 if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
29885 return elem;
29887 elem = elem->next;
29889 return &nullElement;
29892 /* Remove a single entry from the hash table given a pointer to that
29893 ** element and a hash on the element's key.
29895 static void removeElementGivenHash(
29896 Hash *pH, /* The pH containing "elem" */
29897 HashElem* elem, /* The element to be removed from the pH */
29898 unsigned int h /* Hash value for the element */
29900 struct _ht *pEntry;
29901 if( elem->prev ){
29902 elem->prev->next = elem->next;
29903 }else{
29904 pH->first = elem->next;
29906 if( elem->next ){
29907 elem->next->prev = elem->prev;
29909 if( pH->ht ){
29910 pEntry = &pH->ht[h];
29911 if( pEntry->chain==elem ){
29912 pEntry->chain = elem->next;
29914 pEntry->count--;
29915 assert( pEntry->count>=0 );
29917 sqlite3_free( elem );
29918 pH->count--;
29919 if( pH->count==0 ){
29920 assert( pH->first==0 );
29921 assert( pH->count==0 );
29922 sqlite3HashClear(pH);
29926 /* Attempt to locate an element of the hash table pH with a key
29927 ** that matches pKey. Return the data for this element if it is
29928 ** found, or NULL if there is no match.
29930 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
29931 assert( pH!=0 );
29932 assert( pKey!=0 );
29933 return findElementWithHash(pH, pKey, 0)->data;
29936 /* Insert an element into the hash table pH. The key is pKey
29937 ** and the data is "data".
29939 ** If no element exists with a matching key, then a new
29940 ** element is created and NULL is returned.
29942 ** If another element already exists with the same key, then the
29943 ** new data replaces the old data and the old data is returned.
29944 ** The key is not copied in this instance. If a malloc fails, then
29945 ** the new data is returned and the hash table is unchanged.
29947 ** If the "data" parameter to this function is NULL, then the
29948 ** element corresponding to "key" is removed from the hash table.
29950 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
29951 unsigned int h; /* the hash of the key modulo hash table size */
29952 HashElem *elem; /* Used to loop thru the element list */
29953 HashElem *new_elem; /* New element added to the pH */
29955 assert( pH!=0 );
29956 assert( pKey!=0 );
29957 elem = findElementWithHash(pH,pKey,&h);
29958 if( elem->data ){
29959 void *old_data = elem->data;
29960 if( data==0 ){
29961 removeElementGivenHash(pH,elem,h);
29962 }else{
29963 elem->data = data;
29964 elem->pKey = pKey;
29966 return old_data;
29968 if( data==0 ) return 0;
29969 new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
29970 if( new_elem==0 ) return data;
29971 new_elem->pKey = pKey;
29972 new_elem->data = data;
29973 pH->count++;
29974 if( pH->count>=10 && pH->count > 2*pH->htsize ){
29975 if( rehash(pH, pH->count*2) ){
29976 assert( pH->htsize>0 );
29977 h = strHash(pKey) % pH->htsize;
29980 insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
29981 return 0;
29984 /************** End of hash.c ************************************************/
29985 /************** Begin file opcodes.c *****************************************/
29986 /* Automatically generated. Do not edit */
29987 /* See the tool/mkopcodec.tcl script for details. */
29988 #if !defined(SQLITE_OMIT_EXPLAIN) \
29989 || defined(VDBE_PROFILE) \
29990 || defined(SQLITE_DEBUG)
29991 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
29992 # define OpHelp(X) "\0" X
29993 #else
29994 # define OpHelp(X)
29995 #endif
29996 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
29997 static const char *const azName[] = {
29998 /* 0 */ "Savepoint" OpHelp(""),
29999 /* 1 */ "AutoCommit" OpHelp(""),
30000 /* 2 */ "Transaction" OpHelp(""),
30001 /* 3 */ "SorterNext" OpHelp(""),
30002 /* 4 */ "PrevIfOpen" OpHelp(""),
30003 /* 5 */ "NextIfOpen" OpHelp(""),
30004 /* 6 */ "Prev" OpHelp(""),
30005 /* 7 */ "Next" OpHelp(""),
30006 /* 8 */ "Checkpoint" OpHelp(""),
30007 /* 9 */ "JournalMode" OpHelp(""),
30008 /* 10 */ "Vacuum" OpHelp(""),
30009 /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
30010 /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
30011 /* 13 */ "Goto" OpHelp(""),
30012 /* 14 */ "Gosub" OpHelp(""),
30013 /* 15 */ "InitCoroutine" OpHelp(""),
30014 /* 16 */ "Yield" OpHelp(""),
30015 /* 17 */ "MustBeInt" OpHelp(""),
30016 /* 18 */ "Jump" OpHelp(""),
30017 /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
30018 /* 20 */ "Once" OpHelp(""),
30019 /* 21 */ "If" OpHelp(""),
30020 /* 22 */ "IfNot" OpHelp(""),
30021 /* 23 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
30022 /* 24 */ "SeekLT" OpHelp("key=r[P3@P4]"),
30023 /* 25 */ "SeekLE" OpHelp("key=r[P3@P4]"),
30024 /* 26 */ "SeekGE" OpHelp("key=r[P3@P4]"),
30025 /* 27 */ "SeekGT" OpHelp("key=r[P3@P4]"),
30026 /* 28 */ "NoConflict" OpHelp("key=r[P3@P4]"),
30027 /* 29 */ "NotFound" OpHelp("key=r[P3@P4]"),
30028 /* 30 */ "Found" OpHelp("key=r[P3@P4]"),
30029 /* 31 */ "SeekRowid" OpHelp("intkey=r[P3]"),
30030 /* 32 */ "NotExists" OpHelp("intkey=r[P3]"),
30031 /* 33 */ "Last" OpHelp(""),
30032 /* 34 */ "IfSmaller" OpHelp(""),
30033 /* 35 */ "SorterSort" OpHelp(""),
30034 /* 36 */ "Sort" OpHelp(""),
30035 /* 37 */ "Rewind" OpHelp(""),
30036 /* 38 */ "IdxLE" OpHelp("key=r[P3@P4]"),
30037 /* 39 */ "IdxGT" OpHelp("key=r[P3@P4]"),
30038 /* 40 */ "IdxLT" OpHelp("key=r[P3@P4]"),
30039 /* 41 */ "IdxGE" OpHelp("key=r[P3@P4]"),
30040 /* 42 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
30041 /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
30042 /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
30043 /* 45 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
30044 /* 46 */ "Program" OpHelp(""),
30045 /* 47 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
30046 /* 48 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
30047 /* 49 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
30048 /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
30049 /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
30050 /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
30051 /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
30052 /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
30053 /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
30054 /* 56 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
30055 /* 57 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
30056 /* 58 */ "ElseNotEq" OpHelp(""),
30057 /* 59 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
30058 /* 60 */ "IncrVacuum" OpHelp(""),
30059 /* 61 */ "VNext" OpHelp(""),
30060 /* 62 */ "Init" OpHelp("Start at P2"),
30061 /* 63 */ "Return" OpHelp(""),
30062 /* 64 */ "EndCoroutine" OpHelp(""),
30063 /* 65 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
30064 /* 66 */ "Halt" OpHelp(""),
30065 /* 67 */ "Integer" OpHelp("r[P2]=P1"),
30066 /* 68 */ "Int64" OpHelp("r[P2]=P4"),
30067 /* 69 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
30068 /* 70 */ "Null" OpHelp("r[P2..P3]=NULL"),
30069 /* 71 */ "SoftNull" OpHelp("r[P1]=NULL"),
30070 /* 72 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
30071 /* 73 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
30072 /* 74 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
30073 /* 75 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
30074 /* 76 */ "SCopy" OpHelp("r[P2]=r[P1]"),
30075 /* 77 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
30076 /* 78 */ "ResultRow" OpHelp("output=r[P1@P2]"),
30077 /* 79 */ "CollSeq" OpHelp(""),
30078 /* 80 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
30079 /* 81 */ "RealAffinity" OpHelp(""),
30080 /* 82 */ "Cast" OpHelp("affinity(r[P1])"),
30081 /* 83 */ "Permutation" OpHelp(""),
30082 /* 84 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
30083 /* 85 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
30084 /* 86 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
30085 /* 87 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
30086 /* 88 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
30087 /* 89 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
30088 /* 90 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
30089 /* 91 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
30090 /* 92 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
30091 /* 93 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
30092 /* 94 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
30093 /* 95 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
30094 /* 96 */ "Column" OpHelp("r[P3]=PX"),
30095 /* 97 */ "String8" OpHelp("r[P2]='P4'"),
30096 /* 98 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
30097 /* 99 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
30098 /* 100 */ "Count" OpHelp("r[P2]=count()"),
30099 /* 101 */ "ReadCookie" OpHelp(""),
30100 /* 102 */ "SetCookie" OpHelp(""),
30101 /* 103 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
30102 /* 104 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
30103 /* 105 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
30104 /* 106 */ "OpenDup" OpHelp(""),
30105 /* 107 */ "OpenAutoindex" OpHelp("nColumn=P2"),
30106 /* 108 */ "OpenEphemeral" OpHelp("nColumn=P2"),
30107 /* 109 */ "SorterOpen" OpHelp(""),
30108 /* 110 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
30109 /* 111 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
30110 /* 112 */ "Close" OpHelp(""),
30111 /* 113 */ "ColumnsUsed" OpHelp(""),
30112 /* 114 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
30113 /* 115 */ "NewRowid" OpHelp("r[P2]=rowid"),
30114 /* 116 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
30115 /* 117 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
30116 /* 118 */ "Delete" OpHelp(""),
30117 /* 119 */ "ResetCount" OpHelp(""),
30118 /* 120 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
30119 /* 121 */ "SorterData" OpHelp("r[P2]=data"),
30120 /* 122 */ "RowData" OpHelp("r[P2]=data"),
30121 /* 123 */ "Rowid" OpHelp("r[P2]=rowid"),
30122 /* 124 */ "NullRow" OpHelp(""),
30123 /* 125 */ "SeekEnd" OpHelp(""),
30124 /* 126 */ "SorterInsert" OpHelp("key=r[P2]"),
30125 /* 127 */ "IdxInsert" OpHelp("key=r[P2]"),
30126 /* 128 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
30127 /* 129 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
30128 /* 130 */ "IdxRowid" OpHelp("r[P2]=rowid"),
30129 /* 131 */ "Destroy" OpHelp(""),
30130 /* 132 */ "Real" OpHelp("r[P2]=P4"),
30131 /* 133 */ "Clear" OpHelp(""),
30132 /* 134 */ "ResetSorter" OpHelp(""),
30133 /* 135 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
30134 /* 136 */ "SqlExec" OpHelp(""),
30135 /* 137 */ "ParseSchema" OpHelp(""),
30136 /* 138 */ "LoadAnalysis" OpHelp(""),
30137 /* 139 */ "DropTable" OpHelp(""),
30138 /* 140 */ "DropIndex" OpHelp(""),
30139 /* 141 */ "DropTrigger" OpHelp(""),
30140 /* 142 */ "IntegrityCk" OpHelp(""),
30141 /* 143 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
30142 /* 144 */ "Param" OpHelp(""),
30143 /* 145 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
30144 /* 146 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
30145 /* 147 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
30146 /* 148 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
30147 /* 149 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
30148 /* 150 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
30149 /* 151 */ "Expire" OpHelp(""),
30150 /* 152 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
30151 /* 153 */ "VBegin" OpHelp(""),
30152 /* 154 */ "VCreate" OpHelp(""),
30153 /* 155 */ "VDestroy" OpHelp(""),
30154 /* 156 */ "VOpen" OpHelp(""),
30155 /* 157 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
30156 /* 158 */ "VRename" OpHelp(""),
30157 /* 159 */ "Pagecount" OpHelp(""),
30158 /* 160 */ "MaxPgcnt" OpHelp(""),
30159 /* 161 */ "PureFunc0" OpHelp(""),
30160 /* 162 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
30161 /* 163 */ "PureFunc" OpHelp(""),
30162 /* 164 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
30163 /* 165 */ "CursorHint" OpHelp(""),
30164 /* 166 */ "Noop" OpHelp(""),
30165 /* 167 */ "Explain" OpHelp(""),
30167 return azName[i];
30169 #endif
30171 /************** End of opcodes.c *********************************************/
30172 /************** Begin file os_unix.c *****************************************/
30174 ** 2004 May 22
30176 ** The author disclaims copyright to this source code. In place of
30177 ** a legal notice, here is a blessing:
30179 ** May you do good and not evil.
30180 ** May you find forgiveness for yourself and forgive others.
30181 ** May you share freely, never taking more than you give.
30183 ******************************************************************************
30185 ** This file contains the VFS implementation for unix-like operating systems
30186 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
30188 ** There are actually several different VFS implementations in this file.
30189 ** The differences are in the way that file locking is done. The default
30190 ** implementation uses Posix Advisory Locks. Alternative implementations
30191 ** use flock(), dot-files, various proprietary locking schemas, or simply
30192 ** skip locking all together.
30194 ** This source file is organized into divisions where the logic for various
30195 ** subfunctions is contained within the appropriate division. PLEASE
30196 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
30197 ** in the correct division and should be clearly labeled.
30199 ** The layout of divisions is as follows:
30201 ** * General-purpose declarations and utility functions.
30202 ** * Unique file ID logic used by VxWorks.
30203 ** * Various locking primitive implementations (all except proxy locking):
30204 ** + for Posix Advisory Locks
30205 ** + for no-op locks
30206 ** + for dot-file locks
30207 ** + for flock() locking
30208 ** + for named semaphore locks (VxWorks only)
30209 ** + for AFP filesystem locks (MacOSX only)
30210 ** * sqlite3_file methods not associated with locking.
30211 ** * Definitions of sqlite3_io_methods objects for all locking
30212 ** methods plus "finder" functions for each locking method.
30213 ** * sqlite3_vfs method implementations.
30214 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
30215 ** * Definitions of sqlite3_vfs objects for all locking methods
30216 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
30218 /* #include "sqliteInt.h" */
30219 #if SQLITE_OS_UNIX /* This file is used on unix only */
30222 ** There are various methods for file locking used for concurrency
30223 ** control:
30225 ** 1. POSIX locking (the default),
30226 ** 2. No locking,
30227 ** 3. Dot-file locking,
30228 ** 4. flock() locking,
30229 ** 5. AFP locking (OSX only),
30230 ** 6. Named POSIX semaphores (VXWorks only),
30231 ** 7. proxy locking. (OSX only)
30233 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
30234 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
30235 ** selection of the appropriate locking style based on the filesystem
30236 ** where the database is located.
30238 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
30239 # if defined(__APPLE__)
30240 # define SQLITE_ENABLE_LOCKING_STYLE 1
30241 # else
30242 # define SQLITE_ENABLE_LOCKING_STYLE 0
30243 # endif
30244 #endif
30246 /* Use pread() and pwrite() if they are available */
30247 #if defined(__APPLE__)
30248 # define HAVE_PREAD 1
30249 # define HAVE_PWRITE 1
30250 #endif
30251 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
30252 # undef USE_PREAD
30253 # define USE_PREAD64 1
30254 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
30255 # undef USE_PREAD64
30256 # define USE_PREAD 1
30257 #endif
30260 ** standard include files.
30262 #include <sys/types.h>
30263 #include <sys/stat.h>
30264 #include <fcntl.h>
30265 #include <sys/ioctl.h>
30266 #include <unistd.h>
30267 /* #include <time.h> */
30268 #include <sys/time.h>
30269 #include <errno.h>
30270 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30271 # include <sys/mman.h>
30272 #endif
30274 #if SQLITE_ENABLE_LOCKING_STYLE
30275 /* # include <sys/ioctl.h> */
30276 # include <sys/file.h>
30277 # include <sys/param.h>
30278 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
30280 #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
30281 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
30282 # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
30283 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
30284 # define HAVE_GETHOSTUUID 1
30285 # else
30286 # warning "gethostuuid() is disabled."
30287 # endif
30288 #endif
30291 #if OS_VXWORKS
30292 /* # include <sys/ioctl.h> */
30293 # include <semaphore.h>
30294 # include <limits.h>
30295 #endif /* OS_VXWORKS */
30297 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30298 # include <sys/mount.h>
30299 #endif
30301 #ifdef HAVE_UTIME
30302 # include <utime.h>
30303 #endif
30306 ** Allowed values of unixFile.fsFlags
30308 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
30311 ** If we are to be thread-safe, include the pthreads header and define
30312 ** the SQLITE_UNIX_THREADS macro.
30314 #if SQLITE_THREADSAFE
30315 /* # include <pthread.h> */
30316 # define SQLITE_UNIX_THREADS 1
30317 #endif
30320 ** Default permissions when creating a new file
30322 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
30323 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
30324 #endif
30327 ** Default permissions when creating auto proxy dir
30329 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
30330 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
30331 #endif
30334 ** Maximum supported path-length.
30336 #define MAX_PATHNAME 512
30339 ** Maximum supported symbolic links
30341 #define SQLITE_MAX_SYMLINKS 100
30343 /* Always cast the getpid() return type for compatibility with
30344 ** kernel modules in VxWorks. */
30345 #define osGetpid(X) (pid_t)getpid()
30348 ** Only set the lastErrno if the error code is a real error and not
30349 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
30351 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
30353 /* Forward references */
30354 typedef struct unixShm unixShm; /* Connection shared memory */
30355 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
30356 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
30357 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
30360 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
30361 ** cannot be closed immediately. In these cases, instances of the following
30362 ** structure are used to store the file descriptor while waiting for an
30363 ** opportunity to either close or reuse it.
30365 struct UnixUnusedFd {
30366 int fd; /* File descriptor to close */
30367 int flags; /* Flags this file descriptor was opened with */
30368 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
30372 ** The unixFile structure is subclass of sqlite3_file specific to the unix
30373 ** VFS implementations.
30375 typedef struct unixFile unixFile;
30376 struct unixFile {
30377 sqlite3_io_methods const *pMethod; /* Always the first entry */
30378 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
30379 unixInodeInfo *pInode; /* Info about locks on this inode */
30380 int h; /* The file descriptor */
30381 unsigned char eFileLock; /* The type of lock held on this fd */
30382 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
30383 int lastErrno; /* The unix errno from last I/O error */
30384 void *lockingContext; /* Locking style specific state */
30385 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
30386 const char *zPath; /* Name of the file */
30387 unixShm *pShm; /* Shared memory segment information */
30388 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
30389 #if SQLITE_MAX_MMAP_SIZE>0
30390 int nFetchOut; /* Number of outstanding xFetch refs */
30391 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
30392 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
30393 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
30394 void *pMapRegion; /* Memory mapped region */
30395 #endif
30396 int sectorSize; /* Device sector size */
30397 int deviceCharacteristics; /* Precomputed device characteristics */
30398 #if SQLITE_ENABLE_LOCKING_STYLE
30399 int openFlags; /* The flags specified at open() */
30400 #endif
30401 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
30402 unsigned fsFlags; /* cached details from statfs() */
30403 #endif
30404 #if OS_VXWORKS
30405 struct vxworksFileId *pId; /* Unique file ID */
30406 #endif
30407 #ifdef SQLITE_DEBUG
30408 /* The next group of variables are used to track whether or not the
30409 ** transaction counter in bytes 24-27 of database files are updated
30410 ** whenever any part of the database changes. An assertion fault will
30411 ** occur if a file is updated without also updating the transaction
30412 ** counter. This test is made to avoid new problems similar to the
30413 ** one described by ticket #3584.
30415 unsigned char transCntrChng; /* True if the transaction counter changed */
30416 unsigned char dbUpdate; /* True if any part of database file changed */
30417 unsigned char inNormalWrite; /* True if in a normal write operation */
30419 #endif
30421 #ifdef SQLITE_TEST
30422 /* In test mode, increase the size of this structure a bit so that
30423 ** it is larger than the struct CrashFile defined in test6.c.
30425 char aPadding[32];
30426 #endif
30429 /* This variable holds the process id (pid) from when the xRandomness()
30430 ** method was called. If xOpen() is called from a different process id,
30431 ** indicating that a fork() has occurred, the PRNG will be reset.
30433 static pid_t randomnessPid = 0;
30436 ** Allowed values for the unixFile.ctrlFlags bitmask:
30438 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
30439 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
30440 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
30441 #ifndef SQLITE_DISABLE_DIRSYNC
30442 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
30443 #else
30444 # define UNIXFILE_DIRSYNC 0x00
30445 #endif
30446 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
30447 #define UNIXFILE_DELETE 0x20 /* Delete on close */
30448 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
30449 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
30452 ** Include code that is common to all os_*.c files
30454 /************** Include os_common.h in the middle of os_unix.c ***************/
30455 /************** Begin file os_common.h ***************************************/
30457 ** 2004 May 22
30459 ** The author disclaims copyright to this source code. In place of
30460 ** a legal notice, here is a blessing:
30462 ** May you do good and not evil.
30463 ** May you find forgiveness for yourself and forgive others.
30464 ** May you share freely, never taking more than you give.
30466 ******************************************************************************
30468 ** This file contains macros and a little bit of code that is common to
30469 ** all of the platform-specific files (os_*.c) and is #included into those
30470 ** files.
30472 ** This file should be #included by the os_*.c files only. It is not a
30473 ** general purpose header file.
30475 #ifndef _OS_COMMON_H_
30476 #define _OS_COMMON_H_
30479 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
30480 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
30481 ** switch. The following code should catch this problem at compile-time.
30483 #ifdef MEMORY_DEBUG
30484 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
30485 #endif
30488 ** Macros for performance tracing. Normally turned off. Only works
30489 ** on i486 hardware.
30491 #ifdef SQLITE_PERFORMANCE_TRACE
30494 ** hwtime.h contains inline assembler code for implementing
30495 ** high-performance timing routines.
30497 /************** Include hwtime.h in the middle of os_common.h ****************/
30498 /************** Begin file hwtime.h ******************************************/
30500 ** 2008 May 27
30502 ** The author disclaims copyright to this source code. In place of
30503 ** a legal notice, here is a blessing:
30505 ** May you do good and not evil.
30506 ** May you find forgiveness for yourself and forgive others.
30507 ** May you share freely, never taking more than you give.
30509 ******************************************************************************
30511 ** This file contains inline asm code for retrieving "high-performance"
30512 ** counters for x86 class CPUs.
30514 #ifndef SQLITE_HWTIME_H
30515 #define SQLITE_HWTIME_H
30518 ** The following routine only works on pentium-class (or newer) processors.
30519 ** It uses the RDTSC opcode to read the cycle count value out of the
30520 ** processor and returns that value. This can be used for high-res
30521 ** profiling.
30523 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
30524 (defined(i386) || defined(__i386__) || defined(_M_IX86))
30526 #if defined(__GNUC__)
30528 __inline__ sqlite_uint64 sqlite3Hwtime(void){
30529 unsigned int lo, hi;
30530 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30531 return (sqlite_uint64)hi << 32 | lo;
30534 #elif defined(_MSC_VER)
30536 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30537 __asm {
30538 rdtsc
30539 ret ; return value at EDX:EAX
30543 #endif
30545 #elif (defined(__GNUC__) && defined(__x86_64__))
30547 __inline__ sqlite_uint64 sqlite3Hwtime(void){
30548 unsigned long val;
30549 __asm__ __volatile__ ("rdtsc" : "=A" (val));
30550 return val;
30553 #elif (defined(__GNUC__) && defined(__ppc__))
30555 __inline__ sqlite_uint64 sqlite3Hwtime(void){
30556 unsigned long long retval;
30557 unsigned long junk;
30558 __asm__ __volatile__ ("\n\
30559 1: mftbu %1\n\
30560 mftb %L0\n\
30561 mftbu %0\n\
30562 cmpw %0,%1\n\
30563 bne 1b"
30564 : "=r" (retval), "=r" (junk));
30565 return retval;
30568 #else
30570 #error Need implementation of sqlite3Hwtime() for your platform.
30573 ** To compile without implementing sqlite3Hwtime() for your platform,
30574 ** you can remove the above #error and use the following
30575 ** stub function. You will lose timing support for many
30576 ** of the debugging and testing utilities, but it should at
30577 ** least compile and run.
30579 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
30581 #endif
30583 #endif /* !defined(SQLITE_HWTIME_H) */
30585 /************** End of hwtime.h **********************************************/
30586 /************** Continuing where we left off in os_common.h ******************/
30588 static sqlite_uint64 g_start;
30589 static sqlite_uint64 g_elapsed;
30590 #define TIMER_START g_start=sqlite3Hwtime()
30591 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
30592 #define TIMER_ELAPSED g_elapsed
30593 #else
30594 #define TIMER_START
30595 #define TIMER_END
30596 #define TIMER_ELAPSED ((sqlite_uint64)0)
30597 #endif
30600 ** If we compile with the SQLITE_TEST macro set, then the following block
30601 ** of code will give us the ability to simulate a disk I/O error. This
30602 ** is used for testing the I/O recovery logic.
30604 #if defined(SQLITE_TEST)
30605 SQLITE_API extern int sqlite3_io_error_hit;
30606 SQLITE_API extern int sqlite3_io_error_hardhit;
30607 SQLITE_API extern int sqlite3_io_error_pending;
30608 SQLITE_API extern int sqlite3_io_error_persist;
30609 SQLITE_API extern int sqlite3_io_error_benign;
30610 SQLITE_API extern int sqlite3_diskfull_pending;
30611 SQLITE_API extern int sqlite3_diskfull;
30612 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
30613 #define SimulateIOError(CODE) \
30614 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
30615 || sqlite3_io_error_pending-- == 1 ) \
30616 { local_ioerr(); CODE; }
30617 static void local_ioerr(){
30618 IOTRACE(("IOERR\n"));
30619 sqlite3_io_error_hit++;
30620 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
30622 #define SimulateDiskfullError(CODE) \
30623 if( sqlite3_diskfull_pending ){ \
30624 if( sqlite3_diskfull_pending == 1 ){ \
30625 local_ioerr(); \
30626 sqlite3_diskfull = 1; \
30627 sqlite3_io_error_hit = 1; \
30628 CODE; \
30629 }else{ \
30630 sqlite3_diskfull_pending--; \
30633 #else
30634 #define SimulateIOErrorBenign(X)
30635 #define SimulateIOError(A)
30636 #define SimulateDiskfullError(A)
30637 #endif /* defined(SQLITE_TEST) */
30640 ** When testing, keep a count of the number of open files.
30642 #if defined(SQLITE_TEST)
30643 SQLITE_API extern int sqlite3_open_file_count;
30644 #define OpenCounter(X) sqlite3_open_file_count+=(X)
30645 #else
30646 #define OpenCounter(X)
30647 #endif /* defined(SQLITE_TEST) */
30649 #endif /* !defined(_OS_COMMON_H_) */
30651 /************** End of os_common.h *******************************************/
30652 /************** Continuing where we left off in os_unix.c ********************/
30655 ** Define various macros that are missing from some systems.
30657 #ifndef O_LARGEFILE
30658 # define O_LARGEFILE 0
30659 #endif
30660 #ifdef SQLITE_DISABLE_LFS
30661 # undef O_LARGEFILE
30662 # define O_LARGEFILE 0
30663 #endif
30664 #ifndef O_NOFOLLOW
30665 # define O_NOFOLLOW 0
30666 #endif
30667 #ifndef O_BINARY
30668 # define O_BINARY 0
30669 #endif
30672 ** The threadid macro resolves to the thread-id or to 0. Used for
30673 ** testing and debugging only.
30675 #if SQLITE_THREADSAFE
30676 #define threadid pthread_self()
30677 #else
30678 #define threadid 0
30679 #endif
30682 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
30684 #if !defined(HAVE_MREMAP)
30685 # if defined(__linux__) && defined(_GNU_SOURCE)
30686 # define HAVE_MREMAP 1
30687 # else
30688 # define HAVE_MREMAP 0
30689 # endif
30690 #endif
30693 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
30694 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
30696 #ifdef __ANDROID__
30697 # define lseek lseek64
30698 #endif
30700 #ifdef __linux__
30702 ** Linux-specific IOCTL magic numbers used for controlling F2FS
30704 #define F2FS_IOCTL_MAGIC 0xf5
30705 #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
30706 #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
30707 #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
30708 #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
30709 #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
30710 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
30711 #endif /* __linux__ */
30715 ** Different Unix systems declare open() in different ways. Same use
30716 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
30717 ** The difference is important when using a pointer to the function.
30719 ** The safest way to deal with the problem is to always use this wrapper
30720 ** which always has the same well-defined interface.
30722 static int posixOpen(const char *zFile, int flags, int mode){
30723 return open(zFile, flags, mode);
30726 /* Forward reference */
30727 static int openDirectory(const char*, int*);
30728 static int unixGetpagesize(void);
30731 ** Many system calls are accessed through pointer-to-functions so that
30732 ** they may be overridden at runtime to facilitate fault injection during
30733 ** testing and sandboxing. The following array holds the names and pointers
30734 ** to all overrideable system calls.
30736 static struct unix_syscall {
30737 const char *zName; /* Name of the system call */
30738 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
30739 sqlite3_syscall_ptr pDefault; /* Default value */
30740 } aSyscall[] = {
30741 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
30742 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
30744 { "close", (sqlite3_syscall_ptr)close, 0 },
30745 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
30747 { "access", (sqlite3_syscall_ptr)access, 0 },
30748 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
30750 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
30751 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
30753 { "stat", (sqlite3_syscall_ptr)stat, 0 },
30754 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
30757 ** The DJGPP compiler environment looks mostly like Unix, but it
30758 ** lacks the fcntl() system call. So redefine fcntl() to be something
30759 ** that always succeeds. This means that locking does not occur under
30760 ** DJGPP. But it is DOS - what did you expect?
30762 #ifdef __DJGPP__
30763 { "fstat", 0, 0 },
30764 #define osFstat(a,b,c) 0
30765 #else
30766 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
30767 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
30768 #endif
30770 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
30771 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
30773 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
30774 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
30776 { "read", (sqlite3_syscall_ptr)read, 0 },
30777 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
30779 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
30780 { "pread", (sqlite3_syscall_ptr)pread, 0 },
30781 #else
30782 { "pread", (sqlite3_syscall_ptr)0, 0 },
30783 #endif
30784 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
30786 #if defined(USE_PREAD64)
30787 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
30788 #else
30789 { "pread64", (sqlite3_syscall_ptr)0, 0 },
30790 #endif
30791 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
30793 { "write", (sqlite3_syscall_ptr)write, 0 },
30794 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
30796 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
30797 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
30798 #else
30799 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
30800 #endif
30801 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
30802 aSyscall[12].pCurrent)
30804 #if defined(USE_PREAD64)
30805 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
30806 #else
30807 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
30808 #endif
30809 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
30810 aSyscall[13].pCurrent)
30812 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
30813 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
30815 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
30816 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
30817 #else
30818 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
30819 #endif
30820 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
30822 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
30823 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
30825 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
30826 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
30828 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
30829 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
30831 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
30832 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
30834 #if defined(HAVE_FCHOWN)
30835 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
30836 #else
30837 { "fchown", (sqlite3_syscall_ptr)0, 0 },
30838 #endif
30839 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
30841 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
30842 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
30844 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30845 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
30846 #else
30847 { "mmap", (sqlite3_syscall_ptr)0, 0 },
30848 #endif
30849 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
30851 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30852 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
30853 #else
30854 { "munmap", (sqlite3_syscall_ptr)0, 0 },
30855 #endif
30856 #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
30858 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
30859 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
30860 #else
30861 { "mremap", (sqlite3_syscall_ptr)0, 0 },
30862 #endif
30863 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
30865 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30866 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
30867 #else
30868 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
30869 #endif
30870 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
30872 #if defined(HAVE_READLINK)
30873 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
30874 #else
30875 { "readlink", (sqlite3_syscall_ptr)0, 0 },
30876 #endif
30877 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
30879 #if defined(HAVE_LSTAT)
30880 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
30881 #else
30882 { "lstat", (sqlite3_syscall_ptr)0, 0 },
30883 #endif
30884 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
30886 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
30887 #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
30889 }; /* End of the overrideable system calls */
30893 ** On some systems, calls to fchown() will trigger a message in a security
30894 ** log if they come from non-root processes. So avoid calling fchown() if
30895 ** we are not running as root.
30897 static int robustFchown(int fd, uid_t uid, gid_t gid){
30898 #if defined(HAVE_FCHOWN)
30899 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
30900 #else
30901 return 0;
30902 #endif
30906 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
30907 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
30908 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
30909 ** system call named zName.
30911 static int unixSetSystemCall(
30912 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
30913 const char *zName, /* Name of system call to override */
30914 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
30916 unsigned int i;
30917 int rc = SQLITE_NOTFOUND;
30919 UNUSED_PARAMETER(pNotUsed);
30920 if( zName==0 ){
30921 /* If no zName is given, restore all system calls to their default
30922 ** settings and return NULL
30924 rc = SQLITE_OK;
30925 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30926 if( aSyscall[i].pDefault ){
30927 aSyscall[i].pCurrent = aSyscall[i].pDefault;
30930 }else{
30931 /* If zName is specified, operate on only the one system call
30932 ** specified.
30934 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30935 if( strcmp(zName, aSyscall[i].zName)==0 ){
30936 if( aSyscall[i].pDefault==0 ){
30937 aSyscall[i].pDefault = aSyscall[i].pCurrent;
30939 rc = SQLITE_OK;
30940 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
30941 aSyscall[i].pCurrent = pNewFunc;
30942 break;
30946 return rc;
30950 ** Return the value of a system call. Return NULL if zName is not a
30951 ** recognized system call name. NULL is also returned if the system call
30952 ** is currently undefined.
30954 static sqlite3_syscall_ptr unixGetSystemCall(
30955 sqlite3_vfs *pNotUsed,
30956 const char *zName
30958 unsigned int i;
30960 UNUSED_PARAMETER(pNotUsed);
30961 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30962 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
30964 return 0;
30968 ** Return the name of the first system call after zName. If zName==NULL
30969 ** then return the name of the first system call. Return NULL if zName
30970 ** is the last system call or if zName is not the name of a valid
30971 ** system call.
30973 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
30974 int i = -1;
30976 UNUSED_PARAMETER(p);
30977 if( zName ){
30978 for(i=0; i<ArraySize(aSyscall)-1; i++){
30979 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
30982 for(i++; i<ArraySize(aSyscall); i++){
30983 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
30985 return 0;
30989 ** Do not accept any file descriptor less than this value, in order to avoid
30990 ** opening database file using file descriptors that are commonly used for
30991 ** standard input, output, and error.
30993 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
30994 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
30995 #endif
30998 ** Invoke open(). Do so multiple times, until it either succeeds or
30999 ** fails for some reason other than EINTR.
31001 ** If the file creation mode "m" is 0 then set it to the default for
31002 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
31003 ** 0644) as modified by the system umask. If m is not 0, then
31004 ** make the file creation mode be exactly m ignoring the umask.
31006 ** The m parameter will be non-zero only when creating -wal, -journal,
31007 ** and -shm files. We want those files to have *exactly* the same
31008 ** permissions as their original database, unadulterated by the umask.
31009 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
31010 ** transaction crashes and leaves behind hot journals, then any
31011 ** process that is able to write to the database will also be able to
31012 ** recover the hot journals.
31014 static int robust_open(const char *z, int f, mode_t m){
31015 int fd;
31016 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
31017 while(1){
31018 #if defined(O_CLOEXEC)
31019 fd = osOpen(z,f|O_CLOEXEC,m2);
31020 #else
31021 fd = osOpen(z,f,m2);
31022 #endif
31023 if( fd<0 ){
31024 if( errno==EINTR ) continue;
31025 break;
31027 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
31028 osClose(fd);
31029 sqlite3_log(SQLITE_WARNING,
31030 "attempt to open \"%s\" as file descriptor %d", z, fd);
31031 fd = -1;
31032 if( osOpen("/dev/null", f, m)<0 ) break;
31034 if( fd>=0 ){
31035 if( m!=0 ){
31036 struct stat statbuf;
31037 if( osFstat(fd, &statbuf)==0
31038 && statbuf.st_size==0
31039 && (statbuf.st_mode&0777)!=m
31041 osFchmod(fd, m);
31044 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
31045 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
31046 #endif
31048 return fd;
31052 ** Helper functions to obtain and relinquish the global mutex. The
31053 ** global mutex is used to protect the unixInodeInfo and
31054 ** vxworksFileId objects used by this file, all of which may be
31055 ** shared by multiple threads.
31057 ** Function unixMutexHeld() is used to assert() that the global mutex
31058 ** is held when required. This function is only used as part of assert()
31059 ** statements. e.g.
31061 ** unixEnterMutex()
31062 ** assert( unixMutexHeld() );
31063 ** unixEnterLeave()
31065 static void unixEnterMutex(void){
31066 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
31068 static void unixLeaveMutex(void){
31069 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
31071 #ifdef SQLITE_DEBUG
31072 static int unixMutexHeld(void) {
31073 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
31075 #endif
31078 #ifdef SQLITE_HAVE_OS_TRACE
31080 ** Helper function for printing out trace information from debugging
31081 ** binaries. This returns the string representation of the supplied
31082 ** integer lock-type.
31084 static const char *azFileLock(int eFileLock){
31085 switch( eFileLock ){
31086 case NO_LOCK: return "NONE";
31087 case SHARED_LOCK: return "SHARED";
31088 case RESERVED_LOCK: return "RESERVED";
31089 case PENDING_LOCK: return "PENDING";
31090 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
31092 return "ERROR";
31094 #endif
31096 #ifdef SQLITE_LOCK_TRACE
31098 ** Print out information about all locking operations.
31100 ** This routine is used for troubleshooting locks on multithreaded
31101 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
31102 ** command-line option on the compiler. This code is normally
31103 ** turned off.
31105 static int lockTrace(int fd, int op, struct flock *p){
31106 char *zOpName, *zType;
31107 int s;
31108 int savedErrno;
31109 if( op==F_GETLK ){
31110 zOpName = "GETLK";
31111 }else if( op==F_SETLK ){
31112 zOpName = "SETLK";
31113 }else{
31114 s = osFcntl(fd, op, p);
31115 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
31116 return s;
31118 if( p->l_type==F_RDLCK ){
31119 zType = "RDLCK";
31120 }else if( p->l_type==F_WRLCK ){
31121 zType = "WRLCK";
31122 }else if( p->l_type==F_UNLCK ){
31123 zType = "UNLCK";
31124 }else{
31125 assert( 0 );
31127 assert( p->l_whence==SEEK_SET );
31128 s = osFcntl(fd, op, p);
31129 savedErrno = errno;
31130 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
31131 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
31132 (int)p->l_pid, s);
31133 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
31134 struct flock l2;
31135 l2 = *p;
31136 osFcntl(fd, F_GETLK, &l2);
31137 if( l2.l_type==F_RDLCK ){
31138 zType = "RDLCK";
31139 }else if( l2.l_type==F_WRLCK ){
31140 zType = "WRLCK";
31141 }else if( l2.l_type==F_UNLCK ){
31142 zType = "UNLCK";
31143 }else{
31144 assert( 0 );
31146 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
31147 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
31149 errno = savedErrno;
31150 return s;
31152 #undef osFcntl
31153 #define osFcntl lockTrace
31154 #endif /* SQLITE_LOCK_TRACE */
31157 ** Retry ftruncate() calls that fail due to EINTR
31159 ** All calls to ftruncate() within this file should be made through
31160 ** this wrapper. On the Android platform, bypassing the logic below
31161 ** could lead to a corrupt database.
31163 static int robust_ftruncate(int h, sqlite3_int64 sz){
31164 int rc;
31165 #ifdef __ANDROID__
31166 /* On Android, ftruncate() always uses 32-bit offsets, even if
31167 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
31168 ** truncate a file to any size larger than 2GiB. Silently ignore any
31169 ** such attempts. */
31170 if( sz>(sqlite3_int64)0x7FFFFFFF ){
31171 rc = SQLITE_OK;
31172 }else
31173 #endif
31174 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
31175 return rc;
31179 ** This routine translates a standard POSIX errno code into something
31180 ** useful to the clients of the sqlite3 functions. Specifically, it is
31181 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
31182 ** and a variety of "please close the file descriptor NOW" errors into
31183 ** SQLITE_IOERR
31185 ** Errors during initialization of locks, or file system support for locks,
31186 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
31188 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
31189 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
31190 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
31191 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
31192 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
31193 switch (posixError) {
31194 case EACCES:
31195 case EAGAIN:
31196 case ETIMEDOUT:
31197 case EBUSY:
31198 case EINTR:
31199 case ENOLCK:
31200 /* random NFS retry error, unless during file system support
31201 * introspection, in which it actually means what it says */
31202 return SQLITE_BUSY;
31204 case EPERM:
31205 return SQLITE_PERM;
31207 default:
31208 return sqliteIOErr;
31213 /******************************************************************************
31214 ****************** Begin Unique File ID Utility Used By VxWorks ***************
31216 ** On most versions of unix, we can get a unique ID for a file by concatenating
31217 ** the device number and the inode number. But this does not work on VxWorks.
31218 ** On VxWorks, a unique file id must be based on the canonical filename.
31220 ** A pointer to an instance of the following structure can be used as a
31221 ** unique file ID in VxWorks. Each instance of this structure contains
31222 ** a copy of the canonical filename. There is also a reference count.
31223 ** The structure is reclaimed when the number of pointers to it drops to
31224 ** zero.
31226 ** There are never very many files open at one time and lookups are not
31227 ** a performance-critical path, so it is sufficient to put these
31228 ** structures on a linked list.
31230 struct vxworksFileId {
31231 struct vxworksFileId *pNext; /* Next in a list of them all */
31232 int nRef; /* Number of references to this one */
31233 int nName; /* Length of the zCanonicalName[] string */
31234 char *zCanonicalName; /* Canonical filename */
31237 #if OS_VXWORKS
31239 ** All unique filenames are held on a linked list headed by this
31240 ** variable:
31242 static struct vxworksFileId *vxworksFileList = 0;
31245 ** Simplify a filename into its canonical form
31246 ** by making the following changes:
31248 ** * removing any trailing and duplicate /
31249 ** * convert /./ into just /
31250 ** * convert /A/../ where A is any simple name into just /
31252 ** Changes are made in-place. Return the new name length.
31254 ** The original filename is in z[0..n-1]. Return the number of
31255 ** characters in the simplified name.
31257 static int vxworksSimplifyName(char *z, int n){
31258 int i, j;
31259 while( n>1 && z[n-1]=='/' ){ n--; }
31260 for(i=j=0; i<n; i++){
31261 if( z[i]=='/' ){
31262 if( z[i+1]=='/' ) continue;
31263 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
31264 i += 1;
31265 continue;
31267 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
31268 while( j>0 && z[j-1]!='/' ){ j--; }
31269 if( j>0 ){ j--; }
31270 i += 2;
31271 continue;
31274 z[j++] = z[i];
31276 z[j] = 0;
31277 return j;
31281 ** Find a unique file ID for the given absolute pathname. Return
31282 ** a pointer to the vxworksFileId object. This pointer is the unique
31283 ** file ID.
31285 ** The nRef field of the vxworksFileId object is incremented before
31286 ** the object is returned. A new vxworksFileId object is created
31287 ** and added to the global list if necessary.
31289 ** If a memory allocation error occurs, return NULL.
31291 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
31292 struct vxworksFileId *pNew; /* search key and new file ID */
31293 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
31294 int n; /* Length of zAbsoluteName string */
31296 assert( zAbsoluteName[0]=='/' );
31297 n = (int)strlen(zAbsoluteName);
31298 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
31299 if( pNew==0 ) return 0;
31300 pNew->zCanonicalName = (char*)&pNew[1];
31301 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
31302 n = vxworksSimplifyName(pNew->zCanonicalName, n);
31304 /* Search for an existing entry that matching the canonical name.
31305 ** If found, increment the reference count and return a pointer to
31306 ** the existing file ID.
31308 unixEnterMutex();
31309 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
31310 if( pCandidate->nName==n
31311 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
31313 sqlite3_free(pNew);
31314 pCandidate->nRef++;
31315 unixLeaveMutex();
31316 return pCandidate;
31320 /* No match was found. We will make a new file ID */
31321 pNew->nRef = 1;
31322 pNew->nName = n;
31323 pNew->pNext = vxworksFileList;
31324 vxworksFileList = pNew;
31325 unixLeaveMutex();
31326 return pNew;
31330 ** Decrement the reference count on a vxworksFileId object. Free
31331 ** the object when the reference count reaches zero.
31333 static void vxworksReleaseFileId(struct vxworksFileId *pId){
31334 unixEnterMutex();
31335 assert( pId->nRef>0 );
31336 pId->nRef--;
31337 if( pId->nRef==0 ){
31338 struct vxworksFileId **pp;
31339 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
31340 assert( *pp==pId );
31341 *pp = pId->pNext;
31342 sqlite3_free(pId);
31344 unixLeaveMutex();
31346 #endif /* OS_VXWORKS */
31347 /*************** End of Unique File ID Utility Used By VxWorks ****************
31348 ******************************************************************************/
31351 /******************************************************************************
31352 *************************** Posix Advisory Locking ****************************
31354 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
31355 ** section 6.5.2.2 lines 483 through 490 specify that when a process
31356 ** sets or clears a lock, that operation overrides any prior locks set
31357 ** by the same process. It does not explicitly say so, but this implies
31358 ** that it overrides locks set by the same process using a different
31359 ** file descriptor. Consider this test case:
31361 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
31362 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
31364 ** Suppose ./file1 and ./file2 are really the same file (because
31365 ** one is a hard or symbolic link to the other) then if you set
31366 ** an exclusive lock on fd1, then try to get an exclusive lock
31367 ** on fd2, it works. I would have expected the second lock to
31368 ** fail since there was already a lock on the file due to fd1.
31369 ** But not so. Since both locks came from the same process, the
31370 ** second overrides the first, even though they were on different
31371 ** file descriptors opened on different file names.
31373 ** This means that we cannot use POSIX locks to synchronize file access
31374 ** among competing threads of the same process. POSIX locks will work fine
31375 ** to synchronize access for threads in separate processes, but not
31376 ** threads within the same process.
31378 ** To work around the problem, SQLite has to manage file locks internally
31379 ** on its own. Whenever a new database is opened, we have to find the
31380 ** specific inode of the database file (the inode is determined by the
31381 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
31382 ** and check for locks already existing on that inode. When locks are
31383 ** created or removed, we have to look at our own internal record of the
31384 ** locks to see if another thread has previously set a lock on that same
31385 ** inode.
31387 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
31388 ** For VxWorks, we have to use the alternative unique ID system based on
31389 ** canonical filename and implemented in the previous division.)
31391 ** The sqlite3_file structure for POSIX is no longer just an integer file
31392 ** descriptor. It is now a structure that holds the integer file
31393 ** descriptor and a pointer to a structure that describes the internal
31394 ** locks on the corresponding inode. There is one locking structure
31395 ** per inode, so if the same inode is opened twice, both unixFile structures
31396 ** point to the same locking structure. The locking structure keeps
31397 ** a reference count (so we will know when to delete it) and a "cnt"
31398 ** field that tells us its internal lock status. cnt==0 means the
31399 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
31400 ** cnt>0 means there are cnt shared locks on the file.
31402 ** Any attempt to lock or unlock a file first checks the locking
31403 ** structure. The fcntl() system call is only invoked to set a
31404 ** POSIX lock if the internal lock structure transitions between
31405 ** a locked and an unlocked state.
31407 ** But wait: there are yet more problems with POSIX advisory locks.
31409 ** If you close a file descriptor that points to a file that has locks,
31410 ** all locks on that file that are owned by the current process are
31411 ** released. To work around this problem, each unixInodeInfo object
31412 ** maintains a count of the number of pending locks on tha inode.
31413 ** When an attempt is made to close an unixFile, if there are
31414 ** other unixFile open on the same inode that are holding locks, the call
31415 ** to close() the file descriptor is deferred until all of the locks clear.
31416 ** The unixInodeInfo structure keeps a list of file descriptors that need to
31417 ** be closed and that list is walked (and cleared) when the last lock
31418 ** clears.
31420 ** Yet another problem: LinuxThreads do not play well with posix locks.
31422 ** Many older versions of linux use the LinuxThreads library which is
31423 ** not posix compliant. Under LinuxThreads, a lock created by thread
31424 ** A cannot be modified or overridden by a different thread B.
31425 ** Only thread A can modify the lock. Locking behavior is correct
31426 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
31427 ** on linux - with NPTL a lock created by thread A can override locks
31428 ** in thread B. But there is no way to know at compile-time which
31429 ** threading library is being used. So there is no way to know at
31430 ** compile-time whether or not thread A can override locks on thread B.
31431 ** One has to do a run-time check to discover the behavior of the
31432 ** current process.
31434 ** SQLite used to support LinuxThreads. But support for LinuxThreads
31435 ** was dropped beginning with version 3.7.0. SQLite will still work with
31436 ** LinuxThreads provided that (1) there is no more than one connection
31437 ** per database file in the same process and (2) database connections
31438 ** do not move across threads.
31442 ** An instance of the following structure serves as the key used
31443 ** to locate a particular unixInodeInfo object.
31445 struct unixFileId {
31446 dev_t dev; /* Device number */
31447 #if OS_VXWORKS
31448 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
31449 #else
31450 /* We are told that some versions of Android contain a bug that
31451 ** sizes ino_t at only 32-bits instead of 64-bits. (See
31452 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
31453 ** To work around this, always allocate 64-bits for the inode number.
31454 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
31455 ** but that should not be a big deal. */
31456 /* WAS: ino_t ino; */
31457 u64 ino; /* Inode number */
31458 #endif
31462 ** An instance of the following structure is allocated for each open
31463 ** inode. Or, on LinuxThreads, there is one of these structures for
31464 ** each inode opened by each thread.
31466 ** A single inode can have multiple file descriptors, so each unixFile
31467 ** structure contains a pointer to an instance of this object and this
31468 ** object keeps a count of the number of unixFile pointing to it.
31470 struct unixInodeInfo {
31471 struct unixFileId fileId; /* The lookup key */
31472 int nShared; /* Number of SHARED locks held */
31473 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
31474 unsigned char bProcessLock; /* An exclusive process lock is held */
31475 int nRef; /* Number of pointers to this structure */
31476 unixShmNode *pShmNode; /* Shared memory associated with this inode */
31477 int nLock; /* Number of outstanding file locks */
31478 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
31479 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
31480 unixInodeInfo *pPrev; /* .... doubly linked */
31481 #if SQLITE_ENABLE_LOCKING_STYLE
31482 unsigned long long sharedByte; /* for AFP simulated shared lock */
31483 #endif
31484 #if OS_VXWORKS
31485 sem_t *pSem; /* Named POSIX semaphore */
31486 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
31487 #endif
31491 ** A lists of all unixInodeInfo objects.
31493 static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
31494 static unsigned int nUnusedFd = 0; /* Total unused file descriptors */
31498 ** This function - unixLogErrorAtLine(), is only ever called via the macro
31499 ** unixLogError().
31501 ** It is invoked after an error occurs in an OS function and errno has been
31502 ** set. It logs a message using sqlite3_log() containing the current value of
31503 ** errno and, if possible, the human-readable equivalent from strerror() or
31504 ** strerror_r().
31506 ** The first argument passed to the macro should be the error code that
31507 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
31508 ** The two subsequent arguments should be the name of the OS function that
31509 ** failed (e.g. "unlink", "open") and the associated file-system path,
31510 ** if any.
31512 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
31513 static int unixLogErrorAtLine(
31514 int errcode, /* SQLite error code */
31515 const char *zFunc, /* Name of OS function that failed */
31516 const char *zPath, /* File path associated with error */
31517 int iLine /* Source line number where error occurred */
31519 char *zErr; /* Message from strerror() or equivalent */
31520 int iErrno = errno; /* Saved syscall error number */
31522 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
31523 ** the strerror() function to obtain the human-readable error message
31524 ** equivalent to errno. Otherwise, use strerror_r().
31526 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
31527 char aErr[80];
31528 memset(aErr, 0, sizeof(aErr));
31529 zErr = aErr;
31531 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
31532 ** assume that the system provides the GNU version of strerror_r() that
31533 ** returns a pointer to a buffer containing the error message. That pointer
31534 ** may point to aErr[], or it may point to some static storage somewhere.
31535 ** Otherwise, assume that the system provides the POSIX version of
31536 ** strerror_r(), which always writes an error message into aErr[].
31538 ** If the code incorrectly assumes that it is the POSIX version that is
31539 ** available, the error message will often be an empty string. Not a
31540 ** huge problem. Incorrectly concluding that the GNU version is available
31541 ** could lead to a segfault though.
31543 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
31544 zErr =
31545 # endif
31546 strerror_r(iErrno, aErr, sizeof(aErr)-1);
31548 #elif SQLITE_THREADSAFE
31549 /* This is a threadsafe build, but strerror_r() is not available. */
31550 zErr = "";
31551 #else
31552 /* Non-threadsafe build, use strerror(). */
31553 zErr = strerror(iErrno);
31554 #endif
31556 if( zPath==0 ) zPath = "";
31557 sqlite3_log(errcode,
31558 "os_unix.c:%d: (%d) %s(%s) - %s",
31559 iLine, iErrno, zFunc, zPath, zErr
31562 return errcode;
31566 ** Close a file descriptor.
31568 ** We assume that close() almost always works, since it is only in a
31569 ** very sick application or on a very sick platform that it might fail.
31570 ** If it does fail, simply leak the file descriptor, but do log the
31571 ** error.
31573 ** Note that it is not safe to retry close() after EINTR since the
31574 ** file descriptor might have already been reused by another thread.
31575 ** So we don't even try to recover from an EINTR. Just log the error
31576 ** and move on.
31578 static void robust_close(unixFile *pFile, int h, int lineno){
31579 if( osClose(h) ){
31580 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
31581 pFile ? pFile->zPath : 0, lineno);
31586 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
31587 ** a convenient place to set a breakpoint.
31589 static void storeLastErrno(unixFile *pFile, int error){
31590 pFile->lastErrno = error;
31594 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
31596 static void closePendingFds(unixFile *pFile){
31597 unixInodeInfo *pInode = pFile->pInode;
31598 UnixUnusedFd *p;
31599 UnixUnusedFd *pNext;
31600 for(p=pInode->pUnused; p; p=pNext){
31601 pNext = p->pNext;
31602 robust_close(pFile, p->fd, __LINE__);
31603 sqlite3_free(p);
31604 nUnusedFd--;
31606 pInode->pUnused = 0;
31610 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
31612 ** The mutex entered using the unixEnterMutex() function must be held
31613 ** when this function is called.
31615 static void releaseInodeInfo(unixFile *pFile){
31616 unixInodeInfo *pInode = pFile->pInode;
31617 assert( unixMutexHeld() );
31618 if( ALWAYS(pInode) ){
31619 pInode->nRef--;
31620 if( pInode->nRef==0 ){
31621 assert( pInode->pShmNode==0 );
31622 closePendingFds(pFile);
31623 if( pInode->pPrev ){
31624 assert( pInode->pPrev->pNext==pInode );
31625 pInode->pPrev->pNext = pInode->pNext;
31626 }else{
31627 assert( inodeList==pInode );
31628 inodeList = pInode->pNext;
31630 if( pInode->pNext ){
31631 assert( pInode->pNext->pPrev==pInode );
31632 pInode->pNext->pPrev = pInode->pPrev;
31634 sqlite3_free(pInode);
31637 assert( inodeList!=0 || nUnusedFd==0 );
31641 ** Given a file descriptor, locate the unixInodeInfo object that
31642 ** describes that file descriptor. Create a new one if necessary. The
31643 ** return value might be uninitialized if an error occurs.
31645 ** The mutex entered using the unixEnterMutex() function must be held
31646 ** when this function is called.
31648 ** Return an appropriate error code.
31650 static int findInodeInfo(
31651 unixFile *pFile, /* Unix file with file desc used in the key */
31652 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
31654 int rc; /* System call return code */
31655 int fd; /* The file descriptor for pFile */
31656 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
31657 struct stat statbuf; /* Low-level file information */
31658 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
31660 assert( unixMutexHeld() );
31662 /* Get low-level information about the file that we can used to
31663 ** create a unique name for the file.
31665 fd = pFile->h;
31666 rc = osFstat(fd, &statbuf);
31667 if( rc!=0 ){
31668 storeLastErrno(pFile, errno);
31669 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
31670 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
31671 #endif
31672 return SQLITE_IOERR;
31675 #ifdef __APPLE__
31676 /* On OS X on an msdos filesystem, the inode number is reported
31677 ** incorrectly for zero-size files. See ticket #3260. To work
31678 ** around this problem (we consider it a bug in OS X, not SQLite)
31679 ** we always increase the file size to 1 by writing a single byte
31680 ** prior to accessing the inode number. The one byte written is
31681 ** an ASCII 'S' character which also happens to be the first byte
31682 ** in the header of every SQLite database. In this way, if there
31683 ** is a race condition such that another thread has already populated
31684 ** the first page of the database, no damage is done.
31686 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
31687 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
31688 if( rc!=1 ){
31689 storeLastErrno(pFile, errno);
31690 return SQLITE_IOERR;
31692 rc = osFstat(fd, &statbuf);
31693 if( rc!=0 ){
31694 storeLastErrno(pFile, errno);
31695 return SQLITE_IOERR;
31698 #endif
31700 memset(&fileId, 0, sizeof(fileId));
31701 fileId.dev = statbuf.st_dev;
31702 #if OS_VXWORKS
31703 fileId.pId = pFile->pId;
31704 #else
31705 fileId.ino = (u64)statbuf.st_ino;
31706 #endif
31707 assert( inodeList!=0 || nUnusedFd==0 );
31708 pInode = inodeList;
31709 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
31710 pInode = pInode->pNext;
31712 if( pInode==0 ){
31713 pInode = sqlite3_malloc64( sizeof(*pInode) );
31714 if( pInode==0 ){
31715 return SQLITE_NOMEM_BKPT;
31717 memset(pInode, 0, sizeof(*pInode));
31718 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
31719 pInode->nRef = 1;
31720 pInode->pNext = inodeList;
31721 pInode->pPrev = 0;
31722 if( inodeList ) inodeList->pPrev = pInode;
31723 inodeList = pInode;
31724 }else{
31725 pInode->nRef++;
31727 *ppInode = pInode;
31728 return SQLITE_OK;
31732 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
31734 static int fileHasMoved(unixFile *pFile){
31735 #if OS_VXWORKS
31736 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
31737 #else
31738 struct stat buf;
31739 return pFile->pInode!=0 &&
31740 (osStat(pFile->zPath, &buf)!=0
31741 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
31742 #endif
31747 ** Check a unixFile that is a database. Verify the following:
31749 ** (1) There is exactly one hard link on the file
31750 ** (2) The file is not a symbolic link
31751 ** (3) The file has not been renamed or unlinked
31753 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
31755 static void verifyDbFile(unixFile *pFile){
31756 struct stat buf;
31757 int rc;
31759 /* These verifications occurs for the main database only */
31760 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
31762 rc = osFstat(pFile->h, &buf);
31763 if( rc!=0 ){
31764 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
31765 return;
31767 if( buf.st_nlink==0 ){
31768 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
31769 return;
31771 if( buf.st_nlink>1 ){
31772 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
31773 return;
31775 if( fileHasMoved(pFile) ){
31776 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
31777 return;
31783 ** This routine checks if there is a RESERVED lock held on the specified
31784 ** file by this or any other process. If such a lock is held, set *pResOut
31785 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31786 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31788 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
31789 int rc = SQLITE_OK;
31790 int reserved = 0;
31791 unixFile *pFile = (unixFile*)id;
31793 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31795 assert( pFile );
31796 assert( pFile->eFileLock<=SHARED_LOCK );
31797 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
31799 /* Check if a thread in this process holds such a lock */
31800 if( pFile->pInode->eFileLock>SHARED_LOCK ){
31801 reserved = 1;
31804 /* Otherwise see if some other process holds it.
31806 #ifndef __DJGPP__
31807 if( !reserved && !pFile->pInode->bProcessLock ){
31808 struct flock lock;
31809 lock.l_whence = SEEK_SET;
31810 lock.l_start = RESERVED_BYTE;
31811 lock.l_len = 1;
31812 lock.l_type = F_WRLCK;
31813 if( osFcntl(pFile->h, F_GETLK, &lock) ){
31814 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
31815 storeLastErrno(pFile, errno);
31816 } else if( lock.l_type!=F_UNLCK ){
31817 reserved = 1;
31820 #endif
31822 unixLeaveMutex();
31823 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
31825 *pResOut = reserved;
31826 return rc;
31830 ** Attempt to set a system-lock on the file pFile. The lock is
31831 ** described by pLock.
31833 ** If the pFile was opened read/write from unix-excl, then the only lock
31834 ** ever obtained is an exclusive lock, and it is obtained exactly once
31835 ** the first time any lock is attempted. All subsequent system locking
31836 ** operations become no-ops. Locking operations still happen internally,
31837 ** in order to coordinate access between separate database connections
31838 ** within this process, but all of that is handled in memory and the
31839 ** operating system does not participate.
31841 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
31842 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
31843 ** and is read-only.
31845 ** Zero is returned if the call completes successfully, or -1 if a call
31846 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
31848 static int unixFileLock(unixFile *pFile, struct flock *pLock){
31849 int rc;
31850 unixInodeInfo *pInode = pFile->pInode;
31851 assert( unixMutexHeld() );
31852 assert( pInode!=0 );
31853 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
31854 if( pInode->bProcessLock==0 ){
31855 struct flock lock;
31856 assert( pInode->nLock==0 );
31857 lock.l_whence = SEEK_SET;
31858 lock.l_start = SHARED_FIRST;
31859 lock.l_len = SHARED_SIZE;
31860 lock.l_type = F_WRLCK;
31861 rc = osFcntl(pFile->h, F_SETLK, &lock);
31862 if( rc<0 ) return rc;
31863 pInode->bProcessLock = 1;
31864 pInode->nLock++;
31865 }else{
31866 rc = 0;
31868 }else{
31869 rc = osFcntl(pFile->h, F_SETLK, pLock);
31871 return rc;
31875 ** Lock the file with the lock specified by parameter eFileLock - one
31876 ** of the following:
31878 ** (1) SHARED_LOCK
31879 ** (2) RESERVED_LOCK
31880 ** (3) PENDING_LOCK
31881 ** (4) EXCLUSIVE_LOCK
31883 ** Sometimes when requesting one lock state, additional lock states
31884 ** are inserted in between. The locking might fail on one of the later
31885 ** transitions leaving the lock state different from what it started but
31886 ** still short of its goal. The following chart shows the allowed
31887 ** transitions and the inserted intermediate states:
31889 ** UNLOCKED -> SHARED
31890 ** SHARED -> RESERVED
31891 ** SHARED -> (PENDING) -> EXCLUSIVE
31892 ** RESERVED -> (PENDING) -> EXCLUSIVE
31893 ** PENDING -> EXCLUSIVE
31895 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31896 ** routine to lower a locking level.
31898 static int unixLock(sqlite3_file *id, int eFileLock){
31899 /* The following describes the implementation of the various locks and
31900 ** lock transitions in terms of the POSIX advisory shared and exclusive
31901 ** lock primitives (called read-locks and write-locks below, to avoid
31902 ** confusion with SQLite lock names). The algorithms are complicated
31903 ** slightly in order to be compatible with Windows95 systems simultaneously
31904 ** accessing the same database file, in case that is ever required.
31906 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
31907 ** byte', each single bytes at well known offsets, and the 'shared byte
31908 ** range', a range of 510 bytes at a well known offset.
31910 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
31911 ** byte'. If this is successful, 'shared byte range' is read-locked
31912 ** and the lock on the 'pending byte' released. (Legacy note: When
31913 ** SQLite was first developed, Windows95 systems were still very common,
31914 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
31915 ** single randomly selected by from the 'shared byte range' is locked.
31916 ** Windows95 is now pretty much extinct, but this work-around for the
31917 ** lack of shared-locks on Windows95 lives on, for backwards
31918 ** compatibility.)
31920 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
31921 ** A RESERVED lock is implemented by grabbing a write-lock on the
31922 ** 'reserved byte'.
31924 ** A process may only obtain a PENDING lock after it has obtained a
31925 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
31926 ** on the 'pending byte'. This ensures that no new SHARED locks can be
31927 ** obtained, but existing SHARED locks are allowed to persist. A process
31928 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
31929 ** This property is used by the algorithm for rolling back a journal file
31930 ** after a crash.
31932 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
31933 ** implemented by obtaining a write-lock on the entire 'shared byte
31934 ** range'. Since all other locks require a read-lock on one of the bytes
31935 ** within this range, this ensures that no other locks are held on the
31936 ** database.
31938 int rc = SQLITE_OK;
31939 unixFile *pFile = (unixFile*)id;
31940 unixInodeInfo *pInode;
31941 struct flock lock;
31942 int tErrno = 0;
31944 assert( pFile );
31945 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
31946 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
31947 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
31948 osGetpid(0)));
31950 /* If there is already a lock of this type or more restrictive on the
31951 ** unixFile, do nothing. Don't use the end_lock: exit path, as
31952 ** unixEnterMutex() hasn't been called yet.
31954 if( pFile->eFileLock>=eFileLock ){
31955 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
31956 azFileLock(eFileLock)));
31957 return SQLITE_OK;
31960 /* Make sure the locking sequence is correct.
31961 ** (1) We never move from unlocked to anything higher than shared lock.
31962 ** (2) SQLite never explicitly requests a pendig lock.
31963 ** (3) A shared lock is always held when a reserve lock is requested.
31965 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
31966 assert( eFileLock!=PENDING_LOCK );
31967 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
31969 /* This mutex is needed because pFile->pInode is shared across threads
31971 unixEnterMutex();
31972 pInode = pFile->pInode;
31974 /* If some thread using this PID has a lock via a different unixFile*
31975 ** handle that precludes the requested lock, return BUSY.
31977 if( (pFile->eFileLock!=pInode->eFileLock &&
31978 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
31980 rc = SQLITE_BUSY;
31981 goto end_lock;
31984 /* If a SHARED lock is requested, and some thread using this PID already
31985 ** has a SHARED or RESERVED lock, then increment reference counts and
31986 ** return SQLITE_OK.
31988 if( eFileLock==SHARED_LOCK &&
31989 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
31990 assert( eFileLock==SHARED_LOCK );
31991 assert( pFile->eFileLock==0 );
31992 assert( pInode->nShared>0 );
31993 pFile->eFileLock = SHARED_LOCK;
31994 pInode->nShared++;
31995 pInode->nLock++;
31996 goto end_lock;
32000 /* A PENDING lock is needed before acquiring a SHARED lock and before
32001 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
32002 ** be released.
32004 lock.l_len = 1L;
32005 lock.l_whence = SEEK_SET;
32006 if( eFileLock==SHARED_LOCK
32007 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
32009 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
32010 lock.l_start = PENDING_BYTE;
32011 if( unixFileLock(pFile, &lock) ){
32012 tErrno = errno;
32013 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32014 if( rc!=SQLITE_BUSY ){
32015 storeLastErrno(pFile, tErrno);
32017 goto end_lock;
32022 /* If control gets to this point, then actually go ahead and make
32023 ** operating system calls for the specified lock.
32025 if( eFileLock==SHARED_LOCK ){
32026 assert( pInode->nShared==0 );
32027 assert( pInode->eFileLock==0 );
32028 assert( rc==SQLITE_OK );
32030 /* Now get the read-lock */
32031 lock.l_start = SHARED_FIRST;
32032 lock.l_len = SHARED_SIZE;
32033 if( unixFileLock(pFile, &lock) ){
32034 tErrno = errno;
32035 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32038 /* Drop the temporary PENDING lock */
32039 lock.l_start = PENDING_BYTE;
32040 lock.l_len = 1L;
32041 lock.l_type = F_UNLCK;
32042 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
32043 /* This could happen with a network mount */
32044 tErrno = errno;
32045 rc = SQLITE_IOERR_UNLOCK;
32048 if( rc ){
32049 if( rc!=SQLITE_BUSY ){
32050 storeLastErrno(pFile, tErrno);
32052 goto end_lock;
32053 }else{
32054 pFile->eFileLock = SHARED_LOCK;
32055 pInode->nLock++;
32056 pInode->nShared = 1;
32058 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
32059 /* We are trying for an exclusive lock but another thread in this
32060 ** same process is still holding a shared lock. */
32061 rc = SQLITE_BUSY;
32062 }else{
32063 /* The request was for a RESERVED or EXCLUSIVE lock. It is
32064 ** assumed that there is a SHARED or greater lock on the file
32065 ** already.
32067 assert( 0!=pFile->eFileLock );
32068 lock.l_type = F_WRLCK;
32070 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
32071 if( eFileLock==RESERVED_LOCK ){
32072 lock.l_start = RESERVED_BYTE;
32073 lock.l_len = 1L;
32074 }else{
32075 lock.l_start = SHARED_FIRST;
32076 lock.l_len = SHARED_SIZE;
32079 if( unixFileLock(pFile, &lock) ){
32080 tErrno = errno;
32081 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32082 if( rc!=SQLITE_BUSY ){
32083 storeLastErrno(pFile, tErrno);
32089 #ifdef SQLITE_DEBUG
32090 /* Set up the transaction-counter change checking flags when
32091 ** transitioning from a SHARED to a RESERVED lock. The change
32092 ** from SHARED to RESERVED marks the beginning of a normal
32093 ** write operation (not a hot journal rollback).
32095 if( rc==SQLITE_OK
32096 && pFile->eFileLock<=SHARED_LOCK
32097 && eFileLock==RESERVED_LOCK
32099 pFile->transCntrChng = 0;
32100 pFile->dbUpdate = 0;
32101 pFile->inNormalWrite = 1;
32103 #endif
32106 if( rc==SQLITE_OK ){
32107 pFile->eFileLock = eFileLock;
32108 pInode->eFileLock = eFileLock;
32109 }else if( eFileLock==EXCLUSIVE_LOCK ){
32110 pFile->eFileLock = PENDING_LOCK;
32111 pInode->eFileLock = PENDING_LOCK;
32114 end_lock:
32115 unixLeaveMutex();
32116 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
32117 rc==SQLITE_OK ? "ok" : "failed"));
32118 return rc;
32122 ** Add the file descriptor used by file handle pFile to the corresponding
32123 ** pUnused list.
32125 static void setPendingFd(unixFile *pFile){
32126 unixInodeInfo *pInode = pFile->pInode;
32127 UnixUnusedFd *p = pFile->pPreallocatedUnused;
32128 p->pNext = pInode->pUnused;
32129 pInode->pUnused = p;
32130 pFile->h = -1;
32131 pFile->pPreallocatedUnused = 0;
32132 nUnusedFd++;
32136 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32137 ** must be either NO_LOCK or SHARED_LOCK.
32139 ** If the locking level of the file descriptor is already at or below
32140 ** the requested locking level, this routine is a no-op.
32142 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
32143 ** the byte range is divided into 2 parts and the first part is unlocked then
32144 ** set to a read lock, then the other part is simply unlocked. This works
32145 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
32146 ** remove the write lock on a region when a read lock is set.
32148 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
32149 unixFile *pFile = (unixFile*)id;
32150 unixInodeInfo *pInode;
32151 struct flock lock;
32152 int rc = SQLITE_OK;
32154 assert( pFile );
32155 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
32156 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
32157 osGetpid(0)));
32159 assert( eFileLock<=SHARED_LOCK );
32160 if( pFile->eFileLock<=eFileLock ){
32161 return SQLITE_OK;
32163 unixEnterMutex();
32164 pInode = pFile->pInode;
32165 assert( pInode->nShared!=0 );
32166 if( pFile->eFileLock>SHARED_LOCK ){
32167 assert( pInode->eFileLock==pFile->eFileLock );
32169 #ifdef SQLITE_DEBUG
32170 /* When reducing a lock such that other processes can start
32171 ** reading the database file again, make sure that the
32172 ** transaction counter was updated if any part of the database
32173 ** file changed. If the transaction counter is not updated,
32174 ** other connections to the same file might not realize that
32175 ** the file has changed and hence might not know to flush their
32176 ** cache. The use of a stale cache can lead to database corruption.
32178 pFile->inNormalWrite = 0;
32179 #endif
32181 /* downgrading to a shared lock on NFS involves clearing the write lock
32182 ** before establishing the readlock - to avoid a race condition we downgrade
32183 ** the lock in 2 blocks, so that part of the range will be covered by a
32184 ** write lock until the rest is covered by a read lock:
32185 ** 1: [WWWWW]
32186 ** 2: [....W]
32187 ** 3: [RRRRW]
32188 ** 4: [RRRR.]
32190 if( eFileLock==SHARED_LOCK ){
32191 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
32192 (void)handleNFSUnlock;
32193 assert( handleNFSUnlock==0 );
32194 #endif
32195 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
32196 if( handleNFSUnlock ){
32197 int tErrno; /* Error code from system call errors */
32198 off_t divSize = SHARED_SIZE - 1;
32200 lock.l_type = F_UNLCK;
32201 lock.l_whence = SEEK_SET;
32202 lock.l_start = SHARED_FIRST;
32203 lock.l_len = divSize;
32204 if( unixFileLock(pFile, &lock)==(-1) ){
32205 tErrno = errno;
32206 rc = SQLITE_IOERR_UNLOCK;
32207 storeLastErrno(pFile, tErrno);
32208 goto end_unlock;
32210 lock.l_type = F_RDLCK;
32211 lock.l_whence = SEEK_SET;
32212 lock.l_start = SHARED_FIRST;
32213 lock.l_len = divSize;
32214 if( unixFileLock(pFile, &lock)==(-1) ){
32215 tErrno = errno;
32216 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
32217 if( IS_LOCK_ERROR(rc) ){
32218 storeLastErrno(pFile, tErrno);
32220 goto end_unlock;
32222 lock.l_type = F_UNLCK;
32223 lock.l_whence = SEEK_SET;
32224 lock.l_start = SHARED_FIRST+divSize;
32225 lock.l_len = SHARED_SIZE-divSize;
32226 if( unixFileLock(pFile, &lock)==(-1) ){
32227 tErrno = errno;
32228 rc = SQLITE_IOERR_UNLOCK;
32229 storeLastErrno(pFile, tErrno);
32230 goto end_unlock;
32232 }else
32233 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32235 lock.l_type = F_RDLCK;
32236 lock.l_whence = SEEK_SET;
32237 lock.l_start = SHARED_FIRST;
32238 lock.l_len = SHARED_SIZE;
32239 if( unixFileLock(pFile, &lock) ){
32240 /* In theory, the call to unixFileLock() cannot fail because another
32241 ** process is holding an incompatible lock. If it does, this
32242 ** indicates that the other process is not following the locking
32243 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
32244 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
32245 ** an assert to fail). */
32246 rc = SQLITE_IOERR_RDLOCK;
32247 storeLastErrno(pFile, errno);
32248 goto end_unlock;
32252 lock.l_type = F_UNLCK;
32253 lock.l_whence = SEEK_SET;
32254 lock.l_start = PENDING_BYTE;
32255 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
32256 if( unixFileLock(pFile, &lock)==0 ){
32257 pInode->eFileLock = SHARED_LOCK;
32258 }else{
32259 rc = SQLITE_IOERR_UNLOCK;
32260 storeLastErrno(pFile, errno);
32261 goto end_unlock;
32264 if( eFileLock==NO_LOCK ){
32265 /* Decrement the shared lock counter. Release the lock using an
32266 ** OS call only when all threads in this same process have released
32267 ** the lock.
32269 pInode->nShared--;
32270 if( pInode->nShared==0 ){
32271 lock.l_type = F_UNLCK;
32272 lock.l_whence = SEEK_SET;
32273 lock.l_start = lock.l_len = 0L;
32274 if( unixFileLock(pFile, &lock)==0 ){
32275 pInode->eFileLock = NO_LOCK;
32276 }else{
32277 rc = SQLITE_IOERR_UNLOCK;
32278 storeLastErrno(pFile, errno);
32279 pInode->eFileLock = NO_LOCK;
32280 pFile->eFileLock = NO_LOCK;
32284 /* Decrement the count of locks against this same file. When the
32285 ** count reaches zero, close any other file descriptors whose close
32286 ** was deferred because of outstanding locks.
32288 pInode->nLock--;
32289 assert( pInode->nLock>=0 );
32290 if( pInode->nLock==0 ){
32291 closePendingFds(pFile);
32295 end_unlock:
32296 unixLeaveMutex();
32297 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
32298 return rc;
32302 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32303 ** must be either NO_LOCK or SHARED_LOCK.
32305 ** If the locking level of the file descriptor is already at or below
32306 ** the requested locking level, this routine is a no-op.
32308 static int unixUnlock(sqlite3_file *id, int eFileLock){
32309 #if SQLITE_MAX_MMAP_SIZE>0
32310 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
32311 #endif
32312 return posixUnlock(id, eFileLock, 0);
32315 #if SQLITE_MAX_MMAP_SIZE>0
32316 static int unixMapfile(unixFile *pFd, i64 nByte);
32317 static void unixUnmapfile(unixFile *pFd);
32318 #endif
32321 ** This function performs the parts of the "close file" operation
32322 ** common to all locking schemes. It closes the directory and file
32323 ** handles, if they are valid, and sets all fields of the unixFile
32324 ** structure to 0.
32326 ** It is *not* necessary to hold the mutex when this routine is called,
32327 ** even on VxWorks. A mutex will be acquired on VxWorks by the
32328 ** vxworksReleaseFileId() routine.
32330 static int closeUnixFile(sqlite3_file *id){
32331 unixFile *pFile = (unixFile*)id;
32332 #if SQLITE_MAX_MMAP_SIZE>0
32333 unixUnmapfile(pFile);
32334 #endif
32335 if( pFile->h>=0 ){
32336 robust_close(pFile, pFile->h, __LINE__);
32337 pFile->h = -1;
32339 #if OS_VXWORKS
32340 if( pFile->pId ){
32341 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
32342 osUnlink(pFile->pId->zCanonicalName);
32344 vxworksReleaseFileId(pFile->pId);
32345 pFile->pId = 0;
32347 #endif
32348 #ifdef SQLITE_UNLINK_AFTER_CLOSE
32349 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
32350 osUnlink(pFile->zPath);
32351 sqlite3_free(*(char**)&pFile->zPath);
32352 pFile->zPath = 0;
32354 #endif
32355 OSTRACE(("CLOSE %-3d\n", pFile->h));
32356 OpenCounter(-1);
32357 sqlite3_free(pFile->pPreallocatedUnused);
32358 memset(pFile, 0, sizeof(unixFile));
32359 return SQLITE_OK;
32363 ** Close a file.
32365 static int unixClose(sqlite3_file *id){
32366 int rc = SQLITE_OK;
32367 unixFile *pFile = (unixFile *)id;
32368 verifyDbFile(pFile);
32369 unixUnlock(id, NO_LOCK);
32370 unixEnterMutex();
32372 /* unixFile.pInode is always valid here. Otherwise, a different close
32373 ** routine (e.g. nolockClose()) would be called instead.
32375 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
32376 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
32377 /* If there are outstanding locks, do not actually close the file just
32378 ** yet because that would clear those locks. Instead, add the file
32379 ** descriptor to pInode->pUnused list. It will be automatically closed
32380 ** when the last lock is cleared.
32382 setPendingFd(pFile);
32384 releaseInodeInfo(pFile);
32385 rc = closeUnixFile(id);
32386 unixLeaveMutex();
32387 return rc;
32390 /************** End of the posix advisory lock implementation *****************
32391 ******************************************************************************/
32393 /******************************************************************************
32394 ****************************** No-op Locking **********************************
32396 ** Of the various locking implementations available, this is by far the
32397 ** simplest: locking is ignored. No attempt is made to lock the database
32398 ** file for reading or writing.
32400 ** This locking mode is appropriate for use on read-only databases
32401 ** (ex: databases that are burned into CD-ROM, for example.) It can
32402 ** also be used if the application employs some external mechanism to
32403 ** prevent simultaneous access of the same database by two or more
32404 ** database connections. But there is a serious risk of database
32405 ** corruption if this locking mode is used in situations where multiple
32406 ** database connections are accessing the same database file at the same
32407 ** time and one or more of those connections are writing.
32410 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
32411 UNUSED_PARAMETER(NotUsed);
32412 *pResOut = 0;
32413 return SQLITE_OK;
32415 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
32416 UNUSED_PARAMETER2(NotUsed, NotUsed2);
32417 return SQLITE_OK;
32419 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
32420 UNUSED_PARAMETER2(NotUsed, NotUsed2);
32421 return SQLITE_OK;
32425 ** Close the file.
32427 static int nolockClose(sqlite3_file *id) {
32428 return closeUnixFile(id);
32431 /******************* End of the no-op lock implementation *********************
32432 ******************************************************************************/
32434 /******************************************************************************
32435 ************************* Begin dot-file Locking ******************************
32437 ** The dotfile locking implementation uses the existence of separate lock
32438 ** files (really a directory) to control access to the database. This works
32439 ** on just about every filesystem imaginable. But there are serious downsides:
32441 ** (1) There is zero concurrency. A single reader blocks all other
32442 ** connections from reading or writing the database.
32444 ** (2) An application crash or power loss can leave stale lock files
32445 ** sitting around that need to be cleared manually.
32447 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
32448 ** other locking strategy is available.
32450 ** Dotfile locking works by creating a subdirectory in the same directory as
32451 ** the database and with the same name but with a ".lock" extension added.
32452 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
32453 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
32457 ** The file suffix added to the data base filename in order to create the
32458 ** lock directory.
32460 #define DOTLOCK_SUFFIX ".lock"
32463 ** This routine checks if there is a RESERVED lock held on the specified
32464 ** file by this or any other process. If such a lock is held, set *pResOut
32465 ** to a non-zero value otherwise *pResOut is set to zero. The return value
32466 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32468 ** In dotfile locking, either a lock exists or it does not. So in this
32469 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
32470 ** is held on the file and false if the file is unlocked.
32472 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
32473 int rc = SQLITE_OK;
32474 int reserved = 0;
32475 unixFile *pFile = (unixFile*)id;
32477 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32479 assert( pFile );
32480 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
32481 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
32482 *pResOut = reserved;
32483 return rc;
32487 ** Lock the file with the lock specified by parameter eFileLock - one
32488 ** of the following:
32490 ** (1) SHARED_LOCK
32491 ** (2) RESERVED_LOCK
32492 ** (3) PENDING_LOCK
32493 ** (4) EXCLUSIVE_LOCK
32495 ** Sometimes when requesting one lock state, additional lock states
32496 ** are inserted in between. The locking might fail on one of the later
32497 ** transitions leaving the lock state different from what it started but
32498 ** still short of its goal. The following chart shows the allowed
32499 ** transitions and the inserted intermediate states:
32501 ** UNLOCKED -> SHARED
32502 ** SHARED -> RESERVED
32503 ** SHARED -> (PENDING) -> EXCLUSIVE
32504 ** RESERVED -> (PENDING) -> EXCLUSIVE
32505 ** PENDING -> EXCLUSIVE
32507 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
32508 ** routine to lower a locking level.
32510 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
32511 ** But we track the other locking levels internally.
32513 static int dotlockLock(sqlite3_file *id, int eFileLock) {
32514 unixFile *pFile = (unixFile*)id;
32515 char *zLockFile = (char *)pFile->lockingContext;
32516 int rc = SQLITE_OK;
32519 /* If we have any lock, then the lock file already exists. All we have
32520 ** to do is adjust our internal record of the lock level.
32522 if( pFile->eFileLock > NO_LOCK ){
32523 pFile->eFileLock = eFileLock;
32524 /* Always update the timestamp on the old file */
32525 #ifdef HAVE_UTIME
32526 utime(zLockFile, NULL);
32527 #else
32528 utimes(zLockFile, NULL);
32529 #endif
32530 return SQLITE_OK;
32533 /* grab an exclusive lock */
32534 rc = osMkdir(zLockFile, 0777);
32535 if( rc<0 ){
32536 /* failed to open/create the lock directory */
32537 int tErrno = errno;
32538 if( EEXIST == tErrno ){
32539 rc = SQLITE_BUSY;
32540 } else {
32541 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32542 if( rc!=SQLITE_BUSY ){
32543 storeLastErrno(pFile, tErrno);
32546 return rc;
32549 /* got it, set the type and return ok */
32550 pFile->eFileLock = eFileLock;
32551 return rc;
32555 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32556 ** must be either NO_LOCK or SHARED_LOCK.
32558 ** If the locking level of the file descriptor is already at or below
32559 ** the requested locking level, this routine is a no-op.
32561 ** When the locking level reaches NO_LOCK, delete the lock file.
32563 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
32564 unixFile *pFile = (unixFile*)id;
32565 char *zLockFile = (char *)pFile->lockingContext;
32566 int rc;
32568 assert( pFile );
32569 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
32570 pFile->eFileLock, osGetpid(0)));
32571 assert( eFileLock<=SHARED_LOCK );
32573 /* no-op if possible */
32574 if( pFile->eFileLock==eFileLock ){
32575 return SQLITE_OK;
32578 /* To downgrade to shared, simply update our internal notion of the
32579 ** lock state. No need to mess with the file on disk.
32581 if( eFileLock==SHARED_LOCK ){
32582 pFile->eFileLock = SHARED_LOCK;
32583 return SQLITE_OK;
32586 /* To fully unlock the database, delete the lock file */
32587 assert( eFileLock==NO_LOCK );
32588 rc = osRmdir(zLockFile);
32589 if( rc<0 ){
32590 int tErrno = errno;
32591 if( tErrno==ENOENT ){
32592 rc = SQLITE_OK;
32593 }else{
32594 rc = SQLITE_IOERR_UNLOCK;
32595 storeLastErrno(pFile, tErrno);
32597 return rc;
32599 pFile->eFileLock = NO_LOCK;
32600 return SQLITE_OK;
32604 ** Close a file. Make sure the lock has been released before closing.
32606 static int dotlockClose(sqlite3_file *id) {
32607 unixFile *pFile = (unixFile*)id;
32608 assert( id!=0 );
32609 dotlockUnlock(id, NO_LOCK);
32610 sqlite3_free(pFile->lockingContext);
32611 return closeUnixFile(id);
32613 /****************** End of the dot-file lock implementation *******************
32614 ******************************************************************************/
32616 /******************************************************************************
32617 ************************** Begin flock Locking ********************************
32619 ** Use the flock() system call to do file locking.
32621 ** flock() locking is like dot-file locking in that the various
32622 ** fine-grain locking levels supported by SQLite are collapsed into
32623 ** a single exclusive lock. In other words, SHARED, RESERVED, and
32624 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
32625 ** still works when you do this, but concurrency is reduced since
32626 ** only a single process can be reading the database at a time.
32628 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
32630 #if SQLITE_ENABLE_LOCKING_STYLE
32633 ** Retry flock() calls that fail with EINTR
32635 #ifdef EINTR
32636 static int robust_flock(int fd, int op){
32637 int rc;
32638 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
32639 return rc;
32641 #else
32642 # define robust_flock(a,b) flock(a,b)
32643 #endif
32647 ** This routine checks if there is a RESERVED lock held on the specified
32648 ** file by this or any other process. If such a lock is held, set *pResOut
32649 ** to a non-zero value otherwise *pResOut is set to zero. The return value
32650 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32652 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
32653 int rc = SQLITE_OK;
32654 int reserved = 0;
32655 unixFile *pFile = (unixFile*)id;
32657 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32659 assert( pFile );
32661 /* Check if a thread in this process holds such a lock */
32662 if( pFile->eFileLock>SHARED_LOCK ){
32663 reserved = 1;
32666 /* Otherwise see if some other process holds it. */
32667 if( !reserved ){
32668 /* attempt to get the lock */
32669 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
32670 if( !lrc ){
32671 /* got the lock, unlock it */
32672 lrc = robust_flock(pFile->h, LOCK_UN);
32673 if ( lrc ) {
32674 int tErrno = errno;
32675 /* unlock failed with an error */
32676 lrc = SQLITE_IOERR_UNLOCK;
32677 storeLastErrno(pFile, tErrno);
32678 rc = lrc;
32680 } else {
32681 int tErrno = errno;
32682 reserved = 1;
32683 /* someone else might have it reserved */
32684 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32685 if( IS_LOCK_ERROR(lrc) ){
32686 storeLastErrno(pFile, tErrno);
32687 rc = lrc;
32691 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
32693 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
32694 if( (rc & 0xff) == SQLITE_IOERR ){
32695 rc = SQLITE_OK;
32696 reserved=1;
32698 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
32699 *pResOut = reserved;
32700 return rc;
32704 ** Lock the file with the lock specified by parameter eFileLock - one
32705 ** of the following:
32707 ** (1) SHARED_LOCK
32708 ** (2) RESERVED_LOCK
32709 ** (3) PENDING_LOCK
32710 ** (4) EXCLUSIVE_LOCK
32712 ** Sometimes when requesting one lock state, additional lock states
32713 ** are inserted in between. The locking might fail on one of the later
32714 ** transitions leaving the lock state different from what it started but
32715 ** still short of its goal. The following chart shows the allowed
32716 ** transitions and the inserted intermediate states:
32718 ** UNLOCKED -> SHARED
32719 ** SHARED -> RESERVED
32720 ** SHARED -> (PENDING) -> EXCLUSIVE
32721 ** RESERVED -> (PENDING) -> EXCLUSIVE
32722 ** PENDING -> EXCLUSIVE
32724 ** flock() only really support EXCLUSIVE locks. We track intermediate
32725 ** lock states in the sqlite3_file structure, but all locks SHARED or
32726 ** above are really EXCLUSIVE locks and exclude all other processes from
32727 ** access the file.
32729 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
32730 ** routine to lower a locking level.
32732 static int flockLock(sqlite3_file *id, int eFileLock) {
32733 int rc = SQLITE_OK;
32734 unixFile *pFile = (unixFile*)id;
32736 assert( pFile );
32738 /* if we already have a lock, it is exclusive.
32739 ** Just adjust level and punt on outta here. */
32740 if (pFile->eFileLock > NO_LOCK) {
32741 pFile->eFileLock = eFileLock;
32742 return SQLITE_OK;
32745 /* grab an exclusive lock */
32747 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
32748 int tErrno = errno;
32749 /* didn't get, must be busy */
32750 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32751 if( IS_LOCK_ERROR(rc) ){
32752 storeLastErrno(pFile, tErrno);
32754 } else {
32755 /* got it, set the type and return ok */
32756 pFile->eFileLock = eFileLock;
32758 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
32759 rc==SQLITE_OK ? "ok" : "failed"));
32760 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
32761 if( (rc & 0xff) == SQLITE_IOERR ){
32762 rc = SQLITE_BUSY;
32764 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
32765 return rc;
32770 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32771 ** must be either NO_LOCK or SHARED_LOCK.
32773 ** If the locking level of the file descriptor is already at or below
32774 ** the requested locking level, this routine is a no-op.
32776 static int flockUnlock(sqlite3_file *id, int eFileLock) {
32777 unixFile *pFile = (unixFile*)id;
32779 assert( pFile );
32780 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
32781 pFile->eFileLock, osGetpid(0)));
32782 assert( eFileLock<=SHARED_LOCK );
32784 /* no-op if possible */
32785 if( pFile->eFileLock==eFileLock ){
32786 return SQLITE_OK;
32789 /* shared can just be set because we always have an exclusive */
32790 if (eFileLock==SHARED_LOCK) {
32791 pFile->eFileLock = eFileLock;
32792 return SQLITE_OK;
32795 /* no, really, unlock. */
32796 if( robust_flock(pFile->h, LOCK_UN) ){
32797 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
32798 return SQLITE_OK;
32799 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
32800 return SQLITE_IOERR_UNLOCK;
32801 }else{
32802 pFile->eFileLock = NO_LOCK;
32803 return SQLITE_OK;
32808 ** Close a file.
32810 static int flockClose(sqlite3_file *id) {
32811 assert( id!=0 );
32812 flockUnlock(id, NO_LOCK);
32813 return closeUnixFile(id);
32816 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
32818 /******************* End of the flock lock implementation *********************
32819 ******************************************************************************/
32821 /******************************************************************************
32822 ************************ Begin Named Semaphore Locking ************************
32824 ** Named semaphore locking is only supported on VxWorks.
32826 ** Semaphore locking is like dot-lock and flock in that it really only
32827 ** supports EXCLUSIVE locking. Only a single process can read or write
32828 ** the database file at a time. This reduces potential concurrency, but
32829 ** makes the lock implementation much easier.
32831 #if OS_VXWORKS
32834 ** This routine checks if there is a RESERVED lock held on the specified
32835 ** file by this or any other process. If such a lock is held, set *pResOut
32836 ** to a non-zero value otherwise *pResOut is set to zero. The return value
32837 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32839 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
32840 int rc = SQLITE_OK;
32841 int reserved = 0;
32842 unixFile *pFile = (unixFile*)id;
32844 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32846 assert( pFile );
32848 /* Check if a thread in this process holds such a lock */
32849 if( pFile->eFileLock>SHARED_LOCK ){
32850 reserved = 1;
32853 /* Otherwise see if some other process holds it. */
32854 if( !reserved ){
32855 sem_t *pSem = pFile->pInode->pSem;
32857 if( sem_trywait(pSem)==-1 ){
32858 int tErrno = errno;
32859 if( EAGAIN != tErrno ){
32860 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
32861 storeLastErrno(pFile, tErrno);
32862 } else {
32863 /* someone else has the lock when we are in NO_LOCK */
32864 reserved = (pFile->eFileLock < SHARED_LOCK);
32866 }else{
32867 /* we could have it if we want it */
32868 sem_post(pSem);
32871 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
32873 *pResOut = reserved;
32874 return rc;
32878 ** Lock the file with the lock specified by parameter eFileLock - one
32879 ** of the following:
32881 ** (1) SHARED_LOCK
32882 ** (2) RESERVED_LOCK
32883 ** (3) PENDING_LOCK
32884 ** (4) EXCLUSIVE_LOCK
32886 ** Sometimes when requesting one lock state, additional lock states
32887 ** are inserted in between. The locking might fail on one of the later
32888 ** transitions leaving the lock state different from what it started but
32889 ** still short of its goal. The following chart shows the allowed
32890 ** transitions and the inserted intermediate states:
32892 ** UNLOCKED -> SHARED
32893 ** SHARED -> RESERVED
32894 ** SHARED -> (PENDING) -> EXCLUSIVE
32895 ** RESERVED -> (PENDING) -> EXCLUSIVE
32896 ** PENDING -> EXCLUSIVE
32898 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
32899 ** lock states in the sqlite3_file structure, but all locks SHARED or
32900 ** above are really EXCLUSIVE locks and exclude all other processes from
32901 ** access the file.
32903 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
32904 ** routine to lower a locking level.
32906 static int semXLock(sqlite3_file *id, int eFileLock) {
32907 unixFile *pFile = (unixFile*)id;
32908 sem_t *pSem = pFile->pInode->pSem;
32909 int rc = SQLITE_OK;
32911 /* if we already have a lock, it is exclusive.
32912 ** Just adjust level and punt on outta here. */
32913 if (pFile->eFileLock > NO_LOCK) {
32914 pFile->eFileLock = eFileLock;
32915 rc = SQLITE_OK;
32916 goto sem_end_lock;
32919 /* lock semaphore now but bail out when already locked. */
32920 if( sem_trywait(pSem)==-1 ){
32921 rc = SQLITE_BUSY;
32922 goto sem_end_lock;
32925 /* got it, set the type and return ok */
32926 pFile->eFileLock = eFileLock;
32928 sem_end_lock:
32929 return rc;
32933 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32934 ** must be either NO_LOCK or SHARED_LOCK.
32936 ** If the locking level of the file descriptor is already at or below
32937 ** the requested locking level, this routine is a no-op.
32939 static int semXUnlock(sqlite3_file *id, int eFileLock) {
32940 unixFile *pFile = (unixFile*)id;
32941 sem_t *pSem = pFile->pInode->pSem;
32943 assert( pFile );
32944 assert( pSem );
32945 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
32946 pFile->eFileLock, osGetpid(0)));
32947 assert( eFileLock<=SHARED_LOCK );
32949 /* no-op if possible */
32950 if( pFile->eFileLock==eFileLock ){
32951 return SQLITE_OK;
32954 /* shared can just be set because we always have an exclusive */
32955 if (eFileLock==SHARED_LOCK) {
32956 pFile->eFileLock = eFileLock;
32957 return SQLITE_OK;
32960 /* no, really unlock. */
32961 if ( sem_post(pSem)==-1 ) {
32962 int rc, tErrno = errno;
32963 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
32964 if( IS_LOCK_ERROR(rc) ){
32965 storeLastErrno(pFile, tErrno);
32967 return rc;
32969 pFile->eFileLock = NO_LOCK;
32970 return SQLITE_OK;
32974 ** Close a file.
32976 static int semXClose(sqlite3_file *id) {
32977 if( id ){
32978 unixFile *pFile = (unixFile*)id;
32979 semXUnlock(id, NO_LOCK);
32980 assert( pFile );
32981 unixEnterMutex();
32982 releaseInodeInfo(pFile);
32983 unixLeaveMutex();
32984 closeUnixFile(id);
32986 return SQLITE_OK;
32989 #endif /* OS_VXWORKS */
32991 ** Named semaphore locking is only available on VxWorks.
32993 *************** End of the named semaphore lock implementation ****************
32994 ******************************************************************************/
32997 /******************************************************************************
32998 *************************** Begin AFP Locking *********************************
33000 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
33001 ** on Apple Macintosh computers - both OS9 and OSX.
33003 ** Third-party implementations of AFP are available. But this code here
33004 ** only works on OSX.
33007 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
33009 ** The afpLockingContext structure contains all afp lock specific state
33011 typedef struct afpLockingContext afpLockingContext;
33012 struct afpLockingContext {
33013 int reserved;
33014 const char *dbPath; /* Name of the open file */
33017 struct ByteRangeLockPB2
33019 unsigned long long offset; /* offset to first byte to lock */
33020 unsigned long long length; /* nbr of bytes to lock */
33021 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
33022 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
33023 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
33024 int fd; /* file desc to assoc this lock with */
33027 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
33030 ** This is a utility for setting or clearing a bit-range lock on an
33031 ** AFP filesystem.
33033 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
33035 static int afpSetLock(
33036 const char *path, /* Name of the file to be locked or unlocked */
33037 unixFile *pFile, /* Open file descriptor on path */
33038 unsigned long long offset, /* First byte to be locked */
33039 unsigned long long length, /* Number of bytes to lock */
33040 int setLockFlag /* True to set lock. False to clear lock */
33042 struct ByteRangeLockPB2 pb;
33043 int err;
33045 pb.unLockFlag = setLockFlag ? 0 : 1;
33046 pb.startEndFlag = 0;
33047 pb.offset = offset;
33048 pb.length = length;
33049 pb.fd = pFile->h;
33051 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
33052 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
33053 offset, length));
33054 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
33055 if ( err==-1 ) {
33056 int rc;
33057 int tErrno = errno;
33058 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
33059 path, tErrno, strerror(tErrno)));
33060 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
33061 rc = SQLITE_BUSY;
33062 #else
33063 rc = sqliteErrorFromPosixError(tErrno,
33064 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
33065 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
33066 if( IS_LOCK_ERROR(rc) ){
33067 storeLastErrno(pFile, tErrno);
33069 return rc;
33070 } else {
33071 return SQLITE_OK;
33076 ** This routine checks if there is a RESERVED lock held on the specified
33077 ** file by this or any other process. If such a lock is held, set *pResOut
33078 ** to a non-zero value otherwise *pResOut is set to zero. The return value
33079 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
33081 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
33082 int rc = SQLITE_OK;
33083 int reserved = 0;
33084 unixFile *pFile = (unixFile*)id;
33085 afpLockingContext *context;
33087 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
33089 assert( pFile );
33090 context = (afpLockingContext *) pFile->lockingContext;
33091 if( context->reserved ){
33092 *pResOut = 1;
33093 return SQLITE_OK;
33095 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
33097 /* Check if a thread in this process holds such a lock */
33098 if( pFile->pInode->eFileLock>SHARED_LOCK ){
33099 reserved = 1;
33102 /* Otherwise see if some other process holds it.
33104 if( !reserved ){
33105 /* lock the RESERVED byte */
33106 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
33107 if( SQLITE_OK==lrc ){
33108 /* if we succeeded in taking the reserved lock, unlock it to restore
33109 ** the original state */
33110 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
33111 } else {
33112 /* if we failed to get the lock then someone else must have it */
33113 reserved = 1;
33115 if( IS_LOCK_ERROR(lrc) ){
33116 rc=lrc;
33120 unixLeaveMutex();
33121 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
33123 *pResOut = reserved;
33124 return rc;
33128 ** Lock the file with the lock specified by parameter eFileLock - one
33129 ** of the following:
33131 ** (1) SHARED_LOCK
33132 ** (2) RESERVED_LOCK
33133 ** (3) PENDING_LOCK
33134 ** (4) EXCLUSIVE_LOCK
33136 ** Sometimes when requesting one lock state, additional lock states
33137 ** are inserted in between. The locking might fail on one of the later
33138 ** transitions leaving the lock state different from what it started but
33139 ** still short of its goal. The following chart shows the allowed
33140 ** transitions and the inserted intermediate states:
33142 ** UNLOCKED -> SHARED
33143 ** SHARED -> RESERVED
33144 ** SHARED -> (PENDING) -> EXCLUSIVE
33145 ** RESERVED -> (PENDING) -> EXCLUSIVE
33146 ** PENDING -> EXCLUSIVE
33148 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
33149 ** routine to lower a locking level.
33151 static int afpLock(sqlite3_file *id, int eFileLock){
33152 int rc = SQLITE_OK;
33153 unixFile *pFile = (unixFile*)id;
33154 unixInodeInfo *pInode = pFile->pInode;
33155 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
33157 assert( pFile );
33158 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
33159 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
33160 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
33162 /* If there is already a lock of this type or more restrictive on the
33163 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
33164 ** unixEnterMutex() hasn't been called yet.
33166 if( pFile->eFileLock>=eFileLock ){
33167 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
33168 azFileLock(eFileLock)));
33169 return SQLITE_OK;
33172 /* Make sure the locking sequence is correct
33173 ** (1) We never move from unlocked to anything higher than shared lock.
33174 ** (2) SQLite never explicitly requests a pendig lock.
33175 ** (3) A shared lock is always held when a reserve lock is requested.
33177 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
33178 assert( eFileLock!=PENDING_LOCK );
33179 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
33181 /* This mutex is needed because pFile->pInode is shared across threads
33183 unixEnterMutex();
33184 pInode = pFile->pInode;
33186 /* If some thread using this PID has a lock via a different unixFile*
33187 ** handle that precludes the requested lock, return BUSY.
33189 if( (pFile->eFileLock!=pInode->eFileLock &&
33190 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
33192 rc = SQLITE_BUSY;
33193 goto afp_end_lock;
33196 /* If a SHARED lock is requested, and some thread using this PID already
33197 ** has a SHARED or RESERVED lock, then increment reference counts and
33198 ** return SQLITE_OK.
33200 if( eFileLock==SHARED_LOCK &&
33201 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
33202 assert( eFileLock==SHARED_LOCK );
33203 assert( pFile->eFileLock==0 );
33204 assert( pInode->nShared>0 );
33205 pFile->eFileLock = SHARED_LOCK;
33206 pInode->nShared++;
33207 pInode->nLock++;
33208 goto afp_end_lock;
33211 /* A PENDING lock is needed before acquiring a SHARED lock and before
33212 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
33213 ** be released.
33215 if( eFileLock==SHARED_LOCK
33216 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
33218 int failed;
33219 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
33220 if (failed) {
33221 rc = failed;
33222 goto afp_end_lock;
33226 /* If control gets to this point, then actually go ahead and make
33227 ** operating system calls for the specified lock.
33229 if( eFileLock==SHARED_LOCK ){
33230 int lrc1, lrc2, lrc1Errno = 0;
33231 long lk, mask;
33233 assert( pInode->nShared==0 );
33234 assert( pInode->eFileLock==0 );
33236 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
33237 /* Now get the read-lock SHARED_LOCK */
33238 /* note that the quality of the randomness doesn't matter that much */
33239 lk = random();
33240 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
33241 lrc1 = afpSetLock(context->dbPath, pFile,
33242 SHARED_FIRST+pInode->sharedByte, 1, 1);
33243 if( IS_LOCK_ERROR(lrc1) ){
33244 lrc1Errno = pFile->lastErrno;
33246 /* Drop the temporary PENDING lock */
33247 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
33249 if( IS_LOCK_ERROR(lrc1) ) {
33250 storeLastErrno(pFile, lrc1Errno);
33251 rc = lrc1;
33252 goto afp_end_lock;
33253 } else if( IS_LOCK_ERROR(lrc2) ){
33254 rc = lrc2;
33255 goto afp_end_lock;
33256 } else if( lrc1 != SQLITE_OK ) {
33257 rc = lrc1;
33258 } else {
33259 pFile->eFileLock = SHARED_LOCK;
33260 pInode->nLock++;
33261 pInode->nShared = 1;
33263 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
33264 /* We are trying for an exclusive lock but another thread in this
33265 ** same process is still holding a shared lock. */
33266 rc = SQLITE_BUSY;
33267 }else{
33268 /* The request was for a RESERVED or EXCLUSIVE lock. It is
33269 ** assumed that there is a SHARED or greater lock on the file
33270 ** already.
33272 int failed = 0;
33273 assert( 0!=pFile->eFileLock );
33274 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
33275 /* Acquire a RESERVED lock */
33276 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
33277 if( !failed ){
33278 context->reserved = 1;
33281 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
33282 /* Acquire an EXCLUSIVE lock */
33284 /* Remove the shared lock before trying the range. we'll need to
33285 ** reestablish the shared lock if we can't get the afpUnlock
33287 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
33288 pInode->sharedByte, 1, 0)) ){
33289 int failed2 = SQLITE_OK;
33290 /* now attemmpt to get the exclusive lock range */
33291 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
33292 SHARED_SIZE, 1);
33293 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
33294 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
33295 /* Can't reestablish the shared lock. Sqlite can't deal, this is
33296 ** a critical I/O error
33298 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
33299 SQLITE_IOERR_LOCK;
33300 goto afp_end_lock;
33302 }else{
33303 rc = failed;
33306 if( failed ){
33307 rc = failed;
33311 if( rc==SQLITE_OK ){
33312 pFile->eFileLock = eFileLock;
33313 pInode->eFileLock = eFileLock;
33314 }else if( eFileLock==EXCLUSIVE_LOCK ){
33315 pFile->eFileLock = PENDING_LOCK;
33316 pInode->eFileLock = PENDING_LOCK;
33319 afp_end_lock:
33320 unixLeaveMutex();
33321 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
33322 rc==SQLITE_OK ? "ok" : "failed"));
33323 return rc;
33327 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
33328 ** must be either NO_LOCK or SHARED_LOCK.
33330 ** If the locking level of the file descriptor is already at or below
33331 ** the requested locking level, this routine is a no-op.
33333 static int afpUnlock(sqlite3_file *id, int eFileLock) {
33334 int rc = SQLITE_OK;
33335 unixFile *pFile = (unixFile*)id;
33336 unixInodeInfo *pInode;
33337 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
33338 int skipShared = 0;
33339 #ifdef SQLITE_TEST
33340 int h = pFile->h;
33341 #endif
33343 assert( pFile );
33344 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
33345 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
33346 osGetpid(0)));
33348 assert( eFileLock<=SHARED_LOCK );
33349 if( pFile->eFileLock<=eFileLock ){
33350 return SQLITE_OK;
33352 unixEnterMutex();
33353 pInode = pFile->pInode;
33354 assert( pInode->nShared!=0 );
33355 if( pFile->eFileLock>SHARED_LOCK ){
33356 assert( pInode->eFileLock==pFile->eFileLock );
33357 SimulateIOErrorBenign(1);
33358 SimulateIOError( h=(-1) )
33359 SimulateIOErrorBenign(0);
33361 #ifdef SQLITE_DEBUG
33362 /* When reducing a lock such that other processes can start
33363 ** reading the database file again, make sure that the
33364 ** transaction counter was updated if any part of the database
33365 ** file changed. If the transaction counter is not updated,
33366 ** other connections to the same file might not realize that
33367 ** the file has changed and hence might not know to flush their
33368 ** cache. The use of a stale cache can lead to database corruption.
33370 assert( pFile->inNormalWrite==0
33371 || pFile->dbUpdate==0
33372 || pFile->transCntrChng==1 );
33373 pFile->inNormalWrite = 0;
33374 #endif
33376 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
33377 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
33378 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
33379 /* only re-establish the shared lock if necessary */
33380 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
33381 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
33382 } else {
33383 skipShared = 1;
33386 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
33387 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
33389 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
33390 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
33391 if( !rc ){
33392 context->reserved = 0;
33395 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
33396 pInode->eFileLock = SHARED_LOCK;
33399 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
33401 /* Decrement the shared lock counter. Release the lock using an
33402 ** OS call only when all threads in this same process have released
33403 ** the lock.
33405 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
33406 pInode->nShared--;
33407 if( pInode->nShared==0 ){
33408 SimulateIOErrorBenign(1);
33409 SimulateIOError( h=(-1) )
33410 SimulateIOErrorBenign(0);
33411 if( !skipShared ){
33412 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
33414 if( !rc ){
33415 pInode->eFileLock = NO_LOCK;
33416 pFile->eFileLock = NO_LOCK;
33419 if( rc==SQLITE_OK ){
33420 pInode->nLock--;
33421 assert( pInode->nLock>=0 );
33422 if( pInode->nLock==0 ){
33423 closePendingFds(pFile);
33428 unixLeaveMutex();
33429 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
33430 return rc;
33434 ** Close a file & cleanup AFP specific locking context
33436 static int afpClose(sqlite3_file *id) {
33437 int rc = SQLITE_OK;
33438 unixFile *pFile = (unixFile*)id;
33439 assert( id!=0 );
33440 afpUnlock(id, NO_LOCK);
33441 unixEnterMutex();
33442 if( pFile->pInode && pFile->pInode->nLock ){
33443 /* If there are outstanding locks, do not actually close the file just
33444 ** yet because that would clear those locks. Instead, add the file
33445 ** descriptor to pInode->aPending. It will be automatically closed when
33446 ** the last lock is cleared.
33448 setPendingFd(pFile);
33450 releaseInodeInfo(pFile);
33451 sqlite3_free(pFile->lockingContext);
33452 rc = closeUnixFile(id);
33453 unixLeaveMutex();
33454 return rc;
33457 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
33459 ** The code above is the AFP lock implementation. The code is specific
33460 ** to MacOSX and does not work on other unix platforms. No alternative
33461 ** is available. If you don't compile for a mac, then the "unix-afp"
33462 ** VFS is not available.
33464 ********************* End of the AFP lock implementation **********************
33465 ******************************************************************************/
33467 /******************************************************************************
33468 *************************** Begin NFS Locking ********************************/
33470 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
33472 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
33473 ** must be either NO_LOCK or SHARED_LOCK.
33475 ** If the locking level of the file descriptor is already at or below
33476 ** the requested locking level, this routine is a no-op.
33478 static int nfsUnlock(sqlite3_file *id, int eFileLock){
33479 return posixUnlock(id, eFileLock, 1);
33482 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
33484 ** The code above is the NFS lock implementation. The code is specific
33485 ** to MacOSX and does not work on other unix platforms. No alternative
33486 ** is available.
33488 ********************* End of the NFS lock implementation **********************
33489 ******************************************************************************/
33491 /******************************************************************************
33492 **************** Non-locking sqlite3_file methods *****************************
33494 ** The next division contains implementations for all methods of the
33495 ** sqlite3_file object other than the locking methods. The locking
33496 ** methods were defined in divisions above (one locking method per
33497 ** division). Those methods that are common to all locking modes
33498 ** are gather together into this division.
33502 ** Seek to the offset passed as the second argument, then read cnt
33503 ** bytes into pBuf. Return the number of bytes actually read.
33505 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
33506 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
33507 ** one system to another. Since SQLite does not define USE_PREAD
33508 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
33509 ** See tickets #2741 and #2681.
33511 ** To avoid stomping the errno value on a failed read the lastErrno value
33512 ** is set before returning.
33514 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
33515 int got;
33516 int prior = 0;
33517 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
33518 i64 newOffset;
33519 #endif
33520 TIMER_START;
33521 assert( cnt==(cnt&0x1ffff) );
33522 assert( id->h>2 );
33524 #if defined(USE_PREAD)
33525 got = osPread(id->h, pBuf, cnt, offset);
33526 SimulateIOError( got = -1 );
33527 #elif defined(USE_PREAD64)
33528 got = osPread64(id->h, pBuf, cnt, offset);
33529 SimulateIOError( got = -1 );
33530 #else
33531 newOffset = lseek(id->h, offset, SEEK_SET);
33532 SimulateIOError( newOffset = -1 );
33533 if( newOffset<0 ){
33534 storeLastErrno((unixFile*)id, errno);
33535 return -1;
33537 got = osRead(id->h, pBuf, cnt);
33538 #endif
33539 if( got==cnt ) break;
33540 if( got<0 ){
33541 if( errno==EINTR ){ got = 1; continue; }
33542 prior = 0;
33543 storeLastErrno((unixFile*)id, errno);
33544 break;
33545 }else if( got>0 ){
33546 cnt -= got;
33547 offset += got;
33548 prior += got;
33549 pBuf = (void*)(got + (char*)pBuf);
33551 }while( got>0 );
33552 TIMER_END;
33553 OSTRACE(("READ %-3d %5d %7lld %llu\n",
33554 id->h, got+prior, offset-prior, TIMER_ELAPSED));
33555 return got+prior;
33559 ** Read data from a file into a buffer. Return SQLITE_OK if all
33560 ** bytes were read successfully and SQLITE_IOERR if anything goes
33561 ** wrong.
33563 static int unixRead(
33564 sqlite3_file *id,
33565 void *pBuf,
33566 int amt,
33567 sqlite3_int64 offset
33569 unixFile *pFile = (unixFile *)id;
33570 int got;
33571 assert( id );
33572 assert( offset>=0 );
33573 assert( amt>0 );
33575 /* If this is a database file (not a journal, master-journal or temp
33576 ** file), the bytes in the locking range should never be read or written. */
33577 #if 0
33578 assert( pFile->pPreallocatedUnused==0
33579 || offset>=PENDING_BYTE+512
33580 || offset+amt<=PENDING_BYTE
33582 #endif
33584 #if SQLITE_MAX_MMAP_SIZE>0
33585 /* Deal with as much of this read request as possible by transfering
33586 ** data from the memory mapping using memcpy(). */
33587 if( offset<pFile->mmapSize ){
33588 if( offset+amt <= pFile->mmapSize ){
33589 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
33590 return SQLITE_OK;
33591 }else{
33592 int nCopy = pFile->mmapSize - offset;
33593 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
33594 pBuf = &((u8 *)pBuf)[nCopy];
33595 amt -= nCopy;
33596 offset += nCopy;
33599 #endif
33601 got = seekAndRead(pFile, offset, pBuf, amt);
33602 if( got==amt ){
33603 return SQLITE_OK;
33604 }else if( got<0 ){
33605 /* lastErrno set by seekAndRead */
33606 return SQLITE_IOERR_READ;
33607 }else{
33608 storeLastErrno(pFile, 0); /* not a system error */
33609 /* Unread parts of the buffer must be zero-filled */
33610 memset(&((char*)pBuf)[got], 0, amt-got);
33611 return SQLITE_IOERR_SHORT_READ;
33616 ** Attempt to seek the file-descriptor passed as the first argument to
33617 ** absolute offset iOff, then attempt to write nBuf bytes of data from
33618 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
33619 ** return the actual number of bytes written (which may be less than
33620 ** nBuf).
33622 static int seekAndWriteFd(
33623 int fd, /* File descriptor to write to */
33624 i64 iOff, /* File offset to begin writing at */
33625 const void *pBuf, /* Copy data from this buffer to the file */
33626 int nBuf, /* Size of buffer pBuf in bytes */
33627 int *piErrno /* OUT: Error number if error occurs */
33629 int rc = 0; /* Value returned by system call */
33631 assert( nBuf==(nBuf&0x1ffff) );
33632 assert( fd>2 );
33633 assert( piErrno!=0 );
33634 nBuf &= 0x1ffff;
33635 TIMER_START;
33637 #if defined(USE_PREAD)
33638 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
33639 #elif defined(USE_PREAD64)
33640 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
33641 #else
33643 i64 iSeek = lseek(fd, iOff, SEEK_SET);
33644 SimulateIOError( iSeek = -1 );
33645 if( iSeek<0 ){
33646 rc = -1;
33647 break;
33649 rc = osWrite(fd, pBuf, nBuf);
33650 }while( rc<0 && errno==EINTR );
33651 #endif
33653 TIMER_END;
33654 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
33656 if( rc<0 ) *piErrno = errno;
33657 return rc;
33662 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
33663 ** Return the number of bytes actually read. Update the offset.
33665 ** To avoid stomping the errno value on a failed write the lastErrno value
33666 ** is set before returning.
33668 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
33669 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
33674 ** Write data from a buffer into a file. Return SQLITE_OK on success
33675 ** or some other error code on failure.
33677 static int unixWrite(
33678 sqlite3_file *id,
33679 const void *pBuf,
33680 int amt,
33681 sqlite3_int64 offset
33683 unixFile *pFile = (unixFile*)id;
33684 int wrote = 0;
33685 assert( id );
33686 assert( amt>0 );
33688 /* If this is a database file (not a journal, master-journal or temp
33689 ** file), the bytes in the locking range should never be read or written. */
33690 #if 0
33691 assert( pFile->pPreallocatedUnused==0
33692 || offset>=PENDING_BYTE+512
33693 || offset+amt<=PENDING_BYTE
33695 #endif
33697 #ifdef SQLITE_DEBUG
33698 /* If we are doing a normal write to a database file (as opposed to
33699 ** doing a hot-journal rollback or a write to some file other than a
33700 ** normal database file) then record the fact that the database
33701 ** has changed. If the transaction counter is modified, record that
33702 ** fact too.
33704 if( pFile->inNormalWrite ){
33705 pFile->dbUpdate = 1; /* The database has been modified */
33706 if( offset<=24 && offset+amt>=27 ){
33707 int rc;
33708 char oldCntr[4];
33709 SimulateIOErrorBenign(1);
33710 rc = seekAndRead(pFile, 24, oldCntr, 4);
33711 SimulateIOErrorBenign(0);
33712 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
33713 pFile->transCntrChng = 1; /* The transaction counter has changed */
33717 #endif
33719 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
33720 /* Deal with as much of this write request as possible by transfering
33721 ** data from the memory mapping using memcpy(). */
33722 if( offset<pFile->mmapSize ){
33723 if( offset+amt <= pFile->mmapSize ){
33724 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
33725 return SQLITE_OK;
33726 }else{
33727 int nCopy = pFile->mmapSize - offset;
33728 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
33729 pBuf = &((u8 *)pBuf)[nCopy];
33730 amt -= nCopy;
33731 offset += nCopy;
33734 #endif
33736 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
33737 amt -= wrote;
33738 offset += wrote;
33739 pBuf = &((char*)pBuf)[wrote];
33741 SimulateIOError(( wrote=(-1), amt=1 ));
33742 SimulateDiskfullError(( wrote=0, amt=1 ));
33744 if( amt>wrote ){
33745 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
33746 /* lastErrno set by seekAndWrite */
33747 return SQLITE_IOERR_WRITE;
33748 }else{
33749 storeLastErrno(pFile, 0); /* not a system error */
33750 return SQLITE_FULL;
33754 return SQLITE_OK;
33757 #ifdef SQLITE_TEST
33759 ** Count the number of fullsyncs and normal syncs. This is used to test
33760 ** that syncs and fullsyncs are occurring at the right times.
33762 SQLITE_API int sqlite3_sync_count = 0;
33763 SQLITE_API int sqlite3_fullsync_count = 0;
33764 #endif
33767 ** We do not trust systems to provide a working fdatasync(). Some do.
33768 ** Others do no. To be safe, we will stick with the (slightly slower)
33769 ** fsync(). If you know that your system does support fdatasync() correctly,
33770 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
33772 #if !defined(fdatasync) && !HAVE_FDATASYNC
33773 # define fdatasync fsync
33774 #endif
33777 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
33778 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
33779 ** only available on Mac OS X. But that could change.
33781 #ifdef F_FULLFSYNC
33782 # define HAVE_FULLFSYNC 1
33783 #else
33784 # define HAVE_FULLFSYNC 0
33785 #endif
33789 ** The fsync() system call does not work as advertised on many
33790 ** unix systems. The following procedure is an attempt to make
33791 ** it work better.
33793 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
33794 ** for testing when we want to run through the test suite quickly.
33795 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
33796 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
33797 ** or power failure will likely corrupt the database file.
33799 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
33800 ** The idea behind dataOnly is that it should only write the file content
33801 ** to disk, not the inode. We only set dataOnly if the file size is
33802 ** unchanged since the file size is part of the inode. However,
33803 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
33804 ** file size has changed. The only real difference between fdatasync()
33805 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
33806 ** inode if the mtime or owner or other inode attributes have changed.
33807 ** We only care about the file size, not the other file attributes, so
33808 ** as far as SQLite is concerned, an fdatasync() is always adequate.
33809 ** So, we always use fdatasync() if it is available, regardless of
33810 ** the value of the dataOnly flag.
33812 static int full_fsync(int fd, int fullSync, int dataOnly){
33813 int rc;
33815 /* The following "ifdef/elif/else/" block has the same structure as
33816 ** the one below. It is replicated here solely to avoid cluttering
33817 ** up the real code with the UNUSED_PARAMETER() macros.
33819 #ifdef SQLITE_NO_SYNC
33820 UNUSED_PARAMETER(fd);
33821 UNUSED_PARAMETER(fullSync);
33822 UNUSED_PARAMETER(dataOnly);
33823 #elif HAVE_FULLFSYNC
33824 UNUSED_PARAMETER(dataOnly);
33825 #else
33826 UNUSED_PARAMETER(fullSync);
33827 UNUSED_PARAMETER(dataOnly);
33828 #endif
33830 /* Record the number of times that we do a normal fsync() and
33831 ** FULLSYNC. This is used during testing to verify that this procedure
33832 ** gets called with the correct arguments.
33834 #ifdef SQLITE_TEST
33835 if( fullSync ) sqlite3_fullsync_count++;
33836 sqlite3_sync_count++;
33837 #endif
33839 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
33840 ** no-op. But go ahead and call fstat() to validate the file
33841 ** descriptor as we need a method to provoke a failure during
33842 ** coverate testing.
33844 #ifdef SQLITE_NO_SYNC
33846 struct stat buf;
33847 rc = osFstat(fd, &buf);
33849 #elif HAVE_FULLFSYNC
33850 if( fullSync ){
33851 rc = osFcntl(fd, F_FULLFSYNC, 0);
33852 }else{
33853 rc = 1;
33855 /* If the FULLFSYNC failed, fall back to attempting an fsync().
33856 ** It shouldn't be possible for fullfsync to fail on the local
33857 ** file system (on OSX), so failure indicates that FULLFSYNC
33858 ** isn't supported for this file system. So, attempt an fsync
33859 ** and (for now) ignore the overhead of a superfluous fcntl call.
33860 ** It'd be better to detect fullfsync support once and avoid
33861 ** the fcntl call every time sync is called.
33863 if( rc ) rc = fsync(fd);
33865 #elif defined(__APPLE__)
33866 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
33867 ** so currently we default to the macro that redefines fdatasync to fsync
33869 rc = fsync(fd);
33870 #else
33871 rc = fdatasync(fd);
33872 #if OS_VXWORKS
33873 if( rc==-1 && errno==ENOTSUP ){
33874 rc = fsync(fd);
33876 #endif /* OS_VXWORKS */
33877 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
33879 if( OS_VXWORKS && rc!= -1 ){
33880 rc = 0;
33882 return rc;
33886 ** Open a file descriptor to the directory containing file zFilename.
33887 ** If successful, *pFd is set to the opened file descriptor and
33888 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
33889 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
33890 ** value.
33892 ** The directory file descriptor is used for only one thing - to
33893 ** fsync() a directory to make sure file creation and deletion events
33894 ** are flushed to disk. Such fsyncs are not needed on newer
33895 ** journaling filesystems, but are required on older filesystems.
33897 ** This routine can be overridden using the xSetSysCall interface.
33898 ** The ability to override this routine was added in support of the
33899 ** chromium sandbox. Opening a directory is a security risk (we are
33900 ** told) so making it overrideable allows the chromium sandbox to
33901 ** replace this routine with a harmless no-op. To make this routine
33902 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
33903 ** *pFd set to a negative number.
33905 ** If SQLITE_OK is returned, the caller is responsible for closing
33906 ** the file descriptor *pFd using close().
33908 static int openDirectory(const char *zFilename, int *pFd){
33909 int ii;
33910 int fd = -1;
33911 char zDirname[MAX_PATHNAME+1];
33913 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
33914 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
33915 if( ii>0 ){
33916 zDirname[ii] = '\0';
33917 }else{
33918 if( zDirname[0]!='/' ) zDirname[0] = '.';
33919 zDirname[1] = 0;
33921 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
33922 if( fd>=0 ){
33923 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
33925 *pFd = fd;
33926 if( fd>=0 ) return SQLITE_OK;
33927 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
33931 ** Make sure all writes to a particular file are committed to disk.
33933 ** If dataOnly==0 then both the file itself and its metadata (file
33934 ** size, access time, etc) are synced. If dataOnly!=0 then only the
33935 ** file data is synced.
33937 ** Under Unix, also make sure that the directory entry for the file
33938 ** has been created by fsync-ing the directory that contains the file.
33939 ** If we do not do this and we encounter a power failure, the directory
33940 ** entry for the journal might not exist after we reboot. The next
33941 ** SQLite to access the file will not know that the journal exists (because
33942 ** the directory entry for the journal was never created) and the transaction
33943 ** will not roll back - possibly leading to database corruption.
33945 static int unixSync(sqlite3_file *id, int flags){
33946 int rc;
33947 unixFile *pFile = (unixFile*)id;
33949 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
33950 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
33952 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
33953 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
33954 || (flags&0x0F)==SQLITE_SYNC_FULL
33957 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
33958 ** line is to test that doing so does not cause any problems.
33960 SimulateDiskfullError( return SQLITE_FULL );
33962 assert( pFile );
33963 OSTRACE(("SYNC %-3d\n", pFile->h));
33964 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
33965 SimulateIOError( rc=1 );
33966 if( rc ){
33967 storeLastErrno(pFile, errno);
33968 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
33971 /* Also fsync the directory containing the file if the DIRSYNC flag
33972 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
33973 ** are unable to fsync a directory, so ignore errors on the fsync.
33975 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
33976 int dirfd;
33977 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
33978 HAVE_FULLFSYNC, isFullsync));
33979 rc = osOpenDirectory(pFile->zPath, &dirfd);
33980 if( rc==SQLITE_OK ){
33981 full_fsync(dirfd, 0, 0);
33982 robust_close(pFile, dirfd, __LINE__);
33983 }else{
33984 assert( rc==SQLITE_CANTOPEN );
33985 rc = SQLITE_OK;
33987 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
33989 return rc;
33993 ** Truncate an open file to a specified size
33995 static int unixTruncate(sqlite3_file *id, i64 nByte){
33996 unixFile *pFile = (unixFile *)id;
33997 int rc;
33998 assert( pFile );
33999 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
34001 /* If the user has configured a chunk-size for this file, truncate the
34002 ** file so that it consists of an integer number of chunks (i.e. the
34003 ** actual file size after the operation may be larger than the requested
34004 ** size).
34006 if( pFile->szChunk>0 ){
34007 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
34010 rc = robust_ftruncate(pFile->h, nByte);
34011 if( rc ){
34012 storeLastErrno(pFile, errno);
34013 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
34014 }else{
34015 #ifdef SQLITE_DEBUG
34016 /* If we are doing a normal write to a database file (as opposed to
34017 ** doing a hot-journal rollback or a write to some file other than a
34018 ** normal database file) and we truncate the file to zero length,
34019 ** that effectively updates the change counter. This might happen
34020 ** when restoring a database using the backup API from a zero-length
34021 ** source.
34023 if( pFile->inNormalWrite && nByte==0 ){
34024 pFile->transCntrChng = 1;
34026 #endif
34028 #if SQLITE_MAX_MMAP_SIZE>0
34029 /* If the file was just truncated to a size smaller than the currently
34030 ** mapped region, reduce the effective mapping size as well. SQLite will
34031 ** use read() and write() to access data beyond this point from now on.
34033 if( nByte<pFile->mmapSize ){
34034 pFile->mmapSize = nByte;
34036 #endif
34038 return SQLITE_OK;
34043 ** Determine the current size of a file in bytes
34045 static int unixFileSize(sqlite3_file *id, i64 *pSize){
34046 int rc;
34047 struct stat buf;
34048 assert( id );
34049 rc = osFstat(((unixFile*)id)->h, &buf);
34050 SimulateIOError( rc=1 );
34051 if( rc!=0 ){
34052 storeLastErrno((unixFile*)id, errno);
34053 return SQLITE_IOERR_FSTAT;
34055 *pSize = buf.st_size;
34057 /* When opening a zero-size database, the findInodeInfo() procedure
34058 ** writes a single byte into that file in order to work around a bug
34059 ** in the OS-X msdos filesystem. In order to avoid problems with upper
34060 ** layers, we need to report this file size as zero even though it is
34061 ** really 1. Ticket #3260.
34063 if( *pSize==1 ) *pSize = 0;
34066 return SQLITE_OK;
34069 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34071 ** Handler for proxy-locking file-control verbs. Defined below in the
34072 ** proxying locking division.
34074 static int proxyFileControl(sqlite3_file*,int,void*);
34075 #endif
34078 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
34079 ** file-control operation. Enlarge the database to nBytes in size
34080 ** (rounded up to the next chunk-size). If the database is already
34081 ** nBytes or larger, this routine is a no-op.
34083 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
34084 if( pFile->szChunk>0 ){
34085 i64 nSize; /* Required file size */
34086 struct stat buf; /* Used to hold return values of fstat() */
34088 if( osFstat(pFile->h, &buf) ){
34089 return SQLITE_IOERR_FSTAT;
34092 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
34093 if( nSize>(i64)buf.st_size ){
34095 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
34096 /* The code below is handling the return value of osFallocate()
34097 ** correctly. posix_fallocate() is defined to "returns zero on success,
34098 ** or an error number on failure". See the manpage for details. */
34099 int err;
34101 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
34102 }while( err==EINTR );
34103 if( err ) return SQLITE_IOERR_WRITE;
34104 #else
34105 /* If the OS does not have posix_fallocate(), fake it. Write a
34106 ** single byte to the last byte in each block that falls entirely
34107 ** within the extended region. Then, if required, a single byte
34108 ** at offset (nSize-1), to set the size of the file correctly.
34109 ** This is a similar technique to that used by glibc on systems
34110 ** that do not have a real fallocate() call.
34112 int nBlk = buf.st_blksize; /* File-system block size */
34113 int nWrite = 0; /* Number of bytes written by seekAndWrite */
34114 i64 iWrite; /* Next offset to write to */
34116 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
34117 assert( iWrite>=buf.st_size );
34118 assert( ((iWrite+1)%nBlk)==0 );
34119 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
34120 if( iWrite>=nSize ) iWrite = nSize - 1;
34121 nWrite = seekAndWrite(pFile, iWrite, "", 1);
34122 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
34124 #endif
34128 #if SQLITE_MAX_MMAP_SIZE>0
34129 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
34130 int rc;
34131 if( pFile->szChunk<=0 ){
34132 if( robust_ftruncate(pFile->h, nByte) ){
34133 storeLastErrno(pFile, errno);
34134 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
34138 rc = unixMapfile(pFile, nByte);
34139 return rc;
34141 #endif
34143 return SQLITE_OK;
34147 ** If *pArg is initially negative then this is a query. Set *pArg to
34148 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
34150 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
34152 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
34153 if( *pArg<0 ){
34154 *pArg = (pFile->ctrlFlags & mask)!=0;
34155 }else if( (*pArg)==0 ){
34156 pFile->ctrlFlags &= ~mask;
34157 }else{
34158 pFile->ctrlFlags |= mask;
34162 /* Forward declaration */
34163 static int unixGetTempname(int nBuf, char *zBuf);
34166 ** Information and control of an open file handle.
34168 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
34169 unixFile *pFile = (unixFile*)id;
34170 switch( op ){
34171 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
34172 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
34173 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
34174 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
34176 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
34177 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
34178 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
34180 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
34181 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
34182 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
34184 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
34186 case SQLITE_FCNTL_LOCKSTATE: {
34187 *(int*)pArg = pFile->eFileLock;
34188 return SQLITE_OK;
34190 case SQLITE_FCNTL_LAST_ERRNO: {
34191 *(int*)pArg = pFile->lastErrno;
34192 return SQLITE_OK;
34194 case SQLITE_FCNTL_CHUNK_SIZE: {
34195 pFile->szChunk = *(int *)pArg;
34196 return SQLITE_OK;
34198 case SQLITE_FCNTL_SIZE_HINT: {
34199 int rc;
34200 SimulateIOErrorBenign(1);
34201 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
34202 SimulateIOErrorBenign(0);
34203 return rc;
34205 case SQLITE_FCNTL_PERSIST_WAL: {
34206 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
34207 return SQLITE_OK;
34209 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
34210 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
34211 return SQLITE_OK;
34213 case SQLITE_FCNTL_VFSNAME: {
34214 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
34215 return SQLITE_OK;
34217 case SQLITE_FCNTL_TEMPFILENAME: {
34218 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
34219 if( zTFile ){
34220 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
34221 *(char**)pArg = zTFile;
34223 return SQLITE_OK;
34225 case SQLITE_FCNTL_HAS_MOVED: {
34226 *(int*)pArg = fileHasMoved(pFile);
34227 return SQLITE_OK;
34229 #if SQLITE_MAX_MMAP_SIZE>0
34230 case SQLITE_FCNTL_MMAP_SIZE: {
34231 i64 newLimit = *(i64*)pArg;
34232 int rc = SQLITE_OK;
34233 if( newLimit>sqlite3GlobalConfig.mxMmap ){
34234 newLimit = sqlite3GlobalConfig.mxMmap;
34237 /* The value of newLimit may be eventually cast to (size_t) and passed
34238 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
34239 ** 64-bit type. */
34240 if( newLimit>0 && sizeof(size_t)<8 ){
34241 newLimit = (newLimit & 0x7FFFFFFF);
34244 *(i64*)pArg = pFile->mmapSizeMax;
34245 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
34246 pFile->mmapSizeMax = newLimit;
34247 if( pFile->mmapSize>0 ){
34248 unixUnmapfile(pFile);
34249 rc = unixMapfile(pFile, -1);
34252 return rc;
34254 #endif
34255 #ifdef SQLITE_DEBUG
34256 /* The pager calls this method to signal that it has done
34257 ** a rollback and that the database is therefore unchanged and
34258 ** it hence it is OK for the transaction change counter to be
34259 ** unchanged.
34261 case SQLITE_FCNTL_DB_UNCHANGED: {
34262 ((unixFile*)id)->dbUpdate = 0;
34263 return SQLITE_OK;
34265 #endif
34266 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34267 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
34268 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
34269 return proxyFileControl(id,op,pArg);
34271 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
34273 return SQLITE_NOTFOUND;
34277 ** If pFd->sectorSize is non-zero when this function is called, it is a
34278 ** no-op. Otherwise, the values of pFd->sectorSize and
34279 ** pFd->deviceCharacteristics are set according to the file-system
34280 ** characteristics.
34282 ** There are two versions of this function. One for QNX and one for all
34283 ** other systems.
34285 #ifndef __QNXNTO__
34286 static void setDeviceCharacteristics(unixFile *pFd){
34287 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
34288 if( pFd->sectorSize==0 ){
34289 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
34290 int res;
34291 u32 f = 0;
34293 /* Check for support for F2FS atomic batch writes. */
34294 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
34295 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
34296 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
34298 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
34300 /* Set the POWERSAFE_OVERWRITE flag if requested. */
34301 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
34302 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
34305 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
34308 #else
34309 #include <sys/dcmd_blk.h>
34310 #include <sys/statvfs.h>
34311 static void setDeviceCharacteristics(unixFile *pFile){
34312 if( pFile->sectorSize == 0 ){
34313 struct statvfs fsInfo;
34315 /* Set defaults for non-supported filesystems */
34316 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
34317 pFile->deviceCharacteristics = 0;
34318 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
34319 return pFile->sectorSize;
34322 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
34323 pFile->sectorSize = fsInfo.f_bsize;
34324 pFile->deviceCharacteristics =
34325 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
34326 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
34327 ** the write succeeds */
34328 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
34329 ** so it is ordered */
34331 }else if( strstr(fsInfo.f_basetype, "etfs") ){
34332 pFile->sectorSize = fsInfo.f_bsize;
34333 pFile->deviceCharacteristics =
34334 /* etfs cluster size writes are atomic */
34335 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
34336 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
34337 ** the write succeeds */
34338 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
34339 ** so it is ordered */
34341 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
34342 pFile->sectorSize = fsInfo.f_bsize;
34343 pFile->deviceCharacteristics =
34344 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
34345 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
34346 ** the write succeeds */
34347 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
34348 ** so it is ordered */
34350 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
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 */
34358 }else if( strstr(fsInfo.f_basetype, "dos") ){
34359 pFile->sectorSize = fsInfo.f_bsize;
34360 pFile->deviceCharacteristics =
34361 /* full bitset of atomics from max sector size and smaller */
34362 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
34363 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
34364 ** so it is ordered */
34366 }else{
34367 pFile->deviceCharacteristics =
34368 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
34369 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
34370 ** the write succeeds */
34374 /* Last chance verification. If the sector size isn't a multiple of 512
34375 ** then it isn't valid.*/
34376 if( pFile->sectorSize % 512 != 0 ){
34377 pFile->deviceCharacteristics = 0;
34378 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
34381 #endif
34384 ** Return the sector size in bytes of the underlying block device for
34385 ** the specified file. This is almost always 512 bytes, but may be
34386 ** larger for some devices.
34388 ** SQLite code assumes this function cannot fail. It also assumes that
34389 ** if two files are created in the same file-system directory (i.e.
34390 ** a database and its journal file) that the sector size will be the
34391 ** same for both.
34393 static int unixSectorSize(sqlite3_file *id){
34394 unixFile *pFd = (unixFile*)id;
34395 setDeviceCharacteristics(pFd);
34396 return pFd->sectorSize;
34400 ** Return the device characteristics for the file.
34402 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
34403 ** However, that choice is controversial since technically the underlying
34404 ** file system does not always provide powersafe overwrites. (In other
34405 ** words, after a power-loss event, parts of the file that were never
34406 ** written might end up being altered.) However, non-PSOW behavior is very,
34407 ** very rare. And asserting PSOW makes a large reduction in the amount
34408 ** of required I/O for journaling, since a lot of padding is eliminated.
34409 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
34410 ** available to turn it off and URI query parameter available to turn it off.
34412 static int unixDeviceCharacteristics(sqlite3_file *id){
34413 unixFile *pFd = (unixFile*)id;
34414 setDeviceCharacteristics(pFd);
34415 return pFd->deviceCharacteristics;
34418 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
34421 ** Return the system page size.
34423 ** This function should not be called directly by other code in this file.
34424 ** Instead, it should be called via macro osGetpagesize().
34426 static int unixGetpagesize(void){
34427 #if OS_VXWORKS
34428 return 1024;
34429 #elif defined(_BSD_SOURCE)
34430 return getpagesize();
34431 #else
34432 return (int)sysconf(_SC_PAGESIZE);
34433 #endif
34436 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
34438 #ifndef SQLITE_OMIT_WAL
34441 ** Object used to represent an shared memory buffer.
34443 ** When multiple threads all reference the same wal-index, each thread
34444 ** has its own unixShm object, but they all point to a single instance
34445 ** of this unixShmNode object. In other words, each wal-index is opened
34446 ** only once per process.
34448 ** Each unixShmNode object is connected to a single unixInodeInfo object.
34449 ** We could coalesce this object into unixInodeInfo, but that would mean
34450 ** every open file that does not use shared memory (in other words, most
34451 ** open files) would have to carry around this extra information. So
34452 ** the unixInodeInfo object contains a pointer to this unixShmNode object
34453 ** and the unixShmNode object is created only when needed.
34455 ** unixMutexHeld() must be true when creating or destroying
34456 ** this object or while reading or writing the following fields:
34458 ** nRef
34460 ** The following fields are read-only after the object is created:
34462 ** fid
34463 ** zFilename
34465 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
34466 ** unixMutexHeld() is true when reading or writing any other field
34467 ** in this structure.
34469 struct unixShmNode {
34470 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
34471 sqlite3_mutex *mutex; /* Mutex to access this object */
34472 char *zFilename; /* Name of the mmapped file */
34473 int h; /* Open file descriptor */
34474 int szRegion; /* Size of shared-memory regions */
34475 u16 nRegion; /* Size of array apRegion */
34476 u8 isReadonly; /* True if read-only */
34477 char **apRegion; /* Array of mapped shared-memory regions */
34478 int nRef; /* Number of unixShm objects pointing to this */
34479 unixShm *pFirst; /* All unixShm objects pointing to this */
34480 #ifdef SQLITE_DEBUG
34481 u8 exclMask; /* Mask of exclusive locks held */
34482 u8 sharedMask; /* Mask of shared locks held */
34483 u8 nextShmId; /* Next available unixShm.id value */
34484 #endif
34488 ** Structure used internally by this VFS to record the state of an
34489 ** open shared memory connection.
34491 ** The following fields are initialized when this object is created and
34492 ** are read-only thereafter:
34494 ** unixShm.pFile
34495 ** unixShm.id
34497 ** All other fields are read/write. The unixShm.pFile->mutex must be held
34498 ** while accessing any read/write fields.
34500 struct unixShm {
34501 unixShmNode *pShmNode; /* The underlying unixShmNode object */
34502 unixShm *pNext; /* Next unixShm with the same unixShmNode */
34503 u8 hasMutex; /* True if holding the unixShmNode mutex */
34504 u8 id; /* Id of this connection within its unixShmNode */
34505 u16 sharedMask; /* Mask of shared locks held */
34506 u16 exclMask; /* Mask of exclusive locks held */
34510 ** Constants used for locking
34512 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
34513 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
34516 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
34518 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
34519 ** otherwise.
34521 static int unixShmSystemLock(
34522 unixFile *pFile, /* Open connection to the WAL file */
34523 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
34524 int ofst, /* First byte of the locking range */
34525 int n /* Number of bytes to lock */
34527 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
34528 struct flock f; /* The posix advisory locking structure */
34529 int rc = SQLITE_OK; /* Result code form fcntl() */
34531 /* Access to the unixShmNode object is serialized by the caller */
34532 pShmNode = pFile->pInode->pShmNode;
34533 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
34535 /* Shared locks never span more than one byte */
34536 assert( n==1 || lockType!=F_RDLCK );
34538 /* Locks are within range */
34539 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
34541 if( pShmNode->h>=0 ){
34542 /* Initialize the locking parameters */
34543 memset(&f, 0, sizeof(f));
34544 f.l_type = lockType;
34545 f.l_whence = SEEK_SET;
34546 f.l_start = ofst;
34547 f.l_len = n;
34549 rc = osFcntl(pShmNode->h, F_SETLK, &f);
34550 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
34553 /* Update the global lock state and do debug tracing */
34554 #ifdef SQLITE_DEBUG
34555 { u16 mask;
34556 OSTRACE(("SHM-LOCK "));
34557 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
34558 if( rc==SQLITE_OK ){
34559 if( lockType==F_UNLCK ){
34560 OSTRACE(("unlock %d ok", ofst));
34561 pShmNode->exclMask &= ~mask;
34562 pShmNode->sharedMask &= ~mask;
34563 }else if( lockType==F_RDLCK ){
34564 OSTRACE(("read-lock %d ok", ofst));
34565 pShmNode->exclMask &= ~mask;
34566 pShmNode->sharedMask |= mask;
34567 }else{
34568 assert( lockType==F_WRLCK );
34569 OSTRACE(("write-lock %d ok", ofst));
34570 pShmNode->exclMask |= mask;
34571 pShmNode->sharedMask &= ~mask;
34573 }else{
34574 if( lockType==F_UNLCK ){
34575 OSTRACE(("unlock %d failed", ofst));
34576 }else if( lockType==F_RDLCK ){
34577 OSTRACE(("read-lock failed"));
34578 }else{
34579 assert( lockType==F_WRLCK );
34580 OSTRACE(("write-lock %d failed", ofst));
34583 OSTRACE((" - afterwards %03x,%03x\n",
34584 pShmNode->sharedMask, pShmNode->exclMask));
34586 #endif
34588 return rc;
34592 ** Return the minimum number of 32KB shm regions that should be mapped at
34593 ** a time, assuming that each mapping must be an integer multiple of the
34594 ** current system page-size.
34596 ** Usually, this is 1. The exception seems to be systems that are configured
34597 ** to use 64KB pages - in this case each mapping must cover at least two
34598 ** shm regions.
34600 static int unixShmRegionPerMap(void){
34601 int shmsz = 32*1024; /* SHM region size */
34602 int pgsz = osGetpagesize(); /* System page size */
34603 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
34604 if( pgsz<shmsz ) return 1;
34605 return pgsz/shmsz;
34609 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
34611 ** This is not a VFS shared-memory method; it is a utility function called
34612 ** by VFS shared-memory methods.
34614 static void unixShmPurge(unixFile *pFd){
34615 unixShmNode *p = pFd->pInode->pShmNode;
34616 assert( unixMutexHeld() );
34617 if( p && ALWAYS(p->nRef==0) ){
34618 int nShmPerMap = unixShmRegionPerMap();
34619 int i;
34620 assert( p->pInode==pFd->pInode );
34621 sqlite3_mutex_free(p->mutex);
34622 for(i=0; i<p->nRegion; i+=nShmPerMap){
34623 if( p->h>=0 ){
34624 osMunmap(p->apRegion[i], p->szRegion);
34625 }else{
34626 sqlite3_free(p->apRegion[i]);
34629 sqlite3_free(p->apRegion);
34630 if( p->h>=0 ){
34631 robust_close(pFd, p->h, __LINE__);
34632 p->h = -1;
34634 p->pInode->pShmNode = 0;
34635 sqlite3_free(p);
34640 ** Open a shared-memory area associated with open database file pDbFd.
34641 ** This particular implementation uses mmapped files.
34643 ** The file used to implement shared-memory is in the same directory
34644 ** as the open database file and has the same name as the open database
34645 ** file with the "-shm" suffix added. For example, if the database file
34646 ** is "/home/user1/config.db" then the file that is created and mmapped
34647 ** for shared memory will be called "/home/user1/config.db-shm".
34649 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
34650 ** some other tmpfs mount. But if a file in a different directory
34651 ** from the database file is used, then differing access permissions
34652 ** or a chroot() might cause two different processes on the same
34653 ** database to end up using different files for shared memory -
34654 ** meaning that their memory would not really be shared - resulting
34655 ** in database corruption. Nevertheless, this tmpfs file usage
34656 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
34657 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
34658 ** option results in an incompatible build of SQLite; builds of SQLite
34659 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
34660 ** same database file at the same time, database corruption will likely
34661 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
34662 ** "unsupported" and may go away in a future SQLite release.
34664 ** When opening a new shared-memory file, if no other instances of that
34665 ** file are currently open, in this process or in other processes, then
34666 ** the file must be truncated to zero length or have its header cleared.
34668 ** If the original database file (pDbFd) is using the "unix-excl" VFS
34669 ** that means that an exclusive lock is held on the database file and
34670 ** that no other processes are able to read or write the database. In
34671 ** that case, we do not really need shared memory. No shared memory
34672 ** file is created. The shared memory will be simulated with heap memory.
34674 static int unixOpenSharedMemory(unixFile *pDbFd){
34675 struct unixShm *p = 0; /* The connection to be opened */
34676 struct unixShmNode *pShmNode; /* The underlying mmapped file */
34677 int rc; /* Result code */
34678 unixInodeInfo *pInode; /* The inode of fd */
34679 char *zShmFilename; /* Name of the file used for SHM */
34680 int nShmFilename; /* Size of the SHM filename in bytes */
34682 /* Allocate space for the new unixShm object. */
34683 p = sqlite3_malloc64( sizeof(*p) );
34684 if( p==0 ) return SQLITE_NOMEM_BKPT;
34685 memset(p, 0, sizeof(*p));
34686 assert( pDbFd->pShm==0 );
34688 /* Check to see if a unixShmNode object already exists. Reuse an existing
34689 ** one if present. Create a new one if necessary.
34691 unixEnterMutex();
34692 pInode = pDbFd->pInode;
34693 pShmNode = pInode->pShmNode;
34694 if( pShmNode==0 ){
34695 struct stat sStat; /* fstat() info for database file */
34696 #ifndef SQLITE_SHM_DIRECTORY
34697 const char *zBasePath = pDbFd->zPath;
34698 #endif
34700 /* Call fstat() to figure out the permissions on the database file. If
34701 ** a new *-shm file is created, an attempt will be made to create it
34702 ** with the same permissions.
34704 if( osFstat(pDbFd->h, &sStat) ){
34705 rc = SQLITE_IOERR_FSTAT;
34706 goto shm_open_err;
34709 #ifdef SQLITE_SHM_DIRECTORY
34710 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
34711 #else
34712 nShmFilename = 6 + (int)strlen(zBasePath);
34713 #endif
34714 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
34715 if( pShmNode==0 ){
34716 rc = SQLITE_NOMEM_BKPT;
34717 goto shm_open_err;
34719 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
34720 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
34721 #ifdef SQLITE_SHM_DIRECTORY
34722 sqlite3_snprintf(nShmFilename, zShmFilename,
34723 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
34724 (u32)sStat.st_ino, (u32)sStat.st_dev);
34725 #else
34726 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
34727 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
34728 #endif
34729 pShmNode->h = -1;
34730 pDbFd->pInode->pShmNode = pShmNode;
34731 pShmNode->pInode = pDbFd->pInode;
34732 if( sqlite3GlobalConfig.bCoreMutex ){
34733 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
34734 if( pShmNode->mutex==0 ){
34735 rc = SQLITE_NOMEM_BKPT;
34736 goto shm_open_err;
34740 if( pInode->bProcessLock==0 ){
34741 int openFlags = O_RDWR | O_CREAT;
34742 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
34743 openFlags = O_RDONLY;
34744 pShmNode->isReadonly = 1;
34746 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
34747 if( pShmNode->h<0 ){
34748 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
34749 goto shm_open_err;
34752 /* If this process is running as root, make sure that the SHM file
34753 ** is owned by the same user that owns the original database. Otherwise,
34754 ** the original owner will not be able to connect.
34756 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
34758 /* Check to see if another process is holding the dead-man switch.
34759 ** If not, truncate the file to zero length.
34761 rc = SQLITE_OK;
34762 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
34763 if( robust_ftruncate(pShmNode->h, 0) ){
34764 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
34767 if( rc==SQLITE_OK ){
34768 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
34770 if( rc ) goto shm_open_err;
34774 /* Make the new connection a child of the unixShmNode */
34775 p->pShmNode = pShmNode;
34776 #ifdef SQLITE_DEBUG
34777 p->id = pShmNode->nextShmId++;
34778 #endif
34779 pShmNode->nRef++;
34780 pDbFd->pShm = p;
34781 unixLeaveMutex();
34783 /* The reference count on pShmNode has already been incremented under
34784 ** the cover of the unixEnterMutex() mutex and the pointer from the
34785 ** new (struct unixShm) object to the pShmNode has been set. All that is
34786 ** left to do is to link the new object into the linked list starting
34787 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
34788 ** mutex.
34790 sqlite3_mutex_enter(pShmNode->mutex);
34791 p->pNext = pShmNode->pFirst;
34792 pShmNode->pFirst = p;
34793 sqlite3_mutex_leave(pShmNode->mutex);
34794 return SQLITE_OK;
34796 /* Jump here on any error */
34797 shm_open_err:
34798 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
34799 sqlite3_free(p);
34800 unixLeaveMutex();
34801 return rc;
34805 ** This function is called to obtain a pointer to region iRegion of the
34806 ** shared-memory associated with the database file fd. Shared-memory regions
34807 ** are numbered starting from zero. Each shared-memory region is szRegion
34808 ** bytes in size.
34810 ** If an error occurs, an error code is returned and *pp is set to NULL.
34812 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
34813 ** region has not been allocated (by any client, including one running in a
34814 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
34815 ** bExtend is non-zero and the requested shared-memory region has not yet
34816 ** been allocated, it is allocated by this function.
34818 ** If the shared-memory region has already been allocated or is allocated by
34819 ** this call as described above, then it is mapped into this processes
34820 ** address space (if it is not already), *pp is set to point to the mapped
34821 ** memory and SQLITE_OK returned.
34823 static int unixShmMap(
34824 sqlite3_file *fd, /* Handle open on database file */
34825 int iRegion, /* Region to retrieve */
34826 int szRegion, /* Size of regions */
34827 int bExtend, /* True to extend file if necessary */
34828 void volatile **pp /* OUT: Mapped memory */
34830 unixFile *pDbFd = (unixFile*)fd;
34831 unixShm *p;
34832 unixShmNode *pShmNode;
34833 int rc = SQLITE_OK;
34834 int nShmPerMap = unixShmRegionPerMap();
34835 int nReqRegion;
34837 /* If the shared-memory file has not yet been opened, open it now. */
34838 if( pDbFd->pShm==0 ){
34839 rc = unixOpenSharedMemory(pDbFd);
34840 if( rc!=SQLITE_OK ) return rc;
34843 p = pDbFd->pShm;
34844 pShmNode = p->pShmNode;
34845 sqlite3_mutex_enter(pShmNode->mutex);
34846 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
34847 assert( pShmNode->pInode==pDbFd->pInode );
34848 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
34849 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
34851 /* Minimum number of regions required to be mapped. */
34852 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
34854 if( pShmNode->nRegion<nReqRegion ){
34855 char **apNew; /* New apRegion[] array */
34856 int nByte = nReqRegion*szRegion; /* Minimum required file size */
34857 struct stat sStat; /* Used by fstat() */
34859 pShmNode->szRegion = szRegion;
34861 if( pShmNode->h>=0 ){
34862 /* The requested region is not mapped into this processes address space.
34863 ** Check to see if it has been allocated (i.e. if the wal-index file is
34864 ** large enough to contain the requested region).
34866 if( osFstat(pShmNode->h, &sStat) ){
34867 rc = SQLITE_IOERR_SHMSIZE;
34868 goto shmpage_out;
34871 if( sStat.st_size<nByte ){
34872 /* The requested memory region does not exist. If bExtend is set to
34873 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
34875 if( !bExtend ){
34876 goto shmpage_out;
34879 /* Alternatively, if bExtend is true, extend the file. Do this by
34880 ** writing a single byte to the end of each (OS) page being
34881 ** allocated or extended. Technically, we need only write to the
34882 ** last page in order to extend the file. But writing to all new
34883 ** pages forces the OS to allocate them immediately, which reduces
34884 ** the chances of SIGBUS while accessing the mapped region later on.
34886 else{
34887 static const int pgsz = 4096;
34888 int iPg;
34890 /* Write to the last byte of each newly allocated or extended page */
34891 assert( (nByte % pgsz)==0 );
34892 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
34893 int x = 0;
34894 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
34895 const char *zFile = pShmNode->zFilename;
34896 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
34897 goto shmpage_out;
34904 /* Map the requested memory region into this processes address space. */
34905 apNew = (char **)sqlite3_realloc(
34906 pShmNode->apRegion, nReqRegion*sizeof(char *)
34908 if( !apNew ){
34909 rc = SQLITE_IOERR_NOMEM_BKPT;
34910 goto shmpage_out;
34912 pShmNode->apRegion = apNew;
34913 while( pShmNode->nRegion<nReqRegion ){
34914 int nMap = szRegion*nShmPerMap;
34915 int i;
34916 void *pMem;
34917 if( pShmNode->h>=0 ){
34918 pMem = osMmap(0, nMap,
34919 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
34920 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
34922 if( pMem==MAP_FAILED ){
34923 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
34924 goto shmpage_out;
34926 }else{
34927 pMem = sqlite3_malloc64(szRegion);
34928 if( pMem==0 ){
34929 rc = SQLITE_NOMEM_BKPT;
34930 goto shmpage_out;
34932 memset(pMem, 0, szRegion);
34935 for(i=0; i<nShmPerMap; i++){
34936 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
34938 pShmNode->nRegion += nShmPerMap;
34942 shmpage_out:
34943 if( pShmNode->nRegion>iRegion ){
34944 *pp = pShmNode->apRegion[iRegion];
34945 }else{
34946 *pp = 0;
34948 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
34949 sqlite3_mutex_leave(pShmNode->mutex);
34950 return rc;
34954 ** Change the lock state for a shared-memory segment.
34956 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
34957 ** different here than in posix. In xShmLock(), one can go from unlocked
34958 ** to shared and back or from unlocked to exclusive and back. But one may
34959 ** not go from shared to exclusive or from exclusive to shared.
34961 static int unixShmLock(
34962 sqlite3_file *fd, /* Database file holding the shared memory */
34963 int ofst, /* First lock to acquire or release */
34964 int n, /* Number of locks to acquire or release */
34965 int flags /* What to do with the lock */
34967 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
34968 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
34969 unixShm *pX; /* For looping over all siblings */
34970 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
34971 int rc = SQLITE_OK; /* Result code */
34972 u16 mask; /* Mask of locks to take or release */
34974 assert( pShmNode==pDbFd->pInode->pShmNode );
34975 assert( pShmNode->pInode==pDbFd->pInode );
34976 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
34977 assert( n>=1 );
34978 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
34979 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
34980 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
34981 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
34982 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
34983 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
34984 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
34986 mask = (1<<(ofst+n)) - (1<<ofst);
34987 assert( n>1 || mask==(1<<ofst) );
34988 sqlite3_mutex_enter(pShmNode->mutex);
34989 if( flags & SQLITE_SHM_UNLOCK ){
34990 u16 allMask = 0; /* Mask of locks held by siblings */
34992 /* See if any siblings hold this same lock */
34993 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34994 if( pX==p ) continue;
34995 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
34996 allMask |= pX->sharedMask;
34999 /* Unlock the system-level locks */
35000 if( (mask & allMask)==0 ){
35001 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
35002 }else{
35003 rc = SQLITE_OK;
35006 /* Undo the local locks */
35007 if( rc==SQLITE_OK ){
35008 p->exclMask &= ~mask;
35009 p->sharedMask &= ~mask;
35011 }else if( flags & SQLITE_SHM_SHARED ){
35012 u16 allShared = 0; /* Union of locks held by connections other than "p" */
35014 /* Find out which shared locks are already held by sibling connections.
35015 ** If any sibling already holds an exclusive lock, go ahead and return
35016 ** SQLITE_BUSY.
35018 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35019 if( (pX->exclMask & mask)!=0 ){
35020 rc = SQLITE_BUSY;
35021 break;
35023 allShared |= pX->sharedMask;
35026 /* Get shared locks at the system level, if necessary */
35027 if( rc==SQLITE_OK ){
35028 if( (allShared & mask)==0 ){
35029 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
35030 }else{
35031 rc = SQLITE_OK;
35035 /* Get the local shared locks */
35036 if( rc==SQLITE_OK ){
35037 p->sharedMask |= mask;
35039 }else{
35040 /* Make sure no sibling connections hold locks that will block this
35041 ** lock. If any do, return SQLITE_BUSY right away.
35043 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35044 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
35045 rc = SQLITE_BUSY;
35046 break;
35050 /* Get the exclusive locks at the system level. Then if successful
35051 ** also mark the local connection as being locked.
35053 if( rc==SQLITE_OK ){
35054 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
35055 if( rc==SQLITE_OK ){
35056 assert( (p->sharedMask & mask)==0 );
35057 p->exclMask |= mask;
35061 sqlite3_mutex_leave(pShmNode->mutex);
35062 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
35063 p->id, osGetpid(0), p->sharedMask, p->exclMask));
35064 return rc;
35068 ** Implement a memory barrier or memory fence on shared memory.
35070 ** All loads and stores begun before the barrier must complete before
35071 ** any load or store begun after the barrier.
35073 static void unixShmBarrier(
35074 sqlite3_file *fd /* Database file holding the shared memory */
35076 UNUSED_PARAMETER(fd);
35077 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
35078 unixEnterMutex(); /* Also mutex, for redundancy */
35079 unixLeaveMutex();
35083 ** Close a connection to shared-memory. Delete the underlying
35084 ** storage if deleteFlag is true.
35086 ** If there is no shared memory associated with the connection then this
35087 ** routine is a harmless no-op.
35089 static int unixShmUnmap(
35090 sqlite3_file *fd, /* The underlying database file */
35091 int deleteFlag /* Delete shared-memory if true */
35093 unixShm *p; /* The connection to be closed */
35094 unixShmNode *pShmNode; /* The underlying shared-memory file */
35095 unixShm **pp; /* For looping over sibling connections */
35096 unixFile *pDbFd; /* The underlying database file */
35098 pDbFd = (unixFile*)fd;
35099 p = pDbFd->pShm;
35100 if( p==0 ) return SQLITE_OK;
35101 pShmNode = p->pShmNode;
35103 assert( pShmNode==pDbFd->pInode->pShmNode );
35104 assert( pShmNode->pInode==pDbFd->pInode );
35106 /* Remove connection p from the set of connections associated
35107 ** with pShmNode */
35108 sqlite3_mutex_enter(pShmNode->mutex);
35109 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
35110 *pp = p->pNext;
35112 /* Free the connection p */
35113 sqlite3_free(p);
35114 pDbFd->pShm = 0;
35115 sqlite3_mutex_leave(pShmNode->mutex);
35117 /* If pShmNode->nRef has reached 0, then close the underlying
35118 ** shared-memory file, too */
35119 unixEnterMutex();
35120 assert( pShmNode->nRef>0 );
35121 pShmNode->nRef--;
35122 if( pShmNode->nRef==0 ){
35123 if( deleteFlag && pShmNode->h>=0 ){
35124 osUnlink(pShmNode->zFilename);
35126 unixShmPurge(pDbFd);
35128 unixLeaveMutex();
35130 return SQLITE_OK;
35134 #else
35135 # define unixShmMap 0
35136 # define unixShmLock 0
35137 # define unixShmBarrier 0
35138 # define unixShmUnmap 0
35139 #endif /* #ifndef SQLITE_OMIT_WAL */
35141 #if SQLITE_MAX_MMAP_SIZE>0
35143 ** If it is currently memory mapped, unmap file pFd.
35145 static void unixUnmapfile(unixFile *pFd){
35146 assert( pFd->nFetchOut==0 );
35147 if( pFd->pMapRegion ){
35148 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
35149 pFd->pMapRegion = 0;
35150 pFd->mmapSize = 0;
35151 pFd->mmapSizeActual = 0;
35156 ** Attempt to set the size of the memory mapping maintained by file
35157 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
35159 ** If successful, this function sets the following variables:
35161 ** unixFile.pMapRegion
35162 ** unixFile.mmapSize
35163 ** unixFile.mmapSizeActual
35165 ** If unsuccessful, an error message is logged via sqlite3_log() and
35166 ** the three variables above are zeroed. In this case SQLite should
35167 ** continue accessing the database using the xRead() and xWrite()
35168 ** methods.
35170 static void unixRemapfile(
35171 unixFile *pFd, /* File descriptor object */
35172 i64 nNew /* Required mapping size */
35174 const char *zErr = "mmap";
35175 int h = pFd->h; /* File descriptor open on db file */
35176 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
35177 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
35178 u8 *pNew = 0; /* Location of new mapping */
35179 int flags = PROT_READ; /* Flags to pass to mmap() */
35181 assert( pFd->nFetchOut==0 );
35182 assert( nNew>pFd->mmapSize );
35183 assert( nNew<=pFd->mmapSizeMax );
35184 assert( nNew>0 );
35185 assert( pFd->mmapSizeActual>=pFd->mmapSize );
35186 assert( MAP_FAILED!=0 );
35188 #ifdef SQLITE_MMAP_READWRITE
35189 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
35190 #endif
35192 if( pOrig ){
35193 #if HAVE_MREMAP
35194 i64 nReuse = pFd->mmapSize;
35195 #else
35196 const int szSyspage = osGetpagesize();
35197 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
35198 #endif
35199 u8 *pReq = &pOrig[nReuse];
35201 /* Unmap any pages of the existing mapping that cannot be reused. */
35202 if( nReuse!=nOrig ){
35203 osMunmap(pReq, nOrig-nReuse);
35206 #if HAVE_MREMAP
35207 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
35208 zErr = "mremap";
35209 #else
35210 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
35211 if( pNew!=MAP_FAILED ){
35212 if( pNew!=pReq ){
35213 osMunmap(pNew, nNew - nReuse);
35214 pNew = 0;
35215 }else{
35216 pNew = pOrig;
35219 #endif
35221 /* The attempt to extend the existing mapping failed. Free it. */
35222 if( pNew==MAP_FAILED || pNew==0 ){
35223 osMunmap(pOrig, nReuse);
35227 /* If pNew is still NULL, try to create an entirely new mapping. */
35228 if( pNew==0 ){
35229 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
35232 if( pNew==MAP_FAILED ){
35233 pNew = 0;
35234 nNew = 0;
35235 unixLogError(SQLITE_OK, zErr, pFd->zPath);
35237 /* If the mmap() above failed, assume that all subsequent mmap() calls
35238 ** will probably fail too. Fall back to using xRead/xWrite exclusively
35239 ** in this case. */
35240 pFd->mmapSizeMax = 0;
35242 pFd->pMapRegion = (void *)pNew;
35243 pFd->mmapSize = pFd->mmapSizeActual = nNew;
35247 ** Memory map or remap the file opened by file-descriptor pFd (if the file
35248 ** is already mapped, the existing mapping is replaced by the new). Or, if
35249 ** there already exists a mapping for this file, and there are still
35250 ** outstanding xFetch() references to it, this function is a no-op.
35252 ** If parameter nByte is non-negative, then it is the requested size of
35253 ** the mapping to create. Otherwise, if nByte is less than zero, then the
35254 ** requested size is the size of the file on disk. The actual size of the
35255 ** created mapping is either the requested size or the value configured
35256 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
35258 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
35259 ** recreated as a result of outstanding references) or an SQLite error
35260 ** code otherwise.
35262 static int unixMapfile(unixFile *pFd, i64 nMap){
35263 assert( nMap>=0 || pFd->nFetchOut==0 );
35264 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
35265 if( pFd->nFetchOut>0 ) return SQLITE_OK;
35267 if( nMap<0 ){
35268 struct stat statbuf; /* Low-level file information */
35269 if( osFstat(pFd->h, &statbuf) ){
35270 return SQLITE_IOERR_FSTAT;
35272 nMap = statbuf.st_size;
35274 if( nMap>pFd->mmapSizeMax ){
35275 nMap = pFd->mmapSizeMax;
35278 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
35279 if( nMap!=pFd->mmapSize ){
35280 unixRemapfile(pFd, nMap);
35283 return SQLITE_OK;
35285 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
35288 ** If possible, return a pointer to a mapping of file fd starting at offset
35289 ** iOff. The mapping must be valid for at least nAmt bytes.
35291 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
35292 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
35293 ** Finally, if an error does occur, return an SQLite error code. The final
35294 ** value of *pp is undefined in this case.
35296 ** If this function does return a pointer, the caller must eventually
35297 ** release the reference by calling unixUnfetch().
35299 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
35300 #if SQLITE_MAX_MMAP_SIZE>0
35301 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
35302 #endif
35303 *pp = 0;
35305 #if SQLITE_MAX_MMAP_SIZE>0
35306 if( pFd->mmapSizeMax>0 ){
35307 if( pFd->pMapRegion==0 ){
35308 int rc = unixMapfile(pFd, -1);
35309 if( rc!=SQLITE_OK ) return rc;
35311 if( pFd->mmapSize >= iOff+nAmt ){
35312 *pp = &((u8 *)pFd->pMapRegion)[iOff];
35313 pFd->nFetchOut++;
35316 #endif
35317 return SQLITE_OK;
35321 ** If the third argument is non-NULL, then this function releases a
35322 ** reference obtained by an earlier call to unixFetch(). The second
35323 ** argument passed to this function must be the same as the corresponding
35324 ** argument that was passed to the unixFetch() invocation.
35326 ** Or, if the third argument is NULL, then this function is being called
35327 ** to inform the VFS layer that, according to POSIX, any existing mapping
35328 ** may now be invalid and should be unmapped.
35330 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
35331 #if SQLITE_MAX_MMAP_SIZE>0
35332 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
35333 UNUSED_PARAMETER(iOff);
35335 /* If p==0 (unmap the entire file) then there must be no outstanding
35336 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
35337 ** then there must be at least one outstanding. */
35338 assert( (p==0)==(pFd->nFetchOut==0) );
35340 /* If p!=0, it must match the iOff value. */
35341 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
35343 if( p ){
35344 pFd->nFetchOut--;
35345 }else{
35346 unixUnmapfile(pFd);
35349 assert( pFd->nFetchOut>=0 );
35350 #else
35351 UNUSED_PARAMETER(fd);
35352 UNUSED_PARAMETER(p);
35353 UNUSED_PARAMETER(iOff);
35354 #endif
35355 return SQLITE_OK;
35359 ** Here ends the implementation of all sqlite3_file methods.
35361 ********************** End sqlite3_file Methods *******************************
35362 ******************************************************************************/
35365 ** This division contains definitions of sqlite3_io_methods objects that
35366 ** implement various file locking strategies. It also contains definitions
35367 ** of "finder" functions. A finder-function is used to locate the appropriate
35368 ** sqlite3_io_methods object for a particular database file. The pAppData
35369 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
35370 ** the correct finder-function for that VFS.
35372 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
35373 ** object. The only interesting finder-function is autolockIoFinder, which
35374 ** looks at the filesystem type and tries to guess the best locking
35375 ** strategy from that.
35377 ** For finder-function F, two objects are created:
35379 ** (1) The real finder-function named "FImpt()".
35381 ** (2) A constant pointer to this function named just "F".
35384 ** A pointer to the F pointer is used as the pAppData value for VFS
35385 ** objects. We have to do this instead of letting pAppData point
35386 ** directly at the finder-function since C90 rules prevent a void*
35387 ** from be cast into a function pointer.
35390 ** Each instance of this macro generates two objects:
35392 ** * A constant sqlite3_io_methods object call METHOD that has locking
35393 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
35395 ** * An I/O method finder function called FINDER that returns a pointer
35396 ** to the METHOD object in the previous bullet.
35398 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
35399 static const sqlite3_io_methods METHOD = { \
35400 VERSION, /* iVersion */ \
35401 CLOSE, /* xClose */ \
35402 unixRead, /* xRead */ \
35403 unixWrite, /* xWrite */ \
35404 unixTruncate, /* xTruncate */ \
35405 unixSync, /* xSync */ \
35406 unixFileSize, /* xFileSize */ \
35407 LOCK, /* xLock */ \
35408 UNLOCK, /* xUnlock */ \
35409 CKLOCK, /* xCheckReservedLock */ \
35410 unixFileControl, /* xFileControl */ \
35411 unixSectorSize, /* xSectorSize */ \
35412 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
35413 SHMMAP, /* xShmMap */ \
35414 unixShmLock, /* xShmLock */ \
35415 unixShmBarrier, /* xShmBarrier */ \
35416 unixShmUnmap, /* xShmUnmap */ \
35417 unixFetch, /* xFetch */ \
35418 unixUnfetch, /* xUnfetch */ \
35419 }; \
35420 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
35421 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
35422 return &METHOD; \
35424 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
35425 = FINDER##Impl;
35428 ** Here are all of the sqlite3_io_methods objects for each of the
35429 ** locking strategies. Functions that return pointers to these methods
35430 ** are also created.
35432 IOMETHODS(
35433 posixIoFinder, /* Finder function name */
35434 posixIoMethods, /* sqlite3_io_methods object name */
35435 3, /* shared memory and mmap are enabled */
35436 unixClose, /* xClose method */
35437 unixLock, /* xLock method */
35438 unixUnlock, /* xUnlock method */
35439 unixCheckReservedLock, /* xCheckReservedLock method */
35440 unixShmMap /* xShmMap method */
35442 IOMETHODS(
35443 nolockIoFinder, /* Finder function name */
35444 nolockIoMethods, /* sqlite3_io_methods object name */
35445 3, /* shared memory is disabled */
35446 nolockClose, /* xClose method */
35447 nolockLock, /* xLock method */
35448 nolockUnlock, /* xUnlock method */
35449 nolockCheckReservedLock, /* xCheckReservedLock method */
35450 0 /* xShmMap method */
35452 IOMETHODS(
35453 dotlockIoFinder, /* Finder function name */
35454 dotlockIoMethods, /* sqlite3_io_methods object name */
35455 1, /* shared memory is disabled */
35456 dotlockClose, /* xClose method */
35457 dotlockLock, /* xLock method */
35458 dotlockUnlock, /* xUnlock method */
35459 dotlockCheckReservedLock, /* xCheckReservedLock method */
35460 0 /* xShmMap method */
35463 #if SQLITE_ENABLE_LOCKING_STYLE
35464 IOMETHODS(
35465 flockIoFinder, /* Finder function name */
35466 flockIoMethods, /* sqlite3_io_methods object name */
35467 1, /* shared memory is disabled */
35468 flockClose, /* xClose method */
35469 flockLock, /* xLock method */
35470 flockUnlock, /* xUnlock method */
35471 flockCheckReservedLock, /* xCheckReservedLock method */
35472 0 /* xShmMap method */
35474 #endif
35476 #if OS_VXWORKS
35477 IOMETHODS(
35478 semIoFinder, /* Finder function name */
35479 semIoMethods, /* sqlite3_io_methods object name */
35480 1, /* shared memory is disabled */
35481 semXClose, /* xClose method */
35482 semXLock, /* xLock method */
35483 semXUnlock, /* xUnlock method */
35484 semXCheckReservedLock, /* xCheckReservedLock method */
35485 0 /* xShmMap method */
35487 #endif
35489 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35490 IOMETHODS(
35491 afpIoFinder, /* Finder function name */
35492 afpIoMethods, /* sqlite3_io_methods object name */
35493 1, /* shared memory is disabled */
35494 afpClose, /* xClose method */
35495 afpLock, /* xLock method */
35496 afpUnlock, /* xUnlock method */
35497 afpCheckReservedLock, /* xCheckReservedLock method */
35498 0 /* xShmMap method */
35500 #endif
35503 ** The proxy locking method is a "super-method" in the sense that it
35504 ** opens secondary file descriptors for the conch and lock files and
35505 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
35506 ** secondary files. For this reason, the division that implements
35507 ** proxy locking is located much further down in the file. But we need
35508 ** to go ahead and define the sqlite3_io_methods and finder function
35509 ** for proxy locking here. So we forward declare the I/O methods.
35511 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35512 static int proxyClose(sqlite3_file*);
35513 static int proxyLock(sqlite3_file*, int);
35514 static int proxyUnlock(sqlite3_file*, int);
35515 static int proxyCheckReservedLock(sqlite3_file*, int*);
35516 IOMETHODS(
35517 proxyIoFinder, /* Finder function name */
35518 proxyIoMethods, /* sqlite3_io_methods object name */
35519 1, /* shared memory is disabled */
35520 proxyClose, /* xClose method */
35521 proxyLock, /* xLock method */
35522 proxyUnlock, /* xUnlock method */
35523 proxyCheckReservedLock, /* xCheckReservedLock method */
35524 0 /* xShmMap method */
35526 #endif
35528 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
35529 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35530 IOMETHODS(
35531 nfsIoFinder, /* Finder function name */
35532 nfsIoMethods, /* sqlite3_io_methods object name */
35533 1, /* shared memory is disabled */
35534 unixClose, /* xClose method */
35535 unixLock, /* xLock method */
35536 nfsUnlock, /* xUnlock method */
35537 unixCheckReservedLock, /* xCheckReservedLock method */
35538 0 /* xShmMap method */
35540 #endif
35542 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35544 ** This "finder" function attempts to determine the best locking strategy
35545 ** for the database file "filePath". It then returns the sqlite3_io_methods
35546 ** object that implements that strategy.
35548 ** This is for MacOSX only.
35550 static const sqlite3_io_methods *autolockIoFinderImpl(
35551 const char *filePath, /* name of the database file */
35552 unixFile *pNew /* open file object for the database file */
35554 static const struct Mapping {
35555 const char *zFilesystem; /* Filesystem type name */
35556 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
35557 } aMap[] = {
35558 { "hfs", &posixIoMethods },
35559 { "ufs", &posixIoMethods },
35560 { "afpfs", &afpIoMethods },
35561 { "smbfs", &afpIoMethods },
35562 { "webdav", &nolockIoMethods },
35563 { 0, 0 }
35565 int i;
35566 struct statfs fsInfo;
35567 struct flock lockInfo;
35569 if( !filePath ){
35570 /* If filePath==NULL that means we are dealing with a transient file
35571 ** that does not need to be locked. */
35572 return &nolockIoMethods;
35574 if( statfs(filePath, &fsInfo) != -1 ){
35575 if( fsInfo.f_flags & MNT_RDONLY ){
35576 return &nolockIoMethods;
35578 for(i=0; aMap[i].zFilesystem; i++){
35579 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
35580 return aMap[i].pMethods;
35585 /* Default case. Handles, amongst others, "nfs".
35586 ** Test byte-range lock using fcntl(). If the call succeeds,
35587 ** assume that the file-system supports POSIX style locks.
35589 lockInfo.l_len = 1;
35590 lockInfo.l_start = 0;
35591 lockInfo.l_whence = SEEK_SET;
35592 lockInfo.l_type = F_RDLCK;
35593 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
35594 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
35595 return &nfsIoMethods;
35596 } else {
35597 return &posixIoMethods;
35599 }else{
35600 return &dotlockIoMethods;
35603 static const sqlite3_io_methods
35604 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
35606 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
35608 #if OS_VXWORKS
35610 ** This "finder" function for VxWorks checks to see if posix advisory
35611 ** locking works. If it does, then that is what is used. If it does not
35612 ** work, then fallback to named semaphore locking.
35614 static const sqlite3_io_methods *vxworksIoFinderImpl(
35615 const char *filePath, /* name of the database file */
35616 unixFile *pNew /* the open file object */
35618 struct flock lockInfo;
35620 if( !filePath ){
35621 /* If filePath==NULL that means we are dealing with a transient file
35622 ** that does not need to be locked. */
35623 return &nolockIoMethods;
35626 /* Test if fcntl() is supported and use POSIX style locks.
35627 ** Otherwise fall back to the named semaphore method.
35629 lockInfo.l_len = 1;
35630 lockInfo.l_start = 0;
35631 lockInfo.l_whence = SEEK_SET;
35632 lockInfo.l_type = F_RDLCK;
35633 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
35634 return &posixIoMethods;
35635 }else{
35636 return &semIoMethods;
35639 static const sqlite3_io_methods
35640 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
35642 #endif /* OS_VXWORKS */
35645 ** An abstract type for a pointer to an IO method finder function:
35647 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
35650 /****************************************************************************
35651 **************************** sqlite3_vfs methods ****************************
35653 ** This division contains the implementation of methods on the
35654 ** sqlite3_vfs object.
35658 ** Initialize the contents of the unixFile structure pointed to by pId.
35660 static int fillInUnixFile(
35661 sqlite3_vfs *pVfs, /* Pointer to vfs object */
35662 int h, /* Open file descriptor of file being opened */
35663 sqlite3_file *pId, /* Write to the unixFile structure here */
35664 const char *zFilename, /* Name of the file being opened */
35665 int ctrlFlags /* Zero or more UNIXFILE_* values */
35667 const sqlite3_io_methods *pLockingStyle;
35668 unixFile *pNew = (unixFile *)pId;
35669 int rc = SQLITE_OK;
35671 assert( pNew->pInode==NULL );
35673 /* No locking occurs in temporary files */
35674 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
35676 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
35677 pNew->h = h;
35678 pNew->pVfs = pVfs;
35679 pNew->zPath = zFilename;
35680 pNew->ctrlFlags = (u8)ctrlFlags;
35681 #if SQLITE_MAX_MMAP_SIZE>0
35682 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
35683 #endif
35684 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
35685 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
35686 pNew->ctrlFlags |= UNIXFILE_PSOW;
35688 if( strcmp(pVfs->zName,"unix-excl")==0 ){
35689 pNew->ctrlFlags |= UNIXFILE_EXCL;
35692 #if OS_VXWORKS
35693 pNew->pId = vxworksFindFileId(zFilename);
35694 if( pNew->pId==0 ){
35695 ctrlFlags |= UNIXFILE_NOLOCK;
35696 rc = SQLITE_NOMEM_BKPT;
35698 #endif
35700 if( ctrlFlags & UNIXFILE_NOLOCK ){
35701 pLockingStyle = &nolockIoMethods;
35702 }else{
35703 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
35704 #if SQLITE_ENABLE_LOCKING_STYLE
35705 /* Cache zFilename in the locking context (AFP and dotlock override) for
35706 ** proxyLock activation is possible (remote proxy is based on db name)
35707 ** zFilename remains valid until file is closed, to support */
35708 pNew->lockingContext = (void*)zFilename;
35709 #endif
35712 if( pLockingStyle == &posixIoMethods
35713 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35714 || pLockingStyle == &nfsIoMethods
35715 #endif
35717 unixEnterMutex();
35718 rc = findInodeInfo(pNew, &pNew->pInode);
35719 if( rc!=SQLITE_OK ){
35720 /* If an error occurred in findInodeInfo(), close the file descriptor
35721 ** immediately, before releasing the mutex. findInodeInfo() may fail
35722 ** in two scenarios:
35724 ** (a) A call to fstat() failed.
35725 ** (b) A malloc failed.
35727 ** Scenario (b) may only occur if the process is holding no other
35728 ** file descriptors open on the same file. If there were other file
35729 ** descriptors on this file, then no malloc would be required by
35730 ** findInodeInfo(). If this is the case, it is quite safe to close
35731 ** handle h - as it is guaranteed that no posix locks will be released
35732 ** by doing so.
35734 ** If scenario (a) caused the error then things are not so safe. The
35735 ** implicit assumption here is that if fstat() fails, things are in
35736 ** such bad shape that dropping a lock or two doesn't matter much.
35738 robust_close(pNew, h, __LINE__);
35739 h = -1;
35741 unixLeaveMutex();
35744 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
35745 else if( pLockingStyle == &afpIoMethods ){
35746 /* AFP locking uses the file path so it needs to be included in
35747 ** the afpLockingContext.
35749 afpLockingContext *pCtx;
35750 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
35751 if( pCtx==0 ){
35752 rc = SQLITE_NOMEM_BKPT;
35753 }else{
35754 /* NB: zFilename exists and remains valid until the file is closed
35755 ** according to requirement F11141. So we do not need to make a
35756 ** copy of the filename. */
35757 pCtx->dbPath = zFilename;
35758 pCtx->reserved = 0;
35759 srandomdev();
35760 unixEnterMutex();
35761 rc = findInodeInfo(pNew, &pNew->pInode);
35762 if( rc!=SQLITE_OK ){
35763 sqlite3_free(pNew->lockingContext);
35764 robust_close(pNew, h, __LINE__);
35765 h = -1;
35767 unixLeaveMutex();
35770 #endif
35772 else if( pLockingStyle == &dotlockIoMethods ){
35773 /* Dotfile locking uses the file path so it needs to be included in
35774 ** the dotlockLockingContext
35776 char *zLockFile;
35777 int nFilename;
35778 assert( zFilename!=0 );
35779 nFilename = (int)strlen(zFilename) + 6;
35780 zLockFile = (char *)sqlite3_malloc64(nFilename);
35781 if( zLockFile==0 ){
35782 rc = SQLITE_NOMEM_BKPT;
35783 }else{
35784 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
35786 pNew->lockingContext = zLockFile;
35789 #if OS_VXWORKS
35790 else if( pLockingStyle == &semIoMethods ){
35791 /* Named semaphore locking uses the file path so it needs to be
35792 ** included in the semLockingContext
35794 unixEnterMutex();
35795 rc = findInodeInfo(pNew, &pNew->pInode);
35796 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
35797 char *zSemName = pNew->pInode->aSemName;
35798 int n;
35799 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
35800 pNew->pId->zCanonicalName);
35801 for( n=1; zSemName[n]; n++ )
35802 if( zSemName[n]=='/' ) zSemName[n] = '_';
35803 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
35804 if( pNew->pInode->pSem == SEM_FAILED ){
35805 rc = SQLITE_NOMEM_BKPT;
35806 pNew->pInode->aSemName[0] = '\0';
35809 unixLeaveMutex();
35811 #endif
35813 storeLastErrno(pNew, 0);
35814 #if OS_VXWORKS
35815 if( rc!=SQLITE_OK ){
35816 if( h>=0 ) robust_close(pNew, h, __LINE__);
35817 h = -1;
35818 osUnlink(zFilename);
35819 pNew->ctrlFlags |= UNIXFILE_DELETE;
35821 #endif
35822 if( rc!=SQLITE_OK ){
35823 if( h>=0 ) robust_close(pNew, h, __LINE__);
35824 }else{
35825 pNew->pMethod = pLockingStyle;
35826 OpenCounter(+1);
35827 verifyDbFile(pNew);
35829 return rc;
35833 ** Return the name of a directory in which to put temporary files.
35834 ** If no suitable temporary file directory can be found, return NULL.
35836 static const char *unixTempFileDir(void){
35837 static const char *azDirs[] = {
35840 "/var/tmp",
35841 "/usr/tmp",
35842 "/tmp",
35845 unsigned int i = 0;
35846 struct stat buf;
35847 const char *zDir = sqlite3_temp_directory;
35849 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
35850 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
35851 while(1){
35852 if( zDir!=0
35853 && osStat(zDir, &buf)==0
35854 && S_ISDIR(buf.st_mode)
35855 && osAccess(zDir, 03)==0
35857 return zDir;
35859 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
35860 zDir = azDirs[i++];
35862 return 0;
35866 ** Create a temporary file name in zBuf. zBuf must be allocated
35867 ** by the calling process and must be big enough to hold at least
35868 ** pVfs->mxPathname bytes.
35870 static int unixGetTempname(int nBuf, char *zBuf){
35871 const char *zDir;
35872 int iLimit = 0;
35874 /* It's odd to simulate an io-error here, but really this is just
35875 ** using the io-error infrastructure to test that SQLite handles this
35876 ** function failing.
35878 zBuf[0] = 0;
35879 SimulateIOError( return SQLITE_IOERR );
35881 zDir = unixTempFileDir();
35882 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
35884 u64 r;
35885 sqlite3_randomness(sizeof(r), &r);
35886 assert( nBuf>2 );
35887 zBuf[nBuf-2] = 0;
35888 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
35889 zDir, r, 0);
35890 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
35891 }while( osAccess(zBuf,0)==0 );
35892 return SQLITE_OK;
35895 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
35897 ** Routine to transform a unixFile into a proxy-locking unixFile.
35898 ** Implementation in the proxy-lock division, but used by unixOpen()
35899 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
35901 static int proxyTransformUnixFile(unixFile*, const char*);
35902 #endif
35905 ** Search for an unused file descriptor that was opened on the database
35906 ** file (not a journal or master-journal file) identified by pathname
35907 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
35908 ** argument to this function.
35910 ** Such a file descriptor may exist if a database connection was closed
35911 ** but the associated file descriptor could not be closed because some
35912 ** other file descriptor open on the same file is holding a file-lock.
35913 ** Refer to comments in the unixClose() function and the lengthy comment
35914 ** describing "Posix Advisory Locking" at the start of this file for
35915 ** further details. Also, ticket #4018.
35917 ** If a suitable file descriptor is found, then it is returned. If no
35918 ** such file descriptor is located, -1 is returned.
35920 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
35921 UnixUnusedFd *pUnused = 0;
35923 /* Do not search for an unused file descriptor on vxworks. Not because
35924 ** vxworks would not benefit from the change (it might, we're not sure),
35925 ** but because no way to test it is currently available. It is better
35926 ** not to risk breaking vxworks support for the sake of such an obscure
35927 ** feature. */
35928 #if !OS_VXWORKS
35929 struct stat sStat; /* Results of stat() call */
35931 unixEnterMutex();
35933 /* A stat() call may fail for various reasons. If this happens, it is
35934 ** almost certain that an open() call on the same path will also fail.
35935 ** For this reason, if an error occurs in the stat() call here, it is
35936 ** ignored and -1 is returned. The caller will try to open a new file
35937 ** descriptor on the same path, fail, and return an error to SQLite.
35939 ** Even if a subsequent open() call does succeed, the consequences of
35940 ** not searching for a reusable file descriptor are not dire. */
35941 if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
35942 unixInodeInfo *pInode;
35944 pInode = inodeList;
35945 while( pInode && (pInode->fileId.dev!=sStat.st_dev
35946 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
35947 pInode = pInode->pNext;
35949 if( pInode ){
35950 UnixUnusedFd **pp;
35951 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
35952 pUnused = *pp;
35953 if( pUnused ){
35954 nUnusedFd--;
35955 *pp = pUnused->pNext;
35959 unixLeaveMutex();
35960 #endif /* if !OS_VXWORKS */
35961 return pUnused;
35965 ** Find the mode, uid and gid of file zFile.
35967 static int getFileMode(
35968 const char *zFile, /* File name */
35969 mode_t *pMode, /* OUT: Permissions of zFile */
35970 uid_t *pUid, /* OUT: uid of zFile. */
35971 gid_t *pGid /* OUT: gid of zFile. */
35973 struct stat sStat; /* Output of stat() on database file */
35974 int rc = SQLITE_OK;
35975 if( 0==osStat(zFile, &sStat) ){
35976 *pMode = sStat.st_mode & 0777;
35977 *pUid = sStat.st_uid;
35978 *pGid = sStat.st_gid;
35979 }else{
35980 rc = SQLITE_IOERR_FSTAT;
35982 return rc;
35986 ** This function is called by unixOpen() to determine the unix permissions
35987 ** to create new files with. If no error occurs, then SQLITE_OK is returned
35988 ** and a value suitable for passing as the third argument to open(2) is
35989 ** written to *pMode. If an IO error occurs, an SQLite error code is
35990 ** returned and the value of *pMode is not modified.
35992 ** In most cases, this routine sets *pMode to 0, which will become
35993 ** an indication to robust_open() to create the file using
35994 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
35995 ** But if the file being opened is a WAL or regular journal file, then
35996 ** this function queries the file-system for the permissions on the
35997 ** corresponding database file and sets *pMode to this value. Whenever
35998 ** possible, WAL and journal files are created using the same permissions
35999 ** as the associated database file.
36001 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
36002 ** original filename is unavailable. But 8_3_NAMES is only used for
36003 ** FAT filesystems and permissions do not matter there, so just use
36004 ** the default permissions.
36006 static int findCreateFileMode(
36007 const char *zPath, /* Path of file (possibly) being created */
36008 int flags, /* Flags passed as 4th argument to xOpen() */
36009 mode_t *pMode, /* OUT: Permissions to open file with */
36010 uid_t *pUid, /* OUT: uid to set on the file */
36011 gid_t *pGid /* OUT: gid to set on the file */
36013 int rc = SQLITE_OK; /* Return Code */
36014 *pMode = 0;
36015 *pUid = 0;
36016 *pGid = 0;
36017 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
36018 char zDb[MAX_PATHNAME+1]; /* Database file path */
36019 int nDb; /* Number of valid bytes in zDb */
36021 /* zPath is a path to a WAL or journal file. The following block derives
36022 ** the path to the associated database file from zPath. This block handles
36023 ** the following naming conventions:
36025 ** "<path to db>-journal"
36026 ** "<path to db>-wal"
36027 ** "<path to db>-journalNN"
36028 ** "<path to db>-walNN"
36030 ** where NN is a decimal number. The NN naming schemes are
36031 ** used by the test_multiplex.c module.
36033 nDb = sqlite3Strlen30(zPath) - 1;
36034 while( zPath[nDb]!='-' ){
36035 /* In normal operation, the journal file name will always contain
36036 ** a '-' character. However in 8+3 filename mode, or if a corrupt
36037 ** rollback journal specifies a master journal with a goofy name, then
36038 ** the '-' might be missing. */
36039 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
36040 nDb--;
36042 memcpy(zDb, zPath, nDb);
36043 zDb[nDb] = '\0';
36045 rc = getFileMode(zDb, pMode, pUid, pGid);
36046 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
36047 *pMode = 0600;
36048 }else if( flags & SQLITE_OPEN_URI ){
36049 /* If this is a main database file and the file was opened using a URI
36050 ** filename, check for the "modeof" parameter. If present, interpret
36051 ** its value as a filename and try to copy the mode, uid and gid from
36052 ** that file. */
36053 const char *z = sqlite3_uri_parameter(zPath, "modeof");
36054 if( z ){
36055 rc = getFileMode(z, pMode, pUid, pGid);
36058 return rc;
36062 ** Open the file zPath.
36064 ** Previously, the SQLite OS layer used three functions in place of this
36065 ** one:
36067 ** sqlite3OsOpenReadWrite();
36068 ** sqlite3OsOpenReadOnly();
36069 ** sqlite3OsOpenExclusive();
36071 ** These calls correspond to the following combinations of flags:
36073 ** ReadWrite() -> (READWRITE | CREATE)
36074 ** ReadOnly() -> (READONLY)
36075 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
36077 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
36078 ** true, the file was configured to be automatically deleted when the
36079 ** file handle closed. To achieve the same effect using this new
36080 ** interface, add the DELETEONCLOSE flag to those specified above for
36081 ** OpenExclusive().
36083 static int unixOpen(
36084 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
36085 const char *zPath, /* Pathname of file to be opened */
36086 sqlite3_file *pFile, /* The file descriptor to be filled in */
36087 int flags, /* Input flags to control the opening */
36088 int *pOutFlags /* Output flags returned to SQLite core */
36090 unixFile *p = (unixFile *)pFile;
36091 int fd = -1; /* File descriptor returned by open() */
36092 int openFlags = 0; /* Flags to pass to open() */
36093 int eType = flags&0xFFFFFF00; /* Type of file to open */
36094 int noLock; /* True to omit locking primitives */
36095 int rc = SQLITE_OK; /* Function Return Code */
36096 int ctrlFlags = 0; /* UNIXFILE_* flags */
36098 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
36099 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
36100 int isCreate = (flags & SQLITE_OPEN_CREATE);
36101 int isReadonly = (flags & SQLITE_OPEN_READONLY);
36102 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
36103 #if SQLITE_ENABLE_LOCKING_STYLE
36104 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
36105 #endif
36106 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
36107 struct statfs fsInfo;
36108 #endif
36110 /* If creating a master or main-file journal, this function will open
36111 ** a file-descriptor on the directory too. The first time unixSync()
36112 ** is called the directory file descriptor will be fsync()ed and close()d.
36114 int syncDir = (isCreate && (
36115 eType==SQLITE_OPEN_MASTER_JOURNAL
36116 || eType==SQLITE_OPEN_MAIN_JOURNAL
36117 || eType==SQLITE_OPEN_WAL
36120 /* If argument zPath is a NULL pointer, this function is required to open
36121 ** a temporary file. Use this buffer to store the file name in.
36123 char zTmpname[MAX_PATHNAME+2];
36124 const char *zName = zPath;
36126 /* Check the following statements are true:
36128 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
36129 ** (b) if CREATE is set, then READWRITE must also be set, and
36130 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
36131 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
36133 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
36134 assert(isCreate==0 || isReadWrite);
36135 assert(isExclusive==0 || isCreate);
36136 assert(isDelete==0 || isCreate);
36138 /* The main DB, main journal, WAL file and master journal are never
36139 ** automatically deleted. Nor are they ever temporary files. */
36140 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
36141 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
36142 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
36143 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
36145 /* Assert that the upper layer has set one of the "file-type" flags. */
36146 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
36147 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
36148 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
36149 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
36152 /* Detect a pid change and reset the PRNG. There is a race condition
36153 ** here such that two or more threads all trying to open databases at
36154 ** the same instant might all reset the PRNG. But multiple resets
36155 ** are harmless.
36157 if( randomnessPid!=osGetpid(0) ){
36158 randomnessPid = osGetpid(0);
36159 sqlite3_randomness(0,0);
36162 memset(p, 0, sizeof(unixFile));
36164 if( eType==SQLITE_OPEN_MAIN_DB ){
36165 UnixUnusedFd *pUnused;
36166 pUnused = findReusableFd(zName, flags);
36167 if( pUnused ){
36168 fd = pUnused->fd;
36169 }else{
36170 pUnused = sqlite3_malloc64(sizeof(*pUnused));
36171 if( !pUnused ){
36172 return SQLITE_NOMEM_BKPT;
36175 p->pPreallocatedUnused = pUnused;
36177 /* Database filenames are double-zero terminated if they are not
36178 ** URIs with parameters. Hence, they can always be passed into
36179 ** sqlite3_uri_parameter(). */
36180 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
36182 }else if( !zName ){
36183 /* If zName is NULL, the upper layer is requesting a temp file. */
36184 assert(isDelete && !syncDir);
36185 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
36186 if( rc!=SQLITE_OK ){
36187 return rc;
36189 zName = zTmpname;
36191 /* Generated temporary filenames are always double-zero terminated
36192 ** for use by sqlite3_uri_parameter(). */
36193 assert( zName[strlen(zName)+1]==0 );
36196 /* Determine the value of the flags parameter passed to POSIX function
36197 ** open(). These must be calculated even if open() is not called, as
36198 ** they may be stored as part of the file handle and used by the
36199 ** 'conch file' locking functions later on. */
36200 if( isReadonly ) openFlags |= O_RDONLY;
36201 if( isReadWrite ) openFlags |= O_RDWR;
36202 if( isCreate ) openFlags |= O_CREAT;
36203 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
36204 openFlags |= (O_LARGEFILE|O_BINARY);
36206 if( fd<0 ){
36207 mode_t openMode; /* Permissions to create file with */
36208 uid_t uid; /* Userid for the file */
36209 gid_t gid; /* Groupid for the file */
36210 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
36211 if( rc!=SQLITE_OK ){
36212 assert( !p->pPreallocatedUnused );
36213 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
36214 return rc;
36216 fd = robust_open(zName, openFlags, openMode);
36217 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
36218 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
36219 if( fd<0 && errno!=EISDIR && isReadWrite ){
36220 /* Failed to open the file for read/write access. Try read-only. */
36221 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
36222 openFlags &= ~(O_RDWR|O_CREAT);
36223 flags |= SQLITE_OPEN_READONLY;
36224 openFlags |= O_RDONLY;
36225 isReadonly = 1;
36226 fd = robust_open(zName, openFlags, openMode);
36228 if( fd<0 ){
36229 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
36230 goto open_finished;
36233 /* If this process is running as root and if creating a new rollback
36234 ** journal or WAL file, set the ownership of the journal or WAL to be
36235 ** the same as the original database.
36237 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
36238 robustFchown(fd, uid, gid);
36241 assert( fd>=0 );
36242 if( pOutFlags ){
36243 *pOutFlags = flags;
36246 if( p->pPreallocatedUnused ){
36247 p->pPreallocatedUnused->fd = fd;
36248 p->pPreallocatedUnused->flags = flags;
36251 if( isDelete ){
36252 #if OS_VXWORKS
36253 zPath = zName;
36254 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
36255 zPath = sqlite3_mprintf("%s", zName);
36256 if( zPath==0 ){
36257 robust_close(p, fd, __LINE__);
36258 return SQLITE_NOMEM_BKPT;
36260 #else
36261 osUnlink(zName);
36262 #endif
36264 #if SQLITE_ENABLE_LOCKING_STYLE
36265 else{
36266 p->openFlags = openFlags;
36268 #endif
36270 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
36271 if( fstatfs(fd, &fsInfo) == -1 ){
36272 storeLastErrno(p, errno);
36273 robust_close(p, fd, __LINE__);
36274 return SQLITE_IOERR_ACCESS;
36276 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
36277 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
36279 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
36280 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
36282 #endif
36284 /* Set up appropriate ctrlFlags */
36285 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
36286 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
36287 noLock = eType!=SQLITE_OPEN_MAIN_DB;
36288 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
36289 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
36290 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
36292 #if SQLITE_ENABLE_LOCKING_STYLE
36293 #if SQLITE_PREFER_PROXY_LOCKING
36294 isAutoProxy = 1;
36295 #endif
36296 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
36297 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
36298 int useProxy = 0;
36300 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
36301 ** never use proxy, NULL means use proxy for non-local files only. */
36302 if( envforce!=NULL ){
36303 useProxy = atoi(envforce)>0;
36304 }else{
36305 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
36307 if( useProxy ){
36308 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
36309 if( rc==SQLITE_OK ){
36310 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
36311 if( rc!=SQLITE_OK ){
36312 /* Use unixClose to clean up the resources added in fillInUnixFile
36313 ** and clear all the structure's references. Specifically,
36314 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
36316 unixClose(pFile);
36317 return rc;
36320 goto open_finished;
36323 #endif
36325 assert( zPath==0 || zPath[0]=='/'
36326 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
36328 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
36330 open_finished:
36331 if( rc!=SQLITE_OK ){
36332 sqlite3_free(p->pPreallocatedUnused);
36334 return rc;
36339 ** Delete the file at zPath. If the dirSync argument is true, fsync()
36340 ** the directory after deleting the file.
36342 static int unixDelete(
36343 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
36344 const char *zPath, /* Name of file to be deleted */
36345 int dirSync /* If true, fsync() directory after deleting file */
36347 int rc = SQLITE_OK;
36348 UNUSED_PARAMETER(NotUsed);
36349 SimulateIOError(return SQLITE_IOERR_DELETE);
36350 if( osUnlink(zPath)==(-1) ){
36351 if( errno==ENOENT
36352 #if OS_VXWORKS
36353 || osAccess(zPath,0)!=0
36354 #endif
36356 rc = SQLITE_IOERR_DELETE_NOENT;
36357 }else{
36358 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
36360 return rc;
36362 #ifndef SQLITE_DISABLE_DIRSYNC
36363 if( (dirSync & 1)!=0 ){
36364 int fd;
36365 rc = osOpenDirectory(zPath, &fd);
36366 if( rc==SQLITE_OK ){
36367 if( full_fsync(fd,0,0) ){
36368 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
36370 robust_close(0, fd, __LINE__);
36371 }else{
36372 assert( rc==SQLITE_CANTOPEN );
36373 rc = SQLITE_OK;
36376 #endif
36377 return rc;
36381 ** Test the existence of or access permissions of file zPath. The
36382 ** test performed depends on the value of flags:
36384 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
36385 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
36386 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
36388 ** Otherwise return 0.
36390 static int unixAccess(
36391 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
36392 const char *zPath, /* Path of the file to examine */
36393 int flags, /* What do we want to learn about the zPath file? */
36394 int *pResOut /* Write result boolean here */
36396 UNUSED_PARAMETER(NotUsed);
36397 SimulateIOError( return SQLITE_IOERR_ACCESS; );
36398 assert( pResOut!=0 );
36400 /* The spec says there are three possible values for flags. But only
36401 ** two of them are actually used */
36402 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
36404 if( flags==SQLITE_ACCESS_EXISTS ){
36405 struct stat buf;
36406 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
36407 }else{
36408 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
36410 return SQLITE_OK;
36416 static int mkFullPathname(
36417 const char *zPath, /* Input path */
36418 char *zOut, /* Output buffer */
36419 int nOut /* Allocated size of buffer zOut */
36421 int nPath = sqlite3Strlen30(zPath);
36422 int iOff = 0;
36423 if( zPath[0]!='/' ){
36424 if( osGetcwd(zOut, nOut-2)==0 ){
36425 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
36427 iOff = sqlite3Strlen30(zOut);
36428 zOut[iOff++] = '/';
36430 if( (iOff+nPath+1)>nOut ){
36431 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
36432 ** even if it returns an error. */
36433 zOut[iOff] = '\0';
36434 return SQLITE_CANTOPEN_BKPT;
36436 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
36437 return SQLITE_OK;
36441 ** Turn a relative pathname into a full pathname. The relative path
36442 ** is stored as a nul-terminated string in the buffer pointed to by
36443 ** zPath.
36445 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
36446 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
36447 ** this buffer before returning.
36449 static int unixFullPathname(
36450 sqlite3_vfs *pVfs, /* Pointer to vfs object */
36451 const char *zPath, /* Possibly relative input path */
36452 int nOut, /* Size of output buffer in bytes */
36453 char *zOut /* Output buffer */
36455 #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
36456 return mkFullPathname(zPath, zOut, nOut);
36457 #else
36458 int rc = SQLITE_OK;
36459 int nByte;
36460 int nLink = 1; /* Number of symbolic links followed so far */
36461 const char *zIn = zPath; /* Input path for each iteration of loop */
36462 char *zDel = 0;
36464 assert( pVfs->mxPathname==MAX_PATHNAME );
36465 UNUSED_PARAMETER(pVfs);
36467 /* It's odd to simulate an io-error here, but really this is just
36468 ** using the io-error infrastructure to test that SQLite handles this
36469 ** function failing. This function could fail if, for example, the
36470 ** current working directory has been unlinked.
36472 SimulateIOError( return SQLITE_ERROR );
36474 do {
36476 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
36477 ** link, or false otherwise. */
36478 int bLink = 0;
36479 struct stat buf;
36480 if( osLstat(zIn, &buf)!=0 ){
36481 if( errno!=ENOENT ){
36482 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
36484 }else{
36485 bLink = S_ISLNK(buf.st_mode);
36488 if( bLink ){
36489 if( zDel==0 ){
36490 zDel = sqlite3_malloc(nOut);
36491 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
36492 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
36493 rc = SQLITE_CANTOPEN_BKPT;
36496 if( rc==SQLITE_OK ){
36497 nByte = osReadlink(zIn, zDel, nOut-1);
36498 if( nByte<0 ){
36499 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
36500 }else{
36501 if( zDel[0]!='/' ){
36502 int n;
36503 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
36504 if( nByte+n+1>nOut ){
36505 rc = SQLITE_CANTOPEN_BKPT;
36506 }else{
36507 memmove(&zDel[n], zDel, nByte+1);
36508 memcpy(zDel, zIn, n);
36509 nByte += n;
36512 zDel[nByte] = '\0';
36516 zIn = zDel;
36519 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
36520 if( rc==SQLITE_OK && zIn!=zOut ){
36521 rc = mkFullPathname(zIn, zOut, nOut);
36523 if( bLink==0 ) break;
36524 zIn = zOut;
36525 }while( rc==SQLITE_OK );
36527 sqlite3_free(zDel);
36528 return rc;
36529 #endif /* HAVE_READLINK && HAVE_LSTAT */
36533 #ifndef SQLITE_OMIT_LOAD_EXTENSION
36535 ** Interfaces for opening a shared library, finding entry points
36536 ** within the shared library, and closing the shared library.
36538 #include <dlfcn.h>
36539 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
36540 UNUSED_PARAMETER(NotUsed);
36541 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
36545 ** SQLite calls this function immediately after a call to unixDlSym() or
36546 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
36547 ** message is available, it is written to zBufOut. If no error message
36548 ** is available, zBufOut is left unmodified and SQLite uses a default
36549 ** error message.
36551 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
36552 const char *zErr;
36553 UNUSED_PARAMETER(NotUsed);
36554 unixEnterMutex();
36555 zErr = dlerror();
36556 if( zErr ){
36557 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
36559 unixLeaveMutex();
36561 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
36563 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
36564 ** cast into a pointer to a function. And yet the library dlsym() routine
36565 ** returns a void* which is really a pointer to a function. So how do we
36566 ** use dlsym() with -pedantic-errors?
36568 ** Variable x below is defined to be a pointer to a function taking
36569 ** parameters void* and const char* and returning a pointer to a function.
36570 ** We initialize x by assigning it a pointer to the dlsym() function.
36571 ** (That assignment requires a cast.) Then we call the function that
36572 ** x points to.
36574 ** This work-around is unlikely to work correctly on any system where
36575 ** you really cannot cast a function pointer into void*. But then, on the
36576 ** other hand, dlsym() will not work on such a system either, so we have
36577 ** not really lost anything.
36579 void (*(*x)(void*,const char*))(void);
36580 UNUSED_PARAMETER(NotUsed);
36581 x = (void(*(*)(void*,const char*))(void))dlsym;
36582 return (*x)(p, zSym);
36584 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
36585 UNUSED_PARAMETER(NotUsed);
36586 dlclose(pHandle);
36588 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
36589 #define unixDlOpen 0
36590 #define unixDlError 0
36591 #define unixDlSym 0
36592 #define unixDlClose 0
36593 #endif
36596 ** Write nBuf bytes of random data to the supplied buffer zBuf.
36598 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
36599 UNUSED_PARAMETER(NotUsed);
36600 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
36602 /* We have to initialize zBuf to prevent valgrind from reporting
36603 ** errors. The reports issued by valgrind are incorrect - we would
36604 ** prefer that the randomness be increased by making use of the
36605 ** uninitialized space in zBuf - but valgrind errors tend to worry
36606 ** some users. Rather than argue, it seems easier just to initialize
36607 ** the whole array and silence valgrind, even if that means less randomness
36608 ** in the random seed.
36610 ** When testing, initializing zBuf[] to zero is all we do. That means
36611 ** that we always use the same random number sequence. This makes the
36612 ** tests repeatable.
36614 memset(zBuf, 0, nBuf);
36615 randomnessPid = osGetpid(0);
36616 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
36618 int fd, got;
36619 fd = robust_open("/dev/urandom", O_RDONLY, 0);
36620 if( fd<0 ){
36621 time_t t;
36622 time(&t);
36623 memcpy(zBuf, &t, sizeof(t));
36624 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
36625 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
36626 nBuf = sizeof(t) + sizeof(randomnessPid);
36627 }else{
36628 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
36629 robust_close(0, fd, __LINE__);
36632 #endif
36633 return nBuf;
36638 ** Sleep for a little while. Return the amount of time slept.
36639 ** The argument is the number of microseconds we want to sleep.
36640 ** The return value is the number of microseconds of sleep actually
36641 ** requested from the underlying operating system, a number which
36642 ** might be greater than or equal to the argument, but not less
36643 ** than the argument.
36645 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
36646 #if OS_VXWORKS
36647 struct timespec sp;
36649 sp.tv_sec = microseconds / 1000000;
36650 sp.tv_nsec = (microseconds % 1000000) * 1000;
36651 nanosleep(&sp, NULL);
36652 UNUSED_PARAMETER(NotUsed);
36653 return microseconds;
36654 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
36655 usleep(microseconds);
36656 UNUSED_PARAMETER(NotUsed);
36657 return microseconds;
36658 #else
36659 int seconds = (microseconds+999999)/1000000;
36660 sleep(seconds);
36661 UNUSED_PARAMETER(NotUsed);
36662 return seconds*1000000;
36663 #endif
36667 ** The following variable, if set to a non-zero value, is interpreted as
36668 ** the number of seconds since 1970 and is used to set the result of
36669 ** sqlite3OsCurrentTime() during testing.
36671 #ifdef SQLITE_TEST
36672 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
36673 #endif
36676 ** Find the current time (in Universal Coordinated Time). Write into *piNow
36677 ** the current time and date as a Julian Day number times 86_400_000. In
36678 ** other words, write into *piNow the number of milliseconds since the Julian
36679 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
36680 ** proleptic Gregorian calendar.
36682 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
36683 ** cannot be found.
36685 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
36686 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
36687 int rc = SQLITE_OK;
36688 #if defined(NO_GETTOD)
36689 time_t t;
36690 time(&t);
36691 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
36692 #elif OS_VXWORKS
36693 struct timespec sNow;
36694 clock_gettime(CLOCK_REALTIME, &sNow);
36695 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
36696 #else
36697 struct timeval sNow;
36698 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
36699 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
36700 #endif
36702 #ifdef SQLITE_TEST
36703 if( sqlite3_current_time ){
36704 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
36706 #endif
36707 UNUSED_PARAMETER(NotUsed);
36708 return rc;
36711 #ifndef SQLITE_OMIT_DEPRECATED
36713 ** Find the current time (in Universal Coordinated Time). Write the
36714 ** current time and date as a Julian Day number into *prNow and
36715 ** return 0. Return 1 if the time and date cannot be found.
36717 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
36718 sqlite3_int64 i = 0;
36719 int rc;
36720 UNUSED_PARAMETER(NotUsed);
36721 rc = unixCurrentTimeInt64(0, &i);
36722 *prNow = i/86400000.0;
36723 return rc;
36725 #else
36726 # define unixCurrentTime 0
36727 #endif
36730 ** The xGetLastError() method is designed to return a better
36731 ** low-level error message when operating-system problems come up
36732 ** during SQLite operation. Only the integer return code is currently
36733 ** used.
36735 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
36736 UNUSED_PARAMETER(NotUsed);
36737 UNUSED_PARAMETER(NotUsed2);
36738 UNUSED_PARAMETER(NotUsed3);
36739 return errno;
36744 ************************ End of sqlite3_vfs methods ***************************
36745 ******************************************************************************/
36747 /******************************************************************************
36748 ************************** Begin Proxy Locking ********************************
36750 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
36751 ** other locking methods on secondary lock files. Proxy locking is a
36752 ** meta-layer over top of the primitive locking implemented above. For
36753 ** this reason, the division that implements of proxy locking is deferred
36754 ** until late in the file (here) after all of the other I/O methods have
36755 ** been defined - so that the primitive locking methods are available
36756 ** as services to help with the implementation of proxy locking.
36758 ****
36760 ** The default locking schemes in SQLite use byte-range locks on the
36761 ** database file to coordinate safe, concurrent access by multiple readers
36762 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
36763 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
36764 ** as POSIX read & write locks over fixed set of locations (via fsctl),
36765 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
36766 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
36767 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
36768 ** address in the shared range is taken for a SHARED lock, the entire
36769 ** shared range is taken for an EXCLUSIVE lock):
36771 ** PENDING_BYTE 0x40000000
36772 ** RESERVED_BYTE 0x40000001
36773 ** SHARED_RANGE 0x40000002 -> 0x40000200
36775 ** This works well on the local file system, but shows a nearly 100x
36776 ** slowdown in read performance on AFP because the AFP client disables
36777 ** the read cache when byte-range locks are present. Enabling the read
36778 ** cache exposes a cache coherency problem that is present on all OS X
36779 ** supported network file systems. NFS and AFP both observe the
36780 ** close-to-open semantics for ensuring cache coherency
36781 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
36782 ** address the requirements for concurrent database access by multiple
36783 ** readers and writers
36784 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
36786 ** To address the performance and cache coherency issues, proxy file locking
36787 ** changes the way database access is controlled by limiting access to a
36788 ** single host at a time and moving file locks off of the database file
36789 ** and onto a proxy file on the local file system.
36792 ** Using proxy locks
36793 ** -----------------
36795 ** C APIs
36797 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
36798 ** <proxy_path> | ":auto:");
36799 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
36800 ** &<proxy_path>);
36803 ** SQL pragmas
36805 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
36806 ** PRAGMA [database.]lock_proxy_file
36808 ** Specifying ":auto:" means that if there is a conch file with a matching
36809 ** host ID in it, the proxy path in the conch file will be used, otherwise
36810 ** a proxy path based on the user's temp dir
36811 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
36812 ** actual proxy file name is generated from the name and path of the
36813 ** database file. For example:
36815 ** For database path "/Users/me/foo.db"
36816 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
36818 ** Once a lock proxy is configured for a database connection, it can not
36819 ** be removed, however it may be switched to a different proxy path via
36820 ** the above APIs (assuming the conch file is not being held by another
36821 ** connection or process).
36824 ** How proxy locking works
36825 ** -----------------------
36827 ** Proxy file locking relies primarily on two new supporting files:
36829 ** * conch file to limit access to the database file to a single host
36830 ** at a time
36832 ** * proxy file to act as a proxy for the advisory locks normally
36833 ** taken on the database
36835 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
36836 ** by taking an sqlite-style shared lock on the conch file, reading the
36837 ** contents and comparing the host's unique host ID (see below) and lock
36838 ** proxy path against the values stored in the conch. The conch file is
36839 ** stored in the same directory as the database file and the file name
36840 ** is patterned after the database file name as ".<databasename>-conch".
36841 ** If the conch file does not exist, or its contents do not match the
36842 ** host ID and/or proxy path, then the lock is escalated to an exclusive
36843 ** lock and the conch file contents is updated with the host ID and proxy
36844 ** path and the lock is downgraded to a shared lock again. If the conch
36845 ** is held by another process (with a shared lock), the exclusive lock
36846 ** will fail and SQLITE_BUSY is returned.
36848 ** The proxy file - a single-byte file used for all advisory file locks
36849 ** normally taken on the database file. This allows for safe sharing
36850 ** of the database file for multiple readers and writers on the same
36851 ** host (the conch ensures that they all use the same local lock file).
36853 ** Requesting the lock proxy does not immediately take the conch, it is
36854 ** only taken when the first request to lock database file is made.
36855 ** This matches the semantics of the traditional locking behavior, where
36856 ** opening a connection to a database file does not take a lock on it.
36857 ** The shared lock and an open file descriptor are maintained until
36858 ** the connection to the database is closed.
36860 ** The proxy file and the lock file are never deleted so they only need
36861 ** to be created the first time they are used.
36863 ** Configuration options
36864 ** ---------------------
36866 ** SQLITE_PREFER_PROXY_LOCKING
36868 ** Database files accessed on non-local file systems are
36869 ** automatically configured for proxy locking, lock files are
36870 ** named automatically using the same logic as
36871 ** PRAGMA lock_proxy_file=":auto:"
36873 ** SQLITE_PROXY_DEBUG
36875 ** Enables the logging of error messages during host id file
36876 ** retrieval and creation
36878 ** LOCKPROXYDIR
36880 ** Overrides the default directory used for lock proxy files that
36881 ** are named automatically via the ":auto:" setting
36883 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
36885 ** Permissions to use when creating a directory for storing the
36886 ** lock proxy files, only used when LOCKPROXYDIR is not set.
36889 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
36890 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
36891 ** force proxy locking to be used for every database file opened, and 0
36892 ** will force automatic proxy locking to be disabled for all database
36893 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
36894 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
36898 ** Proxy locking is only available on MacOSX
36900 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
36903 ** The proxyLockingContext has the path and file structures for the remote
36904 ** and local proxy files in it
36906 typedef struct proxyLockingContext proxyLockingContext;
36907 struct proxyLockingContext {
36908 unixFile *conchFile; /* Open conch file */
36909 char *conchFilePath; /* Name of the conch file */
36910 unixFile *lockProxy; /* Open proxy lock file */
36911 char *lockProxyPath; /* Name of the proxy lock file */
36912 char *dbPath; /* Name of the open file */
36913 int conchHeld; /* 1 if the conch is held, -1 if lockless */
36914 int nFails; /* Number of conch taking failures */
36915 void *oldLockingContext; /* Original lockingcontext to restore on close */
36916 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
36920 ** The proxy lock file path for the database at dbPath is written into lPath,
36921 ** which must point to valid, writable memory large enough for a maxLen length
36922 ** file path.
36924 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
36925 int len;
36926 int dbLen;
36927 int i;
36929 #ifdef LOCKPROXYDIR
36930 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
36931 #else
36932 # ifdef _CS_DARWIN_USER_TEMP_DIR
36934 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
36935 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
36936 lPath, errno, osGetpid(0)));
36937 return SQLITE_IOERR_LOCK;
36939 len = strlcat(lPath, "sqliteplocks", maxLen);
36941 # else
36942 len = strlcpy(lPath, "/tmp/", maxLen);
36943 # endif
36944 #endif
36946 if( lPath[len-1]!='/' ){
36947 len = strlcat(lPath, "/", maxLen);
36950 /* transform the db path to a unique cache name */
36951 dbLen = (int)strlen(dbPath);
36952 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
36953 char c = dbPath[i];
36954 lPath[i+len] = (c=='/')?'_':c;
36956 lPath[i+len]='\0';
36957 strlcat(lPath, ":auto:", maxLen);
36958 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
36959 return SQLITE_OK;
36963 ** Creates the lock file and any missing directories in lockPath
36965 static int proxyCreateLockPath(const char *lockPath){
36966 int i, len;
36967 char buf[MAXPATHLEN];
36968 int start = 0;
36970 assert(lockPath!=NULL);
36971 /* try to create all the intermediate directories */
36972 len = (int)strlen(lockPath);
36973 buf[0] = lockPath[0];
36974 for( i=1; i<len; i++ ){
36975 if( lockPath[i] == '/' && (i - start > 0) ){
36976 /* only mkdir if leaf dir != "." or "/" or ".." */
36977 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
36978 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
36979 buf[i]='\0';
36980 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
36981 int err=errno;
36982 if( err!=EEXIST ) {
36983 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
36984 "'%s' proxy lock path=%s pid=%d\n",
36985 buf, strerror(err), lockPath, osGetpid(0)));
36986 return err;
36990 start=i+1;
36992 buf[i] = lockPath[i];
36994 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
36995 return 0;
36999 ** Create a new VFS file descriptor (stored in memory obtained from
37000 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
37002 ** The caller is responsible not only for closing the file descriptor
37003 ** but also for freeing the memory associated with the file descriptor.
37005 static int proxyCreateUnixFile(
37006 const char *path, /* path for the new unixFile */
37007 unixFile **ppFile, /* unixFile created and returned by ref */
37008 int islockfile /* if non zero missing dirs will be created */
37010 int fd = -1;
37011 unixFile *pNew;
37012 int rc = SQLITE_OK;
37013 int openFlags = O_RDWR | O_CREAT;
37014 sqlite3_vfs dummyVfs;
37015 int terrno = 0;
37016 UnixUnusedFd *pUnused = NULL;
37018 /* 1. first try to open/create the file
37019 ** 2. if that fails, and this is a lock file (not-conch), try creating
37020 ** the parent directories and then try again.
37021 ** 3. if that fails, try to open the file read-only
37022 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
37024 pUnused = findReusableFd(path, openFlags);
37025 if( pUnused ){
37026 fd = pUnused->fd;
37027 }else{
37028 pUnused = sqlite3_malloc64(sizeof(*pUnused));
37029 if( !pUnused ){
37030 return SQLITE_NOMEM_BKPT;
37033 if( fd<0 ){
37034 fd = robust_open(path, openFlags, 0);
37035 terrno = errno;
37036 if( fd<0 && errno==ENOENT && islockfile ){
37037 if( proxyCreateLockPath(path) == SQLITE_OK ){
37038 fd = robust_open(path, openFlags, 0);
37042 if( fd<0 ){
37043 openFlags = O_RDONLY;
37044 fd = robust_open(path, openFlags, 0);
37045 terrno = errno;
37047 if( fd<0 ){
37048 if( islockfile ){
37049 return SQLITE_BUSY;
37051 switch (terrno) {
37052 case EACCES:
37053 return SQLITE_PERM;
37054 case EIO:
37055 return SQLITE_IOERR_LOCK; /* even though it is the conch */
37056 default:
37057 return SQLITE_CANTOPEN_BKPT;
37061 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
37062 if( pNew==NULL ){
37063 rc = SQLITE_NOMEM_BKPT;
37064 goto end_create_proxy;
37066 memset(pNew, 0, sizeof(unixFile));
37067 pNew->openFlags = openFlags;
37068 memset(&dummyVfs, 0, sizeof(dummyVfs));
37069 dummyVfs.pAppData = (void*)&autolockIoFinder;
37070 dummyVfs.zName = "dummy";
37071 pUnused->fd = fd;
37072 pUnused->flags = openFlags;
37073 pNew->pPreallocatedUnused = pUnused;
37075 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
37076 if( rc==SQLITE_OK ){
37077 *ppFile = pNew;
37078 return SQLITE_OK;
37080 end_create_proxy:
37081 robust_close(pNew, fd, __LINE__);
37082 sqlite3_free(pNew);
37083 sqlite3_free(pUnused);
37084 return rc;
37087 #ifdef SQLITE_TEST
37088 /* simulate multiple hosts by creating unique hostid file paths */
37089 SQLITE_API int sqlite3_hostid_num = 0;
37090 #endif
37092 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
37094 #ifdef HAVE_GETHOSTUUID
37095 /* Not always defined in the headers as it ought to be */
37096 extern int gethostuuid(uuid_t id, const struct timespec *wait);
37097 #endif
37099 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
37100 ** bytes of writable memory.
37102 static int proxyGetHostID(unsigned char *pHostID, int *pError){
37103 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
37104 memset(pHostID, 0, PROXY_HOSTIDLEN);
37105 #ifdef HAVE_GETHOSTUUID
37107 struct timespec timeout = {1, 0}; /* 1 sec timeout */
37108 if( gethostuuid(pHostID, &timeout) ){
37109 int err = errno;
37110 if( pError ){
37111 *pError = err;
37113 return SQLITE_IOERR;
37116 #else
37117 UNUSED_PARAMETER(pError);
37118 #endif
37119 #ifdef SQLITE_TEST
37120 /* simulate multiple hosts by creating unique hostid file paths */
37121 if( sqlite3_hostid_num != 0){
37122 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
37124 #endif
37126 return SQLITE_OK;
37129 /* The conch file contains the header, host id and lock file path
37131 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
37132 #define PROXY_HEADERLEN 1 /* conch file header length */
37133 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
37134 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
37137 ** Takes an open conch file, copies the contents to a new path and then moves
37138 ** it back. The newly created file's file descriptor is assigned to the
37139 ** conch file structure and finally the original conch file descriptor is
37140 ** closed. Returns zero if successful.
37142 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
37143 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37144 unixFile *conchFile = pCtx->conchFile;
37145 char tPath[MAXPATHLEN];
37146 char buf[PROXY_MAXCONCHLEN];
37147 char *cPath = pCtx->conchFilePath;
37148 size_t readLen = 0;
37149 size_t pathLen = 0;
37150 char errmsg[64] = "";
37151 int fd = -1;
37152 int rc = -1;
37153 UNUSED_PARAMETER(myHostID);
37155 /* create a new path by replace the trailing '-conch' with '-break' */
37156 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
37157 if( pathLen>MAXPATHLEN || pathLen<6 ||
37158 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
37159 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
37160 goto end_breaklock;
37162 /* read the conch content */
37163 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
37164 if( readLen<PROXY_PATHINDEX ){
37165 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
37166 goto end_breaklock;
37168 /* write it out to the temporary break file */
37169 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
37170 if( fd<0 ){
37171 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
37172 goto end_breaklock;
37174 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
37175 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
37176 goto end_breaklock;
37178 if( rename(tPath, cPath) ){
37179 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
37180 goto end_breaklock;
37182 rc = 0;
37183 fprintf(stderr, "broke stale lock on %s\n", cPath);
37184 robust_close(pFile, conchFile->h, __LINE__);
37185 conchFile->h = fd;
37186 conchFile->openFlags = O_RDWR | O_CREAT;
37188 end_breaklock:
37189 if( rc ){
37190 if( fd>=0 ){
37191 osUnlink(tPath);
37192 robust_close(pFile, fd, __LINE__);
37194 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
37196 return rc;
37199 /* Take the requested lock on the conch file and break a stale lock if the
37200 ** host id matches.
37202 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
37203 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37204 unixFile *conchFile = pCtx->conchFile;
37205 int rc = SQLITE_OK;
37206 int nTries = 0;
37207 struct timespec conchModTime;
37209 memset(&conchModTime, 0, sizeof(conchModTime));
37210 do {
37211 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
37212 nTries ++;
37213 if( rc==SQLITE_BUSY ){
37214 /* If the lock failed (busy):
37215 * 1st try: get the mod time of the conch, wait 0.5s and try again.
37216 * 2nd try: fail if the mod time changed or host id is different, wait
37217 * 10 sec and try again
37218 * 3rd try: break the lock unless the mod time has changed.
37220 struct stat buf;
37221 if( osFstat(conchFile->h, &buf) ){
37222 storeLastErrno(pFile, errno);
37223 return SQLITE_IOERR_LOCK;
37226 if( nTries==1 ){
37227 conchModTime = buf.st_mtimespec;
37228 usleep(500000); /* wait 0.5 sec and try the lock again*/
37229 continue;
37232 assert( nTries>1 );
37233 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
37234 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
37235 return SQLITE_BUSY;
37238 if( nTries==2 ){
37239 char tBuf[PROXY_MAXCONCHLEN];
37240 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
37241 if( len<0 ){
37242 storeLastErrno(pFile, errno);
37243 return SQLITE_IOERR_LOCK;
37245 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
37246 /* don't break the lock if the host id doesn't match */
37247 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
37248 return SQLITE_BUSY;
37250 }else{
37251 /* don't break the lock on short read or a version mismatch */
37252 return SQLITE_BUSY;
37254 usleep(10000000); /* wait 10 sec and try the lock again */
37255 continue;
37258 assert( nTries==3 );
37259 if( 0==proxyBreakConchLock(pFile, myHostID) ){
37260 rc = SQLITE_OK;
37261 if( lockType==EXCLUSIVE_LOCK ){
37262 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
37264 if( !rc ){
37265 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
37269 } while( rc==SQLITE_BUSY && nTries<3 );
37271 return rc;
37274 /* Takes the conch by taking a shared lock and read the contents conch, if
37275 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
37276 ** lockPath means that the lockPath in the conch file will be used if the
37277 ** host IDs match, or a new lock path will be generated automatically
37278 ** and written to the conch file.
37280 static int proxyTakeConch(unixFile *pFile){
37281 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37283 if( pCtx->conchHeld!=0 ){
37284 return SQLITE_OK;
37285 }else{
37286 unixFile *conchFile = pCtx->conchFile;
37287 uuid_t myHostID;
37288 int pError = 0;
37289 char readBuf[PROXY_MAXCONCHLEN];
37290 char lockPath[MAXPATHLEN];
37291 char *tempLockPath = NULL;
37292 int rc = SQLITE_OK;
37293 int createConch = 0;
37294 int hostIdMatch = 0;
37295 int readLen = 0;
37296 int tryOldLockPath = 0;
37297 int forceNewLockPath = 0;
37299 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
37300 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
37301 osGetpid(0)));
37303 rc = proxyGetHostID(myHostID, &pError);
37304 if( (rc&0xff)==SQLITE_IOERR ){
37305 storeLastErrno(pFile, pError);
37306 goto end_takeconch;
37308 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
37309 if( rc!=SQLITE_OK ){
37310 goto end_takeconch;
37312 /* read the existing conch file */
37313 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
37314 if( readLen<0 ){
37315 /* I/O error: lastErrno set by seekAndRead */
37316 storeLastErrno(pFile, conchFile->lastErrno);
37317 rc = SQLITE_IOERR_READ;
37318 goto end_takeconch;
37319 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
37320 readBuf[0]!=(char)PROXY_CONCHVERSION ){
37321 /* a short read or version format mismatch means we need to create a new
37322 ** conch file.
37324 createConch = 1;
37326 /* if the host id matches and the lock path already exists in the conch
37327 ** we'll try to use the path there, if we can't open that path, we'll
37328 ** retry with a new auto-generated path
37330 do { /* in case we need to try again for an :auto: named lock file */
37332 if( !createConch && !forceNewLockPath ){
37333 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
37334 PROXY_HOSTIDLEN);
37335 /* if the conch has data compare the contents */
37336 if( !pCtx->lockProxyPath ){
37337 /* for auto-named local lock file, just check the host ID and we'll
37338 ** use the local lock file path that's already in there
37340 if( hostIdMatch ){
37341 size_t pathLen = (readLen - PROXY_PATHINDEX);
37343 if( pathLen>=MAXPATHLEN ){
37344 pathLen=MAXPATHLEN-1;
37346 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
37347 lockPath[pathLen] = 0;
37348 tempLockPath = lockPath;
37349 tryOldLockPath = 1;
37350 /* create a copy of the lock path if the conch is taken */
37351 goto end_takeconch;
37353 }else if( hostIdMatch
37354 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
37355 readLen-PROXY_PATHINDEX)
37357 /* conch host and lock path match */
37358 goto end_takeconch;
37362 /* if the conch isn't writable and doesn't match, we can't take it */
37363 if( (conchFile->openFlags&O_RDWR) == 0 ){
37364 rc = SQLITE_BUSY;
37365 goto end_takeconch;
37368 /* either the conch didn't match or we need to create a new one */
37369 if( !pCtx->lockProxyPath ){
37370 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
37371 tempLockPath = lockPath;
37372 /* create a copy of the lock path _only_ if the conch is taken */
37375 /* update conch with host and path (this will fail if other process
37376 ** has a shared lock already), if the host id matches, use the big
37377 ** stick.
37379 futimes(conchFile->h, NULL);
37380 if( hostIdMatch && !createConch ){
37381 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
37382 /* We are trying for an exclusive lock but another thread in this
37383 ** same process is still holding a shared lock. */
37384 rc = SQLITE_BUSY;
37385 } else {
37386 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
37388 }else{
37389 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
37391 if( rc==SQLITE_OK ){
37392 char writeBuffer[PROXY_MAXCONCHLEN];
37393 int writeSize = 0;
37395 writeBuffer[0] = (char)PROXY_CONCHVERSION;
37396 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
37397 if( pCtx->lockProxyPath!=NULL ){
37398 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
37399 MAXPATHLEN);
37400 }else{
37401 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
37403 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
37404 robust_ftruncate(conchFile->h, writeSize);
37405 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
37406 full_fsync(conchFile->h,0,0);
37407 /* If we created a new conch file (not just updated the contents of a
37408 ** valid conch file), try to match the permissions of the database
37410 if( rc==SQLITE_OK && createConch ){
37411 struct stat buf;
37412 int err = osFstat(pFile->h, &buf);
37413 if( err==0 ){
37414 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
37415 S_IROTH|S_IWOTH);
37416 /* try to match the database file R/W permissions, ignore failure */
37417 #ifndef SQLITE_PROXY_DEBUG
37418 osFchmod(conchFile->h, cmode);
37419 #else
37421 rc = osFchmod(conchFile->h, cmode);
37422 }while( rc==(-1) && errno==EINTR );
37423 if( rc!=0 ){
37424 int code = errno;
37425 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
37426 cmode, code, strerror(code));
37427 } else {
37428 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
37430 }else{
37431 int code = errno;
37432 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
37433 err, code, strerror(code));
37434 #endif
37438 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
37440 end_takeconch:
37441 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
37442 if( rc==SQLITE_OK && pFile->openFlags ){
37443 int fd;
37444 if( pFile->h>=0 ){
37445 robust_close(pFile, pFile->h, __LINE__);
37447 pFile->h = -1;
37448 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
37449 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
37450 if( fd>=0 ){
37451 pFile->h = fd;
37452 }else{
37453 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
37454 during locking */
37457 if( rc==SQLITE_OK && !pCtx->lockProxy ){
37458 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
37459 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
37460 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
37461 /* we couldn't create the proxy lock file with the old lock file path
37462 ** so try again via auto-naming
37464 forceNewLockPath = 1;
37465 tryOldLockPath = 0;
37466 continue; /* go back to the do {} while start point, try again */
37469 if( rc==SQLITE_OK ){
37470 /* Need to make a copy of path if we extracted the value
37471 ** from the conch file or the path was allocated on the stack
37473 if( tempLockPath ){
37474 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
37475 if( !pCtx->lockProxyPath ){
37476 rc = SQLITE_NOMEM_BKPT;
37480 if( rc==SQLITE_OK ){
37481 pCtx->conchHeld = 1;
37483 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
37484 afpLockingContext *afpCtx;
37485 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
37486 afpCtx->dbPath = pCtx->lockProxyPath;
37488 } else {
37489 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
37491 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
37492 rc==SQLITE_OK?"ok":"failed"));
37493 return rc;
37494 } while (1); /* in case we need to retry the :auto: lock file -
37495 ** we should never get here except via the 'continue' call. */
37500 ** If pFile holds a lock on a conch file, then release that lock.
37502 static int proxyReleaseConch(unixFile *pFile){
37503 int rc = SQLITE_OK; /* Subroutine return code */
37504 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
37505 unixFile *conchFile; /* Name of the conch file */
37507 pCtx = (proxyLockingContext *)pFile->lockingContext;
37508 conchFile = pCtx->conchFile;
37509 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
37510 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
37511 osGetpid(0)));
37512 if( pCtx->conchHeld>0 ){
37513 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
37515 pCtx->conchHeld = 0;
37516 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
37517 (rc==SQLITE_OK ? "ok" : "failed")));
37518 return rc;
37522 ** Given the name of a database file, compute the name of its conch file.
37523 ** Store the conch filename in memory obtained from sqlite3_malloc64().
37524 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
37525 ** or SQLITE_NOMEM if unable to obtain memory.
37527 ** The caller is responsible for ensuring that the allocated memory
37528 ** space is eventually freed.
37530 ** *pConchPath is set to NULL if a memory allocation error occurs.
37532 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
37533 int i; /* Loop counter */
37534 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
37535 char *conchPath; /* buffer in which to construct conch name */
37537 /* Allocate space for the conch filename and initialize the name to
37538 ** the name of the original database file. */
37539 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
37540 if( conchPath==0 ){
37541 return SQLITE_NOMEM_BKPT;
37543 memcpy(conchPath, dbPath, len+1);
37545 /* now insert a "." before the last / character */
37546 for( i=(len-1); i>=0; i-- ){
37547 if( conchPath[i]=='/' ){
37548 i++;
37549 break;
37552 conchPath[i]='.';
37553 while ( i<len ){
37554 conchPath[i+1]=dbPath[i];
37555 i++;
37558 /* append the "-conch" suffix to the file */
37559 memcpy(&conchPath[i+1], "-conch", 7);
37560 assert( (int)strlen(conchPath) == len+7 );
37562 return SQLITE_OK;
37566 /* Takes a fully configured proxy locking-style unix file and switches
37567 ** the local lock file path
37569 static int switchLockProxyPath(unixFile *pFile, const char *path) {
37570 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
37571 char *oldPath = pCtx->lockProxyPath;
37572 int rc = SQLITE_OK;
37574 if( pFile->eFileLock!=NO_LOCK ){
37575 return SQLITE_BUSY;
37578 /* nothing to do if the path is NULL, :auto: or matches the existing path */
37579 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
37580 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
37581 return SQLITE_OK;
37582 }else{
37583 unixFile *lockProxy = pCtx->lockProxy;
37584 pCtx->lockProxy=NULL;
37585 pCtx->conchHeld = 0;
37586 if( lockProxy!=NULL ){
37587 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
37588 if( rc ) return rc;
37589 sqlite3_free(lockProxy);
37591 sqlite3_free(oldPath);
37592 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
37595 return rc;
37599 ** pFile is a file that has been opened by a prior xOpen call. dbPath
37600 ** is a string buffer at least MAXPATHLEN+1 characters in size.
37602 ** This routine find the filename associated with pFile and writes it
37603 ** int dbPath.
37605 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
37606 #if defined(__APPLE__)
37607 if( pFile->pMethod == &afpIoMethods ){
37608 /* afp style keeps a reference to the db path in the filePath field
37609 ** of the struct */
37610 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
37611 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
37612 MAXPATHLEN);
37613 } else
37614 #endif
37615 if( pFile->pMethod == &dotlockIoMethods ){
37616 /* dot lock style uses the locking context to store the dot lock
37617 ** file path */
37618 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
37619 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
37620 }else{
37621 /* all other styles use the locking context to store the db file path */
37622 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
37623 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
37625 return SQLITE_OK;
37629 ** Takes an already filled in unix file and alters it so all file locking
37630 ** will be performed on the local proxy lock file. The following fields
37631 ** are preserved in the locking context so that they can be restored and
37632 ** the unix structure properly cleaned up at close time:
37633 ** ->lockingContext
37634 ** ->pMethod
37636 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
37637 proxyLockingContext *pCtx;
37638 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
37639 char *lockPath=NULL;
37640 int rc = SQLITE_OK;
37642 if( pFile->eFileLock!=NO_LOCK ){
37643 return SQLITE_BUSY;
37645 proxyGetDbPathForUnixFile(pFile, dbPath);
37646 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
37647 lockPath=NULL;
37648 }else{
37649 lockPath=(char *)path;
37652 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
37653 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
37655 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
37656 if( pCtx==0 ){
37657 return SQLITE_NOMEM_BKPT;
37659 memset(pCtx, 0, sizeof(*pCtx));
37661 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
37662 if( rc==SQLITE_OK ){
37663 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
37664 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
37665 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
37666 ** (c) the file system is read-only, then enable no-locking access.
37667 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
37668 ** that openFlags will have only one of O_RDONLY or O_RDWR.
37670 struct statfs fsInfo;
37671 struct stat conchInfo;
37672 int goLockless = 0;
37674 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
37675 int err = errno;
37676 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
37677 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
37680 if( goLockless ){
37681 pCtx->conchHeld = -1; /* read only FS/ lockless */
37682 rc = SQLITE_OK;
37686 if( rc==SQLITE_OK && lockPath ){
37687 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
37690 if( rc==SQLITE_OK ){
37691 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
37692 if( pCtx->dbPath==NULL ){
37693 rc = SQLITE_NOMEM_BKPT;
37696 if( rc==SQLITE_OK ){
37697 /* all memory is allocated, proxys are created and assigned,
37698 ** switch the locking context and pMethod then return.
37700 pCtx->oldLockingContext = pFile->lockingContext;
37701 pFile->lockingContext = pCtx;
37702 pCtx->pOldMethod = pFile->pMethod;
37703 pFile->pMethod = &proxyIoMethods;
37704 }else{
37705 if( pCtx->conchFile ){
37706 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
37707 sqlite3_free(pCtx->conchFile);
37709 sqlite3DbFree(0, pCtx->lockProxyPath);
37710 sqlite3_free(pCtx->conchFilePath);
37711 sqlite3_free(pCtx);
37713 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
37714 (rc==SQLITE_OK ? "ok" : "failed")));
37715 return rc;
37720 ** This routine handles sqlite3_file_control() calls that are specific
37721 ** to proxy locking.
37723 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
37724 switch( op ){
37725 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
37726 unixFile *pFile = (unixFile*)id;
37727 if( pFile->pMethod == &proxyIoMethods ){
37728 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
37729 proxyTakeConch(pFile);
37730 if( pCtx->lockProxyPath ){
37731 *(const char **)pArg = pCtx->lockProxyPath;
37732 }else{
37733 *(const char **)pArg = ":auto: (not held)";
37735 } else {
37736 *(const char **)pArg = NULL;
37738 return SQLITE_OK;
37740 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
37741 unixFile *pFile = (unixFile*)id;
37742 int rc = SQLITE_OK;
37743 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
37744 if( pArg==NULL || (const char *)pArg==0 ){
37745 if( isProxyStyle ){
37746 /* turn off proxy locking - not supported. If support is added for
37747 ** switching proxy locking mode off then it will need to fail if
37748 ** the journal mode is WAL mode.
37750 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
37751 }else{
37752 /* turn off proxy locking - already off - NOOP */
37753 rc = SQLITE_OK;
37755 }else{
37756 const char *proxyPath = (const char *)pArg;
37757 if( isProxyStyle ){
37758 proxyLockingContext *pCtx =
37759 (proxyLockingContext*)pFile->lockingContext;
37760 if( !strcmp(pArg, ":auto:")
37761 || (pCtx->lockProxyPath &&
37762 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
37764 rc = SQLITE_OK;
37765 }else{
37766 rc = switchLockProxyPath(pFile, proxyPath);
37768 }else{
37769 /* turn on proxy file locking */
37770 rc = proxyTransformUnixFile(pFile, proxyPath);
37773 return rc;
37775 default: {
37776 assert( 0 ); /* The call assures that only valid opcodes are sent */
37779 /*NOTREACHED*/
37780 return SQLITE_ERROR;
37784 ** Within this division (the proxying locking implementation) the procedures
37785 ** above this point are all utilities. The lock-related methods of the
37786 ** proxy-locking sqlite3_io_method object follow.
37791 ** This routine checks if there is a RESERVED lock held on the specified
37792 ** file by this or any other process. If such a lock is held, set *pResOut
37793 ** to a non-zero value otherwise *pResOut is set to zero. The return value
37794 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
37796 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
37797 unixFile *pFile = (unixFile*)id;
37798 int rc = proxyTakeConch(pFile);
37799 if( rc==SQLITE_OK ){
37800 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37801 if( pCtx->conchHeld>0 ){
37802 unixFile *proxy = pCtx->lockProxy;
37803 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
37804 }else{ /* conchHeld < 0 is lockless */
37805 pResOut=0;
37808 return rc;
37812 ** Lock the file with the lock specified by parameter eFileLock - one
37813 ** of the following:
37815 ** (1) SHARED_LOCK
37816 ** (2) RESERVED_LOCK
37817 ** (3) PENDING_LOCK
37818 ** (4) EXCLUSIVE_LOCK
37820 ** Sometimes when requesting one lock state, additional lock states
37821 ** are inserted in between. The locking might fail on one of the later
37822 ** transitions leaving the lock state different from what it started but
37823 ** still short of its goal. The following chart shows the allowed
37824 ** transitions and the inserted intermediate states:
37826 ** UNLOCKED -> SHARED
37827 ** SHARED -> RESERVED
37828 ** SHARED -> (PENDING) -> EXCLUSIVE
37829 ** RESERVED -> (PENDING) -> EXCLUSIVE
37830 ** PENDING -> EXCLUSIVE
37832 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
37833 ** routine to lower a locking level.
37835 static int proxyLock(sqlite3_file *id, int eFileLock) {
37836 unixFile *pFile = (unixFile*)id;
37837 int rc = proxyTakeConch(pFile);
37838 if( rc==SQLITE_OK ){
37839 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37840 if( pCtx->conchHeld>0 ){
37841 unixFile *proxy = pCtx->lockProxy;
37842 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
37843 pFile->eFileLock = proxy->eFileLock;
37844 }else{
37845 /* conchHeld < 0 is lockless */
37848 return rc;
37853 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
37854 ** must be either NO_LOCK or SHARED_LOCK.
37856 ** If the locking level of the file descriptor is already at or below
37857 ** the requested locking level, this routine is a no-op.
37859 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
37860 unixFile *pFile = (unixFile*)id;
37861 int rc = proxyTakeConch(pFile);
37862 if( rc==SQLITE_OK ){
37863 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37864 if( pCtx->conchHeld>0 ){
37865 unixFile *proxy = pCtx->lockProxy;
37866 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
37867 pFile->eFileLock = proxy->eFileLock;
37868 }else{
37869 /* conchHeld < 0 is lockless */
37872 return rc;
37876 ** Close a file that uses proxy locks.
37878 static int proxyClose(sqlite3_file *id) {
37879 if( ALWAYS(id) ){
37880 unixFile *pFile = (unixFile*)id;
37881 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37882 unixFile *lockProxy = pCtx->lockProxy;
37883 unixFile *conchFile = pCtx->conchFile;
37884 int rc = SQLITE_OK;
37886 if( lockProxy ){
37887 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
37888 if( rc ) return rc;
37889 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
37890 if( rc ) return rc;
37891 sqlite3_free(lockProxy);
37892 pCtx->lockProxy = 0;
37894 if( conchFile ){
37895 if( pCtx->conchHeld ){
37896 rc = proxyReleaseConch(pFile);
37897 if( rc ) return rc;
37899 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
37900 if( rc ) return rc;
37901 sqlite3_free(conchFile);
37903 sqlite3DbFree(0, pCtx->lockProxyPath);
37904 sqlite3_free(pCtx->conchFilePath);
37905 sqlite3DbFree(0, pCtx->dbPath);
37906 /* restore the original locking context and pMethod then close it */
37907 pFile->lockingContext = pCtx->oldLockingContext;
37908 pFile->pMethod = pCtx->pOldMethod;
37909 sqlite3_free(pCtx);
37910 return pFile->pMethod->xClose(id);
37912 return SQLITE_OK;
37917 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
37919 ** The proxy locking style is intended for use with AFP filesystems.
37920 ** And since AFP is only supported on MacOSX, the proxy locking is also
37921 ** restricted to MacOSX.
37924 ******************* End of the proxy lock implementation **********************
37925 ******************************************************************************/
37928 ** Initialize the operating system interface.
37930 ** This routine registers all VFS implementations for unix-like operating
37931 ** systems. This routine, and the sqlite3_os_end() routine that follows,
37932 ** should be the only routines in this file that are visible from other
37933 ** files.
37935 ** This routine is called once during SQLite initialization and by a
37936 ** single thread. The memory allocation and mutex subsystems have not
37937 ** necessarily been initialized when this routine is called, and so they
37938 ** should not be used.
37940 SQLITE_API int sqlite3_os_init(void){
37942 ** The following macro defines an initializer for an sqlite3_vfs object.
37943 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
37944 ** to the "finder" function. (pAppData is a pointer to a pointer because
37945 ** silly C90 rules prohibit a void* from being cast to a function pointer
37946 ** and so we have to go through the intermediate pointer to avoid problems
37947 ** when compiling with -pedantic-errors on GCC.)
37949 ** The FINDER parameter to this macro is the name of the pointer to the
37950 ** finder-function. The finder-function returns a pointer to the
37951 ** sqlite_io_methods object that implements the desired locking
37952 ** behaviors. See the division above that contains the IOMETHODS
37953 ** macro for addition information on finder-functions.
37955 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
37956 ** object. But the "autolockIoFinder" available on MacOSX does a little
37957 ** more than that; it looks at the filesystem type that hosts the
37958 ** database file and tries to choose an locking method appropriate for
37959 ** that filesystem time.
37961 #define UNIXVFS(VFSNAME, FINDER) { \
37962 3, /* iVersion */ \
37963 sizeof(unixFile), /* szOsFile */ \
37964 MAX_PATHNAME, /* mxPathname */ \
37965 0, /* pNext */ \
37966 VFSNAME, /* zName */ \
37967 (void*)&FINDER, /* pAppData */ \
37968 unixOpen, /* xOpen */ \
37969 unixDelete, /* xDelete */ \
37970 unixAccess, /* xAccess */ \
37971 unixFullPathname, /* xFullPathname */ \
37972 unixDlOpen, /* xDlOpen */ \
37973 unixDlError, /* xDlError */ \
37974 unixDlSym, /* xDlSym */ \
37975 unixDlClose, /* xDlClose */ \
37976 unixRandomness, /* xRandomness */ \
37977 unixSleep, /* xSleep */ \
37978 unixCurrentTime, /* xCurrentTime */ \
37979 unixGetLastError, /* xGetLastError */ \
37980 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
37981 unixSetSystemCall, /* xSetSystemCall */ \
37982 unixGetSystemCall, /* xGetSystemCall */ \
37983 unixNextSystemCall, /* xNextSystemCall */ \
37987 ** All default VFSes for unix are contained in the following array.
37989 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
37990 ** by the SQLite core when the VFS is registered. So the following
37991 ** array cannot be const.
37993 static sqlite3_vfs aVfs[] = {
37994 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
37995 UNIXVFS("unix", autolockIoFinder ),
37996 #elif OS_VXWORKS
37997 UNIXVFS("unix", vxworksIoFinder ),
37998 #else
37999 UNIXVFS("unix", posixIoFinder ),
38000 #endif
38001 UNIXVFS("unix-none", nolockIoFinder ),
38002 UNIXVFS("unix-dotfile", dotlockIoFinder ),
38003 UNIXVFS("unix-excl", posixIoFinder ),
38004 #if OS_VXWORKS
38005 UNIXVFS("unix-namedsem", semIoFinder ),
38006 #endif
38007 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
38008 UNIXVFS("unix-posix", posixIoFinder ),
38009 #endif
38010 #if SQLITE_ENABLE_LOCKING_STYLE
38011 UNIXVFS("unix-flock", flockIoFinder ),
38012 #endif
38013 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
38014 UNIXVFS("unix-afp", afpIoFinder ),
38015 UNIXVFS("unix-nfs", nfsIoFinder ),
38016 UNIXVFS("unix-proxy", proxyIoFinder ),
38017 #endif
38019 unsigned int i; /* Loop counter */
38021 /* Double-check that the aSyscall[] array has been constructed
38022 ** correctly. See ticket [bb3a86e890c8e96ab] */
38023 assert( ArraySize(aSyscall)==29 );
38025 /* Register all VFSes defined in the aVfs[] array */
38026 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
38027 sqlite3_vfs_register(&aVfs[i], i==0);
38029 return SQLITE_OK;
38033 ** Shutdown the operating system interface.
38035 ** Some operating systems might need to do some cleanup in this routine,
38036 ** to release dynamically allocated objects. But not on unix.
38037 ** This routine is a no-op for unix.
38039 SQLITE_API int sqlite3_os_end(void){
38040 return SQLITE_OK;
38043 #endif /* SQLITE_OS_UNIX */
38045 /************** End of os_unix.c *********************************************/
38046 /************** Begin file os_win.c ******************************************/
38048 ** 2004 May 22
38050 ** The author disclaims copyright to this source code. In place of
38051 ** a legal notice, here is a blessing:
38053 ** May you do good and not evil.
38054 ** May you find forgiveness for yourself and forgive others.
38055 ** May you share freely, never taking more than you give.
38057 ******************************************************************************
38059 ** This file contains code that is specific to Windows.
38061 /* #include "sqliteInt.h" */
38062 #if SQLITE_OS_WIN /* This file is used for Windows only */
38065 ** Include code that is common to all os_*.c files
38067 /************** Include os_common.h in the middle of os_win.c ****************/
38068 /************** Begin file os_common.h ***************************************/
38070 ** 2004 May 22
38072 ** The author disclaims copyright to this source code. In place of
38073 ** a legal notice, here is a blessing:
38075 ** May you do good and not evil.
38076 ** May you find forgiveness for yourself and forgive others.
38077 ** May you share freely, never taking more than you give.
38079 ******************************************************************************
38081 ** This file contains macros and a little bit of code that is common to
38082 ** all of the platform-specific files (os_*.c) and is #included into those
38083 ** files.
38085 ** This file should be #included by the os_*.c files only. It is not a
38086 ** general purpose header file.
38088 #ifndef _OS_COMMON_H_
38089 #define _OS_COMMON_H_
38092 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
38093 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
38094 ** switch. The following code should catch this problem at compile-time.
38096 #ifdef MEMORY_DEBUG
38097 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
38098 #endif
38101 ** Macros for performance tracing. Normally turned off. Only works
38102 ** on i486 hardware.
38104 #ifdef SQLITE_PERFORMANCE_TRACE
38107 ** hwtime.h contains inline assembler code for implementing
38108 ** high-performance timing routines.
38110 /************** Include hwtime.h in the middle of os_common.h ****************/
38111 /************** Begin file hwtime.h ******************************************/
38113 ** 2008 May 27
38115 ** The author disclaims copyright to this source code. In place of
38116 ** a legal notice, here is a blessing:
38118 ** May you do good and not evil.
38119 ** May you find forgiveness for yourself and forgive others.
38120 ** May you share freely, never taking more than you give.
38122 ******************************************************************************
38124 ** This file contains inline asm code for retrieving "high-performance"
38125 ** counters for x86 class CPUs.
38127 #ifndef SQLITE_HWTIME_H
38128 #define SQLITE_HWTIME_H
38131 ** The following routine only works on pentium-class (or newer) processors.
38132 ** It uses the RDTSC opcode to read the cycle count value out of the
38133 ** processor and returns that value. This can be used for high-res
38134 ** profiling.
38136 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
38137 (defined(i386) || defined(__i386__) || defined(_M_IX86))
38139 #if defined(__GNUC__)
38141 __inline__ sqlite_uint64 sqlite3Hwtime(void){
38142 unsigned int lo, hi;
38143 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
38144 return (sqlite_uint64)hi << 32 | lo;
38147 #elif defined(_MSC_VER)
38149 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
38150 __asm {
38151 rdtsc
38152 ret ; return value at EDX:EAX
38156 #endif
38158 #elif (defined(__GNUC__) && defined(__x86_64__))
38160 __inline__ sqlite_uint64 sqlite3Hwtime(void){
38161 unsigned long val;
38162 __asm__ __volatile__ ("rdtsc" : "=A" (val));
38163 return val;
38166 #elif (defined(__GNUC__) && defined(__ppc__))
38168 __inline__ sqlite_uint64 sqlite3Hwtime(void){
38169 unsigned long long retval;
38170 unsigned long junk;
38171 __asm__ __volatile__ ("\n\
38172 1: mftbu %1\n\
38173 mftb %L0\n\
38174 mftbu %0\n\
38175 cmpw %0,%1\n\
38176 bne 1b"
38177 : "=r" (retval), "=r" (junk));
38178 return retval;
38181 #else
38183 #error Need implementation of sqlite3Hwtime() for your platform.
38186 ** To compile without implementing sqlite3Hwtime() for your platform,
38187 ** you can remove the above #error and use the following
38188 ** stub function. You will lose timing support for many
38189 ** of the debugging and testing utilities, but it should at
38190 ** least compile and run.
38192 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
38194 #endif
38196 #endif /* !defined(SQLITE_HWTIME_H) */
38198 /************** End of hwtime.h **********************************************/
38199 /************** Continuing where we left off in os_common.h ******************/
38201 static sqlite_uint64 g_start;
38202 static sqlite_uint64 g_elapsed;
38203 #define TIMER_START g_start=sqlite3Hwtime()
38204 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
38205 #define TIMER_ELAPSED g_elapsed
38206 #else
38207 #define TIMER_START
38208 #define TIMER_END
38209 #define TIMER_ELAPSED ((sqlite_uint64)0)
38210 #endif
38213 ** If we compile with the SQLITE_TEST macro set, then the following block
38214 ** of code will give us the ability to simulate a disk I/O error. This
38215 ** is used for testing the I/O recovery logic.
38217 #if defined(SQLITE_TEST)
38218 SQLITE_API extern int sqlite3_io_error_hit;
38219 SQLITE_API extern int sqlite3_io_error_hardhit;
38220 SQLITE_API extern int sqlite3_io_error_pending;
38221 SQLITE_API extern int sqlite3_io_error_persist;
38222 SQLITE_API extern int sqlite3_io_error_benign;
38223 SQLITE_API extern int sqlite3_diskfull_pending;
38224 SQLITE_API extern int sqlite3_diskfull;
38225 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
38226 #define SimulateIOError(CODE) \
38227 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
38228 || sqlite3_io_error_pending-- == 1 ) \
38229 { local_ioerr(); CODE; }
38230 static void local_ioerr(){
38231 IOTRACE(("IOERR\n"));
38232 sqlite3_io_error_hit++;
38233 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
38235 #define SimulateDiskfullError(CODE) \
38236 if( sqlite3_diskfull_pending ){ \
38237 if( sqlite3_diskfull_pending == 1 ){ \
38238 local_ioerr(); \
38239 sqlite3_diskfull = 1; \
38240 sqlite3_io_error_hit = 1; \
38241 CODE; \
38242 }else{ \
38243 sqlite3_diskfull_pending--; \
38246 #else
38247 #define SimulateIOErrorBenign(X)
38248 #define SimulateIOError(A)
38249 #define SimulateDiskfullError(A)
38250 #endif /* defined(SQLITE_TEST) */
38253 ** When testing, keep a count of the number of open files.
38255 #if defined(SQLITE_TEST)
38256 SQLITE_API extern int sqlite3_open_file_count;
38257 #define OpenCounter(X) sqlite3_open_file_count+=(X)
38258 #else
38259 #define OpenCounter(X)
38260 #endif /* defined(SQLITE_TEST) */
38262 #endif /* !defined(_OS_COMMON_H_) */
38264 /************** End of os_common.h *******************************************/
38265 /************** Continuing where we left off in os_win.c *********************/
38268 ** Include the header file for the Windows VFS.
38270 /* #include "os_win.h" */
38273 ** Compiling and using WAL mode requires several APIs that are only
38274 ** available in Windows platforms based on the NT kernel.
38276 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
38277 # error "WAL mode requires support from the Windows NT kernel, compile\
38278 with SQLITE_OMIT_WAL."
38279 #endif
38281 #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
38282 # error "Memory mapped files require support from the Windows NT kernel,\
38283 compile with SQLITE_MAX_MMAP_SIZE=0."
38284 #endif
38287 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
38288 ** based on the sub-platform)?
38290 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
38291 # define SQLITE_WIN32_HAS_ANSI
38292 #endif
38295 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
38296 ** based on the sub-platform)?
38298 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
38299 !defined(SQLITE_WIN32_NO_WIDE)
38300 # define SQLITE_WIN32_HAS_WIDE
38301 #endif
38304 ** Make sure at least one set of Win32 APIs is available.
38306 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
38307 # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
38308 must be defined."
38309 #endif
38312 ** Define the required Windows SDK version constants if they are not
38313 ** already available.
38315 #ifndef NTDDI_WIN8
38316 # define NTDDI_WIN8 0x06020000
38317 #endif
38319 #ifndef NTDDI_WINBLUE
38320 # define NTDDI_WINBLUE 0x06030000
38321 #endif
38323 #ifndef NTDDI_WINTHRESHOLD
38324 # define NTDDI_WINTHRESHOLD 0x06040000
38325 #endif
38328 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
38329 ** target system. GetVersionEx was first deprecated in Win8.1.
38331 #ifndef SQLITE_WIN32_GETVERSIONEX
38332 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
38333 # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
38334 # else
38335 # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
38336 # endif
38337 #endif
38340 ** Check to see if the CreateFileMappingA function is supported on the
38341 ** target system. It is unavailable when using "mincore.lib" on Win10.
38342 ** When compiling for Windows 10, always assume "mincore.lib" is in use.
38344 #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
38345 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
38346 # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
38347 # else
38348 # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
38349 # endif
38350 #endif
38353 ** This constant should already be defined (in the "WinDef.h" SDK file).
38355 #ifndef MAX_PATH
38356 # define MAX_PATH (260)
38357 #endif
38360 ** Maximum pathname length (in chars) for Win32. This should normally be
38361 ** MAX_PATH.
38363 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
38364 # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
38365 #endif
38368 ** This constant should already be defined (in the "WinNT.h" SDK file).
38370 #ifndef UNICODE_STRING_MAX_CHARS
38371 # define UNICODE_STRING_MAX_CHARS (32767)
38372 #endif
38375 ** Maximum pathname length (in chars) for WinNT. This should normally be
38376 ** UNICODE_STRING_MAX_CHARS.
38378 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
38379 # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
38380 #endif
38383 ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
38384 ** characters, so we allocate 4 bytes per character assuming worst-case of
38385 ** 4-bytes-per-character for UTF8.
38387 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
38388 # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
38389 #endif
38392 ** Maximum pathname length (in bytes) for WinNT. This should normally be
38393 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
38395 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
38396 # define SQLITE_WINNT_MAX_PATH_BYTES \
38397 (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
38398 #endif
38401 ** Maximum error message length (in chars) for WinRT.
38403 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
38404 # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
38405 #endif
38408 ** Returns non-zero if the character should be treated as a directory
38409 ** separator.
38411 #ifndef winIsDirSep
38412 # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
38413 #endif
38416 ** This macro is used when a local variable is set to a value that is
38417 ** [sometimes] not used by the code (e.g. via conditional compilation).
38419 #ifndef UNUSED_VARIABLE_VALUE
38420 # define UNUSED_VARIABLE_VALUE(x) (void)(x)
38421 #endif
38424 ** Returns the character that should be used as the directory separator.
38426 #ifndef winGetDirSep
38427 # define winGetDirSep() '\\'
38428 #endif
38431 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
38432 ** mode or memory mapped files (e.g. these APIs are available in the Windows
38433 ** CE SDK; however, they are not present in the header file)?
38435 #if SQLITE_WIN32_FILEMAPPING_API && \
38436 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38438 ** Two of the file mapping APIs are different under WinRT. Figure out which
38439 ** set we need.
38441 #if SQLITE_OS_WINRT
38442 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
38443 LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
38445 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
38446 #else
38447 #if defined(SQLITE_WIN32_HAS_ANSI)
38448 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
38449 DWORD, DWORD, DWORD, LPCSTR);
38450 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
38452 #if defined(SQLITE_WIN32_HAS_WIDE)
38453 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
38454 DWORD, DWORD, DWORD, LPCWSTR);
38455 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
38457 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
38458 #endif /* SQLITE_OS_WINRT */
38461 ** These file mapping APIs are common to both Win32 and WinRT.
38464 WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
38465 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
38466 #endif /* SQLITE_WIN32_FILEMAPPING_API */
38469 ** Some Microsoft compilers lack this definition.
38471 #ifndef INVALID_FILE_ATTRIBUTES
38472 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
38473 #endif
38475 #ifndef FILE_FLAG_MASK
38476 # define FILE_FLAG_MASK (0xFF3C0000)
38477 #endif
38479 #ifndef FILE_ATTRIBUTE_MASK
38480 # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
38481 #endif
38483 #ifndef SQLITE_OMIT_WAL
38484 /* Forward references to structures used for WAL */
38485 typedef struct winShm winShm; /* A connection to shared-memory */
38486 typedef struct winShmNode winShmNode; /* A region of shared-memory */
38487 #endif
38490 ** WinCE lacks native support for file locking so we have to fake it
38491 ** with some code of our own.
38493 #if SQLITE_OS_WINCE
38494 typedef struct winceLock {
38495 int nReaders; /* Number of reader locks obtained */
38496 BOOL bPending; /* Indicates a pending lock has been obtained */
38497 BOOL bReserved; /* Indicates a reserved lock has been obtained */
38498 BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
38499 } winceLock;
38500 #endif
38503 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
38504 ** portability layer.
38506 typedef struct winFile winFile;
38507 struct winFile {
38508 const sqlite3_io_methods *pMethod; /*** Must be first ***/
38509 sqlite3_vfs *pVfs; /* The VFS used to open this file */
38510 HANDLE h; /* Handle for accessing the file */
38511 u8 locktype; /* Type of lock currently held on this file */
38512 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
38513 u8 ctrlFlags; /* Flags. See WINFILE_* below */
38514 DWORD lastErrno; /* The Windows errno from the last I/O error */
38515 #ifndef SQLITE_OMIT_WAL
38516 winShm *pShm; /* Instance of shared memory on this file */
38517 #endif
38518 const char *zPath; /* Full pathname of this file */
38519 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
38520 #if SQLITE_OS_WINCE
38521 LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
38522 HANDLE hMutex; /* Mutex used to control access to shared lock */
38523 HANDLE hShared; /* Shared memory segment used for locking */
38524 winceLock local; /* Locks obtained by this instance of winFile */
38525 winceLock *shared; /* Global shared lock memory for the file */
38526 #endif
38527 #if SQLITE_MAX_MMAP_SIZE>0
38528 int nFetchOut; /* Number of outstanding xFetch references */
38529 HANDLE hMap; /* Handle for accessing memory mapping */
38530 void *pMapRegion; /* Area memory mapped */
38531 sqlite3_int64 mmapSize; /* Usable size of mapped region */
38532 sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
38533 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
38534 #endif
38538 ** The winVfsAppData structure is used for the pAppData member for all of the
38539 ** Win32 VFS variants.
38541 typedef struct winVfsAppData winVfsAppData;
38542 struct winVfsAppData {
38543 const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
38544 void *pAppData; /* The extra pAppData, if any. */
38545 BOOL bNoLock; /* Non-zero if locking is disabled. */
38549 ** Allowed values for winFile.ctrlFlags
38551 #define WINFILE_RDONLY 0x02 /* Connection is read only */
38552 #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
38553 #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
38556 * The size of the buffer used by sqlite3_win32_write_debug().
38558 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
38559 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
38560 #endif
38563 * The value used with sqlite3_win32_set_directory() to specify that
38564 * the data directory should be changed.
38566 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
38567 # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
38568 #endif
38571 * The value used with sqlite3_win32_set_directory() to specify that
38572 * the temporary directory should be changed.
38574 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
38575 # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
38576 #endif
38579 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
38580 * various Win32 API heap functions instead of our own.
38582 #ifdef SQLITE_WIN32_MALLOC
38585 * If this is non-zero, an isolated heap will be created by the native Win32
38586 * allocator subsystem; otherwise, the default process heap will be used. This
38587 * setting has no effect when compiling for WinRT. By default, this is enabled
38588 * and an isolated heap will be created to store all allocated data.
38590 ******************************************************************************
38591 * WARNING: It is important to note that when this setting is non-zero and the
38592 * winMemShutdown function is called (e.g. by the sqlite3_shutdown
38593 * function), all data that was allocated using the isolated heap will
38594 * be freed immediately and any attempt to access any of that freed
38595 * data will almost certainly result in an immediate access violation.
38596 ******************************************************************************
38598 #ifndef SQLITE_WIN32_HEAP_CREATE
38599 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
38600 #endif
38603 * This is the maximum possible initial size of the Win32-specific heap, in
38604 * bytes.
38606 #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
38607 # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
38608 #endif
38611 * This is the extra space for the initial size of the Win32-specific heap,
38612 * in bytes. This value may be zero.
38614 #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
38615 # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
38616 #endif
38619 * Calculate the maximum legal cache size, in pages, based on the maximum
38620 * possible initial heap size and the default page size, setting aside the
38621 * needed extra space.
38623 #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
38624 # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
38625 (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
38626 (SQLITE_DEFAULT_PAGE_SIZE))
38627 #endif
38630 * This is cache size used in the calculation of the initial size of the
38631 * Win32-specific heap. It cannot be negative.
38633 #ifndef SQLITE_WIN32_CACHE_SIZE
38634 # if SQLITE_DEFAULT_CACHE_SIZE>=0
38635 # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
38636 # else
38637 # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
38638 # endif
38639 #endif
38642 * Make sure that the calculated cache size, in pages, cannot cause the
38643 * initial size of the Win32-specific heap to exceed the maximum amount
38644 * of memory that can be specified in the call to HeapCreate.
38646 #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
38647 # undef SQLITE_WIN32_CACHE_SIZE
38648 # define SQLITE_WIN32_CACHE_SIZE (2000)
38649 #endif
38652 * The initial size of the Win32-specific heap. This value may be zero.
38654 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
38655 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
38656 (SQLITE_DEFAULT_PAGE_SIZE) + \
38657 (SQLITE_WIN32_HEAP_INIT_EXTRA))
38658 #endif
38661 * The maximum size of the Win32-specific heap. This value may be zero.
38663 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
38664 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
38665 #endif
38668 * The extra flags to use in calls to the Win32 heap APIs. This value may be
38669 * zero for the default behavior.
38671 #ifndef SQLITE_WIN32_HEAP_FLAGS
38672 # define SQLITE_WIN32_HEAP_FLAGS (0)
38673 #endif
38677 ** The winMemData structure stores information required by the Win32-specific
38678 ** sqlite3_mem_methods implementation.
38680 typedef struct winMemData winMemData;
38681 struct winMemData {
38682 #ifndef NDEBUG
38683 u32 magic1; /* Magic number to detect structure corruption. */
38684 #endif
38685 HANDLE hHeap; /* The handle to our heap. */
38686 BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
38687 #ifndef NDEBUG
38688 u32 magic2; /* Magic number to detect structure corruption. */
38689 #endif
38692 #ifndef NDEBUG
38693 #define WINMEM_MAGIC1 0x42b2830b
38694 #define WINMEM_MAGIC2 0xbd4d7cf4
38695 #endif
38697 static struct winMemData win_mem_data = {
38698 #ifndef NDEBUG
38699 WINMEM_MAGIC1,
38700 #endif
38701 NULL, FALSE
38702 #ifndef NDEBUG
38703 ,WINMEM_MAGIC2
38704 #endif
38707 #ifndef NDEBUG
38708 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
38709 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
38710 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
38711 #else
38712 #define winMemAssertMagic()
38713 #endif
38715 #define winMemGetDataPtr() &win_mem_data
38716 #define winMemGetHeap() win_mem_data.hHeap
38717 #define winMemGetOwned() win_mem_data.bOwned
38719 static void *winMemMalloc(int nBytes);
38720 static void winMemFree(void *pPrior);
38721 static void *winMemRealloc(void *pPrior, int nBytes);
38722 static int winMemSize(void *p);
38723 static int winMemRoundup(int n);
38724 static int winMemInit(void *pAppData);
38725 static void winMemShutdown(void *pAppData);
38727 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
38728 #endif /* SQLITE_WIN32_MALLOC */
38731 ** The following variable is (normally) set once and never changes
38732 ** thereafter. It records whether the operating system is Win9x
38733 ** or WinNT.
38735 ** 0: Operating system unknown.
38736 ** 1: Operating system is Win9x.
38737 ** 2: Operating system is WinNT.
38739 ** In order to facilitate testing on a WinNT system, the test fixture
38740 ** can manually set this value to 1 to emulate Win98 behavior.
38742 #ifdef SQLITE_TEST
38743 SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
38744 #else
38745 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
38746 #endif
38748 #ifndef SYSCALL
38749 # define SYSCALL sqlite3_syscall_ptr
38750 #endif
38753 ** This function is not available on Windows CE or WinRT.
38756 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
38757 # define osAreFileApisANSI() 1
38758 #endif
38761 ** Many system calls are accessed through pointer-to-functions so that
38762 ** they may be overridden at runtime to facilitate fault injection during
38763 ** testing and sandboxing. The following array holds the names and pointers
38764 ** to all overrideable system calls.
38766 static struct win_syscall {
38767 const char *zName; /* Name of the system call */
38768 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
38769 sqlite3_syscall_ptr pDefault; /* Default value */
38770 } aSyscall[] = {
38771 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38772 { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
38773 #else
38774 { "AreFileApisANSI", (SYSCALL)0, 0 },
38775 #endif
38777 #ifndef osAreFileApisANSI
38778 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
38779 #endif
38781 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
38782 { "CharLowerW", (SYSCALL)CharLowerW, 0 },
38783 #else
38784 { "CharLowerW", (SYSCALL)0, 0 },
38785 #endif
38787 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
38789 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
38790 { "CharUpperW", (SYSCALL)CharUpperW, 0 },
38791 #else
38792 { "CharUpperW", (SYSCALL)0, 0 },
38793 #endif
38795 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
38797 { "CloseHandle", (SYSCALL)CloseHandle, 0 },
38799 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
38801 #if defined(SQLITE_WIN32_HAS_ANSI)
38802 { "CreateFileA", (SYSCALL)CreateFileA, 0 },
38803 #else
38804 { "CreateFileA", (SYSCALL)0, 0 },
38805 #endif
38807 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
38808 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
38810 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38811 { "CreateFileW", (SYSCALL)CreateFileW, 0 },
38812 #else
38813 { "CreateFileW", (SYSCALL)0, 0 },
38814 #endif
38816 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
38817 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
38819 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
38820 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
38821 SQLITE_WIN32_CREATEFILEMAPPINGA
38822 { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
38823 #else
38824 { "CreateFileMappingA", (SYSCALL)0, 0 },
38825 #endif
38827 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
38828 DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
38830 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
38831 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
38832 { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
38833 #else
38834 { "CreateFileMappingW", (SYSCALL)0, 0 },
38835 #endif
38837 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
38838 DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
38840 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38841 { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
38842 #else
38843 { "CreateMutexW", (SYSCALL)0, 0 },
38844 #endif
38846 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
38847 LPCWSTR))aSyscall[8].pCurrent)
38849 #if defined(SQLITE_WIN32_HAS_ANSI)
38850 { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
38851 #else
38852 { "DeleteFileA", (SYSCALL)0, 0 },
38853 #endif
38855 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
38857 #if defined(SQLITE_WIN32_HAS_WIDE)
38858 { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
38859 #else
38860 { "DeleteFileW", (SYSCALL)0, 0 },
38861 #endif
38863 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
38865 #if SQLITE_OS_WINCE
38866 { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
38867 #else
38868 { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
38869 #endif
38871 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
38872 LPFILETIME))aSyscall[11].pCurrent)
38874 #if SQLITE_OS_WINCE
38875 { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
38876 #else
38877 { "FileTimeToSystemTime", (SYSCALL)0, 0 },
38878 #endif
38880 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
38881 LPSYSTEMTIME))aSyscall[12].pCurrent)
38883 { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
38885 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
38887 #if defined(SQLITE_WIN32_HAS_ANSI)
38888 { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
38889 #else
38890 { "FormatMessageA", (SYSCALL)0, 0 },
38891 #endif
38893 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
38894 DWORD,va_list*))aSyscall[14].pCurrent)
38896 #if defined(SQLITE_WIN32_HAS_WIDE)
38897 { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
38898 #else
38899 { "FormatMessageW", (SYSCALL)0, 0 },
38900 #endif
38902 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
38903 DWORD,va_list*))aSyscall[15].pCurrent)
38905 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
38906 { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
38907 #else
38908 { "FreeLibrary", (SYSCALL)0, 0 },
38909 #endif
38911 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
38913 { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
38915 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
38917 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
38918 { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
38919 #else
38920 { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
38921 #endif
38923 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
38924 LPDWORD))aSyscall[18].pCurrent)
38926 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38927 { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
38928 #else
38929 { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
38930 #endif
38932 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
38933 LPDWORD))aSyscall[19].pCurrent)
38935 #if defined(SQLITE_WIN32_HAS_ANSI)
38936 { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
38937 #else
38938 { "GetFileAttributesA", (SYSCALL)0, 0 },
38939 #endif
38941 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
38943 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38944 { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
38945 #else
38946 { "GetFileAttributesW", (SYSCALL)0, 0 },
38947 #endif
38949 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
38951 #if defined(SQLITE_WIN32_HAS_WIDE)
38952 { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
38953 #else
38954 { "GetFileAttributesExW", (SYSCALL)0, 0 },
38955 #endif
38957 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
38958 LPVOID))aSyscall[22].pCurrent)
38960 #if !SQLITE_OS_WINRT
38961 { "GetFileSize", (SYSCALL)GetFileSize, 0 },
38962 #else
38963 { "GetFileSize", (SYSCALL)0, 0 },
38964 #endif
38966 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
38968 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
38969 { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
38970 #else
38971 { "GetFullPathNameA", (SYSCALL)0, 0 },
38972 #endif
38974 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
38975 LPSTR*))aSyscall[24].pCurrent)
38977 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38978 { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
38979 #else
38980 { "GetFullPathNameW", (SYSCALL)0, 0 },
38981 #endif
38983 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
38984 LPWSTR*))aSyscall[25].pCurrent)
38986 { "GetLastError", (SYSCALL)GetLastError, 0 },
38988 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
38990 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
38991 #if SQLITE_OS_WINCE
38992 /* The GetProcAddressA() routine is only available on Windows CE. */
38993 { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
38994 #else
38995 /* All other Windows platforms expect GetProcAddress() to take
38996 ** an ANSI string regardless of the _UNICODE setting */
38997 { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
38998 #endif
38999 #else
39000 { "GetProcAddressA", (SYSCALL)0, 0 },
39001 #endif
39003 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
39004 LPCSTR))aSyscall[27].pCurrent)
39006 #if !SQLITE_OS_WINRT
39007 { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
39008 #else
39009 { "GetSystemInfo", (SYSCALL)0, 0 },
39010 #endif
39012 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
39014 { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
39016 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
39018 #if !SQLITE_OS_WINCE
39019 { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
39020 #else
39021 { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
39022 #endif
39024 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
39025 LPFILETIME))aSyscall[30].pCurrent)
39027 #if defined(SQLITE_WIN32_HAS_ANSI)
39028 { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
39029 #else
39030 { "GetTempPathA", (SYSCALL)0, 0 },
39031 #endif
39033 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
39035 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
39036 { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
39037 #else
39038 { "GetTempPathW", (SYSCALL)0, 0 },
39039 #endif
39041 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
39043 #if !SQLITE_OS_WINRT
39044 { "GetTickCount", (SYSCALL)GetTickCount, 0 },
39045 #else
39046 { "GetTickCount", (SYSCALL)0, 0 },
39047 #endif
39049 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
39051 #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
39052 { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
39053 #else
39054 { "GetVersionExA", (SYSCALL)0, 0 },
39055 #endif
39057 #define osGetVersionExA ((BOOL(WINAPI*)( \
39058 LPOSVERSIONINFOA))aSyscall[34].pCurrent)
39060 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
39061 SQLITE_WIN32_GETVERSIONEX
39062 { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
39063 #else
39064 { "GetVersionExW", (SYSCALL)0, 0 },
39065 #endif
39067 #define osGetVersionExW ((BOOL(WINAPI*)( \
39068 LPOSVERSIONINFOW))aSyscall[35].pCurrent)
39070 { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
39072 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
39073 SIZE_T))aSyscall[36].pCurrent)
39075 #if !SQLITE_OS_WINRT
39076 { "HeapCreate", (SYSCALL)HeapCreate, 0 },
39077 #else
39078 { "HeapCreate", (SYSCALL)0, 0 },
39079 #endif
39081 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
39082 SIZE_T))aSyscall[37].pCurrent)
39084 #if !SQLITE_OS_WINRT
39085 { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
39086 #else
39087 { "HeapDestroy", (SYSCALL)0, 0 },
39088 #endif
39090 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
39092 { "HeapFree", (SYSCALL)HeapFree, 0 },
39094 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
39096 { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
39098 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
39099 SIZE_T))aSyscall[40].pCurrent)
39101 { "HeapSize", (SYSCALL)HeapSize, 0 },
39103 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
39104 LPCVOID))aSyscall[41].pCurrent)
39106 #if !SQLITE_OS_WINRT
39107 { "HeapValidate", (SYSCALL)HeapValidate, 0 },
39108 #else
39109 { "HeapValidate", (SYSCALL)0, 0 },
39110 #endif
39112 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
39113 LPCVOID))aSyscall[42].pCurrent)
39115 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
39116 { "HeapCompact", (SYSCALL)HeapCompact, 0 },
39117 #else
39118 { "HeapCompact", (SYSCALL)0, 0 },
39119 #endif
39121 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
39123 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
39124 { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
39125 #else
39126 { "LoadLibraryA", (SYSCALL)0, 0 },
39127 #endif
39129 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
39131 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
39132 !defined(SQLITE_OMIT_LOAD_EXTENSION)
39133 { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
39134 #else
39135 { "LoadLibraryW", (SYSCALL)0, 0 },
39136 #endif
39138 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
39140 #if !SQLITE_OS_WINRT
39141 { "LocalFree", (SYSCALL)LocalFree, 0 },
39142 #else
39143 { "LocalFree", (SYSCALL)0, 0 },
39144 #endif
39146 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
39148 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
39149 { "LockFile", (SYSCALL)LockFile, 0 },
39150 #else
39151 { "LockFile", (SYSCALL)0, 0 },
39152 #endif
39154 #ifndef osLockFile
39155 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
39156 DWORD))aSyscall[47].pCurrent)
39157 #endif
39159 #if !SQLITE_OS_WINCE
39160 { "LockFileEx", (SYSCALL)LockFileEx, 0 },
39161 #else
39162 { "LockFileEx", (SYSCALL)0, 0 },
39163 #endif
39165 #ifndef osLockFileEx
39166 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
39167 LPOVERLAPPED))aSyscall[48].pCurrent)
39168 #endif
39170 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
39171 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
39172 { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
39173 #else
39174 { "MapViewOfFile", (SYSCALL)0, 0 },
39175 #endif
39177 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
39178 SIZE_T))aSyscall[49].pCurrent)
39180 { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
39182 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
39183 int))aSyscall[50].pCurrent)
39185 { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
39187 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
39188 LARGE_INTEGER*))aSyscall[51].pCurrent)
39190 { "ReadFile", (SYSCALL)ReadFile, 0 },
39192 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
39193 LPOVERLAPPED))aSyscall[52].pCurrent)
39195 { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
39197 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
39199 #if !SQLITE_OS_WINRT
39200 { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
39201 #else
39202 { "SetFilePointer", (SYSCALL)0, 0 },
39203 #endif
39205 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
39206 DWORD))aSyscall[54].pCurrent)
39208 #if !SQLITE_OS_WINRT
39209 { "Sleep", (SYSCALL)Sleep, 0 },
39210 #else
39211 { "Sleep", (SYSCALL)0, 0 },
39212 #endif
39214 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
39216 { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
39218 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
39219 LPFILETIME))aSyscall[56].pCurrent)
39221 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
39222 { "UnlockFile", (SYSCALL)UnlockFile, 0 },
39223 #else
39224 { "UnlockFile", (SYSCALL)0, 0 },
39225 #endif
39227 #ifndef osUnlockFile
39228 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
39229 DWORD))aSyscall[57].pCurrent)
39230 #endif
39232 #if !SQLITE_OS_WINCE
39233 { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
39234 #else
39235 { "UnlockFileEx", (SYSCALL)0, 0 },
39236 #endif
39238 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
39239 LPOVERLAPPED))aSyscall[58].pCurrent)
39241 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
39242 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
39243 #else
39244 { "UnmapViewOfFile", (SYSCALL)0, 0 },
39245 #endif
39247 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
39249 { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
39251 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
39252 LPCSTR,LPBOOL))aSyscall[60].pCurrent)
39254 { "WriteFile", (SYSCALL)WriteFile, 0 },
39256 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
39257 LPOVERLAPPED))aSyscall[61].pCurrent)
39259 #if SQLITE_OS_WINRT
39260 { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
39261 #else
39262 { "CreateEventExW", (SYSCALL)0, 0 },
39263 #endif
39265 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
39266 DWORD,DWORD))aSyscall[62].pCurrent)
39268 #if !SQLITE_OS_WINRT
39269 { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
39270 #else
39271 { "WaitForSingleObject", (SYSCALL)0, 0 },
39272 #endif
39274 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
39275 DWORD))aSyscall[63].pCurrent)
39277 #if !SQLITE_OS_WINCE
39278 { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
39279 #else
39280 { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
39281 #endif
39283 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
39284 BOOL))aSyscall[64].pCurrent)
39286 #if SQLITE_OS_WINRT
39287 { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
39288 #else
39289 { "SetFilePointerEx", (SYSCALL)0, 0 },
39290 #endif
39292 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
39293 PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
39295 #if SQLITE_OS_WINRT
39296 { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
39297 #else
39298 { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
39299 #endif
39301 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
39302 FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
39304 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
39305 { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
39306 #else
39307 { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
39308 #endif
39310 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
39311 SIZE_T))aSyscall[67].pCurrent)
39313 #if SQLITE_OS_WINRT
39314 { "CreateFile2", (SYSCALL)CreateFile2, 0 },
39315 #else
39316 { "CreateFile2", (SYSCALL)0, 0 },
39317 #endif
39319 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
39320 LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
39322 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
39323 { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
39324 #else
39325 { "LoadPackagedLibrary", (SYSCALL)0, 0 },
39326 #endif
39328 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
39329 DWORD))aSyscall[69].pCurrent)
39331 #if SQLITE_OS_WINRT
39332 { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
39333 #else
39334 { "GetTickCount64", (SYSCALL)0, 0 },
39335 #endif
39337 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
39339 #if SQLITE_OS_WINRT
39340 { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
39341 #else
39342 { "GetNativeSystemInfo", (SYSCALL)0, 0 },
39343 #endif
39345 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
39346 LPSYSTEM_INFO))aSyscall[71].pCurrent)
39348 #if defined(SQLITE_WIN32_HAS_ANSI)
39349 { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
39350 #else
39351 { "OutputDebugStringA", (SYSCALL)0, 0 },
39352 #endif
39354 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
39356 #if defined(SQLITE_WIN32_HAS_WIDE)
39357 { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
39358 #else
39359 { "OutputDebugStringW", (SYSCALL)0, 0 },
39360 #endif
39362 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
39364 { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
39366 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
39368 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
39369 { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
39370 #else
39371 { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
39372 #endif
39374 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
39375 LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
39378 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
39379 ** is really just a macro that uses a compiler intrinsic (e.g. x64).
39380 ** So do not try to make this is into a redefinable interface.
39382 #if defined(InterlockedCompareExchange)
39383 { "InterlockedCompareExchange", (SYSCALL)0, 0 },
39385 #define osInterlockedCompareExchange InterlockedCompareExchange
39386 #else
39387 { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
39389 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
39390 SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
39391 #endif /* defined(InterlockedCompareExchange) */
39393 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
39394 { "UuidCreate", (SYSCALL)UuidCreate, 0 },
39395 #else
39396 { "UuidCreate", (SYSCALL)0, 0 },
39397 #endif
39399 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
39401 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
39402 { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
39403 #else
39404 { "UuidCreateSequential", (SYSCALL)0, 0 },
39405 #endif
39407 #define osUuidCreateSequential \
39408 ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
39410 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
39411 { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
39412 #else
39413 { "FlushViewOfFile", (SYSCALL)0, 0 },
39414 #endif
39416 #define osFlushViewOfFile \
39417 ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
39419 }; /* End of the overrideable system calls */
39422 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
39423 ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
39424 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
39425 ** system call named zName.
39427 static int winSetSystemCall(
39428 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
39429 const char *zName, /* Name of system call to override */
39430 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
39432 unsigned int i;
39433 int rc = SQLITE_NOTFOUND;
39435 UNUSED_PARAMETER(pNotUsed);
39436 if( zName==0 ){
39437 /* If no zName is given, restore all system calls to their default
39438 ** settings and return NULL
39440 rc = SQLITE_OK;
39441 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
39442 if( aSyscall[i].pDefault ){
39443 aSyscall[i].pCurrent = aSyscall[i].pDefault;
39446 }else{
39447 /* If zName is specified, operate on only the one system call
39448 ** specified.
39450 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
39451 if( strcmp(zName, aSyscall[i].zName)==0 ){
39452 if( aSyscall[i].pDefault==0 ){
39453 aSyscall[i].pDefault = aSyscall[i].pCurrent;
39455 rc = SQLITE_OK;
39456 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
39457 aSyscall[i].pCurrent = pNewFunc;
39458 break;
39462 return rc;
39466 ** Return the value of a system call. Return NULL if zName is not a
39467 ** recognized system call name. NULL is also returned if the system call
39468 ** is currently undefined.
39470 static sqlite3_syscall_ptr winGetSystemCall(
39471 sqlite3_vfs *pNotUsed,
39472 const char *zName
39474 unsigned int i;
39476 UNUSED_PARAMETER(pNotUsed);
39477 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
39478 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
39480 return 0;
39484 ** Return the name of the first system call after zName. If zName==NULL
39485 ** then return the name of the first system call. Return NULL if zName
39486 ** is the last system call or if zName is not the name of a valid
39487 ** system call.
39489 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
39490 int i = -1;
39492 UNUSED_PARAMETER(p);
39493 if( zName ){
39494 for(i=0; i<ArraySize(aSyscall)-1; i++){
39495 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
39498 for(i++; i<ArraySize(aSyscall); i++){
39499 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
39501 return 0;
39504 #ifdef SQLITE_WIN32_MALLOC
39506 ** If a Win32 native heap has been configured, this function will attempt to
39507 ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
39508 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
39509 ** "pnLargest" argument, if non-zero, will be used to return the size of the
39510 ** largest committed free block in the heap, in bytes.
39512 SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
39513 int rc = SQLITE_OK;
39514 UINT nLargest = 0;
39515 HANDLE hHeap;
39517 winMemAssertMagic();
39518 hHeap = winMemGetHeap();
39519 assert( hHeap!=0 );
39520 assert( hHeap!=INVALID_HANDLE_VALUE );
39521 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39522 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
39523 #endif
39524 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
39525 if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
39526 DWORD lastErrno = osGetLastError();
39527 if( lastErrno==NO_ERROR ){
39528 sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
39529 (void*)hHeap);
39530 rc = SQLITE_NOMEM_BKPT;
39531 }else{
39532 sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
39533 osGetLastError(), (void*)hHeap);
39534 rc = SQLITE_ERROR;
39537 #else
39538 sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
39539 (void*)hHeap);
39540 rc = SQLITE_NOTFOUND;
39541 #endif
39542 if( pnLargest ) *pnLargest = nLargest;
39543 return rc;
39547 ** If a Win32 native heap has been configured, this function will attempt to
39548 ** destroy and recreate it. If the Win32 native heap is not isolated and/or
39549 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
39550 ** be returned and no changes will be made to the Win32 native heap.
39552 SQLITE_API int sqlite3_win32_reset_heap(){
39553 int rc;
39554 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
39555 MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
39556 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
39557 MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
39558 sqlite3_mutex_enter(pMaster);
39559 sqlite3_mutex_enter(pMem);
39560 winMemAssertMagic();
39561 if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
39563 ** At this point, there should be no outstanding memory allocations on
39564 ** the heap. Also, since both the master and memsys locks are currently
39565 ** being held by us, no other function (i.e. from another thread) should
39566 ** be able to even access the heap. Attempt to destroy and recreate our
39567 ** isolated Win32 native heap now.
39569 assert( winMemGetHeap()!=NULL );
39570 assert( winMemGetOwned() );
39571 assert( sqlite3_memory_used()==0 );
39572 winMemShutdown(winMemGetDataPtr());
39573 assert( winMemGetHeap()==NULL );
39574 assert( !winMemGetOwned() );
39575 assert( sqlite3_memory_used()==0 );
39576 rc = winMemInit(winMemGetDataPtr());
39577 assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
39578 assert( rc!=SQLITE_OK || winMemGetOwned() );
39579 assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
39580 }else{
39582 ** The Win32 native heap cannot be modified because it may be in use.
39584 rc = SQLITE_BUSY;
39586 sqlite3_mutex_leave(pMem);
39587 sqlite3_mutex_leave(pMaster);
39588 return rc;
39590 #endif /* SQLITE_WIN32_MALLOC */
39593 ** This function outputs the specified (ANSI) string to the Win32 debugger
39594 ** (if available).
39597 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
39598 char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
39599 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
39600 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
39601 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
39602 #ifdef SQLITE_ENABLE_API_ARMOR
39603 if( !zBuf ){
39604 (void)SQLITE_MISUSE_BKPT;
39605 return;
39607 #endif
39608 #if defined(SQLITE_WIN32_HAS_ANSI)
39609 if( nMin>0 ){
39610 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
39611 memcpy(zDbgBuf, zBuf, nMin);
39612 osOutputDebugStringA(zDbgBuf);
39613 }else{
39614 osOutputDebugStringA(zBuf);
39616 #elif defined(SQLITE_WIN32_HAS_WIDE)
39617 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
39618 if ( osMultiByteToWideChar(
39619 osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
39620 nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
39621 return;
39623 osOutputDebugStringW((LPCWSTR)zDbgBuf);
39624 #else
39625 if( nMin>0 ){
39626 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
39627 memcpy(zDbgBuf, zBuf, nMin);
39628 fprintf(stderr, "%s", zDbgBuf);
39629 }else{
39630 fprintf(stderr, "%s", zBuf);
39632 #endif
39636 ** The following routine suspends the current thread for at least ms
39637 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
39639 #if SQLITE_OS_WINRT
39640 static HANDLE sleepObj = NULL;
39641 #endif
39643 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
39644 #if SQLITE_OS_WINRT
39645 if ( sleepObj==NULL ){
39646 sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
39647 SYNCHRONIZE);
39649 assert( sleepObj!=NULL );
39650 osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
39651 #else
39652 osSleep(milliseconds);
39653 #endif
39656 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
39657 SQLITE_THREADSAFE>0
39658 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
39659 DWORD rc;
39660 while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
39661 TRUE))==WAIT_IO_COMPLETION ){}
39662 return rc;
39664 #endif
39667 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
39668 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
39670 ** Here is an interesting observation: Win95, Win98, and WinME lack
39671 ** the LockFileEx() API. But we can still statically link against that
39672 ** API as long as we don't call it when running Win95/98/ME. A call to
39673 ** this routine is used to determine if the host is Win95/98/ME or
39674 ** WinNT/2K/XP so that we will know whether or not we can safely call
39675 ** the LockFileEx() API.
39678 #if !SQLITE_WIN32_GETVERSIONEX
39679 # define osIsNT() (1)
39680 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
39681 # define osIsNT() (1)
39682 #elif !defined(SQLITE_WIN32_HAS_WIDE)
39683 # define osIsNT() (0)
39684 #else
39685 # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
39686 #endif
39689 ** This function determines if the machine is running a version of Windows
39690 ** based on the NT kernel.
39692 SQLITE_API int sqlite3_win32_is_nt(void){
39693 #if SQLITE_OS_WINRT
39695 ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
39696 ** kernel.
39698 return 1;
39699 #elif SQLITE_WIN32_GETVERSIONEX
39700 if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
39701 #if defined(SQLITE_WIN32_HAS_ANSI)
39702 OSVERSIONINFOA sInfo;
39703 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
39704 osGetVersionExA(&sInfo);
39705 osInterlockedCompareExchange(&sqlite3_os_type,
39706 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
39707 #elif defined(SQLITE_WIN32_HAS_WIDE)
39708 OSVERSIONINFOW sInfo;
39709 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
39710 osGetVersionExW(&sInfo);
39711 osInterlockedCompareExchange(&sqlite3_os_type,
39712 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
39713 #endif
39715 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
39716 #elif SQLITE_TEST
39717 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
39718 #else
39720 ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
39721 ** deprecated are always assumed to be based on the NT kernel.
39723 return 1;
39724 #endif
39727 #ifdef SQLITE_WIN32_MALLOC
39729 ** Allocate nBytes of memory.
39731 static void *winMemMalloc(int nBytes){
39732 HANDLE hHeap;
39733 void *p;
39735 winMemAssertMagic();
39736 hHeap = winMemGetHeap();
39737 assert( hHeap!=0 );
39738 assert( hHeap!=INVALID_HANDLE_VALUE );
39739 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39740 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
39741 #endif
39742 assert( nBytes>=0 );
39743 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
39744 if( !p ){
39745 sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
39746 nBytes, osGetLastError(), (void*)hHeap);
39748 return p;
39752 ** Free memory.
39754 static void winMemFree(void *pPrior){
39755 HANDLE hHeap;
39757 winMemAssertMagic();
39758 hHeap = winMemGetHeap();
39759 assert( hHeap!=0 );
39760 assert( hHeap!=INVALID_HANDLE_VALUE );
39761 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39762 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
39763 #endif
39764 if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
39765 if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
39766 sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
39767 pPrior, osGetLastError(), (void*)hHeap);
39772 ** Change the size of an existing memory allocation
39774 static void *winMemRealloc(void *pPrior, int nBytes){
39775 HANDLE hHeap;
39776 void *p;
39778 winMemAssertMagic();
39779 hHeap = winMemGetHeap();
39780 assert( hHeap!=0 );
39781 assert( hHeap!=INVALID_HANDLE_VALUE );
39782 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39783 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
39784 #endif
39785 assert( nBytes>=0 );
39786 if( !pPrior ){
39787 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
39788 }else{
39789 p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
39791 if( !p ){
39792 sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
39793 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
39794 (void*)hHeap);
39796 return p;
39800 ** Return the size of an outstanding allocation, in bytes.
39802 static int winMemSize(void *p){
39803 HANDLE hHeap;
39804 SIZE_T n;
39806 winMemAssertMagic();
39807 hHeap = winMemGetHeap();
39808 assert( hHeap!=0 );
39809 assert( hHeap!=INVALID_HANDLE_VALUE );
39810 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39811 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
39812 #endif
39813 if( !p ) return 0;
39814 n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
39815 if( n==(SIZE_T)-1 ){
39816 sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
39817 p, osGetLastError(), (void*)hHeap);
39818 return 0;
39820 return (int)n;
39824 ** Round up a request size to the next valid allocation size.
39826 static int winMemRoundup(int n){
39827 return n;
39831 ** Initialize this module.
39833 static int winMemInit(void *pAppData){
39834 winMemData *pWinMemData = (winMemData *)pAppData;
39836 if( !pWinMemData ) return SQLITE_ERROR;
39837 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
39838 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
39840 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
39841 if( !pWinMemData->hHeap ){
39842 DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
39843 DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
39844 if( dwMaximumSize==0 ){
39845 dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
39846 }else if( dwInitialSize>dwMaximumSize ){
39847 dwInitialSize = dwMaximumSize;
39849 pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
39850 dwInitialSize, dwMaximumSize);
39851 if( !pWinMemData->hHeap ){
39852 sqlite3_log(SQLITE_NOMEM,
39853 "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
39854 osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
39855 dwMaximumSize);
39856 return SQLITE_NOMEM_BKPT;
39858 pWinMemData->bOwned = TRUE;
39859 assert( pWinMemData->bOwned );
39861 #else
39862 pWinMemData->hHeap = osGetProcessHeap();
39863 if( !pWinMemData->hHeap ){
39864 sqlite3_log(SQLITE_NOMEM,
39865 "failed to GetProcessHeap (%lu)", osGetLastError());
39866 return SQLITE_NOMEM_BKPT;
39868 pWinMemData->bOwned = FALSE;
39869 assert( !pWinMemData->bOwned );
39870 #endif
39871 assert( pWinMemData->hHeap!=0 );
39872 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
39873 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39874 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
39875 #endif
39876 return SQLITE_OK;
39880 ** Deinitialize this module.
39882 static void winMemShutdown(void *pAppData){
39883 winMemData *pWinMemData = (winMemData *)pAppData;
39885 if( !pWinMemData ) return;
39886 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
39887 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
39889 if( pWinMemData->hHeap ){
39890 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
39891 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39892 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
39893 #endif
39894 if( pWinMemData->bOwned ){
39895 if( !osHeapDestroy(pWinMemData->hHeap) ){
39896 sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
39897 osGetLastError(), (void*)pWinMemData->hHeap);
39899 pWinMemData->bOwned = FALSE;
39901 pWinMemData->hHeap = NULL;
39906 ** Populate the low-level memory allocation function pointers in
39907 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
39908 ** arguments specify the block of memory to manage.
39910 ** This routine is only called by sqlite3_config(), and therefore
39911 ** is not required to be threadsafe (it is not).
39913 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
39914 static const sqlite3_mem_methods winMemMethods = {
39915 winMemMalloc,
39916 winMemFree,
39917 winMemRealloc,
39918 winMemSize,
39919 winMemRoundup,
39920 winMemInit,
39921 winMemShutdown,
39922 &win_mem_data
39924 return &winMemMethods;
39927 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
39928 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
39930 #endif /* SQLITE_WIN32_MALLOC */
39933 ** Convert a UTF-8 string to Microsoft Unicode.
39935 ** Space to hold the returned string is obtained from sqlite3_malloc().
39937 static LPWSTR winUtf8ToUnicode(const char *zText){
39938 int nChar;
39939 LPWSTR zWideText;
39941 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
39942 if( nChar==0 ){
39943 return 0;
39945 zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
39946 if( zWideText==0 ){
39947 return 0;
39949 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
39950 nChar);
39951 if( nChar==0 ){
39952 sqlite3_free(zWideText);
39953 zWideText = 0;
39955 return zWideText;
39959 ** Convert a Microsoft Unicode string to UTF-8.
39961 ** Space to hold the returned string is obtained from sqlite3_malloc().
39963 static char *winUnicodeToUtf8(LPCWSTR zWideText){
39964 int nByte;
39965 char *zText;
39967 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
39968 if( nByte == 0 ){
39969 return 0;
39971 zText = sqlite3MallocZero( nByte );
39972 if( zText==0 ){
39973 return 0;
39975 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
39976 0, 0);
39977 if( nByte == 0 ){
39978 sqlite3_free(zText);
39979 zText = 0;
39981 return zText;
39985 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
39986 ** code page.
39988 ** Space to hold the returned string is obtained from sqlite3_malloc().
39990 static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
39991 int nByte;
39992 LPWSTR zMbcsText;
39993 int codepage = useAnsi ? CP_ACP : CP_OEMCP;
39995 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
39996 0)*sizeof(WCHAR);
39997 if( nByte==0 ){
39998 return 0;
40000 zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
40001 if( zMbcsText==0 ){
40002 return 0;
40004 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
40005 nByte);
40006 if( nByte==0 ){
40007 sqlite3_free(zMbcsText);
40008 zMbcsText = 0;
40010 return zMbcsText;
40014 ** Convert a Microsoft Unicode string to a multi-byte character string,
40015 ** using the ANSI or OEM code page.
40017 ** Space to hold the returned string is obtained from sqlite3_malloc().
40019 static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
40020 int nByte;
40021 char *zText;
40022 int codepage = useAnsi ? CP_ACP : CP_OEMCP;
40024 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
40025 if( nByte == 0 ){
40026 return 0;
40028 zText = sqlite3MallocZero( nByte );
40029 if( zText==0 ){
40030 return 0;
40032 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
40033 nByte, 0, 0);
40034 if( nByte == 0 ){
40035 sqlite3_free(zText);
40036 zText = 0;
40038 return zText;
40042 ** Convert a multi-byte character string to UTF-8.
40044 ** Space to hold the returned string is obtained from sqlite3_malloc().
40046 static char *winMbcsToUtf8(const char *zText, int useAnsi){
40047 char *zTextUtf8;
40048 LPWSTR zTmpWide;
40050 zTmpWide = winMbcsToUnicode(zText, useAnsi);
40051 if( zTmpWide==0 ){
40052 return 0;
40054 zTextUtf8 = winUnicodeToUtf8(zTmpWide);
40055 sqlite3_free(zTmpWide);
40056 return zTextUtf8;
40060 ** Convert a UTF-8 string to a multi-byte character string.
40062 ** Space to hold the returned string is obtained from sqlite3_malloc().
40064 static char *winUtf8ToMbcs(const char *zText, int useAnsi){
40065 char *zTextMbcs;
40066 LPWSTR zTmpWide;
40068 zTmpWide = winUtf8ToUnicode(zText);
40069 if( zTmpWide==0 ){
40070 return 0;
40072 zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
40073 sqlite3_free(zTmpWide);
40074 return zTextMbcs;
40078 ** This is a public wrapper for the winUtf8ToUnicode() function.
40080 SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
40081 #ifdef SQLITE_ENABLE_API_ARMOR
40082 if( !zText ){
40083 (void)SQLITE_MISUSE_BKPT;
40084 return 0;
40086 #endif
40087 #ifndef SQLITE_OMIT_AUTOINIT
40088 if( sqlite3_initialize() ) return 0;
40089 #endif
40090 return winUtf8ToUnicode(zText);
40094 ** This is a public wrapper for the winUnicodeToUtf8() function.
40096 SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
40097 #ifdef SQLITE_ENABLE_API_ARMOR
40098 if( !zWideText ){
40099 (void)SQLITE_MISUSE_BKPT;
40100 return 0;
40102 #endif
40103 #ifndef SQLITE_OMIT_AUTOINIT
40104 if( sqlite3_initialize() ) return 0;
40105 #endif
40106 return winUnicodeToUtf8(zWideText);
40110 ** This is a public wrapper for the winMbcsToUtf8() function.
40112 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
40113 #ifdef SQLITE_ENABLE_API_ARMOR
40114 if( !zText ){
40115 (void)SQLITE_MISUSE_BKPT;
40116 return 0;
40118 #endif
40119 #ifndef SQLITE_OMIT_AUTOINIT
40120 if( sqlite3_initialize() ) return 0;
40121 #endif
40122 return winMbcsToUtf8(zText, osAreFileApisANSI());
40126 ** This is a public wrapper for the winMbcsToUtf8() function.
40128 SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
40129 #ifdef SQLITE_ENABLE_API_ARMOR
40130 if( !zText ){
40131 (void)SQLITE_MISUSE_BKPT;
40132 return 0;
40134 #endif
40135 #ifndef SQLITE_OMIT_AUTOINIT
40136 if( sqlite3_initialize() ) return 0;
40137 #endif
40138 return winMbcsToUtf8(zText, useAnsi);
40142 ** This is a public wrapper for the winUtf8ToMbcs() function.
40144 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
40145 #ifdef SQLITE_ENABLE_API_ARMOR
40146 if( !zText ){
40147 (void)SQLITE_MISUSE_BKPT;
40148 return 0;
40150 #endif
40151 #ifndef SQLITE_OMIT_AUTOINIT
40152 if( sqlite3_initialize() ) return 0;
40153 #endif
40154 return winUtf8ToMbcs(zText, osAreFileApisANSI());
40158 ** This is a public wrapper for the winUtf8ToMbcs() function.
40160 SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
40161 #ifdef SQLITE_ENABLE_API_ARMOR
40162 if( !zText ){
40163 (void)SQLITE_MISUSE_BKPT;
40164 return 0;
40166 #endif
40167 #ifndef SQLITE_OMIT_AUTOINIT
40168 if( sqlite3_initialize() ) return 0;
40169 #endif
40170 return winUtf8ToMbcs(zText, useAnsi);
40174 ** This function sets the data directory or the temporary directory based on
40175 ** the provided arguments. The type argument must be 1 in order to set the
40176 ** data directory or 2 in order to set the temporary directory. The zValue
40177 ** argument is the name of the directory to use. The return value will be
40178 ** SQLITE_OK if successful.
40180 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
40181 char **ppDirectory = 0;
40182 #ifndef SQLITE_OMIT_AUTOINIT
40183 int rc = sqlite3_initialize();
40184 if( rc ) return rc;
40185 #endif
40186 if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
40187 ppDirectory = &sqlite3_data_directory;
40188 }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
40189 ppDirectory = &sqlite3_temp_directory;
40191 assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
40192 || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
40194 assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
40195 if( ppDirectory ){
40196 char *zValueUtf8 = 0;
40197 if( zValue && zValue[0] ){
40198 zValueUtf8 = winUnicodeToUtf8(zValue);
40199 if ( zValueUtf8==0 ){
40200 return SQLITE_NOMEM_BKPT;
40203 sqlite3_free(*ppDirectory);
40204 *ppDirectory = zValueUtf8;
40205 return SQLITE_OK;
40207 return SQLITE_ERROR;
40211 ** The return value of winGetLastErrorMsg
40212 ** is zero if the error message fits in the buffer, or non-zero
40213 ** otherwise (if the message was truncated).
40215 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
40216 /* FormatMessage returns 0 on failure. Otherwise it
40217 ** returns the number of TCHARs written to the output
40218 ** buffer, excluding the terminating null char.
40220 DWORD dwLen = 0;
40221 char *zOut = 0;
40223 if( osIsNT() ){
40224 #if SQLITE_OS_WINRT
40225 WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
40226 dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
40227 FORMAT_MESSAGE_IGNORE_INSERTS,
40228 NULL,
40229 lastErrno,
40231 zTempWide,
40232 SQLITE_WIN32_MAX_ERRMSG_CHARS,
40234 #else
40235 LPWSTR zTempWide = NULL;
40236 dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
40237 FORMAT_MESSAGE_FROM_SYSTEM |
40238 FORMAT_MESSAGE_IGNORE_INSERTS,
40239 NULL,
40240 lastErrno,
40242 (LPWSTR) &zTempWide,
40245 #endif
40246 if( dwLen > 0 ){
40247 /* allocate a buffer and convert to UTF8 */
40248 sqlite3BeginBenignMalloc();
40249 zOut = winUnicodeToUtf8(zTempWide);
40250 sqlite3EndBenignMalloc();
40251 #if !SQLITE_OS_WINRT
40252 /* free the system buffer allocated by FormatMessage */
40253 osLocalFree(zTempWide);
40254 #endif
40257 #ifdef SQLITE_WIN32_HAS_ANSI
40258 else{
40259 char *zTemp = NULL;
40260 dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
40261 FORMAT_MESSAGE_FROM_SYSTEM |
40262 FORMAT_MESSAGE_IGNORE_INSERTS,
40263 NULL,
40264 lastErrno,
40266 (LPSTR) &zTemp,
40269 if( dwLen > 0 ){
40270 /* allocate a buffer and convert to UTF8 */
40271 sqlite3BeginBenignMalloc();
40272 zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
40273 sqlite3EndBenignMalloc();
40274 /* free the system buffer allocated by FormatMessage */
40275 osLocalFree(zTemp);
40278 #endif
40279 if( 0 == dwLen ){
40280 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
40281 }else{
40282 /* copy a maximum of nBuf chars to output buffer */
40283 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
40284 /* free the UTF8 buffer */
40285 sqlite3_free(zOut);
40287 return 0;
40292 ** This function - winLogErrorAtLine() - is only ever called via the macro
40293 ** winLogError().
40295 ** This routine is invoked after an error occurs in an OS function.
40296 ** It logs a message using sqlite3_log() containing the current value of
40297 ** error code and, if possible, the human-readable equivalent from
40298 ** FormatMessage.
40300 ** The first argument passed to the macro should be the error code that
40301 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
40302 ** The two subsequent arguments should be the name of the OS function that
40303 ** failed and the associated file-system path, if any.
40305 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
40306 static int winLogErrorAtLine(
40307 int errcode, /* SQLite error code */
40308 DWORD lastErrno, /* Win32 last error */
40309 const char *zFunc, /* Name of OS function that failed */
40310 const char *zPath, /* File path associated with error */
40311 int iLine /* Source line number where error occurred */
40313 char zMsg[500]; /* Human readable error text */
40314 int i; /* Loop counter */
40316 zMsg[0] = 0;
40317 winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
40318 assert( errcode!=SQLITE_OK );
40319 if( zPath==0 ) zPath = "";
40320 for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
40321 zMsg[i] = 0;
40322 sqlite3_log(errcode,
40323 "os_win.c:%d: (%lu) %s(%s) - %s",
40324 iLine, lastErrno, zFunc, zPath, zMsg
40327 return errcode;
40331 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
40332 ** will be retried following a locking error - probably caused by
40333 ** antivirus software. Also the initial delay before the first retry.
40334 ** The delay increases linearly with each retry.
40336 #ifndef SQLITE_WIN32_IOERR_RETRY
40337 # define SQLITE_WIN32_IOERR_RETRY 10
40338 #endif
40339 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
40340 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
40341 #endif
40342 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
40343 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
40346 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
40347 ** error code obtained via GetLastError() is eligible to be retried. It
40348 ** must accept the error code DWORD as its only argument and should return
40349 ** non-zero if the error code is transient in nature and the operation
40350 ** responsible for generating the original error might succeed upon being
40351 ** retried. The argument to this macro should be a variable.
40353 ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
40354 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
40355 ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
40356 ** may be used to include additional error codes in the set that should
40357 ** result in the failing I/O operation being retried by the caller. If
40358 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
40359 ** identical to those of the "winIoerrCanRetry1" macro.
40361 #if !defined(winIoerrCanRetry1)
40362 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
40363 ((a)==ERROR_SHARING_VIOLATION) || \
40364 ((a)==ERROR_LOCK_VIOLATION) || \
40365 ((a)==ERROR_DEV_NOT_EXIST) || \
40366 ((a)==ERROR_NETNAME_DELETED) || \
40367 ((a)==ERROR_SEM_TIMEOUT) || \
40368 ((a)==ERROR_NETWORK_UNREACHABLE))
40369 #endif
40372 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
40373 ** to see if it should be retried. Return TRUE to retry. Return FALSE
40374 ** to give up with an error.
40376 static int winRetryIoerr(int *pnRetry, DWORD *pError){
40377 DWORD e = osGetLastError();
40378 if( *pnRetry>=winIoerrRetry ){
40379 if( pError ){
40380 *pError = e;
40382 return 0;
40384 if( winIoerrCanRetry1(e) ){
40385 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
40386 ++*pnRetry;
40387 return 1;
40389 #if defined(winIoerrCanRetry2)
40390 else if( winIoerrCanRetry2(e) ){
40391 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
40392 ++*pnRetry;
40393 return 1;
40395 #endif
40396 if( pError ){
40397 *pError = e;
40399 return 0;
40403 ** Log a I/O error retry episode.
40405 static void winLogIoerr(int nRetry, int lineno){
40406 if( nRetry ){
40407 sqlite3_log(SQLITE_NOTICE,
40408 "delayed %dms for lock/sharing conflict at line %d",
40409 winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
40415 ** This #if does not rely on the SQLITE_OS_WINCE define because the
40416 ** corresponding section in "date.c" cannot use it.
40418 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
40419 (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
40421 ** The MSVC CRT on Windows CE may not have a localtime() function.
40422 ** So define a substitute.
40424 /* # include <time.h> */
40425 struct tm *__cdecl localtime(const time_t *t)
40427 static struct tm y;
40428 FILETIME uTm, lTm;
40429 SYSTEMTIME pTm;
40430 sqlite3_int64 t64;
40431 t64 = *t;
40432 t64 = (t64 + 11644473600)*10000000;
40433 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
40434 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
40435 osFileTimeToLocalFileTime(&uTm,&lTm);
40436 osFileTimeToSystemTime(&lTm,&pTm);
40437 y.tm_year = pTm.wYear - 1900;
40438 y.tm_mon = pTm.wMonth - 1;
40439 y.tm_wday = pTm.wDayOfWeek;
40440 y.tm_mday = pTm.wDay;
40441 y.tm_hour = pTm.wHour;
40442 y.tm_min = pTm.wMinute;
40443 y.tm_sec = pTm.wSecond;
40444 return &y;
40446 #endif
40448 #if SQLITE_OS_WINCE
40449 /*************************************************************************
40450 ** This section contains code for WinCE only.
40452 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
40455 ** Acquire a lock on the handle h
40457 static void winceMutexAcquire(HANDLE h){
40458 DWORD dwErr;
40459 do {
40460 dwErr = osWaitForSingleObject(h, INFINITE);
40461 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
40464 ** Release a lock acquired by winceMutexAcquire()
40466 #define winceMutexRelease(h) ReleaseMutex(h)
40469 ** Create the mutex and shared memory used for locking in the file
40470 ** descriptor pFile
40472 static int winceCreateLock(const char *zFilename, winFile *pFile){
40473 LPWSTR zTok;
40474 LPWSTR zName;
40475 DWORD lastErrno;
40476 BOOL bLogged = FALSE;
40477 BOOL bInit = TRUE;
40479 zName = winUtf8ToUnicode(zFilename);
40480 if( zName==0 ){
40481 /* out of memory */
40482 return SQLITE_IOERR_NOMEM_BKPT;
40485 /* Initialize the local lockdata */
40486 memset(&pFile->local, 0, sizeof(pFile->local));
40488 /* Replace the backslashes from the filename and lowercase it
40489 ** to derive a mutex name. */
40490 zTok = osCharLowerW(zName);
40491 for (;*zTok;zTok++){
40492 if (*zTok == '\\') *zTok = '_';
40495 /* Create/open the named mutex */
40496 pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
40497 if (!pFile->hMutex){
40498 pFile->lastErrno = osGetLastError();
40499 sqlite3_free(zName);
40500 return winLogError(SQLITE_IOERR, pFile->lastErrno,
40501 "winceCreateLock1", zFilename);
40504 /* Acquire the mutex before continuing */
40505 winceMutexAcquire(pFile->hMutex);
40507 /* Since the names of named mutexes, semaphores, file mappings etc are
40508 ** case-sensitive, take advantage of that by uppercasing the mutex name
40509 ** and using that as the shared filemapping name.
40511 osCharUpperW(zName);
40512 pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
40513 PAGE_READWRITE, 0, sizeof(winceLock),
40514 zName);
40516 /* Set a flag that indicates we're the first to create the memory so it
40517 ** must be zero-initialized */
40518 lastErrno = osGetLastError();
40519 if (lastErrno == ERROR_ALREADY_EXISTS){
40520 bInit = FALSE;
40523 sqlite3_free(zName);
40525 /* If we succeeded in making the shared memory handle, map it. */
40526 if( pFile->hShared ){
40527 pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
40528 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
40529 /* If mapping failed, close the shared memory handle and erase it */
40530 if( !pFile->shared ){
40531 pFile->lastErrno = osGetLastError();
40532 winLogError(SQLITE_IOERR, pFile->lastErrno,
40533 "winceCreateLock2", zFilename);
40534 bLogged = TRUE;
40535 osCloseHandle(pFile->hShared);
40536 pFile->hShared = NULL;
40540 /* If shared memory could not be created, then close the mutex and fail */
40541 if( pFile->hShared==NULL ){
40542 if( !bLogged ){
40543 pFile->lastErrno = lastErrno;
40544 winLogError(SQLITE_IOERR, pFile->lastErrno,
40545 "winceCreateLock3", zFilename);
40546 bLogged = TRUE;
40548 winceMutexRelease(pFile->hMutex);
40549 osCloseHandle(pFile->hMutex);
40550 pFile->hMutex = NULL;
40551 return SQLITE_IOERR;
40554 /* Initialize the shared memory if we're supposed to */
40555 if( bInit ){
40556 memset(pFile->shared, 0, sizeof(winceLock));
40559 winceMutexRelease(pFile->hMutex);
40560 return SQLITE_OK;
40564 ** Destroy the part of winFile that deals with wince locks
40566 static void winceDestroyLock(winFile *pFile){
40567 if (pFile->hMutex){
40568 /* Acquire the mutex */
40569 winceMutexAcquire(pFile->hMutex);
40571 /* The following blocks should probably assert in debug mode, but they
40572 are to cleanup in case any locks remained open */
40573 if (pFile->local.nReaders){
40574 pFile->shared->nReaders --;
40576 if (pFile->local.bReserved){
40577 pFile->shared->bReserved = FALSE;
40579 if (pFile->local.bPending){
40580 pFile->shared->bPending = FALSE;
40582 if (pFile->local.bExclusive){
40583 pFile->shared->bExclusive = FALSE;
40586 /* De-reference and close our copy of the shared memory handle */
40587 osUnmapViewOfFile(pFile->shared);
40588 osCloseHandle(pFile->hShared);
40590 /* Done with the mutex */
40591 winceMutexRelease(pFile->hMutex);
40592 osCloseHandle(pFile->hMutex);
40593 pFile->hMutex = NULL;
40598 ** An implementation of the LockFile() API of Windows for CE
40600 static BOOL winceLockFile(
40601 LPHANDLE phFile,
40602 DWORD dwFileOffsetLow,
40603 DWORD dwFileOffsetHigh,
40604 DWORD nNumberOfBytesToLockLow,
40605 DWORD nNumberOfBytesToLockHigh
40607 winFile *pFile = HANDLE_TO_WINFILE(phFile);
40608 BOOL bReturn = FALSE;
40610 UNUSED_PARAMETER(dwFileOffsetHigh);
40611 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
40613 if (!pFile->hMutex) return TRUE;
40614 winceMutexAcquire(pFile->hMutex);
40616 /* Wanting an exclusive lock? */
40617 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
40618 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
40619 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
40620 pFile->shared->bExclusive = TRUE;
40621 pFile->local.bExclusive = TRUE;
40622 bReturn = TRUE;
40626 /* Want a read-only lock? */
40627 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
40628 nNumberOfBytesToLockLow == 1){
40629 if (pFile->shared->bExclusive == 0){
40630 pFile->local.nReaders ++;
40631 if (pFile->local.nReaders == 1){
40632 pFile->shared->nReaders ++;
40634 bReturn = TRUE;
40638 /* Want a pending lock? */
40639 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
40640 && nNumberOfBytesToLockLow == 1){
40641 /* If no pending lock has been acquired, then acquire it */
40642 if (pFile->shared->bPending == 0) {
40643 pFile->shared->bPending = TRUE;
40644 pFile->local.bPending = TRUE;
40645 bReturn = TRUE;
40649 /* Want a reserved lock? */
40650 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
40651 && nNumberOfBytesToLockLow == 1){
40652 if (pFile->shared->bReserved == 0) {
40653 pFile->shared->bReserved = TRUE;
40654 pFile->local.bReserved = TRUE;
40655 bReturn = TRUE;
40659 winceMutexRelease(pFile->hMutex);
40660 return bReturn;
40664 ** An implementation of the UnlockFile API of Windows for CE
40666 static BOOL winceUnlockFile(
40667 LPHANDLE phFile,
40668 DWORD dwFileOffsetLow,
40669 DWORD dwFileOffsetHigh,
40670 DWORD nNumberOfBytesToUnlockLow,
40671 DWORD nNumberOfBytesToUnlockHigh
40673 winFile *pFile = HANDLE_TO_WINFILE(phFile);
40674 BOOL bReturn = FALSE;
40676 UNUSED_PARAMETER(dwFileOffsetHigh);
40677 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
40679 if (!pFile->hMutex) return TRUE;
40680 winceMutexAcquire(pFile->hMutex);
40682 /* Releasing a reader lock or an exclusive lock */
40683 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
40684 /* Did we have an exclusive lock? */
40685 if (pFile->local.bExclusive){
40686 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
40687 pFile->local.bExclusive = FALSE;
40688 pFile->shared->bExclusive = FALSE;
40689 bReturn = TRUE;
40692 /* Did we just have a reader lock? */
40693 else if (pFile->local.nReaders){
40694 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
40695 || nNumberOfBytesToUnlockLow == 1);
40696 pFile->local.nReaders --;
40697 if (pFile->local.nReaders == 0)
40699 pFile->shared->nReaders --;
40701 bReturn = TRUE;
40705 /* Releasing a pending lock */
40706 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
40707 && nNumberOfBytesToUnlockLow == 1){
40708 if (pFile->local.bPending){
40709 pFile->local.bPending = FALSE;
40710 pFile->shared->bPending = FALSE;
40711 bReturn = TRUE;
40714 /* Releasing a reserved lock */
40715 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
40716 && nNumberOfBytesToUnlockLow == 1){
40717 if (pFile->local.bReserved) {
40718 pFile->local.bReserved = FALSE;
40719 pFile->shared->bReserved = FALSE;
40720 bReturn = TRUE;
40724 winceMutexRelease(pFile->hMutex);
40725 return bReturn;
40728 ** End of the special code for wince
40729 *****************************************************************************/
40730 #endif /* SQLITE_OS_WINCE */
40733 ** Lock a file region.
40735 static BOOL winLockFile(
40736 LPHANDLE phFile,
40737 DWORD flags,
40738 DWORD offsetLow,
40739 DWORD offsetHigh,
40740 DWORD numBytesLow,
40741 DWORD numBytesHigh
40743 #if SQLITE_OS_WINCE
40745 ** NOTE: Windows CE is handled differently here due its lack of the Win32
40746 ** API LockFile.
40748 return winceLockFile(phFile, offsetLow, offsetHigh,
40749 numBytesLow, numBytesHigh);
40750 #else
40751 if( osIsNT() ){
40752 OVERLAPPED ovlp;
40753 memset(&ovlp, 0, sizeof(OVERLAPPED));
40754 ovlp.Offset = offsetLow;
40755 ovlp.OffsetHigh = offsetHigh;
40756 return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
40757 }else{
40758 return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
40759 numBytesHigh);
40761 #endif
40765 ** Unlock a file region.
40767 static BOOL winUnlockFile(
40768 LPHANDLE phFile,
40769 DWORD offsetLow,
40770 DWORD offsetHigh,
40771 DWORD numBytesLow,
40772 DWORD numBytesHigh
40774 #if SQLITE_OS_WINCE
40776 ** NOTE: Windows CE is handled differently here due its lack of the Win32
40777 ** API UnlockFile.
40779 return winceUnlockFile(phFile, offsetLow, offsetHigh,
40780 numBytesLow, numBytesHigh);
40781 #else
40782 if( osIsNT() ){
40783 OVERLAPPED ovlp;
40784 memset(&ovlp, 0, sizeof(OVERLAPPED));
40785 ovlp.Offset = offsetLow;
40786 ovlp.OffsetHigh = offsetHigh;
40787 return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
40788 }else{
40789 return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
40790 numBytesHigh);
40792 #endif
40795 /*****************************************************************************
40796 ** The next group of routines implement the I/O methods specified
40797 ** by the sqlite3_io_methods object.
40798 ******************************************************************************/
40801 ** Some Microsoft compilers lack this definition.
40803 #ifndef INVALID_SET_FILE_POINTER
40804 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
40805 #endif
40808 ** Move the current position of the file handle passed as the first
40809 ** argument to offset iOffset within the file. If successful, return 0.
40810 ** Otherwise, set pFile->lastErrno and return non-zero.
40812 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
40813 #if !SQLITE_OS_WINRT
40814 LONG upperBits; /* Most sig. 32 bits of new offset */
40815 LONG lowerBits; /* Least sig. 32 bits of new offset */
40816 DWORD dwRet; /* Value returned by SetFilePointer() */
40817 DWORD lastErrno; /* Value returned by GetLastError() */
40819 OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
40821 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
40822 lowerBits = (LONG)(iOffset & 0xffffffff);
40824 /* API oddity: If successful, SetFilePointer() returns a dword
40825 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
40826 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
40827 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
40828 ** whether an error has actually occurred, it is also necessary to call
40829 ** GetLastError().
40831 dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
40833 if( (dwRet==INVALID_SET_FILE_POINTER
40834 && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
40835 pFile->lastErrno = lastErrno;
40836 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
40837 "winSeekFile", pFile->zPath);
40838 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
40839 return 1;
40842 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
40843 return 0;
40844 #else
40846 ** Same as above, except that this implementation works for WinRT.
40849 LARGE_INTEGER x; /* The new offset */
40850 BOOL bRet; /* Value returned by SetFilePointerEx() */
40852 x.QuadPart = iOffset;
40853 bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
40855 if(!bRet){
40856 pFile->lastErrno = osGetLastError();
40857 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
40858 "winSeekFile", pFile->zPath);
40859 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
40860 return 1;
40863 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
40864 return 0;
40865 #endif
40868 #if SQLITE_MAX_MMAP_SIZE>0
40869 /* Forward references to VFS helper methods used for memory mapped files */
40870 static int winMapfile(winFile*, sqlite3_int64);
40871 static int winUnmapfile(winFile*);
40872 #endif
40875 ** Close a file.
40877 ** It is reported that an attempt to close a handle might sometimes
40878 ** fail. This is a very unreasonable result, but Windows is notorious
40879 ** for being unreasonable so I do not doubt that it might happen. If
40880 ** the close fails, we pause for 100 milliseconds and try again. As
40881 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
40882 ** giving up and returning an error.
40884 #define MX_CLOSE_ATTEMPT 3
40885 static int winClose(sqlite3_file *id){
40886 int rc, cnt = 0;
40887 winFile *pFile = (winFile*)id;
40889 assert( id!=0 );
40890 #ifndef SQLITE_OMIT_WAL
40891 assert( pFile->pShm==0 );
40892 #endif
40893 assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
40894 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
40895 osGetCurrentProcessId(), pFile, pFile->h));
40897 #if SQLITE_MAX_MMAP_SIZE>0
40898 winUnmapfile(pFile);
40899 #endif
40902 rc = osCloseHandle(pFile->h);
40903 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
40904 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
40905 #if SQLITE_OS_WINCE
40906 #define WINCE_DELETION_ATTEMPTS 3
40908 winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
40909 if( pAppData==NULL || !pAppData->bNoLock ){
40910 winceDestroyLock(pFile);
40913 if( pFile->zDeleteOnClose ){
40914 int cnt = 0;
40915 while(
40916 osDeleteFileW(pFile->zDeleteOnClose)==0
40917 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
40918 && cnt++ < WINCE_DELETION_ATTEMPTS
40920 sqlite3_win32_sleep(100); /* Wait a little before trying again */
40922 sqlite3_free(pFile->zDeleteOnClose);
40924 #endif
40925 if( rc ){
40926 pFile->h = NULL;
40928 OpenCounter(-1);
40929 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
40930 osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
40931 return rc ? SQLITE_OK
40932 : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
40933 "winClose", pFile->zPath);
40937 ** Read data from a file into a buffer. Return SQLITE_OK if all
40938 ** bytes were read successfully and SQLITE_IOERR if anything goes
40939 ** wrong.
40941 static int winRead(
40942 sqlite3_file *id, /* File to read from */
40943 void *pBuf, /* Write content into this buffer */
40944 int amt, /* Number of bytes to read */
40945 sqlite3_int64 offset /* Begin reading at this offset */
40947 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
40948 OVERLAPPED overlapped; /* The offset for ReadFile. */
40949 #endif
40950 winFile *pFile = (winFile*)id; /* file handle */
40951 DWORD nRead; /* Number of bytes actually read from file */
40952 int nRetry = 0; /* Number of retrys */
40954 assert( id!=0 );
40955 assert( amt>0 );
40956 assert( offset>=0 );
40957 SimulateIOError(return SQLITE_IOERR_READ);
40958 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
40959 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
40960 pFile->h, pBuf, amt, offset, pFile->locktype));
40962 #if SQLITE_MAX_MMAP_SIZE>0
40963 /* Deal with as much of this read request as possible by transfering
40964 ** data from the memory mapping using memcpy(). */
40965 if( offset<pFile->mmapSize ){
40966 if( offset+amt <= pFile->mmapSize ){
40967 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
40968 OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40969 osGetCurrentProcessId(), pFile, pFile->h));
40970 return SQLITE_OK;
40971 }else{
40972 int nCopy = (int)(pFile->mmapSize - offset);
40973 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
40974 pBuf = &((u8 *)pBuf)[nCopy];
40975 amt -= nCopy;
40976 offset += nCopy;
40979 #endif
40981 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
40982 if( winSeekFile(pFile, offset) ){
40983 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
40984 osGetCurrentProcessId(), pFile, pFile->h));
40985 return SQLITE_FULL;
40987 while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
40988 #else
40989 memset(&overlapped, 0, sizeof(OVERLAPPED));
40990 overlapped.Offset = (LONG)(offset & 0xffffffff);
40991 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
40992 while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
40993 osGetLastError()!=ERROR_HANDLE_EOF ){
40994 #endif
40995 DWORD lastErrno;
40996 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
40997 pFile->lastErrno = lastErrno;
40998 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
40999 osGetCurrentProcessId(), pFile, pFile->h));
41000 return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
41001 "winRead", pFile->zPath);
41003 winLogIoerr(nRetry, __LINE__);
41004 if( nRead<(DWORD)amt ){
41005 /* Unread parts of the buffer must be zero-filled */
41006 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
41007 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
41008 osGetCurrentProcessId(), pFile, pFile->h));
41009 return SQLITE_IOERR_SHORT_READ;
41012 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
41013 osGetCurrentProcessId(), pFile, pFile->h));
41014 return SQLITE_OK;
41018 ** Write data from a buffer into a file. Return SQLITE_OK on success
41019 ** or some other error code on failure.
41021 static int winWrite(
41022 sqlite3_file *id, /* File to write into */
41023 const void *pBuf, /* The bytes to be written */
41024 int amt, /* Number of bytes to write */
41025 sqlite3_int64 offset /* Offset into the file to begin writing at */
41027 int rc = 0; /* True if error has occurred, else false */
41028 winFile *pFile = (winFile*)id; /* File handle */
41029 int nRetry = 0; /* Number of retries */
41031 assert( amt>0 );
41032 assert( pFile );
41033 SimulateIOError(return SQLITE_IOERR_WRITE);
41034 SimulateDiskfullError(return SQLITE_FULL);
41036 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
41037 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
41038 pFile->h, pBuf, amt, offset, pFile->locktype));
41040 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
41041 /* Deal with as much of this write request as possible by transfering
41042 ** data from the memory mapping using memcpy(). */
41043 if( offset<pFile->mmapSize ){
41044 if( offset+amt <= pFile->mmapSize ){
41045 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
41046 OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
41047 osGetCurrentProcessId(), pFile, pFile->h));
41048 return SQLITE_OK;
41049 }else{
41050 int nCopy = (int)(pFile->mmapSize - offset);
41051 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
41052 pBuf = &((u8 *)pBuf)[nCopy];
41053 amt -= nCopy;
41054 offset += nCopy;
41057 #endif
41059 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
41060 rc = winSeekFile(pFile, offset);
41061 if( rc==0 ){
41062 #else
41064 #endif
41065 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
41066 OVERLAPPED overlapped; /* The offset for WriteFile. */
41067 #endif
41068 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
41069 int nRem = amt; /* Number of bytes yet to be written */
41070 DWORD nWrite; /* Bytes written by each WriteFile() call */
41071 DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
41073 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
41074 memset(&overlapped, 0, sizeof(OVERLAPPED));
41075 overlapped.Offset = (LONG)(offset & 0xffffffff);
41076 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
41077 #endif
41079 while( nRem>0 ){
41080 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
41081 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
41082 #else
41083 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
41084 #endif
41085 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
41086 break;
41088 assert( nWrite==0 || nWrite<=(DWORD)nRem );
41089 if( nWrite==0 || nWrite>(DWORD)nRem ){
41090 lastErrno = osGetLastError();
41091 break;
41093 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
41094 offset += nWrite;
41095 overlapped.Offset = (LONG)(offset & 0xffffffff);
41096 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
41097 #endif
41098 aRem += nWrite;
41099 nRem -= nWrite;
41101 if( nRem>0 ){
41102 pFile->lastErrno = lastErrno;
41103 rc = 1;
41107 if( rc ){
41108 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
41109 || ( pFile->lastErrno==ERROR_DISK_FULL )){
41110 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
41111 osGetCurrentProcessId(), pFile, pFile->h));
41112 return winLogError(SQLITE_FULL, pFile->lastErrno,
41113 "winWrite1", pFile->zPath);
41115 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
41116 osGetCurrentProcessId(), pFile, pFile->h));
41117 return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
41118 "winWrite2", pFile->zPath);
41119 }else{
41120 winLogIoerr(nRetry, __LINE__);
41122 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
41123 osGetCurrentProcessId(), pFile, pFile->h));
41124 return SQLITE_OK;
41128 ** Truncate an open file to a specified size
41130 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
41131 winFile *pFile = (winFile*)id; /* File handle object */
41132 int rc = SQLITE_OK; /* Return code for this function */
41133 DWORD lastErrno;
41135 assert( pFile );
41136 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
41137 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
41138 osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
41140 /* If the user has configured a chunk-size for this file, truncate the
41141 ** file so that it consists of an integer number of chunks (i.e. the
41142 ** actual file size after the operation may be larger than the requested
41143 ** size).
41145 if( pFile->szChunk>0 ){
41146 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
41149 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
41150 if( winSeekFile(pFile, nByte) ){
41151 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
41152 "winTruncate1", pFile->zPath);
41153 }else if( 0==osSetEndOfFile(pFile->h) &&
41154 ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
41155 pFile->lastErrno = lastErrno;
41156 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
41157 "winTruncate2", pFile->zPath);
41160 #if SQLITE_MAX_MMAP_SIZE>0
41161 /* If the file was truncated to a size smaller than the currently
41162 ** mapped region, reduce the effective mapping size as well. SQLite will
41163 ** use read() and write() to access data beyond this point from now on.
41165 if( pFile->pMapRegion && nByte<pFile->mmapSize ){
41166 pFile->mmapSize = nByte;
41168 #endif
41170 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
41171 osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
41172 return rc;
41175 #ifdef SQLITE_TEST
41177 ** Count the number of fullsyncs and normal syncs. This is used to test
41178 ** that syncs and fullsyncs are occuring at the right times.
41180 SQLITE_API int sqlite3_sync_count = 0;
41181 SQLITE_API int sqlite3_fullsync_count = 0;
41182 #endif
41185 ** Make sure all writes to a particular file are committed to disk.
41187 static int winSync(sqlite3_file *id, int flags){
41188 #ifndef SQLITE_NO_SYNC
41190 ** Used only when SQLITE_NO_SYNC is not defined.
41192 BOOL rc;
41193 #endif
41194 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
41195 defined(SQLITE_HAVE_OS_TRACE)
41197 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
41198 ** OSTRACE() macros.
41200 winFile *pFile = (winFile*)id;
41201 #else
41202 UNUSED_PARAMETER(id);
41203 #endif
41205 assert( pFile );
41206 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
41207 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
41208 || (flags&0x0F)==SQLITE_SYNC_FULL
41211 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
41212 ** line is to test that doing so does not cause any problems.
41214 SimulateDiskfullError( return SQLITE_FULL );
41216 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
41217 osGetCurrentProcessId(), pFile, pFile->h, flags,
41218 pFile->locktype));
41220 #ifndef SQLITE_TEST
41221 UNUSED_PARAMETER(flags);
41222 #else
41223 if( (flags&0x0F)==SQLITE_SYNC_FULL ){
41224 sqlite3_fullsync_count++;
41226 sqlite3_sync_count++;
41227 #endif
41229 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
41230 ** no-op
41232 #ifdef SQLITE_NO_SYNC
41233 OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
41234 osGetCurrentProcessId(), pFile, pFile->h));
41235 return SQLITE_OK;
41236 #else
41237 #if SQLITE_MAX_MMAP_SIZE>0
41238 if( pFile->pMapRegion ){
41239 if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
41240 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
41241 "rc=SQLITE_OK\n", osGetCurrentProcessId(),
41242 pFile, pFile->pMapRegion));
41243 }else{
41244 pFile->lastErrno = osGetLastError();
41245 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
41246 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
41247 pFile, pFile->pMapRegion));
41248 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41249 "winSync1", pFile->zPath);
41252 #endif
41253 rc = osFlushFileBuffers(pFile->h);
41254 SimulateIOError( rc=FALSE );
41255 if( rc ){
41256 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
41257 osGetCurrentProcessId(), pFile, pFile->h));
41258 return SQLITE_OK;
41259 }else{
41260 pFile->lastErrno = osGetLastError();
41261 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
41262 osGetCurrentProcessId(), pFile, pFile->h));
41263 return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
41264 "winSync2", pFile->zPath);
41266 #endif
41270 ** Determine the current size of a file in bytes
41272 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
41273 winFile *pFile = (winFile*)id;
41274 int rc = SQLITE_OK;
41276 assert( id!=0 );
41277 assert( pSize!=0 );
41278 SimulateIOError(return SQLITE_IOERR_FSTAT);
41279 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
41281 #if SQLITE_OS_WINRT
41283 FILE_STANDARD_INFO info;
41284 if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
41285 &info, sizeof(info)) ){
41286 *pSize = info.EndOfFile.QuadPart;
41287 }else{
41288 pFile->lastErrno = osGetLastError();
41289 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
41290 "winFileSize", pFile->zPath);
41293 #else
41295 DWORD upperBits;
41296 DWORD lowerBits;
41297 DWORD lastErrno;
41299 lowerBits = osGetFileSize(pFile->h, &upperBits);
41300 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
41301 if( (lowerBits == INVALID_FILE_SIZE)
41302 && ((lastErrno = osGetLastError())!=NO_ERROR) ){
41303 pFile->lastErrno = lastErrno;
41304 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
41305 "winFileSize", pFile->zPath);
41308 #endif
41309 OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
41310 pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
41311 return rc;
41315 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
41317 #ifndef LOCKFILE_FAIL_IMMEDIATELY
41318 # define LOCKFILE_FAIL_IMMEDIATELY 1
41319 #endif
41321 #ifndef LOCKFILE_EXCLUSIVE_LOCK
41322 # define LOCKFILE_EXCLUSIVE_LOCK 2
41323 #endif
41326 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
41327 ** When the LockFile function was used, it was always expected to fail
41328 ** immediately if the lock could not be obtained. Also, it always expected to
41329 ** obtain an exclusive lock. These flags are used with the LockFileEx function
41330 ** and reflect those expectations; therefore, they should not be changed.
41332 #ifndef SQLITE_LOCKFILE_FLAGS
41333 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
41334 LOCKFILE_EXCLUSIVE_LOCK)
41335 #endif
41338 ** Currently, SQLite never calls the LockFileEx function without wanting the
41339 ** call to fail immediately if the lock cannot be obtained.
41341 #ifndef SQLITE_LOCKFILEEX_FLAGS
41342 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
41343 #endif
41346 ** Acquire a reader lock.
41347 ** Different API routines are called depending on whether or not this
41348 ** is Win9x or WinNT.
41350 static int winGetReadLock(winFile *pFile){
41351 int res;
41352 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
41353 if( osIsNT() ){
41354 #if SQLITE_OS_WINCE
41356 ** NOTE: Windows CE is handled differently here due its lack of the Win32
41357 ** API LockFileEx.
41359 res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
41360 #else
41361 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
41362 SHARED_SIZE, 0);
41363 #endif
41365 #ifdef SQLITE_WIN32_HAS_ANSI
41366 else{
41367 int lk;
41368 sqlite3_randomness(sizeof(lk), &lk);
41369 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
41370 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
41371 SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
41373 #endif
41374 if( res == 0 ){
41375 pFile->lastErrno = osGetLastError();
41376 /* No need to log a failure to lock */
41378 OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
41379 return res;
41383 ** Undo a readlock
41385 static int winUnlockReadLock(winFile *pFile){
41386 int res;
41387 DWORD lastErrno;
41388 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
41389 if( osIsNT() ){
41390 res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
41392 #ifdef SQLITE_WIN32_HAS_ANSI
41393 else{
41394 res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
41396 #endif
41397 if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
41398 pFile->lastErrno = lastErrno;
41399 winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
41400 "winUnlockReadLock", pFile->zPath);
41402 OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
41403 return res;
41407 ** Lock the file with the lock specified by parameter locktype - one
41408 ** of the following:
41410 ** (1) SHARED_LOCK
41411 ** (2) RESERVED_LOCK
41412 ** (3) PENDING_LOCK
41413 ** (4) EXCLUSIVE_LOCK
41415 ** Sometimes when requesting one lock state, additional lock states
41416 ** are inserted in between. The locking might fail on one of the later
41417 ** transitions leaving the lock state different from what it started but
41418 ** still short of its goal. The following chart shows the allowed
41419 ** transitions and the inserted intermediate states:
41421 ** UNLOCKED -> SHARED
41422 ** SHARED -> RESERVED
41423 ** SHARED -> (PENDING) -> EXCLUSIVE
41424 ** RESERVED -> (PENDING) -> EXCLUSIVE
41425 ** PENDING -> EXCLUSIVE
41427 ** This routine will only increase a lock. The winUnlock() routine
41428 ** erases all locks at once and returns us immediately to locking level 0.
41429 ** It is not possible to lower the locking level one step at a time. You
41430 ** must go straight to locking level 0.
41432 static int winLock(sqlite3_file *id, int locktype){
41433 int rc = SQLITE_OK; /* Return code from subroutines */
41434 int res = 1; /* Result of a Windows lock call */
41435 int newLocktype; /* Set pFile->locktype to this value before exiting */
41436 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
41437 winFile *pFile = (winFile*)id;
41438 DWORD lastErrno = NO_ERROR;
41440 assert( id!=0 );
41441 OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
41442 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
41444 /* If there is already a lock of this type or more restrictive on the
41445 ** OsFile, do nothing. Don't use the end_lock: exit path, as
41446 ** sqlite3OsEnterMutex() hasn't been called yet.
41448 if( pFile->locktype>=locktype ){
41449 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
41450 return SQLITE_OK;
41453 /* Do not allow any kind of write-lock on a read-only database
41455 if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
41456 return SQLITE_IOERR_LOCK;
41459 /* Make sure the locking sequence is correct
41461 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
41462 assert( locktype!=PENDING_LOCK );
41463 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
41465 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
41466 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
41467 ** the PENDING_LOCK byte is temporary.
41469 newLocktype = pFile->locktype;
41470 if( pFile->locktype==NO_LOCK
41471 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
41473 int cnt = 3;
41474 while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
41475 PENDING_BYTE, 0, 1, 0))==0 ){
41476 /* Try 3 times to get the pending lock. This is needed to work
41477 ** around problems caused by indexing and/or anti-virus software on
41478 ** Windows systems.
41479 ** If you are using this code as a model for alternative VFSes, do not
41480 ** copy this retry logic. It is a hack intended for Windows only.
41482 lastErrno = osGetLastError();
41483 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
41484 pFile->h, cnt, res));
41485 if( lastErrno==ERROR_INVALID_HANDLE ){
41486 pFile->lastErrno = lastErrno;
41487 rc = SQLITE_IOERR_LOCK;
41488 OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
41489 pFile->h, cnt, sqlite3ErrName(rc)));
41490 return rc;
41492 if( cnt ) sqlite3_win32_sleep(1);
41494 gotPendingLock = res;
41495 if( !res ){
41496 lastErrno = osGetLastError();
41500 /* Acquire a shared lock
41502 if( locktype==SHARED_LOCK && res ){
41503 assert( pFile->locktype==NO_LOCK );
41504 res = winGetReadLock(pFile);
41505 if( res ){
41506 newLocktype = SHARED_LOCK;
41507 }else{
41508 lastErrno = osGetLastError();
41512 /* Acquire a RESERVED lock
41514 if( locktype==RESERVED_LOCK && res ){
41515 assert( pFile->locktype==SHARED_LOCK );
41516 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
41517 if( res ){
41518 newLocktype = RESERVED_LOCK;
41519 }else{
41520 lastErrno = osGetLastError();
41524 /* Acquire a PENDING lock
41526 if( locktype==EXCLUSIVE_LOCK && res ){
41527 newLocktype = PENDING_LOCK;
41528 gotPendingLock = 0;
41531 /* Acquire an EXCLUSIVE lock
41533 if( locktype==EXCLUSIVE_LOCK && res ){
41534 assert( pFile->locktype>=SHARED_LOCK );
41535 res = winUnlockReadLock(pFile);
41536 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
41537 SHARED_SIZE, 0);
41538 if( res ){
41539 newLocktype = EXCLUSIVE_LOCK;
41540 }else{
41541 lastErrno = osGetLastError();
41542 winGetReadLock(pFile);
41546 /* If we are holding a PENDING lock that ought to be released, then
41547 ** release it now.
41549 if( gotPendingLock && locktype==SHARED_LOCK ){
41550 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
41553 /* Update the state of the lock has held in the file descriptor then
41554 ** return the appropriate result code.
41556 if( res ){
41557 rc = SQLITE_OK;
41558 }else{
41559 pFile->lastErrno = lastErrno;
41560 rc = SQLITE_BUSY;
41561 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
41562 pFile->h, locktype, newLocktype));
41564 pFile->locktype = (u8)newLocktype;
41565 OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
41566 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
41567 return rc;
41571 ** This routine checks if there is a RESERVED lock held on the specified
41572 ** file by this or any other process. If such a lock is held, return
41573 ** non-zero, otherwise zero.
41575 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
41576 int res;
41577 winFile *pFile = (winFile*)id;
41579 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
41580 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
41582 assert( id!=0 );
41583 if( pFile->locktype>=RESERVED_LOCK ){
41584 res = 1;
41585 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
41586 }else{
41587 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
41588 if( res ){
41589 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
41591 res = !res;
41592 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
41594 *pResOut = res;
41595 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
41596 pFile->h, pResOut, *pResOut));
41597 return SQLITE_OK;
41601 ** Lower the locking level on file descriptor id to locktype. locktype
41602 ** must be either NO_LOCK or SHARED_LOCK.
41604 ** If the locking level of the file descriptor is already at or below
41605 ** the requested locking level, this routine is a no-op.
41607 ** It is not possible for this routine to fail if the second argument
41608 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
41609 ** might return SQLITE_IOERR;
41611 static int winUnlock(sqlite3_file *id, int locktype){
41612 int type;
41613 winFile *pFile = (winFile*)id;
41614 int rc = SQLITE_OK;
41615 assert( pFile!=0 );
41616 assert( locktype<=SHARED_LOCK );
41617 OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
41618 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
41619 type = pFile->locktype;
41620 if( type>=EXCLUSIVE_LOCK ){
41621 winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
41622 if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
41623 /* This should never happen. We should always be able to
41624 ** reacquire the read lock */
41625 rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
41626 "winUnlock", pFile->zPath);
41629 if( type>=RESERVED_LOCK ){
41630 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
41632 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
41633 winUnlockReadLock(pFile);
41635 if( type>=PENDING_LOCK ){
41636 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
41638 pFile->locktype = (u8)locktype;
41639 OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
41640 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
41641 return rc;
41644 /******************************************************************************
41645 ****************************** No-op Locking **********************************
41647 ** Of the various locking implementations available, this is by far the
41648 ** simplest: locking is ignored. No attempt is made to lock the database
41649 ** file for reading or writing.
41651 ** This locking mode is appropriate for use on read-only databases
41652 ** (ex: databases that are burned into CD-ROM, for example.) It can
41653 ** also be used if the application employs some external mechanism to
41654 ** prevent simultaneous access of the same database by two or more
41655 ** database connections. But there is a serious risk of database
41656 ** corruption if this locking mode is used in situations where multiple
41657 ** database connections are accessing the same database file at the same
41658 ** time and one or more of those connections are writing.
41661 static int winNolockLock(sqlite3_file *id, int locktype){
41662 UNUSED_PARAMETER(id);
41663 UNUSED_PARAMETER(locktype);
41664 return SQLITE_OK;
41667 static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
41668 UNUSED_PARAMETER(id);
41669 UNUSED_PARAMETER(pResOut);
41670 return SQLITE_OK;
41673 static int winNolockUnlock(sqlite3_file *id, int locktype){
41674 UNUSED_PARAMETER(id);
41675 UNUSED_PARAMETER(locktype);
41676 return SQLITE_OK;
41679 /******************* End of the no-op lock implementation *********************
41680 ******************************************************************************/
41683 ** If *pArg is initially negative then this is a query. Set *pArg to
41684 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
41686 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
41688 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
41689 if( *pArg<0 ){
41690 *pArg = (pFile->ctrlFlags & mask)!=0;
41691 }else if( (*pArg)==0 ){
41692 pFile->ctrlFlags &= ~mask;
41693 }else{
41694 pFile->ctrlFlags |= mask;
41698 /* Forward references to VFS helper methods used for temporary files */
41699 static int winGetTempname(sqlite3_vfs *, char **);
41700 static int winIsDir(const void *);
41701 static BOOL winIsDriveLetterAndColon(const char *);
41704 ** Control and query of the open file handle.
41706 static int winFileControl(sqlite3_file *id, int op, void *pArg){
41707 winFile *pFile = (winFile*)id;
41708 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
41709 switch( op ){
41710 case SQLITE_FCNTL_LOCKSTATE: {
41711 *(int*)pArg = pFile->locktype;
41712 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41713 return SQLITE_OK;
41715 case SQLITE_FCNTL_LAST_ERRNO: {
41716 *(int*)pArg = (int)pFile->lastErrno;
41717 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41718 return SQLITE_OK;
41720 case SQLITE_FCNTL_CHUNK_SIZE: {
41721 pFile->szChunk = *(int *)pArg;
41722 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41723 return SQLITE_OK;
41725 case SQLITE_FCNTL_SIZE_HINT: {
41726 if( pFile->szChunk>0 ){
41727 sqlite3_int64 oldSz;
41728 int rc = winFileSize(id, &oldSz);
41729 if( rc==SQLITE_OK ){
41730 sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
41731 if( newSz>oldSz ){
41732 SimulateIOErrorBenign(1);
41733 rc = winTruncate(id, newSz);
41734 SimulateIOErrorBenign(0);
41737 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
41738 return rc;
41740 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41741 return SQLITE_OK;
41743 case SQLITE_FCNTL_PERSIST_WAL: {
41744 winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
41745 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41746 return SQLITE_OK;
41748 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
41749 winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
41750 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41751 return SQLITE_OK;
41753 case SQLITE_FCNTL_VFSNAME: {
41754 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
41755 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41756 return SQLITE_OK;
41758 case SQLITE_FCNTL_WIN32_AV_RETRY: {
41759 int *a = (int*)pArg;
41760 if( a[0]>0 ){
41761 winIoerrRetry = a[0];
41762 }else{
41763 a[0] = winIoerrRetry;
41765 if( a[1]>0 ){
41766 winIoerrRetryDelay = a[1];
41767 }else{
41768 a[1] = winIoerrRetryDelay;
41770 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41771 return SQLITE_OK;
41773 case SQLITE_FCNTL_WIN32_GET_HANDLE: {
41774 LPHANDLE phFile = (LPHANDLE)pArg;
41775 *phFile = pFile->h;
41776 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41777 return SQLITE_OK;
41779 #ifdef SQLITE_TEST
41780 case SQLITE_FCNTL_WIN32_SET_HANDLE: {
41781 LPHANDLE phFile = (LPHANDLE)pArg;
41782 HANDLE hOldFile = pFile->h;
41783 pFile->h = *phFile;
41784 *phFile = hOldFile;
41785 OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
41786 hOldFile, pFile->h));
41787 return SQLITE_OK;
41789 #endif
41790 case SQLITE_FCNTL_TEMPFILENAME: {
41791 char *zTFile = 0;
41792 int rc = winGetTempname(pFile->pVfs, &zTFile);
41793 if( rc==SQLITE_OK ){
41794 *(char**)pArg = zTFile;
41796 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
41797 return rc;
41799 #if SQLITE_MAX_MMAP_SIZE>0
41800 case SQLITE_FCNTL_MMAP_SIZE: {
41801 i64 newLimit = *(i64*)pArg;
41802 int rc = SQLITE_OK;
41803 if( newLimit>sqlite3GlobalConfig.mxMmap ){
41804 newLimit = sqlite3GlobalConfig.mxMmap;
41807 /* The value of newLimit may be eventually cast to (SIZE_T) and passed
41808 ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
41809 ** least a 64-bit type. */
41810 if( newLimit>0 && sizeof(SIZE_T)<8 ){
41811 newLimit = (newLimit & 0x7FFFFFFF);
41814 *(i64*)pArg = pFile->mmapSizeMax;
41815 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
41816 pFile->mmapSizeMax = newLimit;
41817 if( pFile->mmapSize>0 ){
41818 winUnmapfile(pFile);
41819 rc = winMapfile(pFile, -1);
41822 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
41823 return rc;
41825 #endif
41827 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
41828 return SQLITE_NOTFOUND;
41832 ** Return the sector size in bytes of the underlying block device for
41833 ** the specified file. This is almost always 512 bytes, but may be
41834 ** larger for some devices.
41836 ** SQLite code assumes this function cannot fail. It also assumes that
41837 ** if two files are created in the same file-system directory (i.e.
41838 ** a database and its journal file) that the sector size will be the
41839 ** same for both.
41841 static int winSectorSize(sqlite3_file *id){
41842 (void)id;
41843 return SQLITE_DEFAULT_SECTOR_SIZE;
41847 ** Return a vector of device characteristics.
41849 static int winDeviceCharacteristics(sqlite3_file *id){
41850 winFile *p = (winFile*)id;
41851 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
41852 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
41856 ** Windows will only let you create file view mappings
41857 ** on allocation size granularity boundaries.
41858 ** During sqlite3_os_init() we do a GetSystemInfo()
41859 ** to get the granularity size.
41861 static SYSTEM_INFO winSysInfo;
41863 #ifndef SQLITE_OMIT_WAL
41866 ** Helper functions to obtain and relinquish the global mutex. The
41867 ** global mutex is used to protect the winLockInfo objects used by
41868 ** this file, all of which may be shared by multiple threads.
41870 ** Function winShmMutexHeld() is used to assert() that the global mutex
41871 ** is held when required. This function is only used as part of assert()
41872 ** statements. e.g.
41874 ** winShmEnterMutex()
41875 ** assert( winShmMutexHeld() );
41876 ** winShmLeaveMutex()
41878 static void winShmEnterMutex(void){
41879 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
41881 static void winShmLeaveMutex(void){
41882 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
41884 #ifndef NDEBUG
41885 static int winShmMutexHeld(void) {
41886 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
41888 #endif
41891 ** Object used to represent a single file opened and mmapped to provide
41892 ** shared memory. When multiple threads all reference the same
41893 ** log-summary, each thread has its own winFile object, but they all
41894 ** point to a single instance of this object. In other words, each
41895 ** log-summary is opened only once per process.
41897 ** winShmMutexHeld() must be true when creating or destroying
41898 ** this object or while reading or writing the following fields:
41900 ** nRef
41901 ** pNext
41903 ** The following fields are read-only after the object is created:
41905 ** fid
41906 ** zFilename
41908 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
41909 ** winShmMutexHeld() is true when reading or writing any other field
41910 ** in this structure.
41913 struct winShmNode {
41914 sqlite3_mutex *mutex; /* Mutex to access this object */
41915 char *zFilename; /* Name of the file */
41916 winFile hFile; /* File handle from winOpen */
41918 int szRegion; /* Size of shared-memory regions */
41919 int nRegion; /* Size of array apRegion */
41920 struct ShmRegion {
41921 HANDLE hMap; /* File handle from CreateFileMapping */
41922 void *pMap;
41923 } *aRegion;
41924 DWORD lastErrno; /* The Windows errno from the last I/O error */
41926 int nRef; /* Number of winShm objects pointing to this */
41927 winShm *pFirst; /* All winShm objects pointing to this */
41928 winShmNode *pNext; /* Next in list of all winShmNode objects */
41929 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
41930 u8 nextShmId; /* Next available winShm.id value */
41931 #endif
41935 ** A global array of all winShmNode objects.
41937 ** The winShmMutexHeld() must be true while reading or writing this list.
41939 static winShmNode *winShmNodeList = 0;
41942 ** Structure used internally by this VFS to record the state of an
41943 ** open shared memory connection.
41945 ** The following fields are initialized when this object is created and
41946 ** are read-only thereafter:
41948 ** winShm.pShmNode
41949 ** winShm.id
41951 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
41952 ** while accessing any read/write fields.
41954 struct winShm {
41955 winShmNode *pShmNode; /* The underlying winShmNode object */
41956 winShm *pNext; /* Next winShm with the same winShmNode */
41957 u8 hasMutex; /* True if holding the winShmNode mutex */
41958 u16 sharedMask; /* Mask of shared locks held */
41959 u16 exclMask; /* Mask of exclusive locks held */
41960 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
41961 u8 id; /* Id of this connection with its winShmNode */
41962 #endif
41966 ** Constants used for locking
41968 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
41969 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
41972 ** Apply advisory locks for all n bytes beginning at ofst.
41974 #define WINSHM_UNLCK 1
41975 #define WINSHM_RDLCK 2
41976 #define WINSHM_WRLCK 3
41977 static int winShmSystemLock(
41978 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
41979 int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
41980 int ofst, /* Offset to first byte to be locked/unlocked */
41981 int nByte /* Number of bytes to lock or unlock */
41983 int rc = 0; /* Result code form Lock/UnlockFileEx() */
41985 /* Access to the winShmNode object is serialized by the caller */
41986 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
41988 OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
41989 pFile->hFile.h, lockType, ofst, nByte));
41991 /* Release/Acquire the system-level lock */
41992 if( lockType==WINSHM_UNLCK ){
41993 rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
41994 }else{
41995 /* Initialize the locking parameters */
41996 DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
41997 if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
41998 rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
42001 if( rc!= 0 ){
42002 rc = SQLITE_OK;
42003 }else{
42004 pFile->lastErrno = osGetLastError();
42005 rc = SQLITE_BUSY;
42008 OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
42009 pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
42010 "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
42012 return rc;
42015 /* Forward references to VFS methods */
42016 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
42017 static int winDelete(sqlite3_vfs *,const char*,int);
42020 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
42022 ** This is not a VFS shared-memory method; it is a utility function called
42023 ** by VFS shared-memory methods.
42025 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
42026 winShmNode **pp;
42027 winShmNode *p;
42028 assert( winShmMutexHeld() );
42029 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
42030 osGetCurrentProcessId(), deleteFlag));
42031 pp = &winShmNodeList;
42032 while( (p = *pp)!=0 ){
42033 if( p->nRef==0 ){
42034 int i;
42035 if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
42036 for(i=0; i<p->nRegion; i++){
42037 BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
42038 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
42039 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
42040 UNUSED_VARIABLE_VALUE(bRc);
42041 bRc = osCloseHandle(p->aRegion[i].hMap);
42042 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
42043 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
42044 UNUSED_VARIABLE_VALUE(bRc);
42046 if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
42047 SimulateIOErrorBenign(1);
42048 winClose((sqlite3_file *)&p->hFile);
42049 SimulateIOErrorBenign(0);
42051 if( deleteFlag ){
42052 SimulateIOErrorBenign(1);
42053 sqlite3BeginBenignMalloc();
42054 winDelete(pVfs, p->zFilename, 0);
42055 sqlite3EndBenignMalloc();
42056 SimulateIOErrorBenign(0);
42058 *pp = p->pNext;
42059 sqlite3_free(p->aRegion);
42060 sqlite3_free(p);
42061 }else{
42062 pp = &p->pNext;
42068 ** Open the shared-memory area associated with database file pDbFd.
42070 ** When opening a new shared-memory file, if no other instances of that
42071 ** file are currently open, in this process or in other processes, then
42072 ** the file must be truncated to zero length or have its header cleared.
42074 static int winOpenSharedMemory(winFile *pDbFd){
42075 struct winShm *p; /* The connection to be opened */
42076 struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
42077 int rc; /* Result code */
42078 struct winShmNode *pNew; /* Newly allocated winShmNode */
42079 int nName; /* Size of zName in bytes */
42081 assert( pDbFd->pShm==0 ); /* Not previously opened */
42083 /* Allocate space for the new sqlite3_shm object. Also speculatively
42084 ** allocate space for a new winShmNode and filename.
42086 p = sqlite3MallocZero( sizeof(*p) );
42087 if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
42088 nName = sqlite3Strlen30(pDbFd->zPath);
42089 pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
42090 if( pNew==0 ){
42091 sqlite3_free(p);
42092 return SQLITE_IOERR_NOMEM_BKPT;
42094 pNew->zFilename = (char*)&pNew[1];
42095 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
42096 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
42098 /* Look to see if there is an existing winShmNode that can be used.
42099 ** If no matching winShmNode currently exists, create a new one.
42101 winShmEnterMutex();
42102 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
42103 /* TBD need to come up with better match here. Perhaps
42104 ** use FILE_ID_BOTH_DIR_INFO Structure.
42106 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
42108 if( pShmNode ){
42109 sqlite3_free(pNew);
42110 }else{
42111 pShmNode = pNew;
42112 pNew = 0;
42113 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
42114 pShmNode->pNext = winShmNodeList;
42115 winShmNodeList = pShmNode;
42117 if( sqlite3GlobalConfig.bCoreMutex ){
42118 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
42119 if( pShmNode->mutex==0 ){
42120 rc = SQLITE_IOERR_NOMEM_BKPT;
42121 goto shm_open_err;
42125 rc = winOpen(pDbFd->pVfs,
42126 pShmNode->zFilename, /* Name of the file (UTF-8) */
42127 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
42128 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
42130 if( SQLITE_OK!=rc ){
42131 goto shm_open_err;
42134 /* Check to see if another process is holding the dead-man switch.
42135 ** If not, truncate the file to zero length.
42137 if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
42138 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
42139 if( rc!=SQLITE_OK ){
42140 rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
42141 "winOpenShm", pDbFd->zPath);
42144 if( rc==SQLITE_OK ){
42145 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
42146 rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
42148 if( rc ) goto shm_open_err;
42151 /* Make the new connection a child of the winShmNode */
42152 p->pShmNode = pShmNode;
42153 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
42154 p->id = pShmNode->nextShmId++;
42155 #endif
42156 pShmNode->nRef++;
42157 pDbFd->pShm = p;
42158 winShmLeaveMutex();
42160 /* The reference count on pShmNode has already been incremented under
42161 ** the cover of the winShmEnterMutex() mutex and the pointer from the
42162 ** new (struct winShm) object to the pShmNode has been set. All that is
42163 ** left to do is to link the new object into the linked list starting
42164 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
42165 ** mutex.
42167 sqlite3_mutex_enter(pShmNode->mutex);
42168 p->pNext = pShmNode->pFirst;
42169 pShmNode->pFirst = p;
42170 sqlite3_mutex_leave(pShmNode->mutex);
42171 return SQLITE_OK;
42173 /* Jump here on any error */
42174 shm_open_err:
42175 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
42176 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
42177 sqlite3_free(p);
42178 sqlite3_free(pNew);
42179 winShmLeaveMutex();
42180 return rc;
42184 ** Close a connection to shared-memory. Delete the underlying
42185 ** storage if deleteFlag is true.
42187 static int winShmUnmap(
42188 sqlite3_file *fd, /* Database holding shared memory */
42189 int deleteFlag /* Delete after closing if true */
42191 winFile *pDbFd; /* Database holding shared-memory */
42192 winShm *p; /* The connection to be closed */
42193 winShmNode *pShmNode; /* The underlying shared-memory file */
42194 winShm **pp; /* For looping over sibling connections */
42196 pDbFd = (winFile*)fd;
42197 p = pDbFd->pShm;
42198 if( p==0 ) return SQLITE_OK;
42199 pShmNode = p->pShmNode;
42201 /* Remove connection p from the set of connections associated
42202 ** with pShmNode */
42203 sqlite3_mutex_enter(pShmNode->mutex);
42204 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
42205 *pp = p->pNext;
42207 /* Free the connection p */
42208 sqlite3_free(p);
42209 pDbFd->pShm = 0;
42210 sqlite3_mutex_leave(pShmNode->mutex);
42212 /* If pShmNode->nRef has reached 0, then close the underlying
42213 ** shared-memory file, too */
42214 winShmEnterMutex();
42215 assert( pShmNode->nRef>0 );
42216 pShmNode->nRef--;
42217 if( pShmNode->nRef==0 ){
42218 winShmPurge(pDbFd->pVfs, deleteFlag);
42220 winShmLeaveMutex();
42222 return SQLITE_OK;
42226 ** Change the lock state for a shared-memory segment.
42228 static int winShmLock(
42229 sqlite3_file *fd, /* Database file holding the shared memory */
42230 int ofst, /* First lock to acquire or release */
42231 int n, /* Number of locks to acquire or release */
42232 int flags /* What to do with the lock */
42234 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
42235 winShm *p = pDbFd->pShm; /* The shared memory being locked */
42236 winShm *pX; /* For looping over all siblings */
42237 winShmNode *pShmNode = p->pShmNode;
42238 int rc = SQLITE_OK; /* Result code */
42239 u16 mask; /* Mask of locks to take or release */
42241 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
42242 assert( n>=1 );
42243 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
42244 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
42245 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
42246 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
42247 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
42249 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
42250 assert( n>1 || mask==(1<<ofst) );
42251 sqlite3_mutex_enter(pShmNode->mutex);
42252 if( flags & SQLITE_SHM_UNLOCK ){
42253 u16 allMask = 0; /* Mask of locks held by siblings */
42255 /* See if any siblings hold this same lock */
42256 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
42257 if( pX==p ) continue;
42258 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
42259 allMask |= pX->sharedMask;
42262 /* Unlock the system-level locks */
42263 if( (mask & allMask)==0 ){
42264 rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
42265 }else{
42266 rc = SQLITE_OK;
42269 /* Undo the local locks */
42270 if( rc==SQLITE_OK ){
42271 p->exclMask &= ~mask;
42272 p->sharedMask &= ~mask;
42274 }else if( flags & SQLITE_SHM_SHARED ){
42275 u16 allShared = 0; /* Union of locks held by connections other than "p" */
42277 /* Find out which shared locks are already held by sibling connections.
42278 ** If any sibling already holds an exclusive lock, go ahead and return
42279 ** SQLITE_BUSY.
42281 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
42282 if( (pX->exclMask & mask)!=0 ){
42283 rc = SQLITE_BUSY;
42284 break;
42286 allShared |= pX->sharedMask;
42289 /* Get shared locks at the system level, if necessary */
42290 if( rc==SQLITE_OK ){
42291 if( (allShared & mask)==0 ){
42292 rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
42293 }else{
42294 rc = SQLITE_OK;
42298 /* Get the local shared locks */
42299 if( rc==SQLITE_OK ){
42300 p->sharedMask |= mask;
42302 }else{
42303 /* Make sure no sibling connections hold locks that will block this
42304 ** lock. If any do, return SQLITE_BUSY right away.
42306 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
42307 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
42308 rc = SQLITE_BUSY;
42309 break;
42313 /* Get the exclusive locks at the system level. Then if successful
42314 ** also mark the local connection as being locked.
42316 if( rc==SQLITE_OK ){
42317 rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
42318 if( rc==SQLITE_OK ){
42319 assert( (p->sharedMask & mask)==0 );
42320 p->exclMask |= mask;
42324 sqlite3_mutex_leave(pShmNode->mutex);
42325 OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
42326 osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
42327 sqlite3ErrName(rc)));
42328 return rc;
42332 ** Implement a memory barrier or memory fence on shared memory.
42334 ** All loads and stores begun before the barrier must complete before
42335 ** any load or store begun after the barrier.
42337 static void winShmBarrier(
42338 sqlite3_file *fd /* Database holding the shared memory */
42340 UNUSED_PARAMETER(fd);
42341 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
42342 winShmEnterMutex(); /* Also mutex, for redundancy */
42343 winShmLeaveMutex();
42347 ** This function is called to obtain a pointer to region iRegion of the
42348 ** shared-memory associated with the database file fd. Shared-memory regions
42349 ** are numbered starting from zero. Each shared-memory region is szRegion
42350 ** bytes in size.
42352 ** If an error occurs, an error code is returned and *pp is set to NULL.
42354 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
42355 ** region has not been allocated (by any client, including one running in a
42356 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
42357 ** isWrite is non-zero and the requested shared-memory region has not yet
42358 ** been allocated, it is allocated by this function.
42360 ** If the shared-memory region has already been allocated or is allocated by
42361 ** this call as described above, then it is mapped into this processes
42362 ** address space (if it is not already), *pp is set to point to the mapped
42363 ** memory and SQLITE_OK returned.
42365 static int winShmMap(
42366 sqlite3_file *fd, /* Handle open on database file */
42367 int iRegion, /* Region to retrieve */
42368 int szRegion, /* Size of regions */
42369 int isWrite, /* True to extend file if necessary */
42370 void volatile **pp /* OUT: Mapped memory */
42372 winFile *pDbFd = (winFile*)fd;
42373 winShm *pShm = pDbFd->pShm;
42374 winShmNode *pShmNode;
42375 int rc = SQLITE_OK;
42377 if( !pShm ){
42378 rc = winOpenSharedMemory(pDbFd);
42379 if( rc!=SQLITE_OK ) return rc;
42380 pShm = pDbFd->pShm;
42382 pShmNode = pShm->pShmNode;
42384 sqlite3_mutex_enter(pShmNode->mutex);
42385 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
42387 if( pShmNode->nRegion<=iRegion ){
42388 struct ShmRegion *apNew; /* New aRegion[] array */
42389 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
42390 sqlite3_int64 sz; /* Current size of wal-index file */
42392 pShmNode->szRegion = szRegion;
42394 /* The requested region is not mapped into this processes address space.
42395 ** Check to see if it has been allocated (i.e. if the wal-index file is
42396 ** large enough to contain the requested region).
42398 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
42399 if( rc!=SQLITE_OK ){
42400 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
42401 "winShmMap1", pDbFd->zPath);
42402 goto shmpage_out;
42405 if( sz<nByte ){
42406 /* The requested memory region does not exist. If isWrite is set to
42407 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
42409 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
42410 ** the requested memory region.
42412 if( !isWrite ) goto shmpage_out;
42413 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
42414 if( rc!=SQLITE_OK ){
42415 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
42416 "winShmMap2", pDbFd->zPath);
42417 goto shmpage_out;
42421 /* Map the requested memory region into this processes address space. */
42422 apNew = (struct ShmRegion *)sqlite3_realloc64(
42423 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
42425 if( !apNew ){
42426 rc = SQLITE_IOERR_NOMEM_BKPT;
42427 goto shmpage_out;
42429 pShmNode->aRegion = apNew;
42431 while( pShmNode->nRegion<=iRegion ){
42432 HANDLE hMap = NULL; /* file-mapping handle */
42433 void *pMap = 0; /* Mapped memory region */
42435 #if SQLITE_OS_WINRT
42436 hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
42437 NULL, PAGE_READWRITE, nByte, NULL
42439 #elif defined(SQLITE_WIN32_HAS_WIDE)
42440 hMap = osCreateFileMappingW(pShmNode->hFile.h,
42441 NULL, PAGE_READWRITE, 0, nByte, NULL
42443 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
42444 hMap = osCreateFileMappingA(pShmNode->hFile.h,
42445 NULL, PAGE_READWRITE, 0, nByte, NULL
42447 #endif
42448 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
42449 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
42450 hMap ? "ok" : "failed"));
42451 if( hMap ){
42452 int iOffset = pShmNode->nRegion*szRegion;
42453 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
42454 #if SQLITE_OS_WINRT
42455 pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
42456 iOffset - iOffsetShift, szRegion + iOffsetShift
42458 #else
42459 pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
42460 0, iOffset - iOffsetShift, szRegion + iOffsetShift
42462 #endif
42463 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
42464 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
42465 szRegion, pMap ? "ok" : "failed"));
42467 if( !pMap ){
42468 pShmNode->lastErrno = osGetLastError();
42469 rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
42470 "winShmMap3", pDbFd->zPath);
42471 if( hMap ) osCloseHandle(hMap);
42472 goto shmpage_out;
42475 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
42476 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
42477 pShmNode->nRegion++;
42481 shmpage_out:
42482 if( pShmNode->nRegion>iRegion ){
42483 int iOffset = iRegion*szRegion;
42484 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
42485 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
42486 *pp = (void *)&p[iOffsetShift];
42487 }else{
42488 *pp = 0;
42490 sqlite3_mutex_leave(pShmNode->mutex);
42491 return rc;
42494 #else
42495 # define winShmMap 0
42496 # define winShmLock 0
42497 # define winShmBarrier 0
42498 # define winShmUnmap 0
42499 #endif /* #ifndef SQLITE_OMIT_WAL */
42502 ** Cleans up the mapped region of the specified file, if any.
42504 #if SQLITE_MAX_MMAP_SIZE>0
42505 static int winUnmapfile(winFile *pFile){
42506 assert( pFile!=0 );
42507 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
42508 "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
42509 osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
42510 pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
42511 if( pFile->pMapRegion ){
42512 if( !osUnmapViewOfFile(pFile->pMapRegion) ){
42513 pFile->lastErrno = osGetLastError();
42514 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
42515 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
42516 pFile->pMapRegion));
42517 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
42518 "winUnmapfile1", pFile->zPath);
42520 pFile->pMapRegion = 0;
42521 pFile->mmapSize = 0;
42522 pFile->mmapSizeActual = 0;
42524 if( pFile->hMap!=NULL ){
42525 if( !osCloseHandle(pFile->hMap) ){
42526 pFile->lastErrno = osGetLastError();
42527 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
42528 osGetCurrentProcessId(), pFile, pFile->hMap));
42529 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
42530 "winUnmapfile2", pFile->zPath);
42532 pFile->hMap = NULL;
42534 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
42535 osGetCurrentProcessId(), pFile));
42536 return SQLITE_OK;
42540 ** Memory map or remap the file opened by file-descriptor pFd (if the file
42541 ** is already mapped, the existing mapping is replaced by the new). Or, if
42542 ** there already exists a mapping for this file, and there are still
42543 ** outstanding xFetch() references to it, this function is a no-op.
42545 ** If parameter nByte is non-negative, then it is the requested size of
42546 ** the mapping to create. Otherwise, if nByte is less than zero, then the
42547 ** requested size is the size of the file on disk. The actual size of the
42548 ** created mapping is either the requested size or the value configured
42549 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
42551 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
42552 ** recreated as a result of outstanding references) or an SQLite error
42553 ** code otherwise.
42555 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
42556 sqlite3_int64 nMap = nByte;
42557 int rc;
42559 assert( nMap>=0 || pFd->nFetchOut==0 );
42560 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
42561 osGetCurrentProcessId(), pFd, nByte));
42563 if( pFd->nFetchOut>0 ) return SQLITE_OK;
42565 if( nMap<0 ){
42566 rc = winFileSize((sqlite3_file*)pFd, &nMap);
42567 if( rc ){
42568 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
42569 osGetCurrentProcessId(), pFd));
42570 return SQLITE_IOERR_FSTAT;
42573 if( nMap>pFd->mmapSizeMax ){
42574 nMap = pFd->mmapSizeMax;
42576 nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
42578 if( nMap==0 && pFd->mmapSize>0 ){
42579 winUnmapfile(pFd);
42581 if( nMap!=pFd->mmapSize ){
42582 void *pNew = 0;
42583 DWORD protect = PAGE_READONLY;
42584 DWORD flags = FILE_MAP_READ;
42586 winUnmapfile(pFd);
42587 #ifdef SQLITE_MMAP_READWRITE
42588 if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
42589 protect = PAGE_READWRITE;
42590 flags |= FILE_MAP_WRITE;
42592 #endif
42593 #if SQLITE_OS_WINRT
42594 pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
42595 #elif defined(SQLITE_WIN32_HAS_WIDE)
42596 pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
42597 (DWORD)((nMap>>32) & 0xffffffff),
42598 (DWORD)(nMap & 0xffffffff), NULL);
42599 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
42600 pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
42601 (DWORD)((nMap>>32) & 0xffffffff),
42602 (DWORD)(nMap & 0xffffffff), NULL);
42603 #endif
42604 if( pFd->hMap==NULL ){
42605 pFd->lastErrno = osGetLastError();
42606 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
42607 "winMapfile1", pFd->zPath);
42608 /* Log the error, but continue normal operation using xRead/xWrite */
42609 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
42610 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
42611 return SQLITE_OK;
42613 assert( (nMap % winSysInfo.dwPageSize)==0 );
42614 assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
42615 #if SQLITE_OS_WINRT
42616 pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
42617 #else
42618 pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
42619 #endif
42620 if( pNew==NULL ){
42621 osCloseHandle(pFd->hMap);
42622 pFd->hMap = NULL;
42623 pFd->lastErrno = osGetLastError();
42624 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
42625 "winMapfile2", pFd->zPath);
42626 /* Log the error, but continue normal operation using xRead/xWrite */
42627 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
42628 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
42629 return SQLITE_OK;
42631 pFd->pMapRegion = pNew;
42632 pFd->mmapSize = nMap;
42633 pFd->mmapSizeActual = nMap;
42636 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
42637 osGetCurrentProcessId(), pFd));
42638 return SQLITE_OK;
42640 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
42643 ** If possible, return a pointer to a mapping of file fd starting at offset
42644 ** iOff. The mapping must be valid for at least nAmt bytes.
42646 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
42647 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
42648 ** Finally, if an error does occur, return an SQLite error code. The final
42649 ** value of *pp is undefined in this case.
42651 ** If this function does return a pointer, the caller must eventually
42652 ** release the reference by calling winUnfetch().
42654 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
42655 #if SQLITE_MAX_MMAP_SIZE>0
42656 winFile *pFd = (winFile*)fd; /* The underlying database file */
42657 #endif
42658 *pp = 0;
42660 OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
42661 osGetCurrentProcessId(), fd, iOff, nAmt, pp));
42663 #if SQLITE_MAX_MMAP_SIZE>0
42664 if( pFd->mmapSizeMax>0 ){
42665 if( pFd->pMapRegion==0 ){
42666 int rc = winMapfile(pFd, -1);
42667 if( rc!=SQLITE_OK ){
42668 OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
42669 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
42670 return rc;
42673 if( pFd->mmapSize >= iOff+nAmt ){
42674 *pp = &((u8 *)pFd->pMapRegion)[iOff];
42675 pFd->nFetchOut++;
42678 #endif
42680 OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
42681 osGetCurrentProcessId(), fd, pp, *pp));
42682 return SQLITE_OK;
42686 ** If the third argument is non-NULL, then this function releases a
42687 ** reference obtained by an earlier call to winFetch(). The second
42688 ** argument passed to this function must be the same as the corresponding
42689 ** argument that was passed to the winFetch() invocation.
42691 ** Or, if the third argument is NULL, then this function is being called
42692 ** to inform the VFS layer that, according to POSIX, any existing mapping
42693 ** may now be invalid and should be unmapped.
42695 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
42696 #if SQLITE_MAX_MMAP_SIZE>0
42697 winFile *pFd = (winFile*)fd; /* The underlying database file */
42699 /* If p==0 (unmap the entire file) then there must be no outstanding
42700 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
42701 ** then there must be at least one outstanding. */
42702 assert( (p==0)==(pFd->nFetchOut==0) );
42704 /* If p!=0, it must match the iOff value. */
42705 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
42707 OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
42708 osGetCurrentProcessId(), pFd, iOff, p));
42710 if( p ){
42711 pFd->nFetchOut--;
42712 }else{
42713 /* FIXME: If Windows truly always prevents truncating or deleting a
42714 ** file while a mapping is held, then the following winUnmapfile() call
42715 ** is unnecessary can be omitted - potentially improving
42716 ** performance. */
42717 winUnmapfile(pFd);
42720 assert( pFd->nFetchOut>=0 );
42721 #endif
42723 OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
42724 osGetCurrentProcessId(), fd));
42725 return SQLITE_OK;
42729 ** Here ends the implementation of all sqlite3_file methods.
42731 ********************** End sqlite3_file Methods *******************************
42732 ******************************************************************************/
42735 ** This vector defines all the methods that can operate on an
42736 ** sqlite3_file for win32.
42738 static const sqlite3_io_methods winIoMethod = {
42739 3, /* iVersion */
42740 winClose, /* xClose */
42741 winRead, /* xRead */
42742 winWrite, /* xWrite */
42743 winTruncate, /* xTruncate */
42744 winSync, /* xSync */
42745 winFileSize, /* xFileSize */
42746 winLock, /* xLock */
42747 winUnlock, /* xUnlock */
42748 winCheckReservedLock, /* xCheckReservedLock */
42749 winFileControl, /* xFileControl */
42750 winSectorSize, /* xSectorSize */
42751 winDeviceCharacteristics, /* xDeviceCharacteristics */
42752 winShmMap, /* xShmMap */
42753 winShmLock, /* xShmLock */
42754 winShmBarrier, /* xShmBarrier */
42755 winShmUnmap, /* xShmUnmap */
42756 winFetch, /* xFetch */
42757 winUnfetch /* xUnfetch */
42761 ** This vector defines all the methods that can operate on an
42762 ** sqlite3_file for win32 without performing any locking.
42764 static const sqlite3_io_methods winIoNolockMethod = {
42765 3, /* iVersion */
42766 winClose, /* xClose */
42767 winRead, /* xRead */
42768 winWrite, /* xWrite */
42769 winTruncate, /* xTruncate */
42770 winSync, /* xSync */
42771 winFileSize, /* xFileSize */
42772 winNolockLock, /* xLock */
42773 winNolockUnlock, /* xUnlock */
42774 winNolockCheckReservedLock, /* xCheckReservedLock */
42775 winFileControl, /* xFileControl */
42776 winSectorSize, /* xSectorSize */
42777 winDeviceCharacteristics, /* xDeviceCharacteristics */
42778 winShmMap, /* xShmMap */
42779 winShmLock, /* xShmLock */
42780 winShmBarrier, /* xShmBarrier */
42781 winShmUnmap, /* xShmUnmap */
42782 winFetch, /* xFetch */
42783 winUnfetch /* xUnfetch */
42786 static winVfsAppData winAppData = {
42787 &winIoMethod, /* pMethod */
42788 0, /* pAppData */
42789 0 /* bNoLock */
42792 static winVfsAppData winNolockAppData = {
42793 &winIoNolockMethod, /* pMethod */
42794 0, /* pAppData */
42795 1 /* bNoLock */
42798 /****************************************************************************
42799 **************************** sqlite3_vfs methods ****************************
42801 ** This division contains the implementation of methods on the
42802 ** sqlite3_vfs object.
42805 #if defined(__CYGWIN__)
42807 ** Convert a filename from whatever the underlying operating system
42808 ** supports for filenames into UTF-8. Space to hold the result is
42809 ** obtained from malloc and must be freed by the calling function.
42811 static char *winConvertToUtf8Filename(const void *zFilename){
42812 char *zConverted = 0;
42813 if( osIsNT() ){
42814 zConverted = winUnicodeToUtf8(zFilename);
42816 #ifdef SQLITE_WIN32_HAS_ANSI
42817 else{
42818 zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
42820 #endif
42821 /* caller will handle out of memory */
42822 return zConverted;
42824 #endif
42827 ** Convert a UTF-8 filename into whatever form the underlying
42828 ** operating system wants filenames in. Space to hold the result
42829 ** is obtained from malloc and must be freed by the calling
42830 ** function.
42832 static void *winConvertFromUtf8Filename(const char *zFilename){
42833 void *zConverted = 0;
42834 if( osIsNT() ){
42835 zConverted = winUtf8ToUnicode(zFilename);
42837 #ifdef SQLITE_WIN32_HAS_ANSI
42838 else{
42839 zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
42841 #endif
42842 /* caller will handle out of memory */
42843 return zConverted;
42847 ** This function returns non-zero if the specified UTF-8 string buffer
42848 ** ends with a directory separator character or one was successfully
42849 ** added to it.
42851 static int winMakeEndInDirSep(int nBuf, char *zBuf){
42852 if( zBuf ){
42853 int nLen = sqlite3Strlen30(zBuf);
42854 if( nLen>0 ){
42855 if( winIsDirSep(zBuf[nLen-1]) ){
42856 return 1;
42857 }else if( nLen+1<nBuf ){
42858 zBuf[nLen] = winGetDirSep();
42859 zBuf[nLen+1] = '\0';
42860 return 1;
42864 return 0;
42868 ** Create a temporary file name and store the resulting pointer into pzBuf.
42869 ** The pointer returned in pzBuf must be freed via sqlite3_free().
42871 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
42872 static char zChars[] =
42873 "abcdefghijklmnopqrstuvwxyz"
42874 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
42875 "0123456789";
42876 size_t i, j;
42877 int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
42878 int nMax, nBuf, nDir, nLen;
42879 char *zBuf;
42881 /* It's odd to simulate an io-error here, but really this is just
42882 ** using the io-error infrastructure to test that SQLite handles this
42883 ** function failing.
42885 SimulateIOError( return SQLITE_IOERR );
42887 /* Allocate a temporary buffer to store the fully qualified file
42888 ** name for the temporary file. If this fails, we cannot continue.
42890 nMax = pVfs->mxPathname; nBuf = nMax + 2;
42891 zBuf = sqlite3MallocZero( nBuf );
42892 if( !zBuf ){
42893 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42894 return SQLITE_IOERR_NOMEM_BKPT;
42897 /* Figure out the effective temporary directory. First, check if one
42898 ** has been explicitly set by the application; otherwise, use the one
42899 ** configured by the operating system.
42901 nDir = nMax - (nPre + 15);
42902 assert( nDir>0 );
42903 if( sqlite3_temp_directory ){
42904 int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
42905 if( nDirLen>0 ){
42906 if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
42907 nDirLen++;
42909 if( nDirLen>nDir ){
42910 sqlite3_free(zBuf);
42911 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
42912 return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
42914 sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
42917 #if defined(__CYGWIN__)
42918 else{
42919 static const char *azDirs[] = {
42920 0, /* getenv("SQLITE_TMPDIR") */
42921 0, /* getenv("TMPDIR") */
42922 0, /* getenv("TMP") */
42923 0, /* getenv("TEMP") */
42924 0, /* getenv("USERPROFILE") */
42925 "/var/tmp",
42926 "/usr/tmp",
42927 "/tmp",
42928 ".",
42929 0 /* List terminator */
42931 unsigned int i;
42932 const char *zDir = 0;
42934 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
42935 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
42936 if( !azDirs[2] ) azDirs[2] = getenv("TMP");
42937 if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
42938 if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
42939 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
42940 void *zConverted;
42941 if( zDir==0 ) continue;
42942 /* If the path starts with a drive letter followed by the colon
42943 ** character, assume it is already a native Win32 path; otherwise,
42944 ** it must be converted to a native Win32 path via the Cygwin API
42945 ** prior to using it.
42947 if( winIsDriveLetterAndColon(zDir) ){
42948 zConverted = winConvertFromUtf8Filename(zDir);
42949 if( !zConverted ){
42950 sqlite3_free(zBuf);
42951 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42952 return SQLITE_IOERR_NOMEM_BKPT;
42954 if( winIsDir(zConverted) ){
42955 sqlite3_snprintf(nMax, zBuf, "%s", zDir);
42956 sqlite3_free(zConverted);
42957 break;
42959 sqlite3_free(zConverted);
42960 }else{
42961 zConverted = sqlite3MallocZero( nMax+1 );
42962 if( !zConverted ){
42963 sqlite3_free(zBuf);
42964 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42965 return SQLITE_IOERR_NOMEM_BKPT;
42967 if( cygwin_conv_path(
42968 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
42969 zConverted, nMax+1)<0 ){
42970 sqlite3_free(zConverted);
42971 sqlite3_free(zBuf);
42972 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
42973 return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
42974 "winGetTempname2", zDir);
42976 if( winIsDir(zConverted) ){
42977 /* At this point, we know the candidate directory exists and should
42978 ** be used. However, we may need to convert the string containing
42979 ** its name into UTF-8 (i.e. if it is UTF-16 right now).
42981 char *zUtf8 = winConvertToUtf8Filename(zConverted);
42982 if( !zUtf8 ){
42983 sqlite3_free(zConverted);
42984 sqlite3_free(zBuf);
42985 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42986 return SQLITE_IOERR_NOMEM_BKPT;
42988 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
42989 sqlite3_free(zUtf8);
42990 sqlite3_free(zConverted);
42991 break;
42993 sqlite3_free(zConverted);
42997 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42998 else if( osIsNT() ){
42999 char *zMulti;
43000 LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
43001 if( !zWidePath ){
43002 sqlite3_free(zBuf);
43003 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
43004 return SQLITE_IOERR_NOMEM_BKPT;
43006 if( osGetTempPathW(nMax, zWidePath)==0 ){
43007 sqlite3_free(zWidePath);
43008 sqlite3_free(zBuf);
43009 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
43010 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
43011 "winGetTempname2", 0);
43013 zMulti = winUnicodeToUtf8(zWidePath);
43014 if( zMulti ){
43015 sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
43016 sqlite3_free(zMulti);
43017 sqlite3_free(zWidePath);
43018 }else{
43019 sqlite3_free(zWidePath);
43020 sqlite3_free(zBuf);
43021 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
43022 return SQLITE_IOERR_NOMEM_BKPT;
43025 #ifdef SQLITE_WIN32_HAS_ANSI
43026 else{
43027 char *zUtf8;
43028 char *zMbcsPath = sqlite3MallocZero( nMax );
43029 if( !zMbcsPath ){
43030 sqlite3_free(zBuf);
43031 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
43032 return SQLITE_IOERR_NOMEM_BKPT;
43034 if( osGetTempPathA(nMax, zMbcsPath)==0 ){
43035 sqlite3_free(zBuf);
43036 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
43037 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
43038 "winGetTempname3", 0);
43040 zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
43041 if( zUtf8 ){
43042 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
43043 sqlite3_free(zUtf8);
43044 }else{
43045 sqlite3_free(zBuf);
43046 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
43047 return SQLITE_IOERR_NOMEM_BKPT;
43050 #endif /* SQLITE_WIN32_HAS_ANSI */
43051 #endif /* !SQLITE_OS_WINRT */
43054 ** Check to make sure the temporary directory ends with an appropriate
43055 ** separator. If it does not and there is not enough space left to add
43056 ** one, fail.
43058 if( !winMakeEndInDirSep(nDir+1, zBuf) ){
43059 sqlite3_free(zBuf);
43060 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
43061 return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
43065 ** Check that the output buffer is large enough for the temporary file
43066 ** name in the following format:
43068 ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
43070 ** If not, return SQLITE_ERROR. The number 17 is used here in order to
43071 ** account for the space used by the 15 character random suffix and the
43072 ** two trailing NUL characters. The final directory separator character
43073 ** has already added if it was not already present.
43075 nLen = sqlite3Strlen30(zBuf);
43076 if( (nLen + nPre + 17) > nBuf ){
43077 sqlite3_free(zBuf);
43078 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
43079 return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
43082 sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
43084 j = sqlite3Strlen30(zBuf);
43085 sqlite3_randomness(15, &zBuf[j]);
43086 for(i=0; i<15; i++, j++){
43087 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
43089 zBuf[j] = 0;
43090 zBuf[j+1] = 0;
43091 *pzBuf = zBuf;
43093 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
43094 return SQLITE_OK;
43098 ** Return TRUE if the named file is really a directory. Return false if
43099 ** it is something other than a directory, or if there is any kind of memory
43100 ** allocation failure.
43102 static int winIsDir(const void *zConverted){
43103 DWORD attr;
43104 int rc = 0;
43105 DWORD lastErrno;
43107 if( osIsNT() ){
43108 int cnt = 0;
43109 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
43110 memset(&sAttrData, 0, sizeof(sAttrData));
43111 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
43112 GetFileExInfoStandard,
43113 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
43114 if( !rc ){
43115 return 0; /* Invalid name? */
43117 attr = sAttrData.dwFileAttributes;
43118 #if SQLITE_OS_WINCE==0
43119 }else{
43120 attr = osGetFileAttributesA((char*)zConverted);
43121 #endif
43123 return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
43126 /* forward reference */
43127 static int winAccess(
43128 sqlite3_vfs *pVfs, /* Not used on win32 */
43129 const char *zFilename, /* Name of file to check */
43130 int flags, /* Type of test to make on this file */
43131 int *pResOut /* OUT: Result */
43135 ** Open a file.
43137 static int winOpen(
43138 sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
43139 const char *zName, /* Name of the file (UTF-8) */
43140 sqlite3_file *id, /* Write the SQLite file handle here */
43141 int flags, /* Open mode flags */
43142 int *pOutFlags /* Status return flags */
43144 HANDLE h;
43145 DWORD lastErrno = 0;
43146 DWORD dwDesiredAccess;
43147 DWORD dwShareMode;
43148 DWORD dwCreationDisposition;
43149 DWORD dwFlagsAndAttributes = 0;
43150 #if SQLITE_OS_WINCE
43151 int isTemp = 0;
43152 #endif
43153 winVfsAppData *pAppData;
43154 winFile *pFile = (winFile*)id;
43155 void *zConverted; /* Filename in OS encoding */
43156 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
43157 int cnt = 0;
43159 /* If argument zPath is a NULL pointer, this function is required to open
43160 ** a temporary file. Use this buffer to store the file name in.
43162 char *zTmpname = 0; /* For temporary filename, if necessary. */
43164 int rc = SQLITE_OK; /* Function Return Code */
43165 #if !defined(NDEBUG) || SQLITE_OS_WINCE
43166 int eType = flags&0xFFFFFF00; /* Type of file to open */
43167 #endif
43169 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
43170 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
43171 int isCreate = (flags & SQLITE_OPEN_CREATE);
43172 int isReadonly = (flags & SQLITE_OPEN_READONLY);
43173 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
43175 #ifndef NDEBUG
43176 int isOpenJournal = (isCreate && (
43177 eType==SQLITE_OPEN_MASTER_JOURNAL
43178 || eType==SQLITE_OPEN_MAIN_JOURNAL
43179 || eType==SQLITE_OPEN_WAL
43181 #endif
43183 OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
43184 zUtf8Name, id, flags, pOutFlags));
43186 /* Check the following statements are true:
43188 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
43189 ** (b) if CREATE is set, then READWRITE must also be set, and
43190 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
43191 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
43193 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
43194 assert(isCreate==0 || isReadWrite);
43195 assert(isExclusive==0 || isCreate);
43196 assert(isDelete==0 || isCreate);
43198 /* The main DB, main journal, WAL file and master journal are never
43199 ** automatically deleted. Nor are they ever temporary files. */
43200 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
43201 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
43202 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
43203 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
43205 /* Assert that the upper layer has set one of the "file-type" flags. */
43206 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
43207 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
43208 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
43209 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
43212 assert( pFile!=0 );
43213 memset(pFile, 0, sizeof(winFile));
43214 pFile->h = INVALID_HANDLE_VALUE;
43216 #if SQLITE_OS_WINRT
43217 if( !zUtf8Name && !sqlite3_temp_directory ){
43218 sqlite3_log(SQLITE_ERROR,
43219 "sqlite3_temp_directory variable should be set for WinRT");
43221 #endif
43223 /* If the second argument to this function is NULL, generate a
43224 ** temporary file name to use
43226 if( !zUtf8Name ){
43227 assert( isDelete && !isOpenJournal );
43228 rc = winGetTempname(pVfs, &zTmpname);
43229 if( rc!=SQLITE_OK ){
43230 OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
43231 return rc;
43233 zUtf8Name = zTmpname;
43236 /* Database filenames are double-zero terminated if they are not
43237 ** URIs with parameters. Hence, they can always be passed into
43238 ** sqlite3_uri_parameter().
43240 assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
43241 zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
43243 /* Convert the filename to the system encoding. */
43244 zConverted = winConvertFromUtf8Filename(zUtf8Name);
43245 if( zConverted==0 ){
43246 sqlite3_free(zTmpname);
43247 OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
43248 return SQLITE_IOERR_NOMEM_BKPT;
43251 if( winIsDir(zConverted) ){
43252 sqlite3_free(zConverted);
43253 sqlite3_free(zTmpname);
43254 OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
43255 return SQLITE_CANTOPEN_ISDIR;
43258 if( isReadWrite ){
43259 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
43260 }else{
43261 dwDesiredAccess = GENERIC_READ;
43264 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
43265 ** created. SQLite doesn't use it to indicate "exclusive access"
43266 ** as it is usually understood.
43268 if( isExclusive ){
43269 /* Creates a new file, only if it does not already exist. */
43270 /* If the file exists, it fails. */
43271 dwCreationDisposition = CREATE_NEW;
43272 }else if( isCreate ){
43273 /* Open existing file, or create if it doesn't exist */
43274 dwCreationDisposition = OPEN_ALWAYS;
43275 }else{
43276 /* Opens a file, only if it exists. */
43277 dwCreationDisposition = OPEN_EXISTING;
43280 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
43282 if( isDelete ){
43283 #if SQLITE_OS_WINCE
43284 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
43285 isTemp = 1;
43286 #else
43287 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
43288 | FILE_ATTRIBUTE_HIDDEN
43289 | FILE_FLAG_DELETE_ON_CLOSE;
43290 #endif
43291 }else{
43292 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
43294 /* Reports from the internet are that performance is always
43295 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
43296 #if SQLITE_OS_WINCE
43297 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
43298 #endif
43300 if( osIsNT() ){
43301 #if SQLITE_OS_WINRT
43302 CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
43303 extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
43304 extendedParameters.dwFileAttributes =
43305 dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
43306 extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
43307 extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
43308 extendedParameters.lpSecurityAttributes = NULL;
43309 extendedParameters.hTemplateFile = NULL;
43311 h = osCreateFile2((LPCWSTR)zConverted,
43312 dwDesiredAccess,
43313 dwShareMode,
43314 dwCreationDisposition,
43315 &extendedParameters);
43316 if( h!=INVALID_HANDLE_VALUE ) break;
43317 if( isReadWrite ){
43318 int isRO = 0;
43319 int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
43320 if( rc2==SQLITE_OK && isRO ) break;
43322 }while( winRetryIoerr(&cnt, &lastErrno) );
43323 #else
43325 h = osCreateFileW((LPCWSTR)zConverted,
43326 dwDesiredAccess,
43327 dwShareMode, NULL,
43328 dwCreationDisposition,
43329 dwFlagsAndAttributes,
43330 NULL);
43331 if( h!=INVALID_HANDLE_VALUE ) break;
43332 if( isReadWrite ){
43333 int isRO = 0;
43334 int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
43335 if( rc2==SQLITE_OK && isRO ) break;
43337 }while( winRetryIoerr(&cnt, &lastErrno) );
43338 #endif
43340 #ifdef SQLITE_WIN32_HAS_ANSI
43341 else{
43343 h = osCreateFileA((LPCSTR)zConverted,
43344 dwDesiredAccess,
43345 dwShareMode, NULL,
43346 dwCreationDisposition,
43347 dwFlagsAndAttributes,
43348 NULL);
43349 if( h!=INVALID_HANDLE_VALUE ) break;
43350 if( isReadWrite ){
43351 int isRO = 0;
43352 int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
43353 if( rc2==SQLITE_OK && isRO ) break;
43355 }while( winRetryIoerr(&cnt, &lastErrno) );
43357 #endif
43358 winLogIoerr(cnt, __LINE__);
43360 OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
43361 dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
43363 if( h==INVALID_HANDLE_VALUE ){
43364 sqlite3_free(zConverted);
43365 sqlite3_free(zTmpname);
43366 if( isReadWrite && !isExclusive ){
43367 return winOpen(pVfs, zName, id,
43368 ((flags|SQLITE_OPEN_READONLY) &
43369 ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
43370 pOutFlags);
43371 }else{
43372 pFile->lastErrno = lastErrno;
43373 winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
43374 return SQLITE_CANTOPEN_BKPT;
43378 if( pOutFlags ){
43379 if( isReadWrite ){
43380 *pOutFlags = SQLITE_OPEN_READWRITE;
43381 }else{
43382 *pOutFlags = SQLITE_OPEN_READONLY;
43386 OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
43387 "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
43388 *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
43390 pAppData = (winVfsAppData*)pVfs->pAppData;
43392 #if SQLITE_OS_WINCE
43394 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
43395 && ((pAppData==NULL) || !pAppData->bNoLock)
43396 && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
43398 osCloseHandle(h);
43399 sqlite3_free(zConverted);
43400 sqlite3_free(zTmpname);
43401 OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
43402 return rc;
43405 if( isTemp ){
43406 pFile->zDeleteOnClose = zConverted;
43407 }else
43408 #endif
43410 sqlite3_free(zConverted);
43413 sqlite3_free(zTmpname);
43414 pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
43415 pFile->pVfs = pVfs;
43416 pFile->h = h;
43417 if( isReadonly ){
43418 pFile->ctrlFlags |= WINFILE_RDONLY;
43420 if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
43421 pFile->ctrlFlags |= WINFILE_PSOW;
43423 pFile->lastErrno = NO_ERROR;
43424 pFile->zPath = zName;
43425 #if SQLITE_MAX_MMAP_SIZE>0
43426 pFile->hMap = NULL;
43427 pFile->pMapRegion = 0;
43428 pFile->mmapSize = 0;
43429 pFile->mmapSizeActual = 0;
43430 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
43431 #endif
43433 OpenCounter(+1);
43434 return rc;
43438 ** Delete the named file.
43440 ** Note that Windows does not allow a file to be deleted if some other
43441 ** process has it open. Sometimes a virus scanner or indexing program
43442 ** will open a journal file shortly after it is created in order to do
43443 ** whatever it does. While this other process is holding the
43444 ** file open, we will be unable to delete it. To work around this
43445 ** problem, we delay 100 milliseconds and try to delete again. Up
43446 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
43447 ** up and returning an error.
43449 static int winDelete(
43450 sqlite3_vfs *pVfs, /* Not used on win32 */
43451 const char *zFilename, /* Name of file to delete */
43452 int syncDir /* Not used on win32 */
43454 int cnt = 0;
43455 int rc;
43456 DWORD attr;
43457 DWORD lastErrno = 0;
43458 void *zConverted;
43459 UNUSED_PARAMETER(pVfs);
43460 UNUSED_PARAMETER(syncDir);
43462 SimulateIOError(return SQLITE_IOERR_DELETE);
43463 OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
43465 zConverted = winConvertFromUtf8Filename(zFilename);
43466 if( zConverted==0 ){
43467 OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
43468 return SQLITE_IOERR_NOMEM_BKPT;
43470 if( osIsNT() ){
43471 do {
43472 #if SQLITE_OS_WINRT
43473 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
43474 memset(&sAttrData, 0, sizeof(sAttrData));
43475 if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
43476 &sAttrData) ){
43477 attr = sAttrData.dwFileAttributes;
43478 }else{
43479 lastErrno = osGetLastError();
43480 if( lastErrno==ERROR_FILE_NOT_FOUND
43481 || lastErrno==ERROR_PATH_NOT_FOUND ){
43482 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
43483 }else{
43484 rc = SQLITE_ERROR;
43486 break;
43488 #else
43489 attr = osGetFileAttributesW(zConverted);
43490 #endif
43491 if ( attr==INVALID_FILE_ATTRIBUTES ){
43492 lastErrno = osGetLastError();
43493 if( lastErrno==ERROR_FILE_NOT_FOUND
43494 || lastErrno==ERROR_PATH_NOT_FOUND ){
43495 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
43496 }else{
43497 rc = SQLITE_ERROR;
43499 break;
43501 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
43502 rc = SQLITE_ERROR; /* Files only. */
43503 break;
43505 if ( osDeleteFileW(zConverted) ){
43506 rc = SQLITE_OK; /* Deleted OK. */
43507 break;
43509 if ( !winRetryIoerr(&cnt, &lastErrno) ){
43510 rc = SQLITE_ERROR; /* No more retries. */
43511 break;
43513 } while(1);
43515 #ifdef SQLITE_WIN32_HAS_ANSI
43516 else{
43517 do {
43518 attr = osGetFileAttributesA(zConverted);
43519 if ( attr==INVALID_FILE_ATTRIBUTES ){
43520 lastErrno = osGetLastError();
43521 if( lastErrno==ERROR_FILE_NOT_FOUND
43522 || lastErrno==ERROR_PATH_NOT_FOUND ){
43523 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
43524 }else{
43525 rc = SQLITE_ERROR;
43527 break;
43529 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
43530 rc = SQLITE_ERROR; /* Files only. */
43531 break;
43533 if ( osDeleteFileA(zConverted) ){
43534 rc = SQLITE_OK; /* Deleted OK. */
43535 break;
43537 if ( !winRetryIoerr(&cnt, &lastErrno) ){
43538 rc = SQLITE_ERROR; /* No more retries. */
43539 break;
43541 } while(1);
43543 #endif
43544 if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
43545 rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
43546 }else{
43547 winLogIoerr(cnt, __LINE__);
43549 sqlite3_free(zConverted);
43550 OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
43551 return rc;
43555 ** Check the existence and status of a file.
43557 static int winAccess(
43558 sqlite3_vfs *pVfs, /* Not used on win32 */
43559 const char *zFilename, /* Name of file to check */
43560 int flags, /* Type of test to make on this file */
43561 int *pResOut /* OUT: Result */
43563 DWORD attr;
43564 int rc = 0;
43565 DWORD lastErrno = 0;
43566 void *zConverted;
43567 UNUSED_PARAMETER(pVfs);
43569 SimulateIOError( return SQLITE_IOERR_ACCESS; );
43570 OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
43571 zFilename, flags, pResOut));
43573 zConverted = winConvertFromUtf8Filename(zFilename);
43574 if( zConverted==0 ){
43575 OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
43576 return SQLITE_IOERR_NOMEM_BKPT;
43578 if( osIsNT() ){
43579 int cnt = 0;
43580 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
43581 memset(&sAttrData, 0, sizeof(sAttrData));
43582 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
43583 GetFileExInfoStandard,
43584 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
43585 if( rc ){
43586 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
43587 ** as if it does not exist.
43589 if( flags==SQLITE_ACCESS_EXISTS
43590 && sAttrData.nFileSizeHigh==0
43591 && sAttrData.nFileSizeLow==0 ){
43592 attr = INVALID_FILE_ATTRIBUTES;
43593 }else{
43594 attr = sAttrData.dwFileAttributes;
43596 }else{
43597 winLogIoerr(cnt, __LINE__);
43598 if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
43599 sqlite3_free(zConverted);
43600 return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
43601 zFilename);
43602 }else{
43603 attr = INVALID_FILE_ATTRIBUTES;
43607 #ifdef SQLITE_WIN32_HAS_ANSI
43608 else{
43609 attr = osGetFileAttributesA((char*)zConverted);
43611 #endif
43612 sqlite3_free(zConverted);
43613 switch( flags ){
43614 case SQLITE_ACCESS_READ:
43615 case SQLITE_ACCESS_EXISTS:
43616 rc = attr!=INVALID_FILE_ATTRIBUTES;
43617 break;
43618 case SQLITE_ACCESS_READWRITE:
43619 rc = attr!=INVALID_FILE_ATTRIBUTES &&
43620 (attr & FILE_ATTRIBUTE_READONLY)==0;
43621 break;
43622 default:
43623 assert(!"Invalid flags argument");
43625 *pResOut = rc;
43626 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
43627 zFilename, pResOut, *pResOut));
43628 return SQLITE_OK;
43632 ** Returns non-zero if the specified path name starts with a drive letter
43633 ** followed by a colon character.
43635 static BOOL winIsDriveLetterAndColon(
43636 const char *zPathname
43638 return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
43642 ** Returns non-zero if the specified path name should be used verbatim. If
43643 ** non-zero is returned from this function, the calling function must simply
43644 ** use the provided path name verbatim -OR- resolve it into a full path name
43645 ** using the GetFullPathName Win32 API function (if available).
43647 static BOOL winIsVerbatimPathname(
43648 const char *zPathname
43651 ** If the path name starts with a forward slash or a backslash, it is either
43652 ** a legal UNC name, a volume relative path, or an absolute path name in the
43653 ** "Unix" format on Windows. There is no easy way to differentiate between
43654 ** the final two cases; therefore, we return the safer return value of TRUE
43655 ** so that callers of this function will simply use it verbatim.
43657 if ( winIsDirSep(zPathname[0]) ){
43658 return TRUE;
43662 ** If the path name starts with a letter and a colon it is either a volume
43663 ** relative path or an absolute path. Callers of this function must not
43664 ** attempt to treat it as a relative path name (i.e. they should simply use
43665 ** it verbatim).
43667 if ( winIsDriveLetterAndColon(zPathname) ){
43668 return TRUE;
43672 ** If we get to this point, the path name should almost certainly be a purely
43673 ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
43675 return FALSE;
43679 ** Turn a relative pathname into a full pathname. Write the full
43680 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
43681 ** bytes in size.
43683 static int winFullPathname(
43684 sqlite3_vfs *pVfs, /* Pointer to vfs object */
43685 const char *zRelative, /* Possibly relative input path */
43686 int nFull, /* Size of output buffer in bytes */
43687 char *zFull /* Output buffer */
43689 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
43690 DWORD nByte;
43691 void *zConverted;
43692 char *zOut;
43693 #endif
43695 /* If this path name begins with "/X:", where "X" is any alphabetic
43696 ** character, discard the initial "/" from the pathname.
43698 if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
43699 zRelative++;
43702 #if defined(__CYGWIN__)
43703 SimulateIOError( return SQLITE_ERROR );
43704 UNUSED_PARAMETER(nFull);
43705 assert( nFull>=pVfs->mxPathname );
43706 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
43708 ** NOTE: We are dealing with a relative path name and the data
43709 ** directory has been set. Therefore, use it as the basis
43710 ** for converting the relative path name to an absolute
43711 ** one by prepending the data directory and a slash.
43713 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
43714 if( !zOut ){
43715 return SQLITE_IOERR_NOMEM_BKPT;
43717 if( cygwin_conv_path(
43718 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
43719 CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
43720 sqlite3_free(zOut);
43721 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
43722 "winFullPathname1", zRelative);
43723 }else{
43724 char *zUtf8 = winConvertToUtf8Filename(zOut);
43725 if( !zUtf8 ){
43726 sqlite3_free(zOut);
43727 return SQLITE_IOERR_NOMEM_BKPT;
43729 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
43730 sqlite3_data_directory, winGetDirSep(), zUtf8);
43731 sqlite3_free(zUtf8);
43732 sqlite3_free(zOut);
43734 }else{
43735 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
43736 if( !zOut ){
43737 return SQLITE_IOERR_NOMEM_BKPT;
43739 if( cygwin_conv_path(
43740 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
43741 zRelative, zOut, pVfs->mxPathname+1)<0 ){
43742 sqlite3_free(zOut);
43743 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
43744 "winFullPathname2", zRelative);
43745 }else{
43746 char *zUtf8 = winConvertToUtf8Filename(zOut);
43747 if( !zUtf8 ){
43748 sqlite3_free(zOut);
43749 return SQLITE_IOERR_NOMEM_BKPT;
43751 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
43752 sqlite3_free(zUtf8);
43753 sqlite3_free(zOut);
43756 return SQLITE_OK;
43757 #endif
43759 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
43760 SimulateIOError( return SQLITE_ERROR );
43761 /* WinCE has no concept of a relative pathname, or so I am told. */
43762 /* WinRT has no way to convert a relative path to an absolute one. */
43763 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
43765 ** NOTE: We are dealing with a relative path name and the data
43766 ** directory has been set. Therefore, use it as the basis
43767 ** for converting the relative path name to an absolute
43768 ** one by prepending the data directory and a backslash.
43770 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
43771 sqlite3_data_directory, winGetDirSep(), zRelative);
43772 }else{
43773 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
43775 return SQLITE_OK;
43776 #endif
43778 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
43779 /* It's odd to simulate an io-error here, but really this is just
43780 ** using the io-error infrastructure to test that SQLite handles this
43781 ** function failing. This function could fail if, for example, the
43782 ** current working directory has been unlinked.
43784 SimulateIOError( return SQLITE_ERROR );
43785 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
43787 ** NOTE: We are dealing with a relative path name and the data
43788 ** directory has been set. Therefore, use it as the basis
43789 ** for converting the relative path name to an absolute
43790 ** one by prepending the data directory and a backslash.
43792 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
43793 sqlite3_data_directory, winGetDirSep(), zRelative);
43794 return SQLITE_OK;
43796 zConverted = winConvertFromUtf8Filename(zRelative);
43797 if( zConverted==0 ){
43798 return SQLITE_IOERR_NOMEM_BKPT;
43800 if( osIsNT() ){
43801 LPWSTR zTemp;
43802 nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
43803 if( nByte==0 ){
43804 sqlite3_free(zConverted);
43805 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43806 "winFullPathname1", zRelative);
43808 nByte += 3;
43809 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
43810 if( zTemp==0 ){
43811 sqlite3_free(zConverted);
43812 return SQLITE_IOERR_NOMEM_BKPT;
43814 nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
43815 if( nByte==0 ){
43816 sqlite3_free(zConverted);
43817 sqlite3_free(zTemp);
43818 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43819 "winFullPathname2", zRelative);
43821 sqlite3_free(zConverted);
43822 zOut = winUnicodeToUtf8(zTemp);
43823 sqlite3_free(zTemp);
43825 #ifdef SQLITE_WIN32_HAS_ANSI
43826 else{
43827 char *zTemp;
43828 nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
43829 if( nByte==0 ){
43830 sqlite3_free(zConverted);
43831 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43832 "winFullPathname3", zRelative);
43834 nByte += 3;
43835 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
43836 if( zTemp==0 ){
43837 sqlite3_free(zConverted);
43838 return SQLITE_IOERR_NOMEM_BKPT;
43840 nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
43841 if( nByte==0 ){
43842 sqlite3_free(zConverted);
43843 sqlite3_free(zTemp);
43844 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43845 "winFullPathname4", zRelative);
43847 sqlite3_free(zConverted);
43848 zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
43849 sqlite3_free(zTemp);
43851 #endif
43852 if( zOut ){
43853 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
43854 sqlite3_free(zOut);
43855 return SQLITE_OK;
43856 }else{
43857 return SQLITE_IOERR_NOMEM_BKPT;
43859 #endif
43862 #ifndef SQLITE_OMIT_LOAD_EXTENSION
43864 ** Interfaces for opening a shared library, finding entry points
43865 ** within the shared library, and closing the shared library.
43867 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
43868 HANDLE h;
43869 #if defined(__CYGWIN__)
43870 int nFull = pVfs->mxPathname+1;
43871 char *zFull = sqlite3MallocZero( nFull );
43872 void *zConverted = 0;
43873 if( zFull==0 ){
43874 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
43875 return 0;
43877 if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
43878 sqlite3_free(zFull);
43879 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
43880 return 0;
43882 zConverted = winConvertFromUtf8Filename(zFull);
43883 sqlite3_free(zFull);
43884 #else
43885 void *zConverted = winConvertFromUtf8Filename(zFilename);
43886 UNUSED_PARAMETER(pVfs);
43887 #endif
43888 if( zConverted==0 ){
43889 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
43890 return 0;
43892 if( osIsNT() ){
43893 #if SQLITE_OS_WINRT
43894 h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
43895 #else
43896 h = osLoadLibraryW((LPCWSTR)zConverted);
43897 #endif
43899 #ifdef SQLITE_WIN32_HAS_ANSI
43900 else{
43901 h = osLoadLibraryA((char*)zConverted);
43903 #endif
43904 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
43905 sqlite3_free(zConverted);
43906 return (void*)h;
43908 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
43909 UNUSED_PARAMETER(pVfs);
43910 winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
43912 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
43913 FARPROC proc;
43914 UNUSED_PARAMETER(pVfs);
43915 proc = osGetProcAddressA((HANDLE)pH, zSym);
43916 OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
43917 (void*)pH, zSym, (void*)proc));
43918 return (void(*)(void))proc;
43920 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
43921 UNUSED_PARAMETER(pVfs);
43922 osFreeLibrary((HANDLE)pHandle);
43923 OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
43925 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
43926 #define winDlOpen 0
43927 #define winDlError 0
43928 #define winDlSym 0
43929 #define winDlClose 0
43930 #endif
43932 /* State information for the randomness gatherer. */
43933 typedef struct EntropyGatherer EntropyGatherer;
43934 struct EntropyGatherer {
43935 unsigned char *a; /* Gather entropy into this buffer */
43936 int na; /* Size of a[] in bytes */
43937 int i; /* XOR next input into a[i] */
43938 int nXor; /* Number of XOR operations done */
43941 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
43942 /* Mix sz bytes of entropy into p. */
43943 static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
43944 int j, k;
43945 for(j=0, k=p->i; j<sz; j++){
43946 p->a[k++] ^= x[j];
43947 if( k>=p->na ) k = 0;
43949 p->i = k;
43950 p->nXor += sz;
43952 #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
43955 ** Write up to nBuf bytes of randomness into zBuf.
43957 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
43958 #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
43959 UNUSED_PARAMETER(pVfs);
43960 memset(zBuf, 0, nBuf);
43961 return nBuf;
43962 #else
43963 EntropyGatherer e;
43964 UNUSED_PARAMETER(pVfs);
43965 memset(zBuf, 0, nBuf);
43966 e.a = (unsigned char*)zBuf;
43967 e.na = nBuf;
43968 e.nXor = 0;
43969 e.i = 0;
43971 SYSTEMTIME x;
43972 osGetSystemTime(&x);
43973 xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
43976 DWORD pid = osGetCurrentProcessId();
43977 xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
43979 #if SQLITE_OS_WINRT
43981 ULONGLONG cnt = osGetTickCount64();
43982 xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
43984 #else
43986 DWORD cnt = osGetTickCount();
43987 xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
43989 #endif /* SQLITE_OS_WINRT */
43991 LARGE_INTEGER i;
43992 osQueryPerformanceCounter(&i);
43993 xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
43995 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
43997 UUID id;
43998 memset(&id, 0, sizeof(UUID));
43999 osUuidCreate(&id);
44000 xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
44001 memset(&id, 0, sizeof(UUID));
44002 osUuidCreateSequential(&id);
44003 xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
44005 #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
44006 return e.nXor>nBuf ? nBuf : e.nXor;
44007 #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
44012 ** Sleep for a little while. Return the amount of time slept.
44014 static int winSleep(sqlite3_vfs *pVfs, int microsec){
44015 sqlite3_win32_sleep((microsec+999)/1000);
44016 UNUSED_PARAMETER(pVfs);
44017 return ((microsec+999)/1000)*1000;
44021 ** The following variable, if set to a non-zero value, is interpreted as
44022 ** the number of seconds since 1970 and is used to set the result of
44023 ** sqlite3OsCurrentTime() during testing.
44025 #ifdef SQLITE_TEST
44026 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
44027 #endif
44030 ** Find the current time (in Universal Coordinated Time). Write into *piNow
44031 ** the current time and date as a Julian Day number times 86_400_000. In
44032 ** other words, write into *piNow the number of milliseconds since the Julian
44033 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
44034 ** proleptic Gregorian calendar.
44036 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
44037 ** cannot be found.
44039 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
44040 /* FILETIME structure is a 64-bit value representing the number of
44041 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
44043 FILETIME ft;
44044 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
44045 #ifdef SQLITE_TEST
44046 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
44047 #endif
44048 /* 2^32 - to avoid use of LL and warnings in gcc */
44049 static const sqlite3_int64 max32BitValue =
44050 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
44051 (sqlite3_int64)294967296;
44053 #if SQLITE_OS_WINCE
44054 SYSTEMTIME time;
44055 osGetSystemTime(&time);
44056 /* if SystemTimeToFileTime() fails, it returns zero. */
44057 if (!osSystemTimeToFileTime(&time,&ft)){
44058 return SQLITE_ERROR;
44060 #else
44061 osGetSystemTimeAsFileTime( &ft );
44062 #endif
44064 *piNow = winFiletimeEpoch +
44065 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
44066 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
44068 #ifdef SQLITE_TEST
44069 if( sqlite3_current_time ){
44070 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
44072 #endif
44073 UNUSED_PARAMETER(pVfs);
44074 return SQLITE_OK;
44078 ** Find the current time (in Universal Coordinated Time). Write the
44079 ** current time and date as a Julian Day number into *prNow and
44080 ** return 0. Return 1 if the time and date cannot be found.
44082 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
44083 int rc;
44084 sqlite3_int64 i;
44085 rc = winCurrentTimeInt64(pVfs, &i);
44086 if( !rc ){
44087 *prNow = i/86400000.0;
44089 return rc;
44093 ** The idea is that this function works like a combination of
44094 ** GetLastError() and FormatMessage() on Windows (or errno and
44095 ** strerror_r() on Unix). After an error is returned by an OS
44096 ** function, SQLite calls this function with zBuf pointing to
44097 ** a buffer of nBuf bytes. The OS layer should populate the
44098 ** buffer with a nul-terminated UTF-8 encoded error message
44099 ** describing the last IO error to have occurred within the calling
44100 ** thread.
44102 ** If the error message is too large for the supplied buffer,
44103 ** it should be truncated. The return value of xGetLastError
44104 ** is zero if the error message fits in the buffer, or non-zero
44105 ** otherwise (if the message was truncated). If non-zero is returned,
44106 ** then it is not necessary to include the nul-terminator character
44107 ** in the output buffer.
44109 ** Not supplying an error message will have no adverse effect
44110 ** on SQLite. It is fine to have an implementation that never
44111 ** returns an error message:
44113 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
44114 ** assert(zBuf[0]=='\0');
44115 ** return 0;
44116 ** }
44118 ** However if an error message is supplied, it will be incorporated
44119 ** by sqlite into the error message available to the user using
44120 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
44122 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
44123 DWORD e = osGetLastError();
44124 UNUSED_PARAMETER(pVfs);
44125 if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
44126 return e;
44130 ** Initialize and deinitialize the operating system interface.
44132 SQLITE_API int sqlite3_os_init(void){
44133 static sqlite3_vfs winVfs = {
44134 3, /* iVersion */
44135 sizeof(winFile), /* szOsFile */
44136 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
44137 0, /* pNext */
44138 "win32", /* zName */
44139 &winAppData, /* pAppData */
44140 winOpen, /* xOpen */
44141 winDelete, /* xDelete */
44142 winAccess, /* xAccess */
44143 winFullPathname, /* xFullPathname */
44144 winDlOpen, /* xDlOpen */
44145 winDlError, /* xDlError */
44146 winDlSym, /* xDlSym */
44147 winDlClose, /* xDlClose */
44148 winRandomness, /* xRandomness */
44149 winSleep, /* xSleep */
44150 winCurrentTime, /* xCurrentTime */
44151 winGetLastError, /* xGetLastError */
44152 winCurrentTimeInt64, /* xCurrentTimeInt64 */
44153 winSetSystemCall, /* xSetSystemCall */
44154 winGetSystemCall, /* xGetSystemCall */
44155 winNextSystemCall, /* xNextSystemCall */
44157 #if defined(SQLITE_WIN32_HAS_WIDE)
44158 static sqlite3_vfs winLongPathVfs = {
44159 3, /* iVersion */
44160 sizeof(winFile), /* szOsFile */
44161 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
44162 0, /* pNext */
44163 "win32-longpath", /* zName */
44164 &winAppData, /* pAppData */
44165 winOpen, /* xOpen */
44166 winDelete, /* xDelete */
44167 winAccess, /* xAccess */
44168 winFullPathname, /* xFullPathname */
44169 winDlOpen, /* xDlOpen */
44170 winDlError, /* xDlError */
44171 winDlSym, /* xDlSym */
44172 winDlClose, /* xDlClose */
44173 winRandomness, /* xRandomness */
44174 winSleep, /* xSleep */
44175 winCurrentTime, /* xCurrentTime */
44176 winGetLastError, /* xGetLastError */
44177 winCurrentTimeInt64, /* xCurrentTimeInt64 */
44178 winSetSystemCall, /* xSetSystemCall */
44179 winGetSystemCall, /* xGetSystemCall */
44180 winNextSystemCall, /* xNextSystemCall */
44182 #endif
44183 static sqlite3_vfs winNolockVfs = {
44184 3, /* iVersion */
44185 sizeof(winFile), /* szOsFile */
44186 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
44187 0, /* pNext */
44188 "win32-none", /* zName */
44189 &winNolockAppData, /* pAppData */
44190 winOpen, /* xOpen */
44191 winDelete, /* xDelete */
44192 winAccess, /* xAccess */
44193 winFullPathname, /* xFullPathname */
44194 winDlOpen, /* xDlOpen */
44195 winDlError, /* xDlError */
44196 winDlSym, /* xDlSym */
44197 winDlClose, /* xDlClose */
44198 winRandomness, /* xRandomness */
44199 winSleep, /* xSleep */
44200 winCurrentTime, /* xCurrentTime */
44201 winGetLastError, /* xGetLastError */
44202 winCurrentTimeInt64, /* xCurrentTimeInt64 */
44203 winSetSystemCall, /* xSetSystemCall */
44204 winGetSystemCall, /* xGetSystemCall */
44205 winNextSystemCall, /* xNextSystemCall */
44207 #if defined(SQLITE_WIN32_HAS_WIDE)
44208 static sqlite3_vfs winLongPathNolockVfs = {
44209 3, /* iVersion */
44210 sizeof(winFile), /* szOsFile */
44211 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
44212 0, /* pNext */
44213 "win32-longpath-none", /* zName */
44214 &winNolockAppData, /* pAppData */
44215 winOpen, /* xOpen */
44216 winDelete, /* xDelete */
44217 winAccess, /* xAccess */
44218 winFullPathname, /* xFullPathname */
44219 winDlOpen, /* xDlOpen */
44220 winDlError, /* xDlError */
44221 winDlSym, /* xDlSym */
44222 winDlClose, /* xDlClose */
44223 winRandomness, /* xRandomness */
44224 winSleep, /* xSleep */
44225 winCurrentTime, /* xCurrentTime */
44226 winGetLastError, /* xGetLastError */
44227 winCurrentTimeInt64, /* xCurrentTimeInt64 */
44228 winSetSystemCall, /* xSetSystemCall */
44229 winGetSystemCall, /* xGetSystemCall */
44230 winNextSystemCall, /* xNextSystemCall */
44232 #endif
44234 /* Double-check that the aSyscall[] array has been constructed
44235 ** correctly. See ticket [bb3a86e890c8e96ab] */
44236 assert( ArraySize(aSyscall)==80 );
44238 /* get memory map allocation granularity */
44239 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
44240 #if SQLITE_OS_WINRT
44241 osGetNativeSystemInfo(&winSysInfo);
44242 #else
44243 osGetSystemInfo(&winSysInfo);
44244 #endif
44245 assert( winSysInfo.dwAllocationGranularity>0 );
44246 assert( winSysInfo.dwPageSize>0 );
44248 sqlite3_vfs_register(&winVfs, 1);
44250 #if defined(SQLITE_WIN32_HAS_WIDE)
44251 sqlite3_vfs_register(&winLongPathVfs, 0);
44252 #endif
44254 sqlite3_vfs_register(&winNolockVfs, 0);
44256 #if defined(SQLITE_WIN32_HAS_WIDE)
44257 sqlite3_vfs_register(&winLongPathNolockVfs, 0);
44258 #endif
44260 return SQLITE_OK;
44263 SQLITE_API int sqlite3_os_end(void){
44264 #if SQLITE_OS_WINRT
44265 if( sleepObj!=NULL ){
44266 osCloseHandle(sleepObj);
44267 sleepObj = NULL;
44269 #endif
44270 return SQLITE_OK;
44273 #endif /* SQLITE_OS_WIN */
44275 /************** End of os_win.c **********************************************/
44276 /************** Begin file bitvec.c ******************************************/
44278 ** 2008 February 16
44280 ** The author disclaims copyright to this source code. In place of
44281 ** a legal notice, here is a blessing:
44283 ** May you do good and not evil.
44284 ** May you find forgiveness for yourself and forgive others.
44285 ** May you share freely, never taking more than you give.
44287 *************************************************************************
44288 ** This file implements an object that represents a fixed-length
44289 ** bitmap. Bits are numbered starting with 1.
44291 ** A bitmap is used to record which pages of a database file have been
44292 ** journalled during a transaction, or which pages have the "dont-write"
44293 ** property. Usually only a few pages are meet either condition.
44294 ** So the bitmap is usually sparse and has low cardinality.
44295 ** But sometimes (for example when during a DROP of a large table) most
44296 ** or all of the pages in a database can get journalled. In those cases,
44297 ** the bitmap becomes dense with high cardinality. The algorithm needs
44298 ** to handle both cases well.
44300 ** The size of the bitmap is fixed when the object is created.
44302 ** All bits are clear when the bitmap is created. Individual bits
44303 ** may be set or cleared one at a time.
44305 ** Test operations are about 100 times more common that set operations.
44306 ** Clear operations are exceedingly rare. There are usually between
44307 ** 5 and 500 set operations per Bitvec object, though the number of sets can
44308 ** sometimes grow into tens of thousands or larger. The size of the
44309 ** Bitvec object is the number of pages in the database file at the
44310 ** start of a transaction, and is thus usually less than a few thousand,
44311 ** but can be as large as 2 billion for a really big database.
44313 /* #include "sqliteInt.h" */
44315 /* Size of the Bitvec structure in bytes. */
44316 #define BITVEC_SZ 512
44318 /* Round the union size down to the nearest pointer boundary, since that's how
44319 ** it will be aligned within the Bitvec struct. */
44320 #define BITVEC_USIZE \
44321 (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
44323 /* Type of the array "element" for the bitmap representation.
44324 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
44325 ** Setting this to the "natural word" size of your CPU may improve
44326 ** performance. */
44327 #define BITVEC_TELEM u8
44328 /* Size, in bits, of the bitmap element. */
44329 #define BITVEC_SZELEM 8
44330 /* Number of elements in a bitmap array. */
44331 #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
44332 /* Number of bits in the bitmap array. */
44333 #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
44335 /* Number of u32 values in hash table. */
44336 #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
44337 /* Maximum number of entries in hash table before
44338 ** sub-dividing and re-hashing. */
44339 #define BITVEC_MXHASH (BITVEC_NINT/2)
44340 /* Hashing function for the aHash representation.
44341 ** Empirical testing showed that the *37 multiplier
44342 ** (an arbitrary prime)in the hash function provided
44343 ** no fewer collisions than the no-op *1. */
44344 #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
44346 #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
44350 ** A bitmap is an instance of the following structure.
44352 ** This bitmap records the existence of zero or more bits
44353 ** with values between 1 and iSize, inclusive.
44355 ** There are three possible representations of the bitmap.
44356 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
44357 ** bitmap. The least significant bit is bit 1.
44359 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
44360 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
44362 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
44363 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
44364 ** handles up to iDivisor separate values of i. apSub[0] holds
44365 ** values between 1 and iDivisor. apSub[1] holds values between
44366 ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
44367 ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
44368 ** to hold deal with values between 1 and iDivisor.
44370 struct Bitvec {
44371 u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
44372 u32 nSet; /* Number of bits that are set - only valid for aHash
44373 ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
44374 ** this would be 125. */
44375 u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
44376 /* Should >=0 for apSub element. */
44377 /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
44378 /* For a BITVEC_SZ of 512, this would be 34,359,739. */
44379 union {
44380 BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
44381 u32 aHash[BITVEC_NINT]; /* Hash table representation */
44382 Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
44383 } u;
44387 ** Create a new bitmap object able to handle bits between 0 and iSize,
44388 ** inclusive. Return a pointer to the new object. Return NULL if
44389 ** malloc fails.
44391 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
44392 Bitvec *p;
44393 assert( sizeof(*p)==BITVEC_SZ );
44394 p = sqlite3MallocZero( sizeof(*p) );
44395 if( p ){
44396 p->iSize = iSize;
44398 return p;
44402 ** Check to see if the i-th bit is set. Return true or false.
44403 ** If p is NULL (if the bitmap has not been created) or if
44404 ** i is out of range, then return false.
44406 SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
44407 assert( p!=0 );
44408 i--;
44409 if( i>=p->iSize ) return 0;
44410 while( p->iDivisor ){
44411 u32 bin = i/p->iDivisor;
44412 i = i%p->iDivisor;
44413 p = p->u.apSub[bin];
44414 if (!p) {
44415 return 0;
44418 if( p->iSize<=BITVEC_NBIT ){
44419 return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
44420 } else{
44421 u32 h = BITVEC_HASH(i++);
44422 while( p->u.aHash[h] ){
44423 if( p->u.aHash[h]==i ) return 1;
44424 h = (h+1) % BITVEC_NINT;
44426 return 0;
44429 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
44430 return p!=0 && sqlite3BitvecTestNotNull(p,i);
44434 ** Set the i-th bit. Return 0 on success and an error code if
44435 ** anything goes wrong.
44437 ** This routine might cause sub-bitmaps to be allocated. Failing
44438 ** to get the memory needed to hold the sub-bitmap is the only
44439 ** that can go wrong with an insert, assuming p and i are valid.
44441 ** The calling function must ensure that p is a valid Bitvec object
44442 ** and that the value for "i" is within range of the Bitvec object.
44443 ** Otherwise the behavior is undefined.
44445 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
44446 u32 h;
44447 if( p==0 ) return SQLITE_OK;
44448 assert( i>0 );
44449 assert( i<=p->iSize );
44450 i--;
44451 while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
44452 u32 bin = i/p->iDivisor;
44453 i = i%p->iDivisor;
44454 if( p->u.apSub[bin]==0 ){
44455 p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
44456 if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
44458 p = p->u.apSub[bin];
44460 if( p->iSize<=BITVEC_NBIT ){
44461 p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
44462 return SQLITE_OK;
44464 h = BITVEC_HASH(i++);
44465 /* if there wasn't a hash collision, and this doesn't */
44466 /* completely fill the hash, then just add it without */
44467 /* worring about sub-dividing and re-hashing. */
44468 if( !p->u.aHash[h] ){
44469 if (p->nSet<(BITVEC_NINT-1)) {
44470 goto bitvec_set_end;
44471 } else {
44472 goto bitvec_set_rehash;
44475 /* there was a collision, check to see if it's already */
44476 /* in hash, if not, try to find a spot for it */
44477 do {
44478 if( p->u.aHash[h]==i ) return SQLITE_OK;
44479 h++;
44480 if( h>=BITVEC_NINT ) h = 0;
44481 } while( p->u.aHash[h] );
44482 /* we didn't find it in the hash. h points to the first */
44483 /* available free spot. check to see if this is going to */
44484 /* make our hash too "full". */
44485 bitvec_set_rehash:
44486 if( p->nSet>=BITVEC_MXHASH ){
44487 unsigned int j;
44488 int rc;
44489 u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
44490 if( aiValues==0 ){
44491 return SQLITE_NOMEM_BKPT;
44492 }else{
44493 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
44494 memset(p->u.apSub, 0, sizeof(p->u.apSub));
44495 p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
44496 rc = sqlite3BitvecSet(p, i);
44497 for(j=0; j<BITVEC_NINT; j++){
44498 if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
44500 sqlite3StackFree(0, aiValues);
44501 return rc;
44504 bitvec_set_end:
44505 p->nSet++;
44506 p->u.aHash[h] = i;
44507 return SQLITE_OK;
44511 ** Clear the i-th bit.
44513 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
44514 ** that BitvecClear can use to rebuilt its hash table.
44516 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
44517 if( p==0 ) return;
44518 assert( i>0 );
44519 i--;
44520 while( p->iDivisor ){
44521 u32 bin = i/p->iDivisor;
44522 i = i%p->iDivisor;
44523 p = p->u.apSub[bin];
44524 if (!p) {
44525 return;
44528 if( p->iSize<=BITVEC_NBIT ){
44529 p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
44530 }else{
44531 unsigned int j;
44532 u32 *aiValues = pBuf;
44533 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
44534 memset(p->u.aHash, 0, sizeof(p->u.aHash));
44535 p->nSet = 0;
44536 for(j=0; j<BITVEC_NINT; j++){
44537 if( aiValues[j] && aiValues[j]!=(i+1) ){
44538 u32 h = BITVEC_HASH(aiValues[j]-1);
44539 p->nSet++;
44540 while( p->u.aHash[h] ){
44541 h++;
44542 if( h>=BITVEC_NINT ) h = 0;
44544 p->u.aHash[h] = aiValues[j];
44551 ** Destroy a bitmap object. Reclaim all memory used.
44553 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
44554 if( p==0 ) return;
44555 if( p->iDivisor ){
44556 unsigned int i;
44557 for(i=0; i<BITVEC_NPTR; i++){
44558 sqlite3BitvecDestroy(p->u.apSub[i]);
44561 sqlite3_free(p);
44565 ** Return the value of the iSize parameter specified when Bitvec *p
44566 ** was created.
44568 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
44569 return p->iSize;
44572 #ifndef SQLITE_UNTESTABLE
44574 ** Let V[] be an array of unsigned characters sufficient to hold
44575 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
44576 ** Then the following macros can be used to set, clear, or test
44577 ** individual bits within V.
44579 #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
44580 #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
44581 #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
44584 ** This routine runs an extensive test of the Bitvec code.
44586 ** The input is an array of integers that acts as a program
44587 ** to test the Bitvec. The integers are opcodes followed
44588 ** by 0, 1, or 3 operands, depending on the opcode. Another
44589 ** opcode follows immediately after the last operand.
44591 ** There are 6 opcodes numbered from 0 through 5. 0 is the
44592 ** "halt" opcode and causes the test to end.
44594 ** 0 Halt and return the number of errors
44595 ** 1 N S X Set N bits beginning with S and incrementing by X
44596 ** 2 N S X Clear N bits beginning with S and incrementing by X
44597 ** 3 N Set N randomly chosen bits
44598 ** 4 N Clear N randomly chosen bits
44599 ** 5 N S X Set N bits from S increment X in array only, not in bitvec
44601 ** The opcodes 1 through 4 perform set and clear operations are performed
44602 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
44603 ** Opcode 5 works on the linear array only, not on the Bitvec.
44604 ** Opcode 5 is used to deliberately induce a fault in order to
44605 ** confirm that error detection works.
44607 ** At the conclusion of the test the linear array is compared
44608 ** against the Bitvec object. If there are any differences,
44609 ** an error is returned. If they are the same, zero is returned.
44611 ** If a memory allocation error occurs, return -1.
44613 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
44614 Bitvec *pBitvec = 0;
44615 unsigned char *pV = 0;
44616 int rc = -1;
44617 int i, nx, pc, op;
44618 void *pTmpSpace;
44620 /* Allocate the Bitvec to be tested and a linear array of
44621 ** bits to act as the reference */
44622 pBitvec = sqlite3BitvecCreate( sz );
44623 pV = sqlite3MallocZero( (sz+7)/8 + 1 );
44624 pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
44625 if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
44627 /* NULL pBitvec tests */
44628 sqlite3BitvecSet(0, 1);
44629 sqlite3BitvecClear(0, 1, pTmpSpace);
44631 /* Run the program */
44632 pc = 0;
44633 while( (op = aOp[pc])!=0 ){
44634 switch( op ){
44635 case 1:
44636 case 2:
44637 case 5: {
44638 nx = 4;
44639 i = aOp[pc+2] - 1;
44640 aOp[pc+2] += aOp[pc+3];
44641 break;
44643 case 3:
44644 case 4:
44645 default: {
44646 nx = 2;
44647 sqlite3_randomness(sizeof(i), &i);
44648 break;
44651 if( (--aOp[pc+1]) > 0 ) nx = 0;
44652 pc += nx;
44653 i = (i & 0x7fffffff)%sz;
44654 if( (op & 1)!=0 ){
44655 SETBIT(pV, (i+1));
44656 if( op!=5 ){
44657 if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
44659 }else{
44660 CLEARBIT(pV, (i+1));
44661 sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
44665 /* Test to make sure the linear array exactly matches the
44666 ** Bitvec object. Start with the assumption that they do
44667 ** match (rc==0). Change rc to non-zero if a discrepancy
44668 ** is found.
44670 rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
44671 + sqlite3BitvecTest(pBitvec, 0)
44672 + (sqlite3BitvecSize(pBitvec) - sz);
44673 for(i=1; i<=sz; i++){
44674 if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
44675 rc = i;
44676 break;
44680 /* Free allocated structure */
44681 bitvec_end:
44682 sqlite3_free(pTmpSpace);
44683 sqlite3_free(pV);
44684 sqlite3BitvecDestroy(pBitvec);
44685 return rc;
44687 #endif /* SQLITE_UNTESTABLE */
44689 /************** End of bitvec.c **********************************************/
44690 /************** Begin file pcache.c ******************************************/
44692 ** 2008 August 05
44694 ** The author disclaims copyright to this source code. In place of
44695 ** a legal notice, here is a blessing:
44697 ** May you do good and not evil.
44698 ** May you find forgiveness for yourself and forgive others.
44699 ** May you share freely, never taking more than you give.
44701 *************************************************************************
44702 ** This file implements that page cache.
44704 /* #include "sqliteInt.h" */
44707 ** A complete page cache is an instance of this structure. Every
44708 ** entry in the cache holds a single page of the database file. The
44709 ** btree layer only operates on the cached copy of the database pages.
44711 ** A page cache entry is "clean" if it exactly matches what is currently
44712 ** on disk. A page is "dirty" if it has been modified and needs to be
44713 ** persisted to disk.
44715 ** pDirty, pDirtyTail, pSynced:
44716 ** All dirty pages are linked into the doubly linked list using
44717 ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
44718 ** such that p was added to the list more recently than p->pDirtyNext.
44719 ** PCache.pDirty points to the first (newest) element in the list and
44720 ** pDirtyTail to the last (oldest).
44722 ** The PCache.pSynced variable is used to optimize searching for a dirty
44723 ** page to eject from the cache mid-transaction. It is better to eject
44724 ** a page that does not require a journal sync than one that does.
44725 ** Therefore, pSynced is maintained to that it *almost* always points
44726 ** to either the oldest page in the pDirty/pDirtyTail list that has a
44727 ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
44728 ** (so that the right page to eject can be found by following pDirtyPrev
44729 ** pointers).
44731 struct PCache {
44732 PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
44733 PgHdr *pSynced; /* Last synced page in dirty page list */
44734 int nRefSum; /* Sum of ref counts over all pages */
44735 int szCache; /* Configured cache size */
44736 int szSpill; /* Size before spilling occurs */
44737 int szPage; /* Size of every page in this cache */
44738 int szExtra; /* Size of extra space for each page */
44739 u8 bPurgeable; /* True if pages are on backing store */
44740 u8 eCreate; /* eCreate value for for xFetch() */
44741 int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
44742 void *pStress; /* Argument to xStress */
44743 sqlite3_pcache *pCache; /* Pluggable cache module */
44746 /********************************** Test and Debug Logic **********************/
44748 ** Debug tracing macros. Enable by by changing the "0" to "1" and
44749 ** recompiling.
44751 ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
44752 ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
44753 ** is displayed for many operations, resulting in a lot of output.
44755 #if defined(SQLITE_DEBUG) && 0
44756 int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
44757 int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
44758 # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
44759 void pcacheDump(PCache *pCache){
44760 int N;
44761 int i, j;
44762 sqlite3_pcache_page *pLower;
44763 PgHdr *pPg;
44764 unsigned char *a;
44766 if( sqlite3PcacheTrace<2 ) return;
44767 if( pCache->pCache==0 ) return;
44768 N = sqlite3PcachePagecount(pCache);
44769 if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
44770 for(i=1; i<=N; i++){
44771 pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
44772 if( pLower==0 ) continue;
44773 pPg = (PgHdr*)pLower->pExtra;
44774 printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
44775 a = (unsigned char *)pLower->pBuf;
44776 for(j=0; j<12; j++) printf("%02x", a[j]);
44777 printf("\n");
44778 if( pPg->pPage==0 ){
44779 sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
44783 #else
44784 # define pcacheTrace(X)
44785 # define pcacheDump(X)
44786 #endif
44789 ** Check invariants on a PgHdr entry. Return true if everything is OK.
44790 ** Return false if any invariant is violated.
44792 ** This routine is for use inside of assert() statements only. For
44793 ** example:
44795 ** assert( sqlite3PcachePageSanity(pPg) );
44797 #ifdef SQLITE_DEBUG
44798 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
44799 PCache *pCache;
44800 assert( pPg!=0 );
44801 assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
44802 pCache = pPg->pCache;
44803 assert( pCache!=0 ); /* Every page has an associated PCache */
44804 if( pPg->flags & PGHDR_CLEAN ){
44805 assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
44806 assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
44807 assert( pCache->pDirtyTail!=pPg );
44809 /* WRITEABLE pages must also be DIRTY */
44810 if( pPg->flags & PGHDR_WRITEABLE ){
44811 assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
44813 /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
44814 ** for example, when using the sqlite3PagerDontWrite() optimization:
44815 ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
44816 ** (2) Page X moved to freelist, WRITEABLE is cleared
44817 ** (3) Page X reused, WRITEABLE is set again
44818 ** If NEED_SYNC had been cleared in step 2, then it would not be reset
44819 ** in step 3, and page might be written into the database without first
44820 ** syncing the rollback journal, which might cause corruption on a power
44821 ** loss.
44823 ** Another example is when the database page size is smaller than the
44824 ** disk sector size. When any page of a sector is journalled, all pages
44825 ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
44826 ** in case they are later modified, since all pages in the same sector
44827 ** must be journalled and synced before any of those pages can be safely
44828 ** written.
44830 return 1;
44832 #endif /* SQLITE_DEBUG */
44835 /********************************** Linked List Management ********************/
44837 /* Allowed values for second argument to pcacheManageDirtyList() */
44838 #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
44839 #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
44840 #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
44843 ** Manage pPage's participation on the dirty list. Bits of the addRemove
44844 ** argument determines what operation to do. The 0x01 bit means first
44845 ** remove pPage from the dirty list. The 0x02 means add pPage back to
44846 ** the dirty list. Doing both moves pPage to the front of the dirty list.
44848 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
44849 PCache *p = pPage->pCache;
44851 pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
44852 addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
44853 pPage->pgno));
44854 if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
44855 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
44856 assert( pPage->pDirtyPrev || pPage==p->pDirty );
44858 /* Update the PCache1.pSynced variable if necessary. */
44859 if( p->pSynced==pPage ){
44860 p->pSynced = pPage->pDirtyPrev;
44863 if( pPage->pDirtyNext ){
44864 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
44865 }else{
44866 assert( pPage==p->pDirtyTail );
44867 p->pDirtyTail = pPage->pDirtyPrev;
44869 if( pPage->pDirtyPrev ){
44870 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
44871 }else{
44872 /* If there are now no dirty pages in the cache, set eCreate to 2.
44873 ** This is an optimization that allows sqlite3PcacheFetch() to skip
44874 ** searching for a dirty page to eject from the cache when it might
44875 ** otherwise have to. */
44876 assert( pPage==p->pDirty );
44877 p->pDirty = pPage->pDirtyNext;
44878 assert( p->bPurgeable || p->eCreate==2 );
44879 if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
44880 assert( p->bPurgeable==0 || p->eCreate==1 );
44881 p->eCreate = 2;
44885 if( addRemove & PCACHE_DIRTYLIST_ADD ){
44886 pPage->pDirtyPrev = 0;
44887 pPage->pDirtyNext = p->pDirty;
44888 if( pPage->pDirtyNext ){
44889 assert( pPage->pDirtyNext->pDirtyPrev==0 );
44890 pPage->pDirtyNext->pDirtyPrev = pPage;
44891 }else{
44892 p->pDirtyTail = pPage;
44893 if( p->bPurgeable ){
44894 assert( p->eCreate==2 );
44895 p->eCreate = 1;
44898 p->pDirty = pPage;
44900 /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
44901 ** pSynced to point to it. Checking the NEED_SYNC flag is an
44902 ** optimization, as if pSynced points to a page with the NEED_SYNC
44903 ** flag set sqlite3PcacheFetchStress() searches through all newer
44904 ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
44905 if( !p->pSynced
44906 && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
44908 p->pSynced = pPage;
44911 pcacheDump(p);
44915 ** Wrapper around the pluggable caches xUnpin method. If the cache is
44916 ** being used for an in-memory database, this function is a no-op.
44918 static void pcacheUnpin(PgHdr *p){
44919 if( p->pCache->bPurgeable ){
44920 pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
44921 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
44922 pcacheDump(p->pCache);
44927 ** Compute the number of pages of cache requested. p->szCache is the
44928 ** cache size requested by the "PRAGMA cache_size" statement.
44930 static int numberOfCachePages(PCache *p){
44931 if( p->szCache>=0 ){
44932 /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
44933 ** suggested cache size is set to N. */
44934 return p->szCache;
44935 }else{
44936 /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
44937 ** the number of cache pages is adjusted to use approximately abs(N*1024)
44938 ** bytes of memory. */
44939 return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
44943 /*************************************************** General Interfaces ******
44945 ** Initialize and shutdown the page cache subsystem. Neither of these
44946 ** functions are threadsafe.
44948 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
44949 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
44950 /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
44951 ** built-in default page cache is used instead of the application defined
44952 ** page cache. */
44953 sqlite3PCacheSetDefault();
44955 return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
44957 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
44958 if( sqlite3GlobalConfig.pcache2.xShutdown ){
44959 /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
44960 sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
44965 ** Return the size in bytes of a PCache object.
44967 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
44970 ** Create a new PCache object. Storage space to hold the object
44971 ** has already been allocated and is passed in as the p pointer.
44972 ** The caller discovers how much space needs to be allocated by
44973 ** calling sqlite3PcacheSize().
44975 ** szExtra is some extra space allocated for each page. The first
44976 ** 8 bytes of the extra space will be zeroed as the page is allocated,
44977 ** but remaining content will be uninitialized. Though it is opaque
44978 ** to this module, the extra space really ends up being the MemPage
44979 ** structure in the pager.
44981 SQLITE_PRIVATE int sqlite3PcacheOpen(
44982 int szPage, /* Size of every page */
44983 int szExtra, /* Extra space associated with each page */
44984 int bPurgeable, /* True if pages are on backing store */
44985 int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
44986 void *pStress, /* Argument to xStress */
44987 PCache *p /* Preallocated space for the PCache */
44989 memset(p, 0, sizeof(PCache));
44990 p->szPage = 1;
44991 p->szExtra = szExtra;
44992 assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
44993 p->bPurgeable = bPurgeable;
44994 p->eCreate = 2;
44995 p->xStress = xStress;
44996 p->pStress = pStress;
44997 p->szCache = 100;
44998 p->szSpill = 1;
44999 pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
45000 return sqlite3PcacheSetPageSize(p, szPage);
45004 ** Change the page size for PCache object. The caller must ensure that there
45005 ** are no outstanding page references when this function is called.
45007 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
45008 assert( pCache->nRefSum==0 && pCache->pDirty==0 );
45009 if( pCache->szPage ){
45010 sqlite3_pcache *pNew;
45011 pNew = sqlite3GlobalConfig.pcache2.xCreate(
45012 szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
45013 pCache->bPurgeable
45015 if( pNew==0 ) return SQLITE_NOMEM_BKPT;
45016 sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
45017 if( pCache->pCache ){
45018 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
45020 pCache->pCache = pNew;
45021 pCache->szPage = szPage;
45022 pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
45024 return SQLITE_OK;
45028 ** Try to obtain a page from the cache.
45030 ** This routine returns a pointer to an sqlite3_pcache_page object if
45031 ** such an object is already in cache, or if a new one is created.
45032 ** This routine returns a NULL pointer if the object was not in cache
45033 ** and could not be created.
45035 ** The createFlags should be 0 to check for existing pages and should
45036 ** be 3 (not 1, but 3) to try to create a new page.
45038 ** If the createFlag is 0, then NULL is always returned if the page
45039 ** is not already in the cache. If createFlag is 1, then a new page
45040 ** is created only if that can be done without spilling dirty pages
45041 ** and without exceeding the cache size limit.
45043 ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
45044 ** initialize the sqlite3_pcache_page object and convert it into a
45045 ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
45046 ** routines are split this way for performance reasons. When separated
45047 ** they can both (usually) operate without having to push values to
45048 ** the stack on entry and pop them back off on exit, which saves a
45049 ** lot of pushing and popping.
45051 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
45052 PCache *pCache, /* Obtain the page from this cache */
45053 Pgno pgno, /* Page number to obtain */
45054 int createFlag /* If true, create page if it does not exist already */
45056 int eCreate;
45057 sqlite3_pcache_page *pRes;
45059 assert( pCache!=0 );
45060 assert( pCache->pCache!=0 );
45061 assert( createFlag==3 || createFlag==0 );
45062 assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
45064 /* eCreate defines what to do if the page does not exist.
45065 ** 0 Do not allocate a new page. (createFlag==0)
45066 ** 1 Allocate a new page if doing so is inexpensive.
45067 ** (createFlag==1 AND bPurgeable AND pDirty)
45068 ** 2 Allocate a new page even it doing so is difficult.
45069 ** (createFlag==1 AND !(bPurgeable AND pDirty)
45071 eCreate = createFlag & pCache->eCreate;
45072 assert( eCreate==0 || eCreate==1 || eCreate==2 );
45073 assert( createFlag==0 || pCache->eCreate==eCreate );
45074 assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
45075 pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
45076 pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
45077 createFlag?" create":"",pRes));
45078 return pRes;
45082 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
45083 ** page because no clean pages are available for reuse and the cache
45084 ** size limit has been reached, then this routine can be invoked to
45085 ** try harder to allocate a page. This routine might invoke the stress
45086 ** callback to spill dirty pages to the journal. It will then try to
45087 ** allocate the new page and will only fail to allocate a new page on
45088 ** an OOM error.
45090 ** This routine should be invoked only after sqlite3PcacheFetch() fails.
45092 SQLITE_PRIVATE int sqlite3PcacheFetchStress(
45093 PCache *pCache, /* Obtain the page from this cache */
45094 Pgno pgno, /* Page number to obtain */
45095 sqlite3_pcache_page **ppPage /* Write result here */
45097 PgHdr *pPg;
45098 if( pCache->eCreate==2 ) return 0;
45100 if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
45101 /* Find a dirty page to write-out and recycle. First try to find a
45102 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
45103 ** cleared), but if that is not possible settle for any other
45104 ** unreferenced dirty page.
45106 ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
45107 ** flag is currently referenced, then the following may leave pSynced
45108 ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
45109 ** cleared). This is Ok, as pSynced is just an optimization. */
45110 for(pPg=pCache->pSynced;
45111 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
45112 pPg=pPg->pDirtyPrev
45114 pCache->pSynced = pPg;
45115 if( !pPg ){
45116 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
45118 if( pPg ){
45119 int rc;
45120 #ifdef SQLITE_LOG_CACHE_SPILL
45121 sqlite3_log(SQLITE_FULL,
45122 "spill page %d making room for %d - cache used: %d/%d",
45123 pPg->pgno, pgno,
45124 sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
45125 numberOfCachePages(pCache));
45126 #endif
45127 pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
45128 rc = pCache->xStress(pCache->pStress, pPg);
45129 pcacheDump(pCache);
45130 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
45131 return rc;
45135 *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
45136 return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
45140 ** This is a helper routine for sqlite3PcacheFetchFinish()
45142 ** In the uncommon case where the page being fetched has not been
45143 ** initialized, this routine is invoked to do the initialization.
45144 ** This routine is broken out into a separate function since it
45145 ** requires extra stack manipulation that can be avoided in the common
45146 ** case.
45148 static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
45149 PCache *pCache, /* Obtain the page from this cache */
45150 Pgno pgno, /* Page number obtained */
45151 sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
45153 PgHdr *pPgHdr;
45154 assert( pPage!=0 );
45155 pPgHdr = (PgHdr*)pPage->pExtra;
45156 assert( pPgHdr->pPage==0 );
45157 memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
45158 pPgHdr->pPage = pPage;
45159 pPgHdr->pData = pPage->pBuf;
45160 pPgHdr->pExtra = (void *)&pPgHdr[1];
45161 memset(pPgHdr->pExtra, 0, 8);
45162 pPgHdr->pCache = pCache;
45163 pPgHdr->pgno = pgno;
45164 pPgHdr->flags = PGHDR_CLEAN;
45165 return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
45169 ** This routine converts the sqlite3_pcache_page object returned by
45170 ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
45171 ** must be called after sqlite3PcacheFetch() in order to get a usable
45172 ** result.
45174 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
45175 PCache *pCache, /* Obtain the page from this cache */
45176 Pgno pgno, /* Page number obtained */
45177 sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
45179 PgHdr *pPgHdr;
45181 assert( pPage!=0 );
45182 pPgHdr = (PgHdr *)pPage->pExtra;
45184 if( !pPgHdr->pPage ){
45185 return pcacheFetchFinishWithInit(pCache, pgno, pPage);
45187 pCache->nRefSum++;
45188 pPgHdr->nRef++;
45189 assert( sqlite3PcachePageSanity(pPgHdr) );
45190 return pPgHdr;
45194 ** Decrement the reference count on a page. If the page is clean and the
45195 ** reference count drops to 0, then it is made eligible for recycling.
45197 SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
45198 assert( p->nRef>0 );
45199 p->pCache->nRefSum--;
45200 if( (--p->nRef)==0 ){
45201 if( p->flags&PGHDR_CLEAN ){
45202 pcacheUnpin(p);
45203 }else{
45204 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
45210 ** Increase the reference count of a supplied page by 1.
45212 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
45213 assert(p->nRef>0);
45214 assert( sqlite3PcachePageSanity(p) );
45215 p->nRef++;
45216 p->pCache->nRefSum++;
45220 ** Drop a page from the cache. There must be exactly one reference to the
45221 ** page. This function deletes that reference, so after it returns the
45222 ** page pointed to by p is invalid.
45224 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
45225 assert( p->nRef==1 );
45226 assert( sqlite3PcachePageSanity(p) );
45227 if( p->flags&PGHDR_DIRTY ){
45228 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
45230 p->pCache->nRefSum--;
45231 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
45235 ** Make sure the page is marked as dirty. If it isn't dirty already,
45236 ** make it so.
45238 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
45239 assert( p->nRef>0 );
45240 assert( sqlite3PcachePageSanity(p) );
45241 if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
45242 p->flags &= ~PGHDR_DONT_WRITE;
45243 if( p->flags & PGHDR_CLEAN ){
45244 p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
45245 pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
45246 assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
45247 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
45249 assert( sqlite3PcachePageSanity(p) );
45254 ** Make sure the page is marked as clean. If it isn't clean already,
45255 ** make it so.
45257 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
45258 assert( sqlite3PcachePageSanity(p) );
45259 if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
45260 assert( (p->flags & PGHDR_CLEAN)==0 );
45261 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
45262 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
45263 p->flags |= PGHDR_CLEAN;
45264 pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
45265 assert( sqlite3PcachePageSanity(p) );
45266 if( p->nRef==0 ){
45267 pcacheUnpin(p);
45273 ** Make every page in the cache clean.
45275 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
45276 PgHdr *p;
45277 pcacheTrace(("%p.CLEAN-ALL\n",pCache));
45278 while( (p = pCache->pDirty)!=0 ){
45279 sqlite3PcacheMakeClean(p);
45284 ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
45286 SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
45287 PgHdr *p;
45288 pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
45289 for(p=pCache->pDirty; p; p=p->pDirtyNext){
45290 p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
45292 pCache->pSynced = pCache->pDirtyTail;
45296 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
45298 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
45299 PgHdr *p;
45300 for(p=pCache->pDirty; p; p=p->pDirtyNext){
45301 p->flags &= ~PGHDR_NEED_SYNC;
45303 pCache->pSynced = pCache->pDirtyTail;
45307 ** Change the page number of page p to newPgno.
45309 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
45310 PCache *pCache = p->pCache;
45311 assert( p->nRef>0 );
45312 assert( newPgno>0 );
45313 assert( sqlite3PcachePageSanity(p) );
45314 pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
45315 sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
45316 p->pgno = newPgno;
45317 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
45318 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
45323 ** Drop every cache entry whose page number is greater than "pgno". The
45324 ** caller must ensure that there are no outstanding references to any pages
45325 ** other than page 1 with a page number greater than pgno.
45327 ** If there is a reference to page 1 and the pgno parameter passed to this
45328 ** function is 0, then the data area associated with page 1 is zeroed, but
45329 ** the page object is not dropped.
45331 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
45332 if( pCache->pCache ){
45333 PgHdr *p;
45334 PgHdr *pNext;
45335 pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
45336 for(p=pCache->pDirty; p; p=pNext){
45337 pNext = p->pDirtyNext;
45338 /* This routine never gets call with a positive pgno except right
45339 ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
45340 ** it must be that pgno==0.
45342 assert( p->pgno>0 );
45343 if( p->pgno>pgno ){
45344 assert( p->flags&PGHDR_DIRTY );
45345 sqlite3PcacheMakeClean(p);
45348 if( pgno==0 && pCache->nRefSum ){
45349 sqlite3_pcache_page *pPage1;
45350 pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
45351 if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
45352 ** pCache->nRefSum>0 */
45353 memset(pPage1->pBuf, 0, pCache->szPage);
45354 pgno = 1;
45357 sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
45362 ** Close a cache.
45364 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
45365 assert( pCache->pCache!=0 );
45366 pcacheTrace(("%p.CLOSE\n",pCache));
45367 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
45371 ** Discard the contents of the cache.
45373 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
45374 sqlite3PcacheTruncate(pCache, 0);
45378 ** Merge two lists of pages connected by pDirty and in pgno order.
45379 ** Do not bother fixing the pDirtyPrev pointers.
45381 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
45382 PgHdr result, *pTail;
45383 pTail = &result;
45384 assert( pA!=0 && pB!=0 );
45385 for(;;){
45386 if( pA->pgno<pB->pgno ){
45387 pTail->pDirty = pA;
45388 pTail = pA;
45389 pA = pA->pDirty;
45390 if( pA==0 ){
45391 pTail->pDirty = pB;
45392 break;
45394 }else{
45395 pTail->pDirty = pB;
45396 pTail = pB;
45397 pB = pB->pDirty;
45398 if( pB==0 ){
45399 pTail->pDirty = pA;
45400 break;
45404 return result.pDirty;
45408 ** Sort the list of pages in accending order by pgno. Pages are
45409 ** connected by pDirty pointers. The pDirtyPrev pointers are
45410 ** corrupted by this sort.
45412 ** Since there cannot be more than 2^31 distinct pages in a database,
45413 ** there cannot be more than 31 buckets required by the merge sorter.
45414 ** One extra bucket is added to catch overflow in case something
45415 ** ever changes to make the previous sentence incorrect.
45417 #define N_SORT_BUCKET 32
45418 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
45419 PgHdr *a[N_SORT_BUCKET], *p;
45420 int i;
45421 memset(a, 0, sizeof(a));
45422 while( pIn ){
45423 p = pIn;
45424 pIn = p->pDirty;
45425 p->pDirty = 0;
45426 for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
45427 if( a[i]==0 ){
45428 a[i] = p;
45429 break;
45430 }else{
45431 p = pcacheMergeDirtyList(a[i], p);
45432 a[i] = 0;
45435 if( NEVER(i==N_SORT_BUCKET-1) ){
45436 /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
45437 ** the input list. But that is impossible.
45439 a[i] = pcacheMergeDirtyList(a[i], p);
45442 p = a[0];
45443 for(i=1; i<N_SORT_BUCKET; i++){
45444 if( a[i]==0 ) continue;
45445 p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
45447 return p;
45451 ** Return a list of all dirty pages in the cache, sorted by page number.
45453 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
45454 PgHdr *p;
45455 for(p=pCache->pDirty; p; p=p->pDirtyNext){
45456 p->pDirty = p->pDirtyNext;
45458 return pcacheSortDirtyList(pCache->pDirty);
45462 ** Return the total number of references to all pages held by the cache.
45464 ** This is not the total number of pages referenced, but the sum of the
45465 ** reference count for all pages.
45467 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
45468 return pCache->nRefSum;
45472 ** Return the number of references to the page supplied as an argument.
45474 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
45475 return p->nRef;
45479 ** Return the total number of pages in the cache.
45481 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
45482 assert( pCache->pCache!=0 );
45483 return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
45486 #ifdef SQLITE_TEST
45488 ** Get the suggested cache-size value.
45490 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
45491 return numberOfCachePages(pCache);
45493 #endif
45496 ** Set the suggested cache-size value.
45498 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
45499 assert( pCache->pCache!=0 );
45500 pCache->szCache = mxPage;
45501 sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
45502 numberOfCachePages(pCache));
45506 ** Set the suggested cache-spill value. Make no changes if if the
45507 ** argument is zero. Return the effective cache-spill size, which will
45508 ** be the larger of the szSpill and szCache.
45510 SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
45511 int res;
45512 assert( p->pCache!=0 );
45513 if( mxPage ){
45514 if( mxPage<0 ){
45515 mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
45517 p->szSpill = mxPage;
45519 res = numberOfCachePages(p);
45520 if( res<p->szSpill ) res = p->szSpill;
45521 return res;
45525 ** Free up as much memory as possible from the page cache.
45527 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
45528 assert( pCache->pCache!=0 );
45529 sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
45533 ** Return the size of the header added by this middleware layer
45534 ** in the page-cache hierarchy.
45536 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
45539 ** Return the number of dirty pages currently in the cache, as a percentage
45540 ** of the configured cache size.
45542 SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
45543 PgHdr *pDirty;
45544 int nDirty = 0;
45545 int nCache = numberOfCachePages(pCache);
45546 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
45547 return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
45550 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
45552 ** For all dirty pages currently in the cache, invoke the specified
45553 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
45554 ** defined.
45556 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
45557 PgHdr *pDirty;
45558 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
45559 xIter(pDirty);
45562 #endif
45564 /************** End of pcache.c **********************************************/
45565 /************** Begin file pcache1.c *****************************************/
45567 ** 2008 November 05
45569 ** The author disclaims copyright to this source code. In place of
45570 ** a legal notice, here is a blessing:
45572 ** May you do good and not evil.
45573 ** May you find forgiveness for yourself and forgive others.
45574 ** May you share freely, never taking more than you give.
45576 *************************************************************************
45578 ** This file implements the default page cache implementation (the
45579 ** sqlite3_pcache interface). It also contains part of the implementation
45580 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
45581 ** If the default page cache implementation is overridden, then neither of
45582 ** these two features are available.
45584 ** A Page cache line looks like this:
45586 ** -------------------------------------------------------------
45587 ** | database page content | PgHdr1 | MemPage | PgHdr |
45588 ** -------------------------------------------------------------
45590 ** The database page content is up front (so that buffer overreads tend to
45591 ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
45592 ** is the extension added by the btree.c module containing information such
45593 ** as the database page number and how that database page is used. PgHdr
45594 ** is added by the pcache.c layer and contains information used to keep track
45595 ** of which pages are "dirty". PgHdr1 is an extension added by this
45596 ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
45597 ** PgHdr1 contains information needed to look up a page by its page number.
45598 ** The superclass sqlite3_pcache_page.pBuf points to the start of the
45599 ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
45601 ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
45602 ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
45603 ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
45604 ** size can vary according to architecture, compile-time options, and
45605 ** SQLite library version number.
45607 ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
45608 ** using a separate memory allocation from the database page content. This
45609 ** seeks to overcome the "clownshoe" problem (also called "internal
45610 ** fragmentation" in academic literature) of allocating a few bytes more
45611 ** than a power of two with the memory allocator rounding up to the next
45612 ** power of two, and leaving the rounded-up space unused.
45614 ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
45615 ** with this module. Information is passed back and forth as PgHdr1 pointers.
45617 ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
45618 ** The btree.c module deals with pointers to MemPage objects.
45620 ** SOURCE OF PAGE CACHE MEMORY:
45622 ** Memory for a page might come from any of three sources:
45624 ** (1) The general-purpose memory allocator - sqlite3Malloc()
45625 ** (2) Global page-cache memory provided using sqlite3_config() with
45626 ** SQLITE_CONFIG_PAGECACHE.
45627 ** (3) PCache-local bulk allocation.
45629 ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
45630 ** that is allocated when the page cache is created. The size of the local
45631 ** bulk allocation can be adjusted using
45633 ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
45635 ** If N is positive, then N pages worth of memory are allocated using a single
45636 ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
45637 ** Or if N is negative, then -1024*N bytes of memory are allocated and used
45638 ** for as many pages as can be accomodated.
45640 ** Only one of (2) or (3) can be used. Once the memory available to (2) or
45641 ** (3) is exhausted, subsequent allocations fail over to the general-purpose
45642 ** memory allocator (1).
45644 ** Earlier versions of SQLite used only methods (1) and (2). But experiments
45645 ** show that method (3) with N==100 provides about a 5% performance boost for
45646 ** common workloads.
45648 /* #include "sqliteInt.h" */
45650 typedef struct PCache1 PCache1;
45651 typedef struct PgHdr1 PgHdr1;
45652 typedef struct PgFreeslot PgFreeslot;
45653 typedef struct PGroup PGroup;
45656 ** Each cache entry is represented by an instance of the following
45657 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
45658 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
45659 ** in memory.
45661 struct PgHdr1 {
45662 sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
45663 unsigned int iKey; /* Key value (page number) */
45664 u8 isBulkLocal; /* This page from bulk local storage */
45665 u8 isAnchor; /* This is the PGroup.lru element */
45666 PgHdr1 *pNext; /* Next in hash table chain */
45667 PCache1 *pCache; /* Cache that currently owns this page */
45668 PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
45669 PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
45673 ** A page is pinned if it is no on the LRU list
45675 #define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
45676 #define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
45678 /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
45679 ** of one or more PCaches that are able to recycle each other's unpinned
45680 ** pages when they are under memory pressure. A PGroup is an instance of
45681 ** the following object.
45683 ** This page cache implementation works in one of two modes:
45685 ** (1) Every PCache is the sole member of its own PGroup. There is
45686 ** one PGroup per PCache.
45688 ** (2) There is a single global PGroup that all PCaches are a member
45689 ** of.
45691 ** Mode 1 uses more memory (since PCache instances are not able to rob
45692 ** unused pages from other PCaches) but it also operates without a mutex,
45693 ** and is therefore often faster. Mode 2 requires a mutex in order to be
45694 ** threadsafe, but recycles pages more efficiently.
45696 ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
45697 ** PGroup which is the pcache1.grp global variable and its mutex is
45698 ** SQLITE_MUTEX_STATIC_LRU.
45700 struct PGroup {
45701 sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
45702 unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
45703 unsigned int nMinPage; /* Sum of nMin for purgeable caches */
45704 unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
45705 unsigned int nPurgeable; /* Number of purgeable pages allocated */
45706 PgHdr1 lru; /* The beginning and end of the LRU list */
45709 /* Each page cache is an instance of the following object. Every
45710 ** open database file (including each in-memory database and each
45711 ** temporary or transient database) has a single page cache which
45712 ** is an instance of this object.
45714 ** Pointers to structures of this type are cast and returned as
45715 ** opaque sqlite3_pcache* handles.
45717 struct PCache1 {
45718 /* Cache configuration parameters. Page size (szPage) and the purgeable
45719 ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
45720 ** cache is created and are never changed thereafter. nMax may be
45721 ** modified at any time by a call to the pcache1Cachesize() method.
45722 ** The PGroup mutex must be held when accessing nMax.
45724 PGroup *pGroup; /* PGroup this cache belongs to */
45725 unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
45726 int szPage; /* Size of database content section */
45727 int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
45728 int szAlloc; /* Total size of one pcache line */
45729 int bPurgeable; /* True if cache is purgeable */
45730 unsigned int nMin; /* Minimum number of pages reserved */
45731 unsigned int nMax; /* Configured "cache_size" value */
45732 unsigned int n90pct; /* nMax*9/10 */
45733 unsigned int iMaxKey; /* Largest key seen since xTruncate() */
45735 /* Hash table of all pages. The following variables may only be accessed
45736 ** when the accessor is holding the PGroup mutex.
45738 unsigned int nRecyclable; /* Number of pages in the LRU list */
45739 unsigned int nPage; /* Total number of pages in apHash */
45740 unsigned int nHash; /* Number of slots in apHash[] */
45741 PgHdr1 **apHash; /* Hash table for fast lookup by key */
45742 PgHdr1 *pFree; /* List of unused pcache-local pages */
45743 void *pBulk; /* Bulk memory used by pcache-local */
45747 ** Free slots in the allocator used to divide up the global page cache
45748 ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
45750 struct PgFreeslot {
45751 PgFreeslot *pNext; /* Next free slot */
45755 ** Global data used by this cache.
45757 static SQLITE_WSD struct PCacheGlobal {
45758 PGroup grp; /* The global PGroup for mode (2) */
45760 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
45761 ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
45762 ** fixed at sqlite3_initialize() time and do not require mutex protection.
45763 ** The nFreeSlot and pFree values do require mutex protection.
45765 int isInit; /* True if initialized */
45766 int separateCache; /* Use a new PGroup for each PCache */
45767 int nInitPage; /* Initial bulk allocation size */
45768 int szSlot; /* Size of each free slot */
45769 int nSlot; /* The number of pcache slots */
45770 int nReserve; /* Try to keep nFreeSlot above this */
45771 void *pStart, *pEnd; /* Bounds of global page cache memory */
45772 /* Above requires no mutex. Use mutex below for variable that follow. */
45773 sqlite3_mutex *mutex; /* Mutex for accessing the following: */
45774 PgFreeslot *pFree; /* Free page blocks */
45775 int nFreeSlot; /* Number of unused pcache slots */
45776 /* The following value requires a mutex to change. We skip the mutex on
45777 ** reading because (1) most platforms read a 32-bit integer atomically and
45778 ** (2) even if an incorrect value is read, no great harm is done since this
45779 ** is really just an optimization. */
45780 int bUnderPressure; /* True if low on PAGECACHE memory */
45781 } pcache1_g;
45784 ** All code in this file should access the global structure above via the
45785 ** alias "pcache1". This ensures that the WSD emulation is used when
45786 ** compiling for systems that do not support real WSD.
45788 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
45791 ** Macros to enter and leave the PCache LRU mutex.
45793 #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
45794 # define pcache1EnterMutex(X) assert((X)->mutex==0)
45795 # define pcache1LeaveMutex(X) assert((X)->mutex==0)
45796 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
45797 #else
45798 # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
45799 # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
45800 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
45801 #endif
45803 /******************************************************************************/
45804 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
45808 ** This function is called during initialization if a static buffer is
45809 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
45810 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
45811 ** enough to contain 'n' buffers of 'sz' bytes each.
45813 ** This routine is called from sqlite3_initialize() and so it is guaranteed
45814 ** to be serialized already. There is no need for further mutexing.
45816 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
45817 if( pcache1.isInit ){
45818 PgFreeslot *p;
45819 if( pBuf==0 ) sz = n = 0;
45820 if( n==0 ) sz = 0;
45821 sz = ROUNDDOWN8(sz);
45822 pcache1.szSlot = sz;
45823 pcache1.nSlot = pcache1.nFreeSlot = n;
45824 pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
45825 pcache1.pStart = pBuf;
45826 pcache1.pFree = 0;
45827 pcache1.bUnderPressure = 0;
45828 while( n-- ){
45829 p = (PgFreeslot*)pBuf;
45830 p->pNext = pcache1.pFree;
45831 pcache1.pFree = p;
45832 pBuf = (void*)&((char*)pBuf)[sz];
45834 pcache1.pEnd = pBuf;
45839 ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
45840 ** true if pCache->pFree ends up containing one or more free pages.
45842 static int pcache1InitBulk(PCache1 *pCache){
45843 i64 szBulk;
45844 char *zBulk;
45845 if( pcache1.nInitPage==0 ) return 0;
45846 /* Do not bother with a bulk allocation if the cache size very small */
45847 if( pCache->nMax<3 ) return 0;
45848 sqlite3BeginBenignMalloc();
45849 if( pcache1.nInitPage>0 ){
45850 szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
45851 }else{
45852 szBulk = -1024 * (i64)pcache1.nInitPage;
45854 if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
45855 szBulk = pCache->szAlloc*(i64)pCache->nMax;
45857 zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
45858 sqlite3EndBenignMalloc();
45859 if( zBulk ){
45860 int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
45862 PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
45863 pX->page.pBuf = zBulk;
45864 pX->page.pExtra = &pX[1];
45865 pX->isBulkLocal = 1;
45866 pX->isAnchor = 0;
45867 pX->pNext = pCache->pFree;
45868 pCache->pFree = pX;
45869 zBulk += pCache->szAlloc;
45870 }while( --nBulk );
45872 return pCache->pFree!=0;
45876 ** Malloc function used within this file to allocate space from the buffer
45877 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
45878 ** such buffer exists or there is no space left in it, this function falls
45879 ** back to sqlite3Malloc().
45881 ** Multiple threads can run this routine at the same time. Global variables
45882 ** in pcache1 need to be protected via mutex.
45884 static void *pcache1Alloc(int nByte){
45885 void *p = 0;
45886 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
45887 if( nByte<=pcache1.szSlot ){
45888 sqlite3_mutex_enter(pcache1.mutex);
45889 p = (PgHdr1 *)pcache1.pFree;
45890 if( p ){
45891 pcache1.pFree = pcache1.pFree->pNext;
45892 pcache1.nFreeSlot--;
45893 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
45894 assert( pcache1.nFreeSlot>=0 );
45895 sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
45896 sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
45898 sqlite3_mutex_leave(pcache1.mutex);
45900 if( p==0 ){
45901 /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
45902 ** it from sqlite3Malloc instead.
45904 p = sqlite3Malloc(nByte);
45905 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
45906 if( p ){
45907 int sz = sqlite3MallocSize(p);
45908 sqlite3_mutex_enter(pcache1.mutex);
45909 sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
45910 sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
45911 sqlite3_mutex_leave(pcache1.mutex);
45913 #endif
45914 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
45916 return p;
45920 ** Free an allocated buffer obtained from pcache1Alloc().
45922 static void pcache1Free(void *p){
45923 if( p==0 ) return;
45924 if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
45925 PgFreeslot *pSlot;
45926 sqlite3_mutex_enter(pcache1.mutex);
45927 sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
45928 pSlot = (PgFreeslot*)p;
45929 pSlot->pNext = pcache1.pFree;
45930 pcache1.pFree = pSlot;
45931 pcache1.nFreeSlot++;
45932 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
45933 assert( pcache1.nFreeSlot<=pcache1.nSlot );
45934 sqlite3_mutex_leave(pcache1.mutex);
45935 }else{
45936 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
45937 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
45938 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
45940 int nFreed = 0;
45941 nFreed = sqlite3MallocSize(p);
45942 sqlite3_mutex_enter(pcache1.mutex);
45943 sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
45944 sqlite3_mutex_leave(pcache1.mutex);
45946 #endif
45947 sqlite3_free(p);
45951 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45953 ** Return the size of a pcache allocation
45955 static int pcache1MemSize(void *p){
45956 if( p>=pcache1.pStart && p<pcache1.pEnd ){
45957 return pcache1.szSlot;
45958 }else{
45959 int iSize;
45960 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
45961 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
45962 iSize = sqlite3MallocSize(p);
45963 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
45964 return iSize;
45967 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
45970 ** Allocate a new page object initially associated with cache pCache.
45972 static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
45973 PgHdr1 *p = 0;
45974 void *pPg;
45976 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45977 if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
45978 p = pCache->pFree;
45979 pCache->pFree = p->pNext;
45980 p->pNext = 0;
45981 }else{
45982 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45983 /* The group mutex must be released before pcache1Alloc() is called. This
45984 ** is because it might call sqlite3_release_memory(), which assumes that
45985 ** this mutex is not held. */
45986 assert( pcache1.separateCache==0 );
45987 assert( pCache->pGroup==&pcache1.grp );
45988 pcache1LeaveMutex(pCache->pGroup);
45989 #endif
45990 if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
45991 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
45992 pPg = pcache1Alloc(pCache->szPage);
45993 p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
45994 if( !pPg || !p ){
45995 pcache1Free(pPg);
45996 sqlite3_free(p);
45997 pPg = 0;
45999 #else
46000 pPg = pcache1Alloc(pCache->szAlloc);
46001 p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
46002 #endif
46003 if( benignMalloc ){ sqlite3EndBenignMalloc(); }
46004 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
46005 pcache1EnterMutex(pCache->pGroup);
46006 #endif
46007 if( pPg==0 ) return 0;
46008 p->page.pBuf = pPg;
46009 p->page.pExtra = &p[1];
46010 p->isBulkLocal = 0;
46011 p->isAnchor = 0;
46013 (*pCache->pnPurgeable)++;
46014 return p;
46018 ** Free a page object allocated by pcache1AllocPage().
46020 static void pcache1FreePage(PgHdr1 *p){
46021 PCache1 *pCache;
46022 assert( p!=0 );
46023 pCache = p->pCache;
46024 assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
46025 if( p->isBulkLocal ){
46026 p->pNext = pCache->pFree;
46027 pCache->pFree = p;
46028 }else{
46029 pcache1Free(p->page.pBuf);
46030 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
46031 sqlite3_free(p);
46032 #endif
46034 (*pCache->pnPurgeable)--;
46038 ** Malloc function used by SQLite to obtain space from the buffer configured
46039 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
46040 ** exists, this function falls back to sqlite3Malloc().
46042 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
46043 return pcache1Alloc(sz);
46047 ** Free an allocated buffer obtained from sqlite3PageMalloc().
46049 SQLITE_PRIVATE void sqlite3PageFree(void *p){
46050 pcache1Free(p);
46055 ** Return true if it desirable to avoid allocating a new page cache
46056 ** entry.
46058 ** If memory was allocated specifically to the page cache using
46059 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
46060 ** it is desirable to avoid allocating a new page cache entry because
46061 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
46062 ** for all page cache needs and we should not need to spill the
46063 ** allocation onto the heap.
46065 ** Or, the heap is used for all page cache memory but the heap is
46066 ** under memory pressure, then again it is desirable to avoid
46067 ** allocating a new page cache entry in order to avoid stressing
46068 ** the heap even further.
46070 static int pcache1UnderMemoryPressure(PCache1 *pCache){
46071 if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
46072 return pcache1.bUnderPressure;
46073 }else{
46074 return sqlite3HeapNearlyFull();
46078 /******************************************************************************/
46079 /******** General Implementation Functions ************************************/
46082 ** This function is used to resize the hash table used by the cache passed
46083 ** as the first argument.
46085 ** The PCache mutex must be held when this function is called.
46087 static void pcache1ResizeHash(PCache1 *p){
46088 PgHdr1 **apNew;
46089 unsigned int nNew;
46090 unsigned int i;
46092 assert( sqlite3_mutex_held(p->pGroup->mutex) );
46094 nNew = p->nHash*2;
46095 if( nNew<256 ){
46096 nNew = 256;
46099 pcache1LeaveMutex(p->pGroup);
46100 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
46101 apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
46102 if( p->nHash ){ sqlite3EndBenignMalloc(); }
46103 pcache1EnterMutex(p->pGroup);
46104 if( apNew ){
46105 for(i=0; i<p->nHash; i++){
46106 PgHdr1 *pPage;
46107 PgHdr1 *pNext = p->apHash[i];
46108 while( (pPage = pNext)!=0 ){
46109 unsigned int h = pPage->iKey % nNew;
46110 pNext = pPage->pNext;
46111 pPage->pNext = apNew[h];
46112 apNew[h] = pPage;
46115 sqlite3_free(p->apHash);
46116 p->apHash = apNew;
46117 p->nHash = nNew;
46122 ** This function is used internally to remove the page pPage from the
46123 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
46124 ** LRU list, then this function is a no-op.
46126 ** The PGroup mutex must be held when this function is called.
46128 static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
46129 assert( pPage!=0 );
46130 assert( PAGE_IS_UNPINNED(pPage) );
46131 assert( pPage->pLruNext );
46132 assert( pPage->pLruPrev );
46133 assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
46134 pPage->pLruPrev->pLruNext = pPage->pLruNext;
46135 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
46136 pPage->pLruNext = 0;
46137 pPage->pLruPrev = 0;
46138 assert( pPage->isAnchor==0 );
46139 assert( pPage->pCache->pGroup->lru.isAnchor==1 );
46140 pPage->pCache->nRecyclable--;
46141 return pPage;
46146 ** Remove the page supplied as an argument from the hash table
46147 ** (PCache1.apHash structure) that it is currently stored in.
46148 ** Also free the page if freePage is true.
46150 ** The PGroup mutex must be held when this function is called.
46152 static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
46153 unsigned int h;
46154 PCache1 *pCache = pPage->pCache;
46155 PgHdr1 **pp;
46157 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
46158 h = pPage->iKey % pCache->nHash;
46159 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
46160 *pp = (*pp)->pNext;
46162 pCache->nPage--;
46163 if( freeFlag ) pcache1FreePage(pPage);
46167 ** If there are currently more than nMaxPage pages allocated, try
46168 ** to recycle pages to reduce the number allocated to nMaxPage.
46170 static void pcache1EnforceMaxPage(PCache1 *pCache){
46171 PGroup *pGroup = pCache->pGroup;
46172 PgHdr1 *p;
46173 assert( sqlite3_mutex_held(pGroup->mutex) );
46174 while( pGroup->nPurgeable>pGroup->nMaxPage
46175 && (p=pGroup->lru.pLruPrev)->isAnchor==0
46177 assert( p->pCache->pGroup==pGroup );
46178 assert( PAGE_IS_UNPINNED(p) );
46179 pcache1PinPage(p);
46180 pcache1RemoveFromHash(p, 1);
46182 if( pCache->nPage==0 && pCache->pBulk ){
46183 sqlite3_free(pCache->pBulk);
46184 pCache->pBulk = pCache->pFree = 0;
46189 ** Discard all pages from cache pCache with a page number (key value)
46190 ** greater than or equal to iLimit. Any pinned pages that meet this
46191 ** criteria are unpinned before they are discarded.
46193 ** The PCache mutex must be held when this function is called.
46195 static void pcache1TruncateUnsafe(
46196 PCache1 *pCache, /* The cache to truncate */
46197 unsigned int iLimit /* Drop pages with this pgno or larger */
46199 TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
46200 unsigned int h, iStop;
46201 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
46202 assert( pCache->iMaxKey >= iLimit );
46203 assert( pCache->nHash > 0 );
46204 if( pCache->iMaxKey - iLimit < pCache->nHash ){
46205 /* If we are just shaving the last few pages off the end of the
46206 ** cache, then there is no point in scanning the entire hash table.
46207 ** Only scan those hash slots that might contain pages that need to
46208 ** be removed. */
46209 h = iLimit % pCache->nHash;
46210 iStop = pCache->iMaxKey % pCache->nHash;
46211 TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
46212 }else{
46213 /* This is the general case where many pages are being removed.
46214 ** It is necessary to scan the entire hash table */
46215 h = pCache->nHash/2;
46216 iStop = h - 1;
46218 for(;;){
46219 PgHdr1 **pp;
46220 PgHdr1 *pPage;
46221 assert( h<pCache->nHash );
46222 pp = &pCache->apHash[h];
46223 while( (pPage = *pp)!=0 ){
46224 if( pPage->iKey>=iLimit ){
46225 pCache->nPage--;
46226 *pp = pPage->pNext;
46227 if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
46228 pcache1FreePage(pPage);
46229 }else{
46230 pp = &pPage->pNext;
46231 TESTONLY( if( nPage>=0 ) nPage++; )
46234 if( h==iStop ) break;
46235 h = (h+1) % pCache->nHash;
46237 assert( nPage<0 || pCache->nPage==(unsigned)nPage );
46240 /******************************************************************************/
46241 /******** sqlite3_pcache Methods **********************************************/
46244 ** Implementation of the sqlite3_pcache.xInit method.
46246 static int pcache1Init(void *NotUsed){
46247 UNUSED_PARAMETER(NotUsed);
46248 assert( pcache1.isInit==0 );
46249 memset(&pcache1, 0, sizeof(pcache1));
46253 ** The pcache1.separateCache variable is true if each PCache has its own
46254 ** private PGroup (mode-1). pcache1.separateCache is false if the single
46255 ** PGroup in pcache1.grp is used for all page caches (mode-2).
46257 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
46259 ** * Use a unified cache in single-threaded applications that have
46260 ** configured a start-time buffer for use as page-cache memory using
46261 ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
46262 ** pBuf argument.
46264 ** * Otherwise use separate caches (mode-1)
46266 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
46267 pcache1.separateCache = 0;
46268 #elif SQLITE_THREADSAFE
46269 pcache1.separateCache = sqlite3GlobalConfig.pPage==0
46270 || sqlite3GlobalConfig.bCoreMutex>0;
46271 #else
46272 pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
46273 #endif
46275 #if SQLITE_THREADSAFE
46276 if( sqlite3GlobalConfig.bCoreMutex ){
46277 pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
46278 pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
46280 #endif
46281 if( pcache1.separateCache
46282 && sqlite3GlobalConfig.nPage!=0
46283 && sqlite3GlobalConfig.pPage==0
46285 pcache1.nInitPage = sqlite3GlobalConfig.nPage;
46286 }else{
46287 pcache1.nInitPage = 0;
46289 pcache1.grp.mxPinned = 10;
46290 pcache1.isInit = 1;
46291 return SQLITE_OK;
46295 ** Implementation of the sqlite3_pcache.xShutdown method.
46296 ** Note that the static mutex allocated in xInit does
46297 ** not need to be freed.
46299 static void pcache1Shutdown(void *NotUsed){
46300 UNUSED_PARAMETER(NotUsed);
46301 assert( pcache1.isInit!=0 );
46302 memset(&pcache1, 0, sizeof(pcache1));
46305 /* forward declaration */
46306 static void pcache1Destroy(sqlite3_pcache *p);
46309 ** Implementation of the sqlite3_pcache.xCreate method.
46311 ** Allocate a new cache.
46313 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
46314 PCache1 *pCache; /* The newly created page cache */
46315 PGroup *pGroup; /* The group the new page cache will belong to */
46316 int sz; /* Bytes of memory required to allocate the new cache */
46318 assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
46319 assert( szExtra < 300 );
46321 sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
46322 pCache = (PCache1 *)sqlite3MallocZero(sz);
46323 if( pCache ){
46324 if( pcache1.separateCache ){
46325 pGroup = (PGroup*)&pCache[1];
46326 pGroup->mxPinned = 10;
46327 }else{
46328 pGroup = &pcache1.grp;
46330 if( pGroup->lru.isAnchor==0 ){
46331 pGroup->lru.isAnchor = 1;
46332 pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
46334 pCache->pGroup = pGroup;
46335 pCache->szPage = szPage;
46336 pCache->szExtra = szExtra;
46337 pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
46338 pCache->bPurgeable = (bPurgeable ? 1 : 0);
46339 pcache1EnterMutex(pGroup);
46340 pcache1ResizeHash(pCache);
46341 if( bPurgeable ){
46342 pCache->nMin = 10;
46343 pGroup->nMinPage += pCache->nMin;
46344 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
46345 pCache->pnPurgeable = &pGroup->nPurgeable;
46346 }else{
46347 static unsigned int dummyCurrentPage;
46348 pCache->pnPurgeable = &dummyCurrentPage;
46350 pcache1LeaveMutex(pGroup);
46351 if( pCache->nHash==0 ){
46352 pcache1Destroy((sqlite3_pcache*)pCache);
46353 pCache = 0;
46356 return (sqlite3_pcache *)pCache;
46360 ** Implementation of the sqlite3_pcache.xCachesize method.
46362 ** Configure the cache_size limit for a cache.
46364 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
46365 PCache1 *pCache = (PCache1 *)p;
46366 if( pCache->bPurgeable ){
46367 PGroup *pGroup = pCache->pGroup;
46368 pcache1EnterMutex(pGroup);
46369 pGroup->nMaxPage += (nMax - pCache->nMax);
46370 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
46371 pCache->nMax = nMax;
46372 pCache->n90pct = pCache->nMax*9/10;
46373 pcache1EnforceMaxPage(pCache);
46374 pcache1LeaveMutex(pGroup);
46379 ** Implementation of the sqlite3_pcache.xShrink method.
46381 ** Free up as much memory as possible.
46383 static void pcache1Shrink(sqlite3_pcache *p){
46384 PCache1 *pCache = (PCache1*)p;
46385 if( pCache->bPurgeable ){
46386 PGroup *pGroup = pCache->pGroup;
46387 int savedMaxPage;
46388 pcache1EnterMutex(pGroup);
46389 savedMaxPage = pGroup->nMaxPage;
46390 pGroup->nMaxPage = 0;
46391 pcache1EnforceMaxPage(pCache);
46392 pGroup->nMaxPage = savedMaxPage;
46393 pcache1LeaveMutex(pGroup);
46398 ** Implementation of the sqlite3_pcache.xPagecount method.
46400 static int pcache1Pagecount(sqlite3_pcache *p){
46401 int n;
46402 PCache1 *pCache = (PCache1*)p;
46403 pcache1EnterMutex(pCache->pGroup);
46404 n = pCache->nPage;
46405 pcache1LeaveMutex(pCache->pGroup);
46406 return n;
46411 ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
46412 ** in the header of the pcache1Fetch() procedure.
46414 ** This steps are broken out into a separate procedure because they are
46415 ** usually not needed, and by avoiding the stack initialization required
46416 ** for these steps, the main pcache1Fetch() procedure can run faster.
46418 static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
46419 PCache1 *pCache,
46420 unsigned int iKey,
46421 int createFlag
46423 unsigned int nPinned;
46424 PGroup *pGroup = pCache->pGroup;
46425 PgHdr1 *pPage = 0;
46427 /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
46428 assert( pCache->nPage >= pCache->nRecyclable );
46429 nPinned = pCache->nPage - pCache->nRecyclable;
46430 assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
46431 assert( pCache->n90pct == pCache->nMax*9/10 );
46432 if( createFlag==1 && (
46433 nPinned>=pGroup->mxPinned
46434 || nPinned>=pCache->n90pct
46435 || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
46437 return 0;
46440 if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
46441 assert( pCache->nHash>0 && pCache->apHash );
46443 /* Step 4. Try to recycle a page. */
46444 if( pCache->bPurgeable
46445 && !pGroup->lru.pLruPrev->isAnchor
46446 && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
46448 PCache1 *pOther;
46449 pPage = pGroup->lru.pLruPrev;
46450 assert( PAGE_IS_UNPINNED(pPage) );
46451 pcache1RemoveFromHash(pPage, 0);
46452 pcache1PinPage(pPage);
46453 pOther = pPage->pCache;
46454 if( pOther->szAlloc != pCache->szAlloc ){
46455 pcache1FreePage(pPage);
46456 pPage = 0;
46457 }else{
46458 pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
46462 /* Step 5. If a usable page buffer has still not been found,
46463 ** attempt to allocate a new one.
46465 if( !pPage ){
46466 pPage = pcache1AllocPage(pCache, createFlag==1);
46469 if( pPage ){
46470 unsigned int h = iKey % pCache->nHash;
46471 pCache->nPage++;
46472 pPage->iKey = iKey;
46473 pPage->pNext = pCache->apHash[h];
46474 pPage->pCache = pCache;
46475 pPage->pLruPrev = 0;
46476 pPage->pLruNext = 0;
46477 *(void **)pPage->page.pExtra = 0;
46478 pCache->apHash[h] = pPage;
46479 if( iKey>pCache->iMaxKey ){
46480 pCache->iMaxKey = iKey;
46483 return pPage;
46487 ** Implementation of the sqlite3_pcache.xFetch method.
46489 ** Fetch a page by key value.
46491 ** Whether or not a new page may be allocated by this function depends on
46492 ** the value of the createFlag argument. 0 means do not allocate a new
46493 ** page. 1 means allocate a new page if space is easily available. 2
46494 ** means to try really hard to allocate a new page.
46496 ** For a non-purgeable cache (a cache used as the storage for an in-memory
46497 ** database) there is really no difference between createFlag 1 and 2. So
46498 ** the calling function (pcache.c) will never have a createFlag of 1 on
46499 ** a non-purgeable cache.
46501 ** There are three different approaches to obtaining space for a page,
46502 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
46504 ** 1. Regardless of the value of createFlag, the cache is searched for a
46505 ** copy of the requested page. If one is found, it is returned.
46507 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
46508 ** returned.
46510 ** 3. If createFlag is 1, and the page is not already in the cache, then
46511 ** return NULL (do not allocate a new page) if any of the following
46512 ** conditions are true:
46514 ** (a) the number of pages pinned by the cache is greater than
46515 ** PCache1.nMax, or
46517 ** (b) the number of pages pinned by the cache is greater than
46518 ** the sum of nMax for all purgeable caches, less the sum of
46519 ** nMin for all other purgeable caches, or
46521 ** 4. If none of the first three conditions apply and the cache is marked
46522 ** as purgeable, and if one of the following is true:
46524 ** (a) The number of pages allocated for the cache is already
46525 ** PCache1.nMax, or
46527 ** (b) The number of pages allocated for all purgeable caches is
46528 ** already equal to or greater than the sum of nMax for all
46529 ** purgeable caches,
46531 ** (c) The system is under memory pressure and wants to avoid
46532 ** unnecessary pages cache entry allocations
46534 ** then attempt to recycle a page from the LRU list. If it is the right
46535 ** size, return the recycled buffer. Otherwise, free the buffer and
46536 ** proceed to step 5.
46538 ** 5. Otherwise, allocate and return a new page buffer.
46540 ** There are two versions of this routine. pcache1FetchWithMutex() is
46541 ** the general case. pcache1FetchNoMutex() is a faster implementation for
46542 ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
46543 ** invokes the appropriate routine.
46545 static PgHdr1 *pcache1FetchNoMutex(
46546 sqlite3_pcache *p,
46547 unsigned int iKey,
46548 int createFlag
46550 PCache1 *pCache = (PCache1 *)p;
46551 PgHdr1 *pPage = 0;
46553 /* Step 1: Search the hash table for an existing entry. */
46554 pPage = pCache->apHash[iKey % pCache->nHash];
46555 while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
46557 /* Step 2: If the page was found in the hash table, then return it.
46558 ** If the page was not in the hash table and createFlag is 0, abort.
46559 ** Otherwise (page not in hash and createFlag!=0) continue with
46560 ** subsequent steps to try to create the page. */
46561 if( pPage ){
46562 if( PAGE_IS_UNPINNED(pPage) ){
46563 return pcache1PinPage(pPage);
46564 }else{
46565 return pPage;
46567 }else if( createFlag ){
46568 /* Steps 3, 4, and 5 implemented by this subroutine */
46569 return pcache1FetchStage2(pCache, iKey, createFlag);
46570 }else{
46571 return 0;
46574 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
46575 static PgHdr1 *pcache1FetchWithMutex(
46576 sqlite3_pcache *p,
46577 unsigned int iKey,
46578 int createFlag
46580 PCache1 *pCache = (PCache1 *)p;
46581 PgHdr1 *pPage;
46583 pcache1EnterMutex(pCache->pGroup);
46584 pPage = pcache1FetchNoMutex(p, iKey, createFlag);
46585 assert( pPage==0 || pCache->iMaxKey>=iKey );
46586 pcache1LeaveMutex(pCache->pGroup);
46587 return pPage;
46589 #endif
46590 static sqlite3_pcache_page *pcache1Fetch(
46591 sqlite3_pcache *p,
46592 unsigned int iKey,
46593 int createFlag
46595 #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
46596 PCache1 *pCache = (PCache1 *)p;
46597 #endif
46599 assert( offsetof(PgHdr1,page)==0 );
46600 assert( pCache->bPurgeable || createFlag!=1 );
46601 assert( pCache->bPurgeable || pCache->nMin==0 );
46602 assert( pCache->bPurgeable==0 || pCache->nMin==10 );
46603 assert( pCache->nMin==0 || pCache->bPurgeable );
46604 assert( pCache->nHash>0 );
46605 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
46606 if( pCache->pGroup->mutex ){
46607 return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
46608 }else
46609 #endif
46611 return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
46617 ** Implementation of the sqlite3_pcache.xUnpin method.
46619 ** Mark a page as unpinned (eligible for asynchronous recycling).
46621 static void pcache1Unpin(
46622 sqlite3_pcache *p,
46623 sqlite3_pcache_page *pPg,
46624 int reuseUnlikely
46626 PCache1 *pCache = (PCache1 *)p;
46627 PgHdr1 *pPage = (PgHdr1 *)pPg;
46628 PGroup *pGroup = pCache->pGroup;
46630 assert( pPage->pCache==pCache );
46631 pcache1EnterMutex(pGroup);
46633 /* It is an error to call this function if the page is already
46634 ** part of the PGroup LRU list.
46636 assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
46637 assert( PAGE_IS_PINNED(pPage) );
46639 if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
46640 pcache1RemoveFromHash(pPage, 1);
46641 }else{
46642 /* Add the page to the PGroup LRU list. */
46643 PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
46644 pPage->pLruPrev = &pGroup->lru;
46645 (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
46646 *ppFirst = pPage;
46647 pCache->nRecyclable++;
46650 pcache1LeaveMutex(pCache->pGroup);
46654 ** Implementation of the sqlite3_pcache.xRekey method.
46656 static void pcache1Rekey(
46657 sqlite3_pcache *p,
46658 sqlite3_pcache_page *pPg,
46659 unsigned int iOld,
46660 unsigned int iNew
46662 PCache1 *pCache = (PCache1 *)p;
46663 PgHdr1 *pPage = (PgHdr1 *)pPg;
46664 PgHdr1 **pp;
46665 unsigned int h;
46666 assert( pPage->iKey==iOld );
46667 assert( pPage->pCache==pCache );
46669 pcache1EnterMutex(pCache->pGroup);
46671 h = iOld%pCache->nHash;
46672 pp = &pCache->apHash[h];
46673 while( (*pp)!=pPage ){
46674 pp = &(*pp)->pNext;
46676 *pp = pPage->pNext;
46678 h = iNew%pCache->nHash;
46679 pPage->iKey = iNew;
46680 pPage->pNext = pCache->apHash[h];
46681 pCache->apHash[h] = pPage;
46682 if( iNew>pCache->iMaxKey ){
46683 pCache->iMaxKey = iNew;
46686 pcache1LeaveMutex(pCache->pGroup);
46690 ** Implementation of the sqlite3_pcache.xTruncate method.
46692 ** Discard all unpinned pages in the cache with a page number equal to
46693 ** or greater than parameter iLimit. Any pinned pages with a page number
46694 ** equal to or greater than iLimit are implicitly unpinned.
46696 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
46697 PCache1 *pCache = (PCache1 *)p;
46698 pcache1EnterMutex(pCache->pGroup);
46699 if( iLimit<=pCache->iMaxKey ){
46700 pcache1TruncateUnsafe(pCache, iLimit);
46701 pCache->iMaxKey = iLimit-1;
46703 pcache1LeaveMutex(pCache->pGroup);
46707 ** Implementation of the sqlite3_pcache.xDestroy method.
46709 ** Destroy a cache allocated using pcache1Create().
46711 static void pcache1Destroy(sqlite3_pcache *p){
46712 PCache1 *pCache = (PCache1 *)p;
46713 PGroup *pGroup = pCache->pGroup;
46714 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
46715 pcache1EnterMutex(pGroup);
46716 if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
46717 assert( pGroup->nMaxPage >= pCache->nMax );
46718 pGroup->nMaxPage -= pCache->nMax;
46719 assert( pGroup->nMinPage >= pCache->nMin );
46720 pGroup->nMinPage -= pCache->nMin;
46721 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
46722 pcache1EnforceMaxPage(pCache);
46723 pcache1LeaveMutex(pGroup);
46724 sqlite3_free(pCache->pBulk);
46725 sqlite3_free(pCache->apHash);
46726 sqlite3_free(pCache);
46730 ** This function is called during initialization (sqlite3_initialize()) to
46731 ** install the default pluggable cache module, assuming the user has not
46732 ** already provided an alternative.
46734 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
46735 static const sqlite3_pcache_methods2 defaultMethods = {
46736 1, /* iVersion */
46737 0, /* pArg */
46738 pcache1Init, /* xInit */
46739 pcache1Shutdown, /* xShutdown */
46740 pcache1Create, /* xCreate */
46741 pcache1Cachesize, /* xCachesize */
46742 pcache1Pagecount, /* xPagecount */
46743 pcache1Fetch, /* xFetch */
46744 pcache1Unpin, /* xUnpin */
46745 pcache1Rekey, /* xRekey */
46746 pcache1Truncate, /* xTruncate */
46747 pcache1Destroy, /* xDestroy */
46748 pcache1Shrink /* xShrink */
46750 sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
46754 ** Return the size of the header on each page of this PCACHE implementation.
46756 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
46759 ** Return the global mutex used by this PCACHE implementation. The
46760 ** sqlite3_status() routine needs access to this mutex.
46762 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
46763 return pcache1.mutex;
46766 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
46768 ** This function is called to free superfluous dynamically allocated memory
46769 ** held by the pager system. Memory in use by any SQLite pager allocated
46770 ** by the current thread may be sqlite3_free()ed.
46772 ** nReq is the number of bytes of memory required. Once this much has
46773 ** been released, the function returns. The return value is the total number
46774 ** of bytes of memory released.
46776 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
46777 int nFree = 0;
46778 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
46779 assert( sqlite3_mutex_notheld(pcache1.mutex) );
46780 if( sqlite3GlobalConfig.pPage==0 ){
46781 PgHdr1 *p;
46782 pcache1EnterMutex(&pcache1.grp);
46783 while( (nReq<0 || nFree<nReq)
46784 && (p=pcache1.grp.lru.pLruPrev)!=0
46785 && p->isAnchor==0
46787 nFree += pcache1MemSize(p->page.pBuf);
46788 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
46789 nFree += sqlite3MemSize(p);
46790 #endif
46791 assert( PAGE_IS_UNPINNED(p) );
46792 pcache1PinPage(p);
46793 pcache1RemoveFromHash(p, 1);
46795 pcache1LeaveMutex(&pcache1.grp);
46797 return nFree;
46799 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
46801 #ifdef SQLITE_TEST
46803 ** This function is used by test procedures to inspect the internal state
46804 ** of the global cache.
46806 SQLITE_PRIVATE void sqlite3PcacheStats(
46807 int *pnCurrent, /* OUT: Total number of pages cached */
46808 int *pnMax, /* OUT: Global maximum cache size */
46809 int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
46810 int *pnRecyclable /* OUT: Total number of pages available for recycling */
46812 PgHdr1 *p;
46813 int nRecyclable = 0;
46814 for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
46815 assert( PAGE_IS_UNPINNED(p) );
46816 nRecyclable++;
46818 *pnCurrent = pcache1.grp.nPurgeable;
46819 *pnMax = (int)pcache1.grp.nMaxPage;
46820 *pnMin = (int)pcache1.grp.nMinPage;
46821 *pnRecyclable = nRecyclable;
46823 #endif
46825 /************** End of pcache1.c *********************************************/
46826 /************** Begin file rowset.c ******************************************/
46828 ** 2008 December 3
46830 ** The author disclaims copyright to this source code. In place of
46831 ** a legal notice, here is a blessing:
46833 ** May you do good and not evil.
46834 ** May you find forgiveness for yourself and forgive others.
46835 ** May you share freely, never taking more than you give.
46837 *************************************************************************
46839 ** This module implements an object we call a "RowSet".
46841 ** The RowSet object is a collection of rowids. Rowids
46842 ** are inserted into the RowSet in an arbitrary order. Inserts
46843 ** can be intermixed with tests to see if a given rowid has been
46844 ** previously inserted into the RowSet.
46846 ** After all inserts are finished, it is possible to extract the
46847 ** elements of the RowSet in sorted order. Once this extraction
46848 ** process has started, no new elements may be inserted.
46850 ** Hence, the primitive operations for a RowSet are:
46852 ** CREATE
46853 ** INSERT
46854 ** TEST
46855 ** SMALLEST
46856 ** DESTROY
46858 ** The CREATE and DESTROY primitives are the constructor and destructor,
46859 ** obviously. The INSERT primitive adds a new element to the RowSet.
46860 ** TEST checks to see if an element is already in the RowSet. SMALLEST
46861 ** extracts the least value from the RowSet.
46863 ** The INSERT primitive might allocate additional memory. Memory is
46864 ** allocated in chunks so most INSERTs do no allocation. There is an
46865 ** upper bound on the size of allocated memory. No memory is freed
46866 ** until DESTROY.
46868 ** The TEST primitive includes a "batch" number. The TEST primitive
46869 ** will only see elements that were inserted before the last change
46870 ** in the batch number. In other words, if an INSERT occurs between
46871 ** two TESTs where the TESTs have the same batch nubmer, then the
46872 ** value added by the INSERT will not be visible to the second TEST.
46873 ** The initial batch number is zero, so if the very first TEST contains
46874 ** a non-zero batch number, it will see all prior INSERTs.
46876 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
46877 ** that is attempted.
46879 ** The cost of an INSERT is roughly constant. (Sometimes new memory
46880 ** has to be allocated on an INSERT.) The cost of a TEST with a new
46881 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
46882 ** The cost of a TEST using the same batch number is O(logN). The cost
46883 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
46884 ** primitives are constant time. The cost of DESTROY is O(N).
46886 ** TEST and SMALLEST may not be used by the same RowSet. This used to
46887 ** be possible, but the feature was not used, so it was removed in order
46888 ** to simplify the code.
46890 /* #include "sqliteInt.h" */
46894 ** Target size for allocation chunks.
46896 #define ROWSET_ALLOCATION_SIZE 1024
46899 ** The number of rowset entries per allocation chunk.
46901 #define ROWSET_ENTRY_PER_CHUNK \
46902 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
46905 ** Each entry in a RowSet is an instance of the following object.
46907 ** This same object is reused to store a linked list of trees of RowSetEntry
46908 ** objects. In that alternative use, pRight points to the next entry
46909 ** in the list, pLeft points to the tree, and v is unused. The
46910 ** RowSet.pForest value points to the head of this forest list.
46912 struct RowSetEntry {
46913 i64 v; /* ROWID value for this entry */
46914 struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
46915 struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
46919 ** RowSetEntry objects are allocated in large chunks (instances of the
46920 ** following structure) to reduce memory allocation overhead. The
46921 ** chunks are kept on a linked list so that they can be deallocated
46922 ** when the RowSet is destroyed.
46924 struct RowSetChunk {
46925 struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
46926 struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
46930 ** A RowSet in an instance of the following structure.
46932 ** A typedef of this structure if found in sqliteInt.h.
46934 struct RowSet {
46935 struct RowSetChunk *pChunk; /* List of all chunk allocations */
46936 sqlite3 *db; /* The database connection */
46937 struct RowSetEntry *pEntry; /* List of entries using pRight */
46938 struct RowSetEntry *pLast; /* Last entry on the pEntry list */
46939 struct RowSetEntry *pFresh; /* Source of new entry objects */
46940 struct RowSetEntry *pForest; /* List of binary trees of entries */
46941 u16 nFresh; /* Number of objects on pFresh */
46942 u16 rsFlags; /* Various flags */
46943 int iBatch; /* Current insert batch */
46947 ** Allowed values for RowSet.rsFlags
46949 #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
46950 #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
46953 ** Turn bulk memory into a RowSet object. N bytes of memory
46954 ** are available at pSpace. The db pointer is used as a memory context
46955 ** for any subsequent allocations that need to occur.
46956 ** Return a pointer to the new RowSet object.
46958 ** It must be the case that N is sufficient to make a Rowset. If not
46959 ** an assertion fault occurs.
46961 ** If N is larger than the minimum, use the surplus as an initial
46962 ** allocation of entries available to be filled.
46964 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
46965 RowSet *p;
46966 assert( N >= ROUND8(sizeof(*p)) );
46967 p = pSpace;
46968 p->pChunk = 0;
46969 p->db = db;
46970 p->pEntry = 0;
46971 p->pLast = 0;
46972 p->pForest = 0;
46973 p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
46974 p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
46975 p->rsFlags = ROWSET_SORTED;
46976 p->iBatch = 0;
46977 return p;
46981 ** Deallocate all chunks from a RowSet. This frees all memory that
46982 ** the RowSet has allocated over its lifetime. This routine is
46983 ** the destructor for the RowSet.
46985 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
46986 struct RowSetChunk *pChunk, *pNextChunk;
46987 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
46988 pNextChunk = pChunk->pNextChunk;
46989 sqlite3DbFree(p->db, pChunk);
46991 p->pChunk = 0;
46992 p->nFresh = 0;
46993 p->pEntry = 0;
46994 p->pLast = 0;
46995 p->pForest = 0;
46996 p->rsFlags = ROWSET_SORTED;
47000 ** Allocate a new RowSetEntry object that is associated with the
47001 ** given RowSet. Return a pointer to the new and completely uninitialized
47002 ** objected.
47004 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
47005 ** routine returns NULL.
47007 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
47008 assert( p!=0 );
47009 if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
47010 /* We could allocate a fresh RowSetEntry each time one is needed, but it
47011 ** is more efficient to pull a preallocated entry from the pool */
47012 struct RowSetChunk *pNew;
47013 pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
47014 if( pNew==0 ){
47015 return 0;
47017 pNew->pNextChunk = p->pChunk;
47018 p->pChunk = pNew;
47019 p->pFresh = pNew->aEntry;
47020 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
47022 p->nFresh--;
47023 return p->pFresh++;
47027 ** Insert a new value into a RowSet.
47029 ** The mallocFailed flag of the database connection is set if a
47030 ** memory allocation fails.
47032 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
47033 struct RowSetEntry *pEntry; /* The new entry */
47034 struct RowSetEntry *pLast; /* The last prior entry */
47036 /* This routine is never called after sqlite3RowSetNext() */
47037 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
47039 pEntry = rowSetEntryAlloc(p);
47040 if( pEntry==0 ) return;
47041 pEntry->v = rowid;
47042 pEntry->pRight = 0;
47043 pLast = p->pLast;
47044 if( pLast ){
47045 if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
47046 /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
47047 ** where possible */
47048 p->rsFlags &= ~ROWSET_SORTED;
47050 pLast->pRight = pEntry;
47051 }else{
47052 p->pEntry = pEntry;
47054 p->pLast = pEntry;
47058 ** Merge two lists of RowSetEntry objects. Remove duplicates.
47060 ** The input lists are connected via pRight pointers and are
47061 ** assumed to each already be in sorted order.
47063 static struct RowSetEntry *rowSetEntryMerge(
47064 struct RowSetEntry *pA, /* First sorted list to be merged */
47065 struct RowSetEntry *pB /* Second sorted list to be merged */
47067 struct RowSetEntry head;
47068 struct RowSetEntry *pTail;
47070 pTail = &head;
47071 assert( pA!=0 && pB!=0 );
47072 for(;;){
47073 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
47074 assert( pB->pRight==0 || pB->v<=pB->pRight->v );
47075 if( pA->v<=pB->v ){
47076 if( pA->v<pB->v ) pTail = pTail->pRight = pA;
47077 pA = pA->pRight;
47078 if( pA==0 ){
47079 pTail->pRight = pB;
47080 break;
47082 }else{
47083 pTail = pTail->pRight = pB;
47084 pB = pB->pRight;
47085 if( pB==0 ){
47086 pTail->pRight = pA;
47087 break;
47091 return head.pRight;
47095 ** Sort all elements on the list of RowSetEntry objects into order of
47096 ** increasing v.
47098 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
47099 unsigned int i;
47100 struct RowSetEntry *pNext, *aBucket[40];
47102 memset(aBucket, 0, sizeof(aBucket));
47103 while( pIn ){
47104 pNext = pIn->pRight;
47105 pIn->pRight = 0;
47106 for(i=0; aBucket[i]; i++){
47107 pIn = rowSetEntryMerge(aBucket[i], pIn);
47108 aBucket[i] = 0;
47110 aBucket[i] = pIn;
47111 pIn = pNext;
47113 pIn = aBucket[0];
47114 for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
47115 if( aBucket[i]==0 ) continue;
47116 pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
47118 return pIn;
47123 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
47124 ** Convert this tree into a linked list connected by the pRight pointers
47125 ** and return pointers to the first and last elements of the new list.
47127 static void rowSetTreeToList(
47128 struct RowSetEntry *pIn, /* Root of the input tree */
47129 struct RowSetEntry **ppFirst, /* Write head of the output list here */
47130 struct RowSetEntry **ppLast /* Write tail of the output list here */
47132 assert( pIn!=0 );
47133 if( pIn->pLeft ){
47134 struct RowSetEntry *p;
47135 rowSetTreeToList(pIn->pLeft, ppFirst, &p);
47136 p->pRight = pIn;
47137 }else{
47138 *ppFirst = pIn;
47140 if( pIn->pRight ){
47141 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
47142 }else{
47143 *ppLast = pIn;
47145 assert( (*ppLast)->pRight==0 );
47150 ** Convert a sorted list of elements (connected by pRight) into a binary
47151 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
47152 ** node taken from the head of *ppList. A depth of 2 means a tree with
47153 ** three nodes. And so forth.
47155 ** Use as many entries from the input list as required and update the
47156 ** *ppList to point to the unused elements of the list. If the input
47157 ** list contains too few elements, then construct an incomplete tree
47158 ** and leave *ppList set to NULL.
47160 ** Return a pointer to the root of the constructed binary tree.
47162 static struct RowSetEntry *rowSetNDeepTree(
47163 struct RowSetEntry **ppList,
47164 int iDepth
47166 struct RowSetEntry *p; /* Root of the new tree */
47167 struct RowSetEntry *pLeft; /* Left subtree */
47168 if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
47169 /* Prevent unnecessary deep recursion when we run out of entries */
47170 return 0;
47172 if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
47173 /* This branch causes a *balanced* tree to be generated. A valid tree
47174 ** is still generated without this branch, but the tree is wildly
47175 ** unbalanced and inefficient. */
47176 pLeft = rowSetNDeepTree(ppList, iDepth-1);
47177 p = *ppList;
47178 if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
47179 /* It is safe to always return here, but the resulting tree
47180 ** would be unbalanced */
47181 return pLeft;
47183 p->pLeft = pLeft;
47184 *ppList = p->pRight;
47185 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
47186 }else{
47187 p = *ppList;
47188 *ppList = p->pRight;
47189 p->pLeft = p->pRight = 0;
47191 return p;
47195 ** Convert a sorted list of elements into a binary tree. Make the tree
47196 ** as deep as it needs to be in order to contain the entire list.
47198 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
47199 int iDepth; /* Depth of the tree so far */
47200 struct RowSetEntry *p; /* Current tree root */
47201 struct RowSetEntry *pLeft; /* Left subtree */
47203 assert( pList!=0 );
47204 p = pList;
47205 pList = p->pRight;
47206 p->pLeft = p->pRight = 0;
47207 for(iDepth=1; pList; iDepth++){
47208 pLeft = p;
47209 p = pList;
47210 pList = p->pRight;
47211 p->pLeft = pLeft;
47212 p->pRight = rowSetNDeepTree(&pList, iDepth);
47214 return p;
47218 ** Extract the smallest element from the RowSet.
47219 ** Write the element into *pRowid. Return 1 on success. Return
47220 ** 0 if the RowSet is already empty.
47222 ** After this routine has been called, the sqlite3RowSetInsert()
47223 ** routine may not be called again.
47225 ** This routine may not be called after sqlite3RowSetTest() has
47226 ** been used. Older versions of RowSet allowed that, but as the
47227 ** capability was not used by the code generator, it was removed
47228 ** for code economy.
47230 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
47231 assert( p!=0 );
47232 assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
47234 /* Merge the forest into a single sorted list on first call */
47235 if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
47236 if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
47237 p->pEntry = rowSetEntrySort(p->pEntry);
47239 p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
47242 /* Return the next entry on the list */
47243 if( p->pEntry ){
47244 *pRowid = p->pEntry->v;
47245 p->pEntry = p->pEntry->pRight;
47246 if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
47247 /* Free memory immediately, rather than waiting on sqlite3_finalize() */
47248 sqlite3RowSetClear(p);
47250 return 1;
47251 }else{
47252 return 0;
47257 ** Check to see if element iRowid was inserted into the rowset as
47258 ** part of any insert batch prior to iBatch. Return 1 or 0.
47260 ** If this is the first test of a new batch and if there exist entries
47261 ** on pRowSet->pEntry, then sort those entries into the forest at
47262 ** pRowSet->pForest so that they can be tested.
47264 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
47265 struct RowSetEntry *p, *pTree;
47267 /* This routine is never called after sqlite3RowSetNext() */
47268 assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
47270 /* Sort entries into the forest on the first test of a new batch.
47271 ** To save unnecessary work, only do this when the batch number changes.
47273 if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
47274 p = pRowSet->pEntry;
47275 if( p ){
47276 struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
47277 if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
47278 /* Only sort the current set of entiries if they need it */
47279 p = rowSetEntrySort(p);
47281 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
47282 ppPrevTree = &pTree->pRight;
47283 if( pTree->pLeft==0 ){
47284 pTree->pLeft = rowSetListToTree(p);
47285 break;
47286 }else{
47287 struct RowSetEntry *pAux, *pTail;
47288 rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
47289 pTree->pLeft = 0;
47290 p = rowSetEntryMerge(pAux, p);
47293 if( pTree==0 ){
47294 *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
47295 if( pTree ){
47296 pTree->v = 0;
47297 pTree->pRight = 0;
47298 pTree->pLeft = rowSetListToTree(p);
47301 pRowSet->pEntry = 0;
47302 pRowSet->pLast = 0;
47303 pRowSet->rsFlags |= ROWSET_SORTED;
47305 pRowSet->iBatch = iBatch;
47308 /* Test to see if the iRowid value appears anywhere in the forest.
47309 ** Return 1 if it does and 0 if not.
47311 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
47312 p = pTree->pLeft;
47313 while( p ){
47314 if( p->v<iRowid ){
47315 p = p->pRight;
47316 }else if( p->v>iRowid ){
47317 p = p->pLeft;
47318 }else{
47319 return 1;
47323 return 0;
47326 /************** End of rowset.c **********************************************/
47327 /************** Begin file pager.c *******************************************/
47329 ** 2001 September 15
47331 ** The author disclaims copyright to this source code. In place of
47332 ** a legal notice, here is a blessing:
47334 ** May you do good and not evil.
47335 ** May you find forgiveness for yourself and forgive others.
47336 ** May you share freely, never taking more than you give.
47338 *************************************************************************
47339 ** This is the implementation of the page cache subsystem or "pager".
47341 ** The pager is used to access a database disk file. It implements
47342 ** atomic commit and rollback through the use of a journal file that
47343 ** is separate from the database file. The pager also implements file
47344 ** locking to prevent two processes from writing the same database
47345 ** file simultaneously, or one process from reading the database while
47346 ** another is writing.
47348 #ifndef SQLITE_OMIT_DISKIO
47349 /* #include "sqliteInt.h" */
47350 /************** Include wal.h in the middle of pager.c ***********************/
47351 /************** Begin file wal.h *********************************************/
47353 ** 2010 February 1
47355 ** The author disclaims copyright to this source code. In place of
47356 ** a legal notice, here is a blessing:
47358 ** May you do good and not evil.
47359 ** May you find forgiveness for yourself and forgive others.
47360 ** May you share freely, never taking more than you give.
47362 *************************************************************************
47363 ** This header file defines the interface to the write-ahead logging
47364 ** system. Refer to the comments below and the header comment attached to
47365 ** the implementation of each function in log.c for further details.
47368 #ifndef SQLITE_WAL_H
47369 #define SQLITE_WAL_H
47371 /* #include "sqliteInt.h" */
47373 /* Macros for extracting appropriate sync flags for either transaction
47374 ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
47376 #define WAL_SYNC_FLAGS(X) ((X)&0x03)
47377 #define CKPT_SYNC_FLAGS(X) (((X)>>2)&0x03)
47379 #ifdef SQLITE_OMIT_WAL
47380 # define sqlite3WalOpen(x,y,z) 0
47381 # define sqlite3WalLimit(x,y)
47382 # define sqlite3WalClose(v,w,x,y,z) 0
47383 # define sqlite3WalBeginReadTransaction(y,z) 0
47384 # define sqlite3WalEndReadTransaction(z)
47385 # define sqlite3WalDbsize(y) 0
47386 # define sqlite3WalBeginWriteTransaction(y) 0
47387 # define sqlite3WalEndWriteTransaction(x) 0
47388 # define sqlite3WalUndo(x,y,z) 0
47389 # define sqlite3WalSavepoint(y,z)
47390 # define sqlite3WalSavepointUndo(y,z) 0
47391 # define sqlite3WalFrames(u,v,w,x,y,z) 0
47392 # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
47393 # define sqlite3WalCallback(z) 0
47394 # define sqlite3WalExclusiveMode(y,z) 0
47395 # define sqlite3WalHeapMemory(z) 0
47396 # define sqlite3WalFramesize(z) 0
47397 # define sqlite3WalFindFrame(x,y,z) 0
47398 # define sqlite3WalFile(x) 0
47399 #else
47401 #define WAL_SAVEPOINT_NDATA 4
47403 /* Connection to a write-ahead log (WAL) file.
47404 ** There is one object of this type for each pager.
47406 typedef struct Wal Wal;
47408 /* Open and close a connection to a write-ahead log. */
47409 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
47410 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
47412 /* Set the limiting size of a WAL file. */
47413 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
47415 /* Used by readers to open (lock) and close (unlock) a snapshot. A
47416 ** snapshot is like a read-transaction. It is the state of the database
47417 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
47418 ** preserves the current state even if the other threads or processes
47419 ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
47420 ** transaction and releases the lock.
47422 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
47423 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
47425 /* Read a page from the write-ahead log, if it is present. */
47426 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
47427 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
47429 /* If the WAL is not empty, return the size of the database. */
47430 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
47432 /* Obtain or release the WRITER lock. */
47433 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
47434 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
47436 /* Undo any frames written (but not committed) to the log */
47437 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
47439 /* Return an integer that records the current (uncommitted) write
47440 ** position in the WAL */
47441 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
47443 /* Move the write position of the WAL back to iFrame. Called in
47444 ** response to a ROLLBACK TO command. */
47445 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
47447 /* Write a frame or frames to the log. */
47448 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
47450 /* Copy pages from the log to the database file */
47451 SQLITE_PRIVATE int sqlite3WalCheckpoint(
47452 Wal *pWal, /* Write-ahead log connection */
47453 sqlite3 *db, /* Check this handle's interrupt flag */
47454 int eMode, /* One of PASSIVE, FULL and RESTART */
47455 int (*xBusy)(void*), /* Function to call when busy */
47456 void *pBusyArg, /* Context argument for xBusyHandler */
47457 int sync_flags, /* Flags to sync db file with (or 0) */
47458 int nBuf, /* Size of buffer nBuf */
47459 u8 *zBuf, /* Temporary buffer to use */
47460 int *pnLog, /* OUT: Number of frames in WAL */
47461 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
47464 /* Return the value to pass to a sqlite3_wal_hook callback, the
47465 ** number of frames in the WAL at the point of the last commit since
47466 ** sqlite3WalCallback() was called. If no commits have occurred since
47467 ** the last call, then return 0.
47469 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
47471 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
47472 ** by the pager layer on the database file.
47474 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
47476 /* Return true if the argument is non-NULL and the WAL module is using
47477 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
47478 ** WAL module is using shared-memory, return false.
47480 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
47482 #ifdef SQLITE_ENABLE_SNAPSHOT
47483 SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
47484 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
47485 SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
47486 #endif
47488 #ifdef SQLITE_ENABLE_ZIPVFS
47489 /* If the WAL file is not empty, return the number of bytes of content
47490 ** stored in each frame (i.e. the db page-size when the WAL was created).
47492 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
47493 #endif
47495 /* Return the sqlite3_file object for the WAL file */
47496 SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
47498 #endif /* ifndef SQLITE_OMIT_WAL */
47499 #endif /* SQLITE_WAL_H */
47501 /************** End of wal.h *************************************************/
47502 /************** Continuing where we left off in pager.c **********************/
47505 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
47507 ** This comment block describes invariants that hold when using a rollback
47508 ** journal. These invariants do not apply for journal_mode=WAL,
47509 ** journal_mode=MEMORY, or journal_mode=OFF.
47511 ** Within this comment block, a page is deemed to have been synced
47512 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
47513 ** Otherwise, the page is not synced until the xSync method of the VFS
47514 ** is called successfully on the file containing the page.
47516 ** Definition: A page of the database file is said to be "overwriteable" if
47517 ** one or more of the following are true about the page:
47519 ** (a) The original content of the page as it was at the beginning of
47520 ** the transaction has been written into the rollback journal and
47521 ** synced.
47523 ** (b) The page was a freelist leaf page at the start of the transaction.
47525 ** (c) The page number is greater than the largest page that existed in
47526 ** the database file at the start of the transaction.
47528 ** (1) A page of the database file is never overwritten unless one of the
47529 ** following are true:
47531 ** (a) The page and all other pages on the same sector are overwriteable.
47533 ** (b) The atomic page write optimization is enabled, and the entire
47534 ** transaction other than the update of the transaction sequence
47535 ** number consists of a single page change.
47537 ** (2) The content of a page written into the rollback journal exactly matches
47538 ** both the content in the database when the rollback journal was written
47539 ** and the content in the database at the beginning of the current
47540 ** transaction.
47542 ** (3) Writes to the database file are an integer multiple of the page size
47543 ** in length and are aligned on a page boundary.
47545 ** (4) Reads from the database file are either aligned on a page boundary and
47546 ** an integer multiple of the page size in length or are taken from the
47547 ** first 100 bytes of the database file.
47549 ** (5) All writes to the database file are synced prior to the rollback journal
47550 ** being deleted, truncated, or zeroed.
47552 ** (6) If a master journal file is used, then all writes to the database file
47553 ** are synced prior to the master journal being deleted.
47555 ** Definition: Two databases (or the same database at two points it time)
47556 ** are said to be "logically equivalent" if they give the same answer to
47557 ** all queries. Note in particular the content of freelist leaf
47558 ** pages can be changed arbitrarily without affecting the logical equivalence
47559 ** of the database.
47561 ** (7) At any time, if any subset, including the empty set and the total set,
47562 ** of the unsynced changes to a rollback journal are removed and the
47563 ** journal is rolled back, the resulting database file will be logically
47564 ** equivalent to the database file at the beginning of the transaction.
47566 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
47567 ** is called to restore the database file to the same size it was at
47568 ** the beginning of the transaction. (In some VFSes, the xTruncate
47569 ** method is a no-op, but that does not change the fact the SQLite will
47570 ** invoke it.)
47572 ** (9) Whenever the database file is modified, at least one bit in the range
47573 ** of bytes from 24 through 39 inclusive will be changed prior to releasing
47574 ** the EXCLUSIVE lock, thus signaling other connections on the same
47575 ** database to flush their caches.
47577 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
47578 ** than one billion transactions.
47580 ** (11) A database file is well-formed at the beginning and at the conclusion
47581 ** of every transaction.
47583 ** (12) An EXCLUSIVE lock is held on the database file when writing to
47584 ** the database file.
47586 ** (13) A SHARED lock is held on the database file while reading any
47587 ** content out of the database file.
47589 ******************************************************************************/
47592 ** Macros for troubleshooting. Normally turned off
47594 #if 0
47595 int sqlite3PagerTrace=1; /* True to enable tracing */
47596 #define sqlite3DebugPrintf printf
47597 #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
47598 #else
47599 #define PAGERTRACE(X)
47600 #endif
47603 ** The following two macros are used within the PAGERTRACE() macros above
47604 ** to print out file-descriptors.
47606 ** PAGERID() takes a pointer to a Pager struct as its argument. The
47607 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
47608 ** struct as its argument.
47610 #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
47611 #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
47614 ** The Pager.eState variable stores the current 'state' of a pager. A
47615 ** pager may be in any one of the seven states shown in the following
47616 ** state diagram.
47618 ** OPEN <------+------+
47619 ** | | |
47620 ** V | |
47621 ** +---------> READER-------+ |
47622 ** | | |
47623 ** | V |
47624 ** |<-------WRITER_LOCKED------> ERROR
47625 ** | | ^
47626 ** | V |
47627 ** |<------WRITER_CACHEMOD-------->|
47628 ** | | |
47629 ** | V |
47630 ** |<-------WRITER_DBMOD---------->|
47631 ** | | |
47632 ** | V |
47633 ** +<------WRITER_FINISHED-------->+
47636 ** List of state transitions and the C [function] that performs each:
47638 ** OPEN -> READER [sqlite3PagerSharedLock]
47639 ** READER -> OPEN [pager_unlock]
47641 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
47642 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
47643 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
47644 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
47645 ** WRITER_*** -> READER [pager_end_transaction]
47647 ** WRITER_*** -> ERROR [pager_error]
47648 ** ERROR -> OPEN [pager_unlock]
47651 ** OPEN:
47653 ** The pager starts up in this state. Nothing is guaranteed in this
47654 ** state - the file may or may not be locked and the database size is
47655 ** unknown. The database may not be read or written.
47657 ** * No read or write transaction is active.
47658 ** * Any lock, or no lock at all, may be held on the database file.
47659 ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
47661 ** READER:
47663 ** In this state all the requirements for reading the database in
47664 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
47665 ** was) in exclusive-locking mode, a user-level read transaction is
47666 ** open. The database size is known in this state.
47668 ** A connection running with locking_mode=normal enters this state when
47669 ** it opens a read-transaction on the database and returns to state
47670 ** OPEN after the read-transaction is completed. However a connection
47671 ** running in locking_mode=exclusive (including temp databases) remains in
47672 ** this state even after the read-transaction is closed. The only way
47673 ** a locking_mode=exclusive connection can transition from READER to OPEN
47674 ** is via the ERROR state (see below).
47676 ** * A read transaction may be active (but a write-transaction cannot).
47677 ** * A SHARED or greater lock is held on the database file.
47678 ** * The dbSize variable may be trusted (even if a user-level read
47679 ** transaction is not active). The dbOrigSize and dbFileSize variables
47680 ** may not be trusted at this point.
47681 ** * If the database is a WAL database, then the WAL connection is open.
47682 ** * Even if a read-transaction is not open, it is guaranteed that
47683 ** there is no hot-journal in the file-system.
47685 ** WRITER_LOCKED:
47687 ** The pager moves to this state from READER when a write-transaction
47688 ** is first opened on the database. In WRITER_LOCKED state, all locks
47689 ** required to start a write-transaction are held, but no actual
47690 ** modifications to the cache or database have taken place.
47692 ** In rollback mode, a RESERVED or (if the transaction was opened with
47693 ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
47694 ** moving to this state, but the journal file is not written to or opened
47695 ** to in this state. If the transaction is committed or rolled back while
47696 ** in WRITER_LOCKED state, all that is required is to unlock the database
47697 ** file.
47699 ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
47700 ** If the connection is running with locking_mode=exclusive, an attempt
47701 ** is made to obtain an EXCLUSIVE lock on the database file.
47703 ** * A write transaction is active.
47704 ** * If the connection is open in rollback-mode, a RESERVED or greater
47705 ** lock is held on the database file.
47706 ** * If the connection is open in WAL-mode, a WAL write transaction
47707 ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
47708 ** called).
47709 ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
47710 ** * The contents of the pager cache have not been modified.
47711 ** * The journal file may or may not be open.
47712 ** * Nothing (not even the first header) has been written to the journal.
47714 ** WRITER_CACHEMOD:
47716 ** A pager moves from WRITER_LOCKED state to this state when a page is
47717 ** first modified by the upper layer. In rollback mode the journal file
47718 ** is opened (if it is not already open) and a header written to the
47719 ** start of it. The database file on disk has not been modified.
47721 ** * A write transaction is active.
47722 ** * A RESERVED or greater lock is held on the database file.
47723 ** * The journal file is open and the first header has been written
47724 ** to it, but the header has not been synced to disk.
47725 ** * The contents of the page cache have been modified.
47727 ** WRITER_DBMOD:
47729 ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
47730 ** when it modifies the contents of the database file. WAL connections
47731 ** never enter this state (since they do not modify the database file,
47732 ** just the log file).
47734 ** * A write transaction is active.
47735 ** * An EXCLUSIVE or greater lock is held on the database file.
47736 ** * The journal file is open and the first header has been written
47737 ** and synced to disk.
47738 ** * The contents of the page cache have been modified (and possibly
47739 ** written to disk).
47741 ** WRITER_FINISHED:
47743 ** It is not possible for a WAL connection to enter this state.
47745 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
47746 ** state after the entire transaction has been successfully written into the
47747 ** database file. In this state the transaction may be committed simply
47748 ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
47749 ** not possible to modify the database further. At this point, the upper
47750 ** layer must either commit or rollback the transaction.
47752 ** * A write transaction is active.
47753 ** * An EXCLUSIVE or greater lock is held on the database file.
47754 ** * All writing and syncing of journal and database data has finished.
47755 ** If no error occurred, all that remains is to finalize the journal to
47756 ** commit the transaction. If an error did occur, the caller will need
47757 ** to rollback the transaction.
47759 ** ERROR:
47761 ** The ERROR state is entered when an IO or disk-full error (including
47762 ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
47763 ** difficult to be sure that the in-memory pager state (cache contents,
47764 ** db size etc.) are consistent with the contents of the file-system.
47766 ** Temporary pager files may enter the ERROR state, but in-memory pagers
47767 ** cannot.
47769 ** For example, if an IO error occurs while performing a rollback,
47770 ** the contents of the page-cache may be left in an inconsistent state.
47771 ** At this point it would be dangerous to change back to READER state
47772 ** (as usually happens after a rollback). Any subsequent readers might
47773 ** report database corruption (due to the inconsistent cache), and if
47774 ** they upgrade to writers, they may inadvertently corrupt the database
47775 ** file. To avoid this hazard, the pager switches into the ERROR state
47776 ** instead of READER following such an error.
47778 ** Once it has entered the ERROR state, any attempt to use the pager
47779 ** to read or write data returns an error. Eventually, once all
47780 ** outstanding transactions have been abandoned, the pager is able to
47781 ** transition back to OPEN state, discarding the contents of the
47782 ** page-cache and any other in-memory state at the same time. Everything
47783 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
47784 ** when a read-transaction is next opened on the pager (transitioning
47785 ** the pager into READER state). At that point the system has recovered
47786 ** from the error.
47788 ** Specifically, the pager jumps into the ERROR state if:
47790 ** 1. An error occurs while attempting a rollback. This happens in
47791 ** function sqlite3PagerRollback().
47793 ** 2. An error occurs while attempting to finalize a journal file
47794 ** following a commit in function sqlite3PagerCommitPhaseTwo().
47796 ** 3. An error occurs while attempting to write to the journal or
47797 ** database file in function pagerStress() in order to free up
47798 ** memory.
47800 ** In other cases, the error is returned to the b-tree layer. The b-tree
47801 ** layer then attempts a rollback operation. If the error condition
47802 ** persists, the pager enters the ERROR state via condition (1) above.
47804 ** Condition (3) is necessary because it can be triggered by a read-only
47805 ** statement executed within a transaction. In this case, if the error
47806 ** code were simply returned to the user, the b-tree layer would not
47807 ** automatically attempt a rollback, as it assumes that an error in a
47808 ** read-only statement cannot leave the pager in an internally inconsistent
47809 ** state.
47811 ** * The Pager.errCode variable is set to something other than SQLITE_OK.
47812 ** * There are one or more outstanding references to pages (after the
47813 ** last reference is dropped the pager should move back to OPEN state).
47814 ** * The pager is not an in-memory pager.
47817 ** Notes:
47819 ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
47820 ** connection is open in WAL mode. A WAL connection is always in one
47821 ** of the first four states.
47823 ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
47824 ** state. There are two exceptions: immediately after exclusive-mode has
47825 ** been turned on (and before any read or write transactions are
47826 ** executed), and when the pager is leaving the "error state".
47828 ** * See also: assert_pager_state().
47830 #define PAGER_OPEN 0
47831 #define PAGER_READER 1
47832 #define PAGER_WRITER_LOCKED 2
47833 #define PAGER_WRITER_CACHEMOD 3
47834 #define PAGER_WRITER_DBMOD 4
47835 #define PAGER_WRITER_FINISHED 5
47836 #define PAGER_ERROR 6
47839 ** The Pager.eLock variable is almost always set to one of the
47840 ** following locking-states, according to the lock currently held on
47841 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
47842 ** This variable is kept up to date as locks are taken and released by
47843 ** the pagerLockDb() and pagerUnlockDb() wrappers.
47845 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
47846 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
47847 ** the operation was successful. In these circumstances pagerLockDb() and
47848 ** pagerUnlockDb() take a conservative approach - eLock is always updated
47849 ** when unlocking the file, and only updated when locking the file if the
47850 ** VFS call is successful. This way, the Pager.eLock variable may be set
47851 ** to a less exclusive (lower) value than the lock that is actually held
47852 ** at the system level, but it is never set to a more exclusive value.
47854 ** This is usually safe. If an xUnlock fails or appears to fail, there may
47855 ** be a few redundant xLock() calls or a lock may be held for longer than
47856 ** required, but nothing really goes wrong.
47858 ** The exception is when the database file is unlocked as the pager moves
47859 ** from ERROR to OPEN state. At this point there may be a hot-journal file
47860 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
47861 ** transition, by the same pager or any other). If the call to xUnlock()
47862 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
47863 ** can confuse the call to xCheckReservedLock() call made later as part
47864 ** of hot-journal detection.
47866 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
47867 ** lock held by this process or any others". So xCheckReservedLock may
47868 ** return true because the caller itself is holding an EXCLUSIVE lock (but
47869 ** doesn't know it because of a previous error in xUnlock). If this happens
47870 ** a hot-journal may be mistaken for a journal being created by an active
47871 ** transaction in another process, causing SQLite to read from the database
47872 ** without rolling it back.
47874 ** To work around this, if a call to xUnlock() fails when unlocking the
47875 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
47876 ** is only changed back to a real locking state after a successful call
47877 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
47878 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
47879 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
47880 ** lock on the database file before attempting to roll it back. See function
47881 ** PagerSharedLock() for more detail.
47883 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
47884 ** PAGER_OPEN state.
47886 #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
47889 ** A macro used for invoking the codec if there is one
47891 #ifdef SQLITE_HAS_CODEC
47892 # define CODEC1(P,D,N,X,E) \
47893 if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
47894 # define CODEC2(P,D,N,X,E,O) \
47895 if( P->xCodec==0 ){ O=(char*)D; }else \
47896 if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
47897 #else
47898 # define CODEC1(P,D,N,X,E) /* NO-OP */
47899 # define CODEC2(P,D,N,X,E,O) O=(char*)D
47900 #endif
47903 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
47904 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
47905 ** This could conceivably cause corruption following a power failure on
47906 ** such a system. This is currently an undocumented limit.
47908 #define MAX_SECTOR_SIZE 0x10000
47912 ** An instance of the following structure is allocated for each active
47913 ** savepoint and statement transaction in the system. All such structures
47914 ** are stored in the Pager.aSavepoint[] array, which is allocated and
47915 ** resized using sqlite3Realloc().
47917 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
47918 ** set to 0. If a journal-header is written into the main journal while
47919 ** the savepoint is active, then iHdrOffset is set to the byte offset
47920 ** immediately following the last journal record written into the main
47921 ** journal before the journal-header. This is required during savepoint
47922 ** rollback (see pagerPlaybackSavepoint()).
47924 typedef struct PagerSavepoint PagerSavepoint;
47925 struct PagerSavepoint {
47926 i64 iOffset; /* Starting offset in main journal */
47927 i64 iHdrOffset; /* See above */
47928 Bitvec *pInSavepoint; /* Set of pages in this savepoint */
47929 Pgno nOrig; /* Original number of pages in file */
47930 Pgno iSubRec; /* Index of first record in sub-journal */
47931 #ifndef SQLITE_OMIT_WAL
47932 u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
47933 #endif
47937 ** Bits of the Pager.doNotSpill flag. See further description below.
47939 #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
47940 #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
47941 #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
47944 ** An open page cache is an instance of struct Pager. A description of
47945 ** some of the more important member variables follows:
47947 ** eState
47949 ** The current 'state' of the pager object. See the comment and state
47950 ** diagram above for a description of the pager state.
47952 ** eLock
47954 ** For a real on-disk database, the current lock held on the database file -
47955 ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
47957 ** For a temporary or in-memory database (neither of which require any
47958 ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
47959 ** databases always have Pager.exclusiveMode==1, this tricks the pager
47960 ** logic into thinking that it already has all the locks it will ever
47961 ** need (and no reason to release them).
47963 ** In some (obscure) circumstances, this variable may also be set to
47964 ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
47965 ** details.
47967 ** changeCountDone
47969 ** This boolean variable is used to make sure that the change-counter
47970 ** (the 4-byte header field at byte offset 24 of the database file) is
47971 ** not updated more often than necessary.
47973 ** It is set to true when the change-counter field is updated, which
47974 ** can only happen if an exclusive lock is held on the database file.
47975 ** It is cleared (set to false) whenever an exclusive lock is
47976 ** relinquished on the database file. Each time a transaction is committed,
47977 ** The changeCountDone flag is inspected. If it is true, the work of
47978 ** updating the change-counter is omitted for the current transaction.
47980 ** This mechanism means that when running in exclusive mode, a connection
47981 ** need only update the change-counter once, for the first transaction
47982 ** committed.
47984 ** setMaster
47986 ** When PagerCommitPhaseOne() is called to commit a transaction, it may
47987 ** (or may not) specify a master-journal name to be written into the
47988 ** journal file before it is synced to disk.
47990 ** Whether or not a journal file contains a master-journal pointer affects
47991 ** the way in which the journal file is finalized after the transaction is
47992 ** committed or rolled back when running in "journal_mode=PERSIST" mode.
47993 ** If a journal file does not contain a master-journal pointer, it is
47994 ** finalized by overwriting the first journal header with zeroes. If
47995 ** it does contain a master-journal pointer the journal file is finalized
47996 ** by truncating it to zero bytes, just as if the connection were
47997 ** running in "journal_mode=truncate" mode.
47999 ** Journal files that contain master journal pointers cannot be finalized
48000 ** simply by overwriting the first journal-header with zeroes, as the
48001 ** master journal pointer could interfere with hot-journal rollback of any
48002 ** subsequently interrupted transaction that reuses the journal file.
48004 ** The flag is cleared as soon as the journal file is finalized (either
48005 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
48006 ** journal file from being successfully finalized, the setMaster flag
48007 ** is cleared anyway (and the pager will move to ERROR state).
48009 ** doNotSpill
48011 ** This variables control the behavior of cache-spills (calls made by
48012 ** the pcache module to the pagerStress() routine to write cached data
48013 ** to the file-system in order to free up memory).
48015 ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
48016 ** writing to the database from pagerStress() is disabled altogether.
48017 ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
48018 ** comes up during savepoint rollback that requires the pcache module
48019 ** to allocate a new page to prevent the journal file from being written
48020 ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
48021 ** case is a user preference.
48023 ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
48024 ** pagerStress() is permitted, but syncing the journal file is not.
48025 ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
48026 ** is larger than the database page-size in order to prevent a journal sync
48027 ** from happening in between the journalling of two pages on the same sector.
48029 ** subjInMemory
48031 ** This is a boolean variable. If true, then any required sub-journal
48032 ** is opened as an in-memory journal file. If false, then in-memory
48033 ** sub-journals are only used for in-memory pager files.
48035 ** This variable is updated by the upper layer each time a new
48036 ** write-transaction is opened.
48038 ** dbSize, dbOrigSize, dbFileSize
48040 ** Variable dbSize is set to the number of pages in the database file.
48041 ** It is valid in PAGER_READER and higher states (all states except for
48042 ** OPEN and ERROR).
48044 ** dbSize is set based on the size of the database file, which may be
48045 ** larger than the size of the database (the value stored at offset
48046 ** 28 of the database header by the btree). If the size of the file
48047 ** is not an integer multiple of the page-size, the value stored in
48048 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
48049 ** Except, any file that is greater than 0 bytes in size is considered
48050 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
48051 ** to dbSize==1).
48053 ** During a write-transaction, if pages with page-numbers greater than
48054 ** dbSize are modified in the cache, dbSize is updated accordingly.
48055 ** Similarly, if the database is truncated using PagerTruncateImage(),
48056 ** dbSize is updated.
48058 ** Variables dbOrigSize and dbFileSize are valid in states
48059 ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
48060 ** variable at the start of the transaction. It is used during rollback,
48061 ** and to determine whether or not pages need to be journalled before
48062 ** being modified.
48064 ** Throughout a write-transaction, dbFileSize contains the size of
48065 ** the file on disk in pages. It is set to a copy of dbSize when the
48066 ** write-transaction is first opened, and updated when VFS calls are made
48067 ** to write or truncate the database file on disk.
48069 ** The only reason the dbFileSize variable is required is to suppress
48070 ** unnecessary calls to xTruncate() after committing a transaction. If,
48071 ** when a transaction is committed, the dbFileSize variable indicates
48072 ** that the database file is larger than the database image (Pager.dbSize),
48073 ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
48074 ** to measure the database file on disk, and then truncates it if required.
48075 ** dbFileSize is not used when rolling back a transaction. In this case
48076 ** pager_truncate() is called unconditionally (which means there may be
48077 ** a call to xFilesize() that is not strictly required). In either case,
48078 ** pager_truncate() may cause the file to become smaller or larger.
48080 ** dbHintSize
48082 ** The dbHintSize variable is used to limit the number of calls made to
48083 ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
48085 ** dbHintSize is set to a copy of the dbSize variable when a
48086 ** write-transaction is opened (at the same time as dbFileSize and
48087 ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
48088 ** dbHintSize is increased to the number of pages that correspond to the
48089 ** size-hint passed to the method call. See pager_write_pagelist() for
48090 ** details.
48092 ** errCode
48094 ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
48095 ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
48096 ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
48097 ** sub-codes.
48099 ** syncFlags, walSyncFlags
48101 ** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
48102 ** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode
48103 ** and contains the flags used to sync the checkpoint operations in the
48104 ** lower two bits, and sync flags used for transaction commits in the WAL
48105 ** file in bits 0x04 and 0x08. In other words, to get the correct sync flags
48106 ** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
48107 ** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note
48108 ** that with synchronous=NORMAL in WAL mode, transaction commit is not synced
48109 ** meaning that the 0x04 and 0x08 bits are both zero.
48111 struct Pager {
48112 sqlite3_vfs *pVfs; /* OS functions to use for IO */
48113 u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
48114 u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
48115 u8 useJournal; /* Use a rollback journal on this file */
48116 u8 noSync; /* Do not sync the journal if true */
48117 u8 fullSync; /* Do extra syncs of the journal for robustness */
48118 u8 extraSync; /* sync directory after journal delete */
48119 u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
48120 u8 walSyncFlags; /* See description above */
48121 u8 tempFile; /* zFilename is a temporary or immutable file */
48122 u8 noLock; /* Do not lock (except in WAL mode) */
48123 u8 readOnly; /* True for a read-only database */
48124 u8 memDb; /* True to inhibit all file I/O */
48126 /**************************************************************************
48127 ** The following block contains those class members that change during
48128 ** routine operation. Class members not in this block are either fixed
48129 ** when the pager is first created or else only change when there is a
48130 ** significant mode change (such as changing the page_size, locking_mode,
48131 ** or the journal_mode). From another view, these class members describe
48132 ** the "state" of the pager, while other class members describe the
48133 ** "configuration" of the pager.
48135 u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
48136 u8 eLock; /* Current lock held on database file */
48137 u8 changeCountDone; /* Set after incrementing the change-counter */
48138 u8 setMaster; /* True if a m-j name has been written to jrnl */
48139 u8 doNotSpill; /* Do not spill the cache when non-zero */
48140 u8 subjInMemory; /* True to use in-memory sub-journals */
48141 u8 bUseFetch; /* True to use xFetch() */
48142 u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
48143 Pgno dbSize; /* Number of pages in the database */
48144 Pgno dbOrigSize; /* dbSize before the current transaction */
48145 Pgno dbFileSize; /* Number of pages in the database file */
48146 Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
48147 int errCode; /* One of several kinds of errors */
48148 int nRec; /* Pages journalled since last j-header written */
48149 u32 cksumInit; /* Quasi-random value added to every checksum */
48150 u32 nSubRec; /* Number of records written to sub-journal */
48151 Bitvec *pInJournal; /* One bit for each page in the database file */
48152 sqlite3_file *fd; /* File descriptor for database */
48153 sqlite3_file *jfd; /* File descriptor for main journal */
48154 sqlite3_file *sjfd; /* File descriptor for sub-journal */
48155 i64 journalOff; /* Current write offset in the journal file */
48156 i64 journalHdr; /* Byte offset to previous journal header */
48157 sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
48158 PagerSavepoint *aSavepoint; /* Array of active savepoints */
48159 int nSavepoint; /* Number of elements in aSavepoint[] */
48160 u32 iDataVersion; /* Changes whenever database content changes */
48161 char dbFileVers[16]; /* Changes whenever database file changes */
48163 int nMmapOut; /* Number of mmap pages currently outstanding */
48164 sqlite3_int64 szMmap; /* Desired maximum mmap size */
48165 PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
48167 ** End of the routinely-changing class members
48168 ***************************************************************************/
48170 u16 nExtra; /* Add this many bytes to each in-memory page */
48171 i16 nReserve; /* Number of unused bytes at end of each page */
48172 u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
48173 u32 sectorSize; /* Assumed sector size during rollback */
48174 int pageSize; /* Number of bytes in a page */
48175 Pgno mxPgno; /* Maximum allowed size of the database */
48176 i64 journalSizeLimit; /* Size limit for persistent journal files */
48177 char *zFilename; /* Name of the database file */
48178 char *zJournal; /* Name of the journal file */
48179 int (*xBusyHandler)(void*); /* Function to call when busy */
48180 void *pBusyHandlerArg; /* Context argument for xBusyHandler */
48181 int aStat[3]; /* Total cache hits, misses and writes */
48182 #ifdef SQLITE_TEST
48183 int nRead; /* Database pages read */
48184 #endif
48185 void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
48186 int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
48187 #ifdef SQLITE_HAS_CODEC
48188 void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
48189 void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
48190 void (*xCodecFree)(void*); /* Destructor for the codec */
48191 void *pCodec; /* First argument to xCodec... methods */
48192 #endif
48193 char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
48194 PCache *pPCache; /* Pointer to page cache object */
48195 #ifndef SQLITE_OMIT_WAL
48196 Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
48197 char *zWal; /* File name for write-ahead log */
48198 #endif
48202 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
48203 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
48204 ** or CACHE_WRITE to sqlite3_db_status().
48206 #define PAGER_STAT_HIT 0
48207 #define PAGER_STAT_MISS 1
48208 #define PAGER_STAT_WRITE 2
48211 ** The following global variables hold counters used for
48212 ** testing purposes only. These variables do not exist in
48213 ** a non-testing build. These variables are not thread-safe.
48215 #ifdef SQLITE_TEST
48216 SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
48217 SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
48218 SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
48219 # define PAGER_INCR(v) v++
48220 #else
48221 # define PAGER_INCR(v)
48222 #endif
48227 ** Journal files begin with the following magic string. The data
48228 ** was obtained from /dev/random. It is used only as a sanity check.
48230 ** Since version 2.8.0, the journal format contains additional sanity
48231 ** checking information. If the power fails while the journal is being
48232 ** written, semi-random garbage data might appear in the journal
48233 ** file after power is restored. If an attempt is then made
48234 ** to roll the journal back, the database could be corrupted. The additional
48235 ** sanity checking data is an attempt to discover the garbage in the
48236 ** journal and ignore it.
48238 ** The sanity checking information for the new journal format consists
48239 ** of a 32-bit checksum on each page of data. The checksum covers both
48240 ** the page number and the pPager->pageSize bytes of data for the page.
48241 ** This cksum is initialized to a 32-bit random value that appears in the
48242 ** journal file right after the header. The random initializer is important,
48243 ** because garbage data that appears at the end of a journal is likely
48244 ** data that was once in other files that have now been deleted. If the
48245 ** garbage data came from an obsolete journal file, the checksums might
48246 ** be correct. But by initializing the checksum to random value which
48247 ** is different for every journal, we minimize that risk.
48249 static const unsigned char aJournalMagic[] = {
48250 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
48254 ** The size of the of each page record in the journal is given by
48255 ** the following macro.
48257 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
48260 ** The journal header size for this pager. This is usually the same
48261 ** size as a single disk sector. See also setSectorSize().
48263 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
48266 ** The macro MEMDB is true if we are dealing with an in-memory database.
48267 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
48268 ** the value of MEMDB will be a constant and the compiler will optimize
48269 ** out code that would never execute.
48271 #ifdef SQLITE_OMIT_MEMORYDB
48272 # define MEMDB 0
48273 #else
48274 # define MEMDB pPager->memDb
48275 #endif
48278 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
48279 ** interfaces to access the database using memory-mapped I/O.
48281 #if SQLITE_MAX_MMAP_SIZE>0
48282 # define USEFETCH(x) ((x)->bUseFetch)
48283 #else
48284 # define USEFETCH(x) 0
48285 #endif
48288 ** The maximum legal page number is (2^31 - 1).
48290 #define PAGER_MAX_PGNO 2147483647
48293 ** The argument to this macro is a file descriptor (type sqlite3_file*).
48294 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
48296 ** This is so that expressions can be written as:
48298 ** if( isOpen(pPager->jfd) ){ ...
48300 ** instead of
48302 ** if( pPager->jfd->pMethods ){ ...
48304 #define isOpen(pFd) ((pFd)->pMethods!=0)
48307 ** Return true if this pager uses a write-ahead log to read page pgno.
48308 ** Return false if the pager reads pgno directly from the database.
48310 #if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ)
48311 SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){
48312 u32 iRead = 0;
48313 int rc;
48314 if( pPager->pWal==0 ) return 0;
48315 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
48316 return rc || iRead;
48318 #endif
48319 #ifndef SQLITE_OMIT_WAL
48320 # define pagerUseWal(x) ((x)->pWal!=0)
48321 #else
48322 # define pagerUseWal(x) 0
48323 # define pagerRollbackWal(x) 0
48324 # define pagerWalFrames(v,w,x,y) 0
48325 # define pagerOpenWalIfPresent(z) SQLITE_OK
48326 # define pagerBeginReadTransaction(z) SQLITE_OK
48327 #endif
48329 #ifndef NDEBUG
48331 ** Usage:
48333 ** assert( assert_pager_state(pPager) );
48335 ** This function runs many asserts to try to find inconsistencies in
48336 ** the internal state of the Pager object.
48338 static int assert_pager_state(Pager *p){
48339 Pager *pPager = p;
48341 /* State must be valid. */
48342 assert( p->eState==PAGER_OPEN
48343 || p->eState==PAGER_READER
48344 || p->eState==PAGER_WRITER_LOCKED
48345 || p->eState==PAGER_WRITER_CACHEMOD
48346 || p->eState==PAGER_WRITER_DBMOD
48347 || p->eState==PAGER_WRITER_FINISHED
48348 || p->eState==PAGER_ERROR
48351 /* Regardless of the current state, a temp-file connection always behaves
48352 ** as if it has an exclusive lock on the database file. It never updates
48353 ** the change-counter field, so the changeCountDone flag is always set.
48355 assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
48356 assert( p->tempFile==0 || pPager->changeCountDone );
48358 /* If the useJournal flag is clear, the journal-mode must be "OFF".
48359 ** And if the journal-mode is "OFF", the journal file must not be open.
48361 assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
48362 assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
48364 /* Check that MEMDB implies noSync. And an in-memory journal. Since
48365 ** this means an in-memory pager performs no IO at all, it cannot encounter
48366 ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
48367 ** a journal file. (although the in-memory journal implementation may
48368 ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
48369 ** is therefore not possible for an in-memory pager to enter the ERROR
48370 ** state.
48372 if( MEMDB ){
48373 assert( !isOpen(p->fd) );
48374 assert( p->noSync );
48375 assert( p->journalMode==PAGER_JOURNALMODE_OFF
48376 || p->journalMode==PAGER_JOURNALMODE_MEMORY
48378 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
48379 assert( pagerUseWal(p)==0 );
48382 /* If changeCountDone is set, a RESERVED lock or greater must be held
48383 ** on the file.
48385 assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
48386 assert( p->eLock!=PENDING_LOCK );
48388 switch( p->eState ){
48389 case PAGER_OPEN:
48390 assert( !MEMDB );
48391 assert( pPager->errCode==SQLITE_OK );
48392 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
48393 break;
48395 case PAGER_READER:
48396 assert( pPager->errCode==SQLITE_OK );
48397 assert( p->eLock!=UNKNOWN_LOCK );
48398 assert( p->eLock>=SHARED_LOCK );
48399 break;
48401 case PAGER_WRITER_LOCKED:
48402 assert( p->eLock!=UNKNOWN_LOCK );
48403 assert( pPager->errCode==SQLITE_OK );
48404 if( !pagerUseWal(pPager) ){
48405 assert( p->eLock>=RESERVED_LOCK );
48407 assert( pPager->dbSize==pPager->dbOrigSize );
48408 assert( pPager->dbOrigSize==pPager->dbFileSize );
48409 assert( pPager->dbOrigSize==pPager->dbHintSize );
48410 assert( pPager->setMaster==0 );
48411 break;
48413 case PAGER_WRITER_CACHEMOD:
48414 assert( p->eLock!=UNKNOWN_LOCK );
48415 assert( pPager->errCode==SQLITE_OK );
48416 if( !pagerUseWal(pPager) ){
48417 /* It is possible that if journal_mode=wal here that neither the
48418 ** journal file nor the WAL file are open. This happens during
48419 ** a rollback transaction that switches from journal_mode=off
48420 ** to journal_mode=wal.
48422 assert( p->eLock>=RESERVED_LOCK );
48423 assert( isOpen(p->jfd)
48424 || p->journalMode==PAGER_JOURNALMODE_OFF
48425 || p->journalMode==PAGER_JOURNALMODE_WAL
48428 assert( pPager->dbOrigSize==pPager->dbFileSize );
48429 assert( pPager->dbOrigSize==pPager->dbHintSize );
48430 break;
48432 case PAGER_WRITER_DBMOD:
48433 assert( p->eLock==EXCLUSIVE_LOCK );
48434 assert( pPager->errCode==SQLITE_OK );
48435 assert( !pagerUseWal(pPager) );
48436 assert( p->eLock>=EXCLUSIVE_LOCK );
48437 assert( isOpen(p->jfd)
48438 || p->journalMode==PAGER_JOURNALMODE_OFF
48439 || p->journalMode==PAGER_JOURNALMODE_WAL
48440 || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
48442 assert( pPager->dbOrigSize<=pPager->dbHintSize );
48443 break;
48445 case PAGER_WRITER_FINISHED:
48446 assert( p->eLock==EXCLUSIVE_LOCK );
48447 assert( pPager->errCode==SQLITE_OK );
48448 assert( !pagerUseWal(pPager) );
48449 assert( isOpen(p->jfd)
48450 || p->journalMode==PAGER_JOURNALMODE_OFF
48451 || p->journalMode==PAGER_JOURNALMODE_WAL
48452 || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
48454 break;
48456 case PAGER_ERROR:
48457 /* There must be at least one outstanding reference to the pager if
48458 ** in ERROR state. Otherwise the pager should have already dropped
48459 ** back to OPEN state.
48461 assert( pPager->errCode!=SQLITE_OK );
48462 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
48463 break;
48466 return 1;
48468 #endif /* ifndef NDEBUG */
48470 #ifdef SQLITE_DEBUG
48472 ** Return a pointer to a human readable string in a static buffer
48473 ** containing the state of the Pager object passed as an argument. This
48474 ** is intended to be used within debuggers. For example, as an alternative
48475 ** to "print *pPager" in gdb:
48477 ** (gdb) printf "%s", print_pager_state(pPager)
48479 static char *print_pager_state(Pager *p){
48480 static char zRet[1024];
48482 sqlite3_snprintf(1024, zRet,
48483 "Filename: %s\n"
48484 "State: %s errCode=%d\n"
48485 "Lock: %s\n"
48486 "Locking mode: locking_mode=%s\n"
48487 "Journal mode: journal_mode=%s\n"
48488 "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
48489 "Journal: journalOff=%lld journalHdr=%lld\n"
48490 "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
48491 , p->zFilename
48492 , p->eState==PAGER_OPEN ? "OPEN" :
48493 p->eState==PAGER_READER ? "READER" :
48494 p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
48495 p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
48496 p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
48497 p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
48498 p->eState==PAGER_ERROR ? "ERROR" : "?error?"
48499 , (int)p->errCode
48500 , p->eLock==NO_LOCK ? "NO_LOCK" :
48501 p->eLock==RESERVED_LOCK ? "RESERVED" :
48502 p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
48503 p->eLock==SHARED_LOCK ? "SHARED" :
48504 p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
48505 , p->exclusiveMode ? "exclusive" : "normal"
48506 , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
48507 p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
48508 p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
48509 p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
48510 p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
48511 p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
48512 , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
48513 , p->journalOff, p->journalHdr
48514 , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
48517 return zRet;
48519 #endif
48521 /* Forward references to the various page getters */
48522 static int getPageNormal(Pager*,Pgno,DbPage**,int);
48523 static int getPageError(Pager*,Pgno,DbPage**,int);
48524 #if SQLITE_MAX_MMAP_SIZE>0
48525 static int getPageMMap(Pager*,Pgno,DbPage**,int);
48526 #endif
48529 ** Set the Pager.xGet method for the appropriate routine used to fetch
48530 ** content from the pager.
48532 static void setGetterMethod(Pager *pPager){
48533 if( pPager->errCode ){
48534 pPager->xGet = getPageError;
48535 #if SQLITE_MAX_MMAP_SIZE>0
48536 }else if( USEFETCH(pPager)
48537 #ifdef SQLITE_HAS_CODEC
48538 && pPager->xCodec==0
48539 #endif
48541 pPager->xGet = getPageMMap;
48542 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
48543 }else{
48544 pPager->xGet = getPageNormal;
48549 ** Return true if it is necessary to write page *pPg into the sub-journal.
48550 ** A page needs to be written into the sub-journal if there exists one
48551 ** or more open savepoints for which:
48553 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
48554 ** * The bit corresponding to the page-number is not set in
48555 ** PagerSavepoint.pInSavepoint.
48557 static int subjRequiresPage(PgHdr *pPg){
48558 Pager *pPager = pPg->pPager;
48559 PagerSavepoint *p;
48560 Pgno pgno = pPg->pgno;
48561 int i;
48562 for(i=0; i<pPager->nSavepoint; i++){
48563 p = &pPager->aSavepoint[i];
48564 if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
48565 return 1;
48568 return 0;
48571 #ifdef SQLITE_DEBUG
48573 ** Return true if the page is already in the journal file.
48575 static int pageInJournal(Pager *pPager, PgHdr *pPg){
48576 return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
48578 #endif
48581 ** Read a 32-bit integer from the given file descriptor. Store the integer
48582 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
48583 ** error code is something goes wrong.
48585 ** All values are stored on disk as big-endian.
48587 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
48588 unsigned char ac[4];
48589 int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
48590 if( rc==SQLITE_OK ){
48591 *pRes = sqlite3Get4byte(ac);
48593 return rc;
48597 ** Write a 32-bit integer into a string buffer in big-endian byte order.
48599 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
48603 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
48604 ** on success or an error code is something goes wrong.
48606 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
48607 char ac[4];
48608 put32bits(ac, val);
48609 return sqlite3OsWrite(fd, ac, 4, offset);
48613 ** Unlock the database file to level eLock, which must be either NO_LOCK
48614 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
48615 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
48617 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
48618 ** called, do not modify it. See the comment above the #define of
48619 ** UNKNOWN_LOCK for an explanation of this.
48621 static int pagerUnlockDb(Pager *pPager, int eLock){
48622 int rc = SQLITE_OK;
48624 assert( !pPager->exclusiveMode || pPager->eLock==eLock );
48625 assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
48626 assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
48627 if( isOpen(pPager->fd) ){
48628 assert( pPager->eLock>=eLock );
48629 rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
48630 if( pPager->eLock!=UNKNOWN_LOCK ){
48631 pPager->eLock = (u8)eLock;
48633 IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
48635 return rc;
48639 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
48640 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
48641 ** Pager.eLock variable to the new locking state.
48643 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
48644 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
48645 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
48646 ** of this.
48648 static int pagerLockDb(Pager *pPager, int eLock){
48649 int rc = SQLITE_OK;
48651 assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
48652 if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
48653 rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
48654 if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
48655 pPager->eLock = (u8)eLock;
48656 IOTRACE(("LOCK %p %d\n", pPager, eLock))
48659 return rc;
48663 ** This function determines whether or not the atomic-write or
48664 ** atomic-batch-write optimizations can be used with this pager. The
48665 ** atomic-write optimization can be used if:
48667 ** (a) the value returned by OsDeviceCharacteristics() indicates that
48668 ** a database page may be written atomically, and
48669 ** (b) the value returned by OsSectorSize() is less than or equal
48670 ** to the page size.
48672 ** If it can be used, then the value returned is the size of the journal
48673 ** file when it contains rollback data for exactly one page.
48675 ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
48676 ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
48677 ** returned in this case.
48679 ** If neither optimization can be used, 0 is returned.
48681 static int jrnlBufferSize(Pager *pPager){
48682 assert( !MEMDB );
48684 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
48685 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
48686 int dc; /* Device characteristics */
48688 assert( isOpen(pPager->fd) );
48689 dc = sqlite3OsDeviceCharacteristics(pPager->fd);
48690 #else
48691 UNUSED_PARAMETER(pPager);
48692 #endif
48694 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
48695 if( dc&SQLITE_IOCAP_BATCH_ATOMIC ){
48696 return -1;
48698 #endif
48700 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
48702 int nSector = pPager->sectorSize;
48703 int szPage = pPager->pageSize;
48705 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
48706 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
48707 if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
48708 return 0;
48712 return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
48713 #endif
48715 return 0;
48719 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
48720 ** on the cache using a hash function. This is used for testing
48721 ** and debugging only.
48723 #ifdef SQLITE_CHECK_PAGES
48725 ** Return a 32-bit hash of the page data for pPage.
48727 static u32 pager_datahash(int nByte, unsigned char *pData){
48728 u32 hash = 0;
48729 int i;
48730 for(i=0; i<nByte; i++){
48731 hash = (hash*1039) + pData[i];
48733 return hash;
48735 static u32 pager_pagehash(PgHdr *pPage){
48736 return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
48738 static void pager_set_pagehash(PgHdr *pPage){
48739 pPage->pageHash = pager_pagehash(pPage);
48743 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
48744 ** is defined, and NDEBUG is not defined, an assert() statement checks
48745 ** that the page is either dirty or still matches the calculated page-hash.
48747 #define CHECK_PAGE(x) checkPage(x)
48748 static void checkPage(PgHdr *pPg){
48749 Pager *pPager = pPg->pPager;
48750 assert( pPager->eState!=PAGER_ERROR );
48751 assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
48754 #else
48755 #define pager_datahash(X,Y) 0
48756 #define pager_pagehash(X) 0
48757 #define pager_set_pagehash(X)
48758 #define CHECK_PAGE(x)
48759 #endif /* SQLITE_CHECK_PAGES */
48762 ** When this is called the journal file for pager pPager must be open.
48763 ** This function attempts to read a master journal file name from the
48764 ** end of the file and, if successful, copies it into memory supplied
48765 ** by the caller. See comments above writeMasterJournal() for the format
48766 ** used to store a master journal file name at the end of a journal file.
48768 ** zMaster must point to a buffer of at least nMaster bytes allocated by
48769 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
48770 ** enough space to write the master journal name). If the master journal
48771 ** name in the journal is longer than nMaster bytes (including a
48772 ** nul-terminator), then this is handled as if no master journal name
48773 ** were present in the journal.
48775 ** If a master journal file name is present at the end of the journal
48776 ** file, then it is copied into the buffer pointed to by zMaster. A
48777 ** nul-terminator byte is appended to the buffer following the master
48778 ** journal file name.
48780 ** If it is determined that no master journal file name is present
48781 ** zMaster[0] is set to 0 and SQLITE_OK returned.
48783 ** If an error occurs while reading from the journal file, an SQLite
48784 ** error code is returned.
48786 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
48787 int rc; /* Return code */
48788 u32 len; /* Length in bytes of master journal name */
48789 i64 szJ; /* Total size in bytes of journal file pJrnl */
48790 u32 cksum; /* MJ checksum value read from journal */
48791 u32 u; /* Unsigned loop counter */
48792 unsigned char aMagic[8]; /* A buffer to hold the magic header */
48793 zMaster[0] = '\0';
48795 if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
48796 || szJ<16
48797 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
48798 || len>=nMaster
48799 || len>szJ-16
48800 || len==0
48801 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
48802 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
48803 || memcmp(aMagic, aJournalMagic, 8)
48804 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
48806 return rc;
48809 /* See if the checksum matches the master journal name */
48810 for(u=0; u<len; u++){
48811 cksum -= zMaster[u];
48813 if( cksum ){
48814 /* If the checksum doesn't add up, then one or more of the disk sectors
48815 ** containing the master journal filename is corrupted. This means
48816 ** definitely roll back, so just return SQLITE_OK and report a (nul)
48817 ** master-journal filename.
48819 len = 0;
48821 zMaster[len] = '\0';
48823 return SQLITE_OK;
48827 ** Return the offset of the sector boundary at or immediately
48828 ** following the value in pPager->journalOff, assuming a sector
48829 ** size of pPager->sectorSize bytes.
48831 ** i.e for a sector size of 512:
48833 ** Pager.journalOff Return value
48834 ** ---------------------------------------
48835 ** 0 0
48836 ** 512 512
48837 ** 100 512
48838 ** 2000 2048
48841 static i64 journalHdrOffset(Pager *pPager){
48842 i64 offset = 0;
48843 i64 c = pPager->journalOff;
48844 if( c ){
48845 offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
48847 assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
48848 assert( offset>=c );
48849 assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
48850 return offset;
48854 ** The journal file must be open when this function is called.
48856 ** This function is a no-op if the journal file has not been written to
48857 ** within the current transaction (i.e. if Pager.journalOff==0).
48859 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
48860 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
48861 ** zero the 28-byte header at the start of the journal file. In either case,
48862 ** if the pager is not in no-sync mode, sync the journal file immediately
48863 ** after writing or truncating it.
48865 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
48866 ** following the truncation or zeroing described above the size of the
48867 ** journal file in bytes is larger than this value, then truncate the
48868 ** journal file to Pager.journalSizeLimit bytes. The journal file does
48869 ** not need to be synced following this operation.
48871 ** If an IO error occurs, abandon processing and return the IO error code.
48872 ** Otherwise, return SQLITE_OK.
48874 static int zeroJournalHdr(Pager *pPager, int doTruncate){
48875 int rc = SQLITE_OK; /* Return code */
48876 assert( isOpen(pPager->jfd) );
48877 assert( !sqlite3JournalIsInMemory(pPager->jfd) );
48878 if( pPager->journalOff ){
48879 const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
48881 IOTRACE(("JZEROHDR %p\n", pPager))
48882 if( doTruncate || iLimit==0 ){
48883 rc = sqlite3OsTruncate(pPager->jfd, 0);
48884 }else{
48885 static const char zeroHdr[28] = {0};
48886 rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
48888 if( rc==SQLITE_OK && !pPager->noSync ){
48889 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
48892 /* At this point the transaction is committed but the write lock
48893 ** is still held on the file. If there is a size limit configured for
48894 ** the persistent journal and the journal file currently consumes more
48895 ** space than that limit allows for, truncate it now. There is no need
48896 ** to sync the file following this operation.
48898 if( rc==SQLITE_OK && iLimit>0 ){
48899 i64 sz;
48900 rc = sqlite3OsFileSize(pPager->jfd, &sz);
48901 if( rc==SQLITE_OK && sz>iLimit ){
48902 rc = sqlite3OsTruncate(pPager->jfd, iLimit);
48906 return rc;
48910 ** The journal file must be open when this routine is called. A journal
48911 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
48912 ** current location.
48914 ** The format for the journal header is as follows:
48915 ** - 8 bytes: Magic identifying journal format.
48916 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
48917 ** - 4 bytes: Random number used for page hash.
48918 ** - 4 bytes: Initial database page count.
48919 ** - 4 bytes: Sector size used by the process that wrote this journal.
48920 ** - 4 bytes: Database page size.
48922 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
48924 static int writeJournalHdr(Pager *pPager){
48925 int rc = SQLITE_OK; /* Return code */
48926 char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
48927 u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
48928 u32 nWrite; /* Bytes of header sector written */
48929 int ii; /* Loop counter */
48931 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
48933 if( nHeader>JOURNAL_HDR_SZ(pPager) ){
48934 nHeader = JOURNAL_HDR_SZ(pPager);
48937 /* If there are active savepoints and any of them were created
48938 ** since the most recent journal header was written, update the
48939 ** PagerSavepoint.iHdrOffset fields now.
48941 for(ii=0; ii<pPager->nSavepoint; ii++){
48942 if( pPager->aSavepoint[ii].iHdrOffset==0 ){
48943 pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
48947 pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
48950 ** Write the nRec Field - the number of page records that follow this
48951 ** journal header. Normally, zero is written to this value at this time.
48952 ** After the records are added to the journal (and the journal synced,
48953 ** if in full-sync mode), the zero is overwritten with the true number
48954 ** of records (see syncJournal()).
48956 ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
48957 ** reading the journal this value tells SQLite to assume that the
48958 ** rest of the journal file contains valid page records. This assumption
48959 ** is dangerous, as if a failure occurred whilst writing to the journal
48960 ** file it may contain some garbage data. There are two scenarios
48961 ** where this risk can be ignored:
48963 ** * When the pager is in no-sync mode. Corruption can follow a
48964 ** power failure in this case anyway.
48966 ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
48967 ** that garbage data is never appended to the journal file.
48969 assert( isOpen(pPager->fd) || pPager->noSync );
48970 if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
48971 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
48973 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
48974 put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
48975 }else{
48976 memset(zHeader, 0, sizeof(aJournalMagic)+4);
48979 /* The random check-hash initializer */
48980 sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
48981 put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
48982 /* The initial database size */
48983 put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
48984 /* The assumed sector size for this process */
48985 put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
48987 /* The page size */
48988 put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
48990 /* Initializing the tail of the buffer is not necessary. Everything
48991 ** works find if the following memset() is omitted. But initializing
48992 ** the memory prevents valgrind from complaining, so we are willing to
48993 ** take the performance hit.
48995 memset(&zHeader[sizeof(aJournalMagic)+20], 0,
48996 nHeader-(sizeof(aJournalMagic)+20));
48998 /* In theory, it is only necessary to write the 28 bytes that the
48999 ** journal header consumes to the journal file here. Then increment the
49000 ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
49001 ** record is written to the following sector (leaving a gap in the file
49002 ** that will be implicitly filled in by the OS).
49004 ** However it has been discovered that on some systems this pattern can
49005 ** be significantly slower than contiguously writing data to the file,
49006 ** even if that means explicitly writing data to the block of
49007 ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
49008 ** is done.
49010 ** The loop is required here in case the sector-size is larger than the
49011 ** database page size. Since the zHeader buffer is only Pager.pageSize
49012 ** bytes in size, more than one call to sqlite3OsWrite() may be required
49013 ** to populate the entire journal header sector.
49015 for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
49016 IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
49017 rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
49018 assert( pPager->journalHdr <= pPager->journalOff );
49019 pPager->journalOff += nHeader;
49022 return rc;
49026 ** The journal file must be open when this is called. A journal header file
49027 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
49028 ** file. The current location in the journal file is given by
49029 ** pPager->journalOff. See comments above function writeJournalHdr() for
49030 ** a description of the journal header format.
49032 ** If the header is read successfully, *pNRec is set to the number of
49033 ** page records following this header and *pDbSize is set to the size of the
49034 ** database before the transaction began, in pages. Also, pPager->cksumInit
49035 ** is set to the value read from the journal header. SQLITE_OK is returned
49036 ** in this case.
49038 ** If the journal header file appears to be corrupted, SQLITE_DONE is
49039 ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
49040 ** cannot be read from the journal file an error code is returned.
49042 static int readJournalHdr(
49043 Pager *pPager, /* Pager object */
49044 int isHot,
49045 i64 journalSize, /* Size of the open journal file in bytes */
49046 u32 *pNRec, /* OUT: Value read from the nRec field */
49047 u32 *pDbSize /* OUT: Value of original database size field */
49049 int rc; /* Return code */
49050 unsigned char aMagic[8]; /* A buffer to hold the magic header */
49051 i64 iHdrOff; /* Offset of journal header being read */
49053 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
49055 /* Advance Pager.journalOff to the start of the next sector. If the
49056 ** journal file is too small for there to be a header stored at this
49057 ** point, return SQLITE_DONE.
49059 pPager->journalOff = journalHdrOffset(pPager);
49060 if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
49061 return SQLITE_DONE;
49063 iHdrOff = pPager->journalOff;
49065 /* Read in the first 8 bytes of the journal header. If they do not match
49066 ** the magic string found at the start of each journal header, return
49067 ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
49068 ** proceed.
49070 if( isHot || iHdrOff!=pPager->journalHdr ){
49071 rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
49072 if( rc ){
49073 return rc;
49075 if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
49076 return SQLITE_DONE;
49080 /* Read the first three 32-bit fields of the journal header: The nRec
49081 ** field, the checksum-initializer and the database size at the start
49082 ** of the transaction. Return an error code if anything goes wrong.
49084 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
49085 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
49086 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
49088 return rc;
49091 if( pPager->journalOff==0 ){
49092 u32 iPageSize; /* Page-size field of journal header */
49093 u32 iSectorSize; /* Sector-size field of journal header */
49095 /* Read the page-size and sector-size journal header fields. */
49096 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
49097 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
49099 return rc;
49102 /* Versions of SQLite prior to 3.5.8 set the page-size field of the
49103 ** journal header to zero. In this case, assume that the Pager.pageSize
49104 ** variable is already set to the correct page size.
49106 if( iPageSize==0 ){
49107 iPageSize = pPager->pageSize;
49110 /* Check that the values read from the page-size and sector-size fields
49111 ** are within range. To be 'in range', both values need to be a power
49112 ** of two greater than or equal to 512 or 32, and not greater than their
49113 ** respective compile time maximum limits.
49115 if( iPageSize<512 || iSectorSize<32
49116 || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
49117 || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
49119 /* If the either the page-size or sector-size in the journal-header is
49120 ** invalid, then the process that wrote the journal-header must have
49121 ** crashed before the header was synced. In this case stop reading
49122 ** the journal file here.
49124 return SQLITE_DONE;
49127 /* Update the page-size to match the value read from the journal.
49128 ** Use a testcase() macro to make sure that malloc failure within
49129 ** PagerSetPagesize() is tested.
49131 rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
49132 testcase( rc!=SQLITE_OK );
49134 /* Update the assumed sector-size to match the value used by
49135 ** the process that created this journal. If this journal was
49136 ** created by a process other than this one, then this routine
49137 ** is being called from within pager_playback(). The local value
49138 ** of Pager.sectorSize is restored at the end of that routine.
49140 pPager->sectorSize = iSectorSize;
49143 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
49144 return rc;
49149 ** Write the supplied master journal name into the journal file for pager
49150 ** pPager at the current location. The master journal name must be the last
49151 ** thing written to a journal file. If the pager is in full-sync mode, the
49152 ** journal file descriptor is advanced to the next sector boundary before
49153 ** anything is written. The format is:
49155 ** + 4 bytes: PAGER_MJ_PGNO.
49156 ** + N bytes: Master journal filename in utf-8.
49157 ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
49158 ** + 4 bytes: Master journal name checksum.
49159 ** + 8 bytes: aJournalMagic[].
49161 ** The master journal page checksum is the sum of the bytes in the master
49162 ** journal name, where each byte is interpreted as a signed 8-bit integer.
49164 ** If zMaster is a NULL pointer (occurs for a single database transaction),
49165 ** this call is a no-op.
49167 static int writeMasterJournal(Pager *pPager, const char *zMaster){
49168 int rc; /* Return code */
49169 int nMaster; /* Length of string zMaster */
49170 i64 iHdrOff; /* Offset of header in journal file */
49171 i64 jrnlSize; /* Size of journal file on disk */
49172 u32 cksum = 0; /* Checksum of string zMaster */
49174 assert( pPager->setMaster==0 );
49175 assert( !pagerUseWal(pPager) );
49177 if( !zMaster
49178 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
49179 || !isOpen(pPager->jfd)
49181 return SQLITE_OK;
49183 pPager->setMaster = 1;
49184 assert( pPager->journalHdr <= pPager->journalOff );
49186 /* Calculate the length in bytes and the checksum of zMaster */
49187 for(nMaster=0; zMaster[nMaster]; nMaster++){
49188 cksum += zMaster[nMaster];
49191 /* If in full-sync mode, advance to the next disk sector before writing
49192 ** the master journal name. This is in case the previous page written to
49193 ** the journal has already been synced.
49195 if( pPager->fullSync ){
49196 pPager->journalOff = journalHdrOffset(pPager);
49198 iHdrOff = pPager->journalOff;
49200 /* Write the master journal data to the end of the journal file. If
49201 ** an error occurs, return the error code to the caller.
49203 if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
49204 || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
49205 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
49206 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
49207 || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
49208 iHdrOff+4+nMaster+8)))
49210 return rc;
49212 pPager->journalOff += (nMaster+20);
49214 /* If the pager is in peristent-journal mode, then the physical
49215 ** journal-file may extend past the end of the master-journal name
49216 ** and 8 bytes of magic data just written to the file. This is
49217 ** dangerous because the code to rollback a hot-journal file
49218 ** will not be able to find the master-journal name to determine
49219 ** whether or not the journal is hot.
49221 ** Easiest thing to do in this scenario is to truncate the journal
49222 ** file to the required size.
49224 if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
49225 && jrnlSize>pPager->journalOff
49227 rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
49229 return rc;
49233 ** Discard the entire contents of the in-memory page-cache.
49235 static void pager_reset(Pager *pPager){
49236 pPager->iDataVersion++;
49237 sqlite3BackupRestart(pPager->pBackup);
49238 sqlite3PcacheClear(pPager->pPCache);
49242 ** Return the pPager->iDataVersion value
49244 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
49245 assert( pPager->eState>PAGER_OPEN );
49246 return pPager->iDataVersion;
49250 ** Free all structures in the Pager.aSavepoint[] array and set both
49251 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
49252 ** if it is open and the pager is not in exclusive mode.
49254 static void releaseAllSavepoints(Pager *pPager){
49255 int ii; /* Iterator for looping through Pager.aSavepoint */
49256 for(ii=0; ii<pPager->nSavepoint; ii++){
49257 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
49259 if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
49260 sqlite3OsClose(pPager->sjfd);
49262 sqlite3_free(pPager->aSavepoint);
49263 pPager->aSavepoint = 0;
49264 pPager->nSavepoint = 0;
49265 pPager->nSubRec = 0;
49269 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
49270 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
49271 ** or SQLITE_NOMEM if a malloc failure occurs.
49273 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
49274 int ii; /* Loop counter */
49275 int rc = SQLITE_OK; /* Result code */
49277 for(ii=0; ii<pPager->nSavepoint; ii++){
49278 PagerSavepoint *p = &pPager->aSavepoint[ii];
49279 if( pgno<=p->nOrig ){
49280 rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
49281 testcase( rc==SQLITE_NOMEM );
49282 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
49285 return rc;
49289 ** This function is a no-op if the pager is in exclusive mode and not
49290 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
49291 ** state.
49293 ** If the pager is not in exclusive-access mode, the database file is
49294 ** completely unlocked. If the file is unlocked and the file-system does
49295 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
49296 ** closed (if it is open).
49298 ** If the pager is in ERROR state when this function is called, the
49299 ** contents of the pager cache are discarded before switching back to
49300 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
49301 ** or not, any journal file left in the file-system will be treated
49302 ** as a hot-journal and rolled back the next time a read-transaction
49303 ** is opened (by this or by any other connection).
49305 static void pager_unlock(Pager *pPager){
49307 assert( pPager->eState==PAGER_READER
49308 || pPager->eState==PAGER_OPEN
49309 || pPager->eState==PAGER_ERROR
49312 sqlite3BitvecDestroy(pPager->pInJournal);
49313 pPager->pInJournal = 0;
49314 releaseAllSavepoints(pPager);
49316 if( pagerUseWal(pPager) ){
49317 assert( !isOpen(pPager->jfd) );
49318 sqlite3WalEndReadTransaction(pPager->pWal);
49319 pPager->eState = PAGER_OPEN;
49320 }else if( !pPager->exclusiveMode ){
49321 int rc; /* Error code returned by pagerUnlockDb() */
49322 int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
49324 /* If the operating system support deletion of open files, then
49325 ** close the journal file when dropping the database lock. Otherwise
49326 ** another connection with journal_mode=delete might delete the file
49327 ** out from under us.
49329 assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
49330 assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
49331 assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
49332 assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
49333 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
49334 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
49335 if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
49336 || 1!=(pPager->journalMode & 5)
49338 sqlite3OsClose(pPager->jfd);
49341 /* If the pager is in the ERROR state and the call to unlock the database
49342 ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
49343 ** above the #define for UNKNOWN_LOCK for an explanation of why this
49344 ** is necessary.
49346 rc = pagerUnlockDb(pPager, NO_LOCK);
49347 if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
49348 pPager->eLock = UNKNOWN_LOCK;
49351 /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
49352 ** without clearing the error code. This is intentional - the error
49353 ** code is cleared and the cache reset in the block below.
49355 assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
49356 pPager->changeCountDone = 0;
49357 pPager->eState = PAGER_OPEN;
49360 /* If Pager.errCode is set, the contents of the pager cache cannot be
49361 ** trusted. Now that there are no outstanding references to the pager,
49362 ** it can safely move back to PAGER_OPEN state. This happens in both
49363 ** normal and exclusive-locking mode.
49365 assert( pPager->errCode==SQLITE_OK || !MEMDB );
49366 if( pPager->errCode ){
49367 if( pPager->tempFile==0 ){
49368 pager_reset(pPager);
49369 pPager->changeCountDone = 0;
49370 pPager->eState = PAGER_OPEN;
49371 }else{
49372 pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
49374 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
49375 pPager->errCode = SQLITE_OK;
49376 setGetterMethod(pPager);
49379 pPager->journalOff = 0;
49380 pPager->journalHdr = 0;
49381 pPager->setMaster = 0;
49385 ** This function is called whenever an IOERR or FULL error that requires
49386 ** the pager to transition into the ERROR state may ahve occurred.
49387 ** The first argument is a pointer to the pager structure, the second
49388 ** the error-code about to be returned by a pager API function. The
49389 ** value returned is a copy of the second argument to this function.
49391 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
49392 ** IOERR sub-codes, the pager enters the ERROR state and the error code
49393 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
49394 ** all major API calls on the Pager will immediately return Pager.errCode.
49396 ** The ERROR state indicates that the contents of the pager-cache
49397 ** cannot be trusted. This state can be cleared by completely discarding
49398 ** the contents of the pager-cache. If a transaction was active when
49399 ** the persistent error occurred, then the rollback journal may need
49400 ** to be replayed to restore the contents of the database file (as if
49401 ** it were a hot-journal).
49403 static int pager_error(Pager *pPager, int rc){
49404 int rc2 = rc & 0xff;
49405 assert( rc==SQLITE_OK || !MEMDB );
49406 assert(
49407 pPager->errCode==SQLITE_FULL ||
49408 pPager->errCode==SQLITE_OK ||
49409 (pPager->errCode & 0xff)==SQLITE_IOERR
49411 if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
49412 pPager->errCode = rc;
49413 pPager->eState = PAGER_ERROR;
49414 setGetterMethod(pPager);
49416 return rc;
49419 static int pager_truncate(Pager *pPager, Pgno nPage);
49422 ** The write transaction open on pPager is being committed (bCommit==1)
49423 ** or rolled back (bCommit==0).
49425 ** Return TRUE if and only if all dirty pages should be flushed to disk.
49427 ** Rules:
49429 ** * For non-TEMP databases, always sync to disk. This is necessary
49430 ** for transactions to be durable.
49432 ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
49433 ** file has been created already (via a spill on pagerStress()) and
49434 ** when the number of dirty pages in memory exceeds 25% of the total
49435 ** cache size.
49437 static int pagerFlushOnCommit(Pager *pPager, int bCommit){
49438 if( pPager->tempFile==0 ) return 1;
49439 if( !bCommit ) return 0;
49440 if( !isOpen(pPager->fd) ) return 0;
49441 return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
49445 ** This routine ends a transaction. A transaction is usually ended by
49446 ** either a COMMIT or a ROLLBACK operation. This routine may be called
49447 ** after rollback of a hot-journal, or if an error occurs while opening
49448 ** the journal file or writing the very first journal-header of a
49449 ** database transaction.
49451 ** This routine is never called in PAGER_ERROR state. If it is called
49452 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
49453 ** exclusive than a RESERVED lock, it is a no-op.
49455 ** Otherwise, any active savepoints are released.
49457 ** If the journal file is open, then it is "finalized". Once a journal
49458 ** file has been finalized it is not possible to use it to roll back a
49459 ** transaction. Nor will it be considered to be a hot-journal by this
49460 ** or any other database connection. Exactly how a journal is finalized
49461 ** depends on whether or not the pager is running in exclusive mode and
49462 ** the current journal-mode (Pager.journalMode value), as follows:
49464 ** journalMode==MEMORY
49465 ** Journal file descriptor is simply closed. This destroys an
49466 ** in-memory journal.
49468 ** journalMode==TRUNCATE
49469 ** Journal file is truncated to zero bytes in size.
49471 ** journalMode==PERSIST
49472 ** The first 28 bytes of the journal file are zeroed. This invalidates
49473 ** the first journal header in the file, and hence the entire journal
49474 ** file. An invalid journal file cannot be rolled back.
49476 ** journalMode==DELETE
49477 ** The journal file is closed and deleted using sqlite3OsDelete().
49479 ** If the pager is running in exclusive mode, this method of finalizing
49480 ** the journal file is never used. Instead, if the journalMode is
49481 ** DELETE and the pager is in exclusive mode, the method described under
49482 ** journalMode==PERSIST is used instead.
49484 ** After the journal is finalized, the pager moves to PAGER_READER state.
49485 ** If running in non-exclusive rollback mode, the lock on the file is
49486 ** downgraded to a SHARED_LOCK.
49488 ** SQLITE_OK is returned if no error occurs. If an error occurs during
49489 ** any of the IO operations to finalize the journal file or unlock the
49490 ** database then the IO error code is returned to the user. If the
49491 ** operation to finalize the journal file fails, then the code still
49492 ** tries to unlock the database file if not in exclusive mode. If the
49493 ** unlock operation fails as well, then the first error code related
49494 ** to the first error encountered (the journal finalization one) is
49495 ** returned.
49497 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
49498 int rc = SQLITE_OK; /* Error code from journal finalization operation */
49499 int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
49501 /* Do nothing if the pager does not have an open write transaction
49502 ** or at least a RESERVED lock. This function may be called when there
49503 ** is no write-transaction active but a RESERVED or greater lock is
49504 ** held under two circumstances:
49506 ** 1. After a successful hot-journal rollback, it is called with
49507 ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
49509 ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
49510 ** lock switches back to locking_mode=normal and then executes a
49511 ** read-transaction, this function is called with eState==PAGER_READER
49512 ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
49514 assert( assert_pager_state(pPager) );
49515 assert( pPager->eState!=PAGER_ERROR );
49516 if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
49517 return SQLITE_OK;
49520 releaseAllSavepoints(pPager);
49521 assert( isOpen(pPager->jfd) || pPager->pInJournal==0
49522 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
49524 if( isOpen(pPager->jfd) ){
49525 assert( !pagerUseWal(pPager) );
49527 /* Finalize the journal file. */
49528 if( sqlite3JournalIsInMemory(pPager->jfd) ){
49529 /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
49530 sqlite3OsClose(pPager->jfd);
49531 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
49532 if( pPager->journalOff==0 ){
49533 rc = SQLITE_OK;
49534 }else{
49535 rc = sqlite3OsTruncate(pPager->jfd, 0);
49536 if( rc==SQLITE_OK && pPager->fullSync ){
49537 /* Make sure the new file size is written into the inode right away.
49538 ** Otherwise the journal might resurrect following a power loss and
49539 ** cause the last transaction to roll back. See
49540 ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
49542 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
49545 pPager->journalOff = 0;
49546 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
49547 || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
49549 rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
49550 pPager->journalOff = 0;
49551 }else{
49552 /* This branch may be executed with Pager.journalMode==MEMORY if
49553 ** a hot-journal was just rolled back. In this case the journal
49554 ** file should be closed and deleted. If this connection writes to
49555 ** the database file, it will do so using an in-memory journal.
49557 int bDelete = !pPager->tempFile;
49558 assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
49559 assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
49560 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
49561 || pPager->journalMode==PAGER_JOURNALMODE_WAL
49563 sqlite3OsClose(pPager->jfd);
49564 if( bDelete ){
49565 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
49570 #ifdef SQLITE_CHECK_PAGES
49571 sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
49572 if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
49573 PgHdr *p = sqlite3PagerLookup(pPager, 1);
49574 if( p ){
49575 p->pageHash = 0;
49576 sqlite3PagerUnrefNotNull(p);
49579 #endif
49581 sqlite3BitvecDestroy(pPager->pInJournal);
49582 pPager->pInJournal = 0;
49583 pPager->nRec = 0;
49584 if( rc==SQLITE_OK ){
49585 if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
49586 sqlite3PcacheCleanAll(pPager->pPCache);
49587 }else{
49588 sqlite3PcacheClearWritable(pPager->pPCache);
49590 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
49593 if( pagerUseWal(pPager) ){
49594 /* Drop the WAL write-lock, if any. Also, if the connection was in
49595 ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
49596 ** lock held on the database file.
49598 rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
49599 assert( rc2==SQLITE_OK );
49600 }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
49601 /* This branch is taken when committing a transaction in rollback-journal
49602 ** mode if the database file on disk is larger than the database image.
49603 ** At this point the journal has been finalized and the transaction
49604 ** successfully committed, but the EXCLUSIVE lock is still held on the
49605 ** file. So it is safe to truncate the database file to its minimum
49606 ** required size. */
49607 assert( pPager->eLock==EXCLUSIVE_LOCK );
49608 rc = pager_truncate(pPager, pPager->dbSize);
49611 if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
49612 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
49613 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
49616 if( !pPager->exclusiveMode
49617 && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
49619 rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
49620 pPager->changeCountDone = 0;
49622 pPager->eState = PAGER_READER;
49623 pPager->setMaster = 0;
49625 return (rc==SQLITE_OK?rc2:rc);
49629 ** Execute a rollback if a transaction is active and unlock the
49630 ** database file.
49632 ** If the pager has already entered the ERROR state, do not attempt
49633 ** the rollback at this time. Instead, pager_unlock() is called. The
49634 ** call to pager_unlock() will discard all in-memory pages, unlock
49635 ** the database file and move the pager back to OPEN state. If this
49636 ** means that there is a hot-journal left in the file-system, the next
49637 ** connection to obtain a shared lock on the pager (which may be this one)
49638 ** will roll it back.
49640 ** If the pager has not already entered the ERROR state, but an IO or
49641 ** malloc error occurs during a rollback, then this will itself cause
49642 ** the pager to enter the ERROR state. Which will be cleared by the
49643 ** call to pager_unlock(), as described above.
49645 static void pagerUnlockAndRollback(Pager *pPager){
49646 if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
49647 assert( assert_pager_state(pPager) );
49648 if( pPager->eState>=PAGER_WRITER_LOCKED ){
49649 sqlite3BeginBenignMalloc();
49650 sqlite3PagerRollback(pPager);
49651 sqlite3EndBenignMalloc();
49652 }else if( !pPager->exclusiveMode ){
49653 assert( pPager->eState==PAGER_READER );
49654 pager_end_transaction(pPager, 0, 0);
49657 pager_unlock(pPager);
49661 ** Parameter aData must point to a buffer of pPager->pageSize bytes
49662 ** of data. Compute and return a checksum based ont the contents of the
49663 ** page of data and the current value of pPager->cksumInit.
49665 ** This is not a real checksum. It is really just the sum of the
49666 ** random initial value (pPager->cksumInit) and every 200th byte
49667 ** of the page data, starting with byte offset (pPager->pageSize%200).
49668 ** Each byte is interpreted as an 8-bit unsigned integer.
49670 ** Changing the formula used to compute this checksum results in an
49671 ** incompatible journal file format.
49673 ** If journal corruption occurs due to a power failure, the most likely
49674 ** scenario is that one end or the other of the record will be changed.
49675 ** It is much less likely that the two ends of the journal record will be
49676 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
49677 ** though fast and simple, catches the mostly likely kind of corruption.
49679 static u32 pager_cksum(Pager *pPager, const u8 *aData){
49680 u32 cksum = pPager->cksumInit; /* Checksum value to return */
49681 int i = pPager->pageSize-200; /* Loop counter */
49682 while( i>0 ){
49683 cksum += aData[i];
49684 i -= 200;
49686 return cksum;
49690 ** Report the current page size and number of reserved bytes back
49691 ** to the codec.
49693 #ifdef SQLITE_HAS_CODEC
49694 static void pagerReportSize(Pager *pPager){
49695 if( pPager->xCodecSizeChng ){
49696 pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
49697 (int)pPager->nReserve);
49700 #else
49701 # define pagerReportSize(X) /* No-op if we do not support a codec */
49702 #endif
49704 #ifdef SQLITE_HAS_CODEC
49706 ** Make sure the number of reserved bits is the same in the destination
49707 ** pager as it is in the source. This comes up when a VACUUM changes the
49708 ** number of reserved bits to the "optimal" amount.
49710 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
49711 if( pDest->nReserve!=pSrc->nReserve ){
49712 pDest->nReserve = pSrc->nReserve;
49713 pagerReportSize(pDest);
49716 #endif
49719 ** Read a single page from either the journal file (if isMainJrnl==1) or
49720 ** from the sub-journal (if isMainJrnl==0) and playback that page.
49721 ** The page begins at offset *pOffset into the file. The *pOffset
49722 ** value is increased to the start of the next page in the journal.
49724 ** The main rollback journal uses checksums - the statement journal does
49725 ** not.
49727 ** If the page number of the page record read from the (sub-)journal file
49728 ** is greater than the current value of Pager.dbSize, then playback is
49729 ** skipped and SQLITE_OK is returned.
49731 ** If pDone is not NULL, then it is a record of pages that have already
49732 ** been played back. If the page at *pOffset has already been played back
49733 ** (if the corresponding pDone bit is set) then skip the playback.
49734 ** Make sure the pDone bit corresponding to the *pOffset page is set
49735 ** prior to returning.
49737 ** If the page record is successfully read from the (sub-)journal file
49738 ** and played back, then SQLITE_OK is returned. If an IO error occurs
49739 ** while reading the record from the (sub-)journal file or while writing
49740 ** to the database file, then the IO error code is returned. If data
49741 ** is successfully read from the (sub-)journal file but appears to be
49742 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
49743 ** two circumstances:
49745 ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
49746 ** * If the record is being rolled back from the main journal file
49747 ** and the checksum field does not match the record content.
49749 ** Neither of these two scenarios are possible during a savepoint rollback.
49751 ** If this is a savepoint rollback, then memory may have to be dynamically
49752 ** allocated by this function. If this is the case and an allocation fails,
49753 ** SQLITE_NOMEM is returned.
49755 static int pager_playback_one_page(
49756 Pager *pPager, /* The pager being played back */
49757 i64 *pOffset, /* Offset of record to playback */
49758 Bitvec *pDone, /* Bitvec of pages already played back */
49759 int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
49760 int isSavepnt /* True for a savepoint rollback */
49762 int rc;
49763 PgHdr *pPg; /* An existing page in the cache */
49764 Pgno pgno; /* The page number of a page in journal */
49765 u32 cksum; /* Checksum used for sanity checking */
49766 char *aData; /* Temporary storage for the page */
49767 sqlite3_file *jfd; /* The file descriptor for the journal file */
49768 int isSynced; /* True if journal page is synced */
49769 #ifdef SQLITE_HAS_CODEC
49770 /* The jrnlEnc flag is true if Journal pages should be passed through
49771 ** the codec. It is false for pure in-memory journals. */
49772 const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
49773 #endif
49775 assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
49776 assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
49777 assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
49778 assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
49780 aData = pPager->pTmpSpace;
49781 assert( aData ); /* Temp storage must have already been allocated */
49782 assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
49784 /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
49785 ** or savepoint rollback done at the request of the caller) or this is
49786 ** a hot-journal rollback. If it is a hot-journal rollback, the pager
49787 ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
49788 ** only reads from the main journal, not the sub-journal.
49790 assert( pPager->eState>=PAGER_WRITER_CACHEMOD
49791 || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
49793 assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
49795 /* Read the page number and page data from the journal or sub-journal
49796 ** file. Return an error code to the caller if an IO error occurs.
49798 jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
49799 rc = read32bits(jfd, *pOffset, &pgno);
49800 if( rc!=SQLITE_OK ) return rc;
49801 rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
49802 if( rc!=SQLITE_OK ) return rc;
49803 *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
49805 /* Sanity checking on the page. This is more important that I originally
49806 ** thought. If a power failure occurs while the journal is being written,
49807 ** it could cause invalid data to be written into the journal. We need to
49808 ** detect this invalid data (with high probability) and ignore it.
49810 if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
49811 assert( !isSavepnt );
49812 return SQLITE_DONE;
49814 if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
49815 return SQLITE_OK;
49817 if( isMainJrnl ){
49818 rc = read32bits(jfd, (*pOffset)-4, &cksum);
49819 if( rc ) return rc;
49820 if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
49821 return SQLITE_DONE;
49825 /* If this page has already been played back before during the current
49826 ** rollback, then don't bother to play it back again.
49828 if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
49829 return rc;
49832 /* When playing back page 1, restore the nReserve setting
49834 if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
49835 pPager->nReserve = ((u8*)aData)[20];
49836 pagerReportSize(pPager);
49839 /* If the pager is in CACHEMOD state, then there must be a copy of this
49840 ** page in the pager cache. In this case just update the pager cache,
49841 ** not the database file. The page is left marked dirty in this case.
49843 ** An exception to the above rule: If the database is in no-sync mode
49844 ** and a page is moved during an incremental vacuum then the page may
49845 ** not be in the pager cache. Later: if a malloc() or IO error occurs
49846 ** during a Movepage() call, then the page may not be in the cache
49847 ** either. So the condition described in the above paragraph is not
49848 ** assert()able.
49850 ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
49851 ** pager cache if it exists and the main file. The page is then marked
49852 ** not dirty. Since this code is only executed in PAGER_OPEN state for
49853 ** a hot-journal rollback, it is guaranteed that the page-cache is empty
49854 ** if the pager is in OPEN state.
49856 ** Ticket #1171: The statement journal might contain page content that is
49857 ** different from the page content at the start of the transaction.
49858 ** This occurs when a page is changed prior to the start of a statement
49859 ** then changed again within the statement. When rolling back such a
49860 ** statement we must not write to the original database unless we know
49861 ** for certain that original page contents are synced into the main rollback
49862 ** journal. Otherwise, a power loss might leave modified data in the
49863 ** database file without an entry in the rollback journal that can
49864 ** restore the database to its original form. Two conditions must be
49865 ** met before writing to the database files. (1) the database must be
49866 ** locked. (2) we know that the original page content is fully synced
49867 ** in the main journal either because the page is not in cache or else
49868 ** the page is marked as needSync==0.
49870 ** 2008-04-14: When attempting to vacuum a corrupt database file, it
49871 ** is possible to fail a statement on a database that does not yet exist.
49872 ** Do not attempt to write if database file has never been opened.
49874 if( pagerUseWal(pPager) ){
49875 pPg = 0;
49876 }else{
49877 pPg = sqlite3PagerLookup(pPager, pgno);
49879 assert( pPg || !MEMDB );
49880 assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
49881 PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
49882 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
49883 (isMainJrnl?"main-journal":"sub-journal")
49885 if( isMainJrnl ){
49886 isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
49887 }else{
49888 isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
49890 if( isOpen(pPager->fd)
49891 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
49892 && isSynced
49894 i64 ofst = (pgno-1)*(i64)pPager->pageSize;
49895 testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
49896 assert( !pagerUseWal(pPager) );
49898 /* Write the data read from the journal back into the database file.
49899 ** This is usually safe even for an encrypted database - as the data
49900 ** was encrypted before it was written to the journal file. The exception
49901 ** is if the data was just read from an in-memory sub-journal. In that
49902 ** case it must be encrypted here before it is copied into the database
49903 ** file. */
49904 #ifdef SQLITE_HAS_CODEC
49905 if( !jrnlEnc ){
49906 CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
49907 rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
49908 CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
49909 }else
49910 #endif
49911 rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
49913 if( pgno>pPager->dbFileSize ){
49914 pPager->dbFileSize = pgno;
49916 if( pPager->pBackup ){
49917 #ifdef SQLITE_HAS_CODEC
49918 if( jrnlEnc ){
49919 CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
49920 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
49921 CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
49922 }else
49923 #endif
49924 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
49926 }else if( !isMainJrnl && pPg==0 ){
49927 /* If this is a rollback of a savepoint and data was not written to
49928 ** the database and the page is not in-memory, there is a potential
49929 ** problem. When the page is next fetched by the b-tree layer, it
49930 ** will be read from the database file, which may or may not be
49931 ** current.
49933 ** There are a couple of different ways this can happen. All are quite
49934 ** obscure. When running in synchronous mode, this can only happen
49935 ** if the page is on the free-list at the start of the transaction, then
49936 ** populated, then moved using sqlite3PagerMovepage().
49938 ** The solution is to add an in-memory page to the cache containing
49939 ** the data just read from the sub-journal. Mark the page as dirty
49940 ** and if the pager requires a journal-sync, then mark the page as
49941 ** requiring a journal-sync before it is written.
49943 assert( isSavepnt );
49944 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
49945 pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
49946 rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
49947 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
49948 pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
49949 if( rc!=SQLITE_OK ) return rc;
49950 sqlite3PcacheMakeDirty(pPg);
49952 if( pPg ){
49953 /* No page should ever be explicitly rolled back that is in use, except
49954 ** for page 1 which is held in use in order to keep the lock on the
49955 ** database active. However such a page may be rolled back as a result
49956 ** of an internal error resulting in an automatic call to
49957 ** sqlite3PagerRollback().
49959 void *pData;
49960 pData = pPg->pData;
49961 memcpy(pData, (u8*)aData, pPager->pageSize);
49962 pPager->xReiniter(pPg);
49963 /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
49964 ** that call was dangerous and had no detectable benefit since the cache
49965 ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
49966 ** has been removed. */
49967 pager_set_pagehash(pPg);
49969 /* If this was page 1, then restore the value of Pager.dbFileVers.
49970 ** Do this before any decoding. */
49971 if( pgno==1 ){
49972 memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
49975 /* Decode the page just read from disk */
49976 #if SQLITE_HAS_CODEC
49977 if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
49978 #endif
49979 sqlite3PcacheRelease(pPg);
49981 return rc;
49985 ** Parameter zMaster is the name of a master journal file. A single journal
49986 ** file that referred to the master journal file has just been rolled back.
49987 ** This routine checks if it is possible to delete the master journal file,
49988 ** and does so if it is.
49990 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
49991 ** available for use within this function.
49993 ** When a master journal file is created, it is populated with the names
49994 ** of all of its child journals, one after another, formatted as utf-8
49995 ** encoded text. The end of each child journal file is marked with a
49996 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
49997 ** file for a transaction involving two databases might be:
49999 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
50001 ** A master journal file may only be deleted once all of its child
50002 ** journals have been rolled back.
50004 ** This function reads the contents of the master-journal file into
50005 ** memory and loops through each of the child journal names. For
50006 ** each child journal, it checks if:
50008 ** * if the child journal exists, and if so
50009 ** * if the child journal contains a reference to master journal
50010 ** file zMaster
50012 ** If a child journal can be found that matches both of the criteria
50013 ** above, this function returns without doing anything. Otherwise, if
50014 ** no such child journal can be found, file zMaster is deleted from
50015 ** the file-system using sqlite3OsDelete().
50017 ** If an IO error within this function, an error code is returned. This
50018 ** function allocates memory by calling sqlite3Malloc(). If an allocation
50019 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
50020 ** occur, SQLITE_OK is returned.
50022 ** TODO: This function allocates a single block of memory to load
50023 ** the entire contents of the master journal file. This could be
50024 ** a couple of kilobytes or so - potentially larger than the page
50025 ** size.
50027 static int pager_delmaster(Pager *pPager, const char *zMaster){
50028 sqlite3_vfs *pVfs = pPager->pVfs;
50029 int rc; /* Return code */
50030 sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
50031 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
50032 char *zMasterJournal = 0; /* Contents of master journal file */
50033 i64 nMasterJournal; /* Size of master journal file */
50034 char *zJournal; /* Pointer to one journal within MJ file */
50035 char *zMasterPtr; /* Space to hold MJ filename from a journal file */
50036 int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
50038 /* Allocate space for both the pJournal and pMaster file descriptors.
50039 ** If successful, open the master journal file for reading.
50041 pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
50042 pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
50043 if( !pMaster ){
50044 rc = SQLITE_NOMEM_BKPT;
50045 }else{
50046 const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
50047 rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
50049 if( rc!=SQLITE_OK ) goto delmaster_out;
50051 /* Load the entire master journal file into space obtained from
50052 ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
50053 ** sufficient space (in zMasterPtr) to hold the names of master
50054 ** journal files extracted from regular rollback-journals.
50056 rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
50057 if( rc!=SQLITE_OK ) goto delmaster_out;
50058 nMasterPtr = pVfs->mxPathname+1;
50059 zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
50060 if( !zMasterJournal ){
50061 rc = SQLITE_NOMEM_BKPT;
50062 goto delmaster_out;
50064 zMasterPtr = &zMasterJournal[nMasterJournal+1];
50065 rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
50066 if( rc!=SQLITE_OK ) goto delmaster_out;
50067 zMasterJournal[nMasterJournal] = 0;
50069 zJournal = zMasterJournal;
50070 while( (zJournal-zMasterJournal)<nMasterJournal ){
50071 int exists;
50072 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
50073 if( rc!=SQLITE_OK ){
50074 goto delmaster_out;
50076 if( exists ){
50077 /* One of the journals pointed to by the master journal exists.
50078 ** Open it and check if it points at the master journal. If
50079 ** so, return without deleting the master journal file.
50081 int c;
50082 int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
50083 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
50084 if( rc!=SQLITE_OK ){
50085 goto delmaster_out;
50088 rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
50089 sqlite3OsClose(pJournal);
50090 if( rc!=SQLITE_OK ){
50091 goto delmaster_out;
50094 c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
50095 if( c ){
50096 /* We have a match. Do not delete the master journal file. */
50097 goto delmaster_out;
50100 zJournal += (sqlite3Strlen30(zJournal)+1);
50103 sqlite3OsClose(pMaster);
50104 rc = sqlite3OsDelete(pVfs, zMaster, 0);
50106 delmaster_out:
50107 sqlite3_free(zMasterJournal);
50108 if( pMaster ){
50109 sqlite3OsClose(pMaster);
50110 assert( !isOpen(pJournal) );
50111 sqlite3_free(pMaster);
50113 return rc;
50118 ** This function is used to change the actual size of the database
50119 ** file in the file-system. This only happens when committing a transaction,
50120 ** or rolling back a transaction (including rolling back a hot-journal).
50122 ** If the main database file is not open, or the pager is not in either
50123 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
50124 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
50125 ** If the file on disk is currently larger than nPage pages, then use the VFS
50126 ** xTruncate() method to truncate it.
50128 ** Or, it might be the case that the file on disk is smaller than
50129 ** nPage pages. Some operating system implementations can get confused if
50130 ** you try to truncate a file to some size that is larger than it
50131 ** currently is, so detect this case and write a single zero byte to
50132 ** the end of the new file instead.
50134 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
50135 ** the database file, return the error code to the caller.
50137 static int pager_truncate(Pager *pPager, Pgno nPage){
50138 int rc = SQLITE_OK;
50139 assert( pPager->eState!=PAGER_ERROR );
50140 assert( pPager->eState!=PAGER_READER );
50142 if( isOpen(pPager->fd)
50143 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
50145 i64 currentSize, newSize;
50146 int szPage = pPager->pageSize;
50147 assert( pPager->eLock==EXCLUSIVE_LOCK );
50148 /* TODO: Is it safe to use Pager.dbFileSize here? */
50149 rc = sqlite3OsFileSize(pPager->fd, &currentSize);
50150 newSize = szPage*(i64)nPage;
50151 if( rc==SQLITE_OK && currentSize!=newSize ){
50152 if( currentSize>newSize ){
50153 rc = sqlite3OsTruncate(pPager->fd, newSize);
50154 }else if( (currentSize+szPage)<=newSize ){
50155 char *pTmp = pPager->pTmpSpace;
50156 memset(pTmp, 0, szPage);
50157 testcase( (newSize-szPage) == currentSize );
50158 testcase( (newSize-szPage) > currentSize );
50159 rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
50161 if( rc==SQLITE_OK ){
50162 pPager->dbFileSize = nPage;
50166 return rc;
50170 ** Return a sanitized version of the sector-size of OS file pFile. The
50171 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
50173 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
50174 int iRet = sqlite3OsSectorSize(pFile);
50175 if( iRet<32 ){
50176 iRet = 512;
50177 }else if( iRet>MAX_SECTOR_SIZE ){
50178 assert( MAX_SECTOR_SIZE>=512 );
50179 iRet = MAX_SECTOR_SIZE;
50181 return iRet;
50185 ** Set the value of the Pager.sectorSize variable for the given
50186 ** pager based on the value returned by the xSectorSize method
50187 ** of the open database file. The sector size will be used
50188 ** to determine the size and alignment of journal header and
50189 ** master journal pointers within created journal files.
50191 ** For temporary files the effective sector size is always 512 bytes.
50193 ** Otherwise, for non-temporary files, the effective sector size is
50194 ** the value returned by the xSectorSize() method rounded up to 32 if
50195 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
50196 ** is greater than MAX_SECTOR_SIZE.
50198 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
50199 ** the effective sector size to its minimum value (512). The purpose of
50200 ** pPager->sectorSize is to define the "blast radius" of bytes that
50201 ** might change if a crash occurs while writing to a single byte in
50202 ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
50203 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
50204 ** size. For backwards compatibility of the rollback journal file format,
50205 ** we cannot reduce the effective sector size below 512.
50207 static void setSectorSize(Pager *pPager){
50208 assert( isOpen(pPager->fd) || pPager->tempFile );
50210 if( pPager->tempFile
50211 || (sqlite3OsDeviceCharacteristics(pPager->fd) &
50212 SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
50214 /* Sector size doesn't matter for temporary files. Also, the file
50215 ** may not have been opened yet, in which case the OsSectorSize()
50216 ** call will segfault. */
50217 pPager->sectorSize = 512;
50218 }else{
50219 pPager->sectorSize = sqlite3SectorSize(pPager->fd);
50224 ** Playback the journal and thus restore the database file to
50225 ** the state it was in before we started making changes.
50227 ** The journal file format is as follows:
50229 ** (1) 8 byte prefix. A copy of aJournalMagic[].
50230 ** (2) 4 byte big-endian integer which is the number of valid page records
50231 ** in the journal. If this value is 0xffffffff, then compute the
50232 ** number of page records from the journal size.
50233 ** (3) 4 byte big-endian integer which is the initial value for the
50234 ** sanity checksum.
50235 ** (4) 4 byte integer which is the number of pages to truncate the
50236 ** database to during a rollback.
50237 ** (5) 4 byte big-endian integer which is the sector size. The header
50238 ** is this many bytes in size.
50239 ** (6) 4 byte big-endian integer which is the page size.
50240 ** (7) zero padding out to the next sector size.
50241 ** (8) Zero or more pages instances, each as follows:
50242 ** + 4 byte page number.
50243 ** + pPager->pageSize bytes of data.
50244 ** + 4 byte checksum
50246 ** When we speak of the journal header, we mean the first 7 items above.
50247 ** Each entry in the journal is an instance of the 8th item.
50249 ** Call the value from the second bullet "nRec". nRec is the number of
50250 ** valid page entries in the journal. In most cases, you can compute the
50251 ** value of nRec from the size of the journal file. But if a power
50252 ** failure occurred while the journal was being written, it could be the
50253 ** case that the size of the journal file had already been increased but
50254 ** the extra entries had not yet made it safely to disk. In such a case,
50255 ** the value of nRec computed from the file size would be too large. For
50256 ** that reason, we always use the nRec value in the header.
50258 ** If the nRec value is 0xffffffff it means that nRec should be computed
50259 ** from the file size. This value is used when the user selects the
50260 ** no-sync option for the journal. A power failure could lead to corruption
50261 ** in this case. But for things like temporary table (which will be
50262 ** deleted when the power is restored) we don't care.
50264 ** If the file opened as the journal file is not a well-formed
50265 ** journal file then all pages up to the first corrupted page are rolled
50266 ** back (or no pages if the journal header is corrupted). The journal file
50267 ** is then deleted and SQLITE_OK returned, just as if no corruption had
50268 ** been encountered.
50270 ** If an I/O or malloc() error occurs, the journal-file is not deleted
50271 ** and an error code is returned.
50273 ** The isHot parameter indicates that we are trying to rollback a journal
50274 ** that might be a hot journal. Or, it could be that the journal is
50275 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
50276 ** If the journal really is hot, reset the pager cache prior rolling
50277 ** back any content. If the journal is merely persistent, no reset is
50278 ** needed.
50280 static int pager_playback(Pager *pPager, int isHot){
50281 sqlite3_vfs *pVfs = pPager->pVfs;
50282 i64 szJ; /* Size of the journal file in bytes */
50283 u32 nRec; /* Number of Records in the journal */
50284 u32 u; /* Unsigned loop counter */
50285 Pgno mxPg = 0; /* Size of the original file in pages */
50286 int rc; /* Result code of a subroutine */
50287 int res = 1; /* Value returned by sqlite3OsAccess() */
50288 char *zMaster = 0; /* Name of master journal file if any */
50289 int needPagerReset; /* True to reset page prior to first page rollback */
50290 int nPlayback = 0; /* Total number of pages restored from journal */
50291 u32 savedPageSize = pPager->pageSize;
50293 /* Figure out how many records are in the journal. Abort early if
50294 ** the journal is empty.
50296 assert( isOpen(pPager->jfd) );
50297 rc = sqlite3OsFileSize(pPager->jfd, &szJ);
50298 if( rc!=SQLITE_OK ){
50299 goto end_playback;
50302 /* Read the master journal name from the journal, if it is present.
50303 ** If a master journal file name is specified, but the file is not
50304 ** present on disk, then the journal is not hot and does not need to be
50305 ** played back.
50307 ** TODO: Technically the following is an error because it assumes that
50308 ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
50309 ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
50310 ** mxPathname is 512, which is the same as the minimum allowable value
50311 ** for pageSize.
50313 zMaster = pPager->pTmpSpace;
50314 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
50315 if( rc==SQLITE_OK && zMaster[0] ){
50316 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
50318 zMaster = 0;
50319 if( rc!=SQLITE_OK || !res ){
50320 goto end_playback;
50322 pPager->journalOff = 0;
50323 needPagerReset = isHot;
50325 /* This loop terminates either when a readJournalHdr() or
50326 ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
50327 ** occurs.
50329 while( 1 ){
50330 /* Read the next journal header from the journal file. If there are
50331 ** not enough bytes left in the journal file for a complete header, or
50332 ** it is corrupted, then a process must have failed while writing it.
50333 ** This indicates nothing more needs to be rolled back.
50335 rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
50336 if( rc!=SQLITE_OK ){
50337 if( rc==SQLITE_DONE ){
50338 rc = SQLITE_OK;
50340 goto end_playback;
50343 /* If nRec is 0xffffffff, then this journal was created by a process
50344 ** working in no-sync mode. This means that the rest of the journal
50345 ** file consists of pages, there are no more journal headers. Compute
50346 ** the value of nRec based on this assumption.
50348 if( nRec==0xffffffff ){
50349 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
50350 nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
50353 /* If nRec is 0 and this rollback is of a transaction created by this
50354 ** process and if this is the final header in the journal, then it means
50355 ** that this part of the journal was being filled but has not yet been
50356 ** synced to disk. Compute the number of pages based on the remaining
50357 ** size of the file.
50359 ** The third term of the test was added to fix ticket #2565.
50360 ** When rolling back a hot journal, nRec==0 always means that the next
50361 ** chunk of the journal contains zero pages to be rolled back. But
50362 ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
50363 ** the journal, it means that the journal might contain additional
50364 ** pages that need to be rolled back and that the number of pages
50365 ** should be computed based on the journal file size.
50367 if( nRec==0 && !isHot &&
50368 pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
50369 nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
50372 /* If this is the first header read from the journal, truncate the
50373 ** database file back to its original size.
50375 if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
50376 rc = pager_truncate(pPager, mxPg);
50377 if( rc!=SQLITE_OK ){
50378 goto end_playback;
50380 pPager->dbSize = mxPg;
50383 /* Copy original pages out of the journal and back into the
50384 ** database file and/or page cache.
50386 for(u=0; u<nRec; u++){
50387 if( needPagerReset ){
50388 pager_reset(pPager);
50389 needPagerReset = 0;
50391 rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
50392 if( rc==SQLITE_OK ){
50393 nPlayback++;
50394 }else{
50395 if( rc==SQLITE_DONE ){
50396 pPager->journalOff = szJ;
50397 break;
50398 }else if( rc==SQLITE_IOERR_SHORT_READ ){
50399 /* If the journal has been truncated, simply stop reading and
50400 ** processing the journal. This might happen if the journal was
50401 ** not completely written and synced prior to a crash. In that
50402 ** case, the database should have never been written in the
50403 ** first place so it is OK to simply abandon the rollback. */
50404 rc = SQLITE_OK;
50405 goto end_playback;
50406 }else{
50407 /* If we are unable to rollback, quit and return the error
50408 ** code. This will cause the pager to enter the error state
50409 ** so that no further harm will be done. Perhaps the next
50410 ** process to come along will be able to rollback the database.
50412 goto end_playback;
50417 /*NOTREACHED*/
50418 assert( 0 );
50420 end_playback:
50421 if( rc==SQLITE_OK ){
50422 rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
50424 /* Following a rollback, the database file should be back in its original
50425 ** state prior to the start of the transaction, so invoke the
50426 ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
50427 ** assertion that the transaction counter was modified.
50429 #ifdef SQLITE_DEBUG
50430 if( pPager->fd->pMethods ){
50431 sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
50433 #endif
50435 /* If this playback is happening automatically as a result of an IO or
50436 ** malloc error that occurred after the change-counter was updated but
50437 ** before the transaction was committed, then the change-counter
50438 ** modification may just have been reverted. If this happens in exclusive
50439 ** mode, then subsequent transactions performed by the connection will not
50440 ** update the change-counter at all. This may lead to cache inconsistency
50441 ** problems for other processes at some point in the future. So, just
50442 ** in case this has happened, clear the changeCountDone flag now.
50444 pPager->changeCountDone = pPager->tempFile;
50446 if( rc==SQLITE_OK ){
50447 zMaster = pPager->pTmpSpace;
50448 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
50449 testcase( rc!=SQLITE_OK );
50451 if( rc==SQLITE_OK
50452 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
50454 rc = sqlite3PagerSync(pPager, 0);
50456 if( rc==SQLITE_OK ){
50457 rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
50458 testcase( rc!=SQLITE_OK );
50460 if( rc==SQLITE_OK && zMaster[0] && res ){
50461 /* If there was a master journal and this routine will return success,
50462 ** see if it is possible to delete the master journal.
50464 rc = pager_delmaster(pPager, zMaster);
50465 testcase( rc!=SQLITE_OK );
50467 if( isHot && nPlayback ){
50468 sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
50469 nPlayback, pPager->zJournal);
50472 /* The Pager.sectorSize variable may have been updated while rolling
50473 ** back a journal created by a process with a different sector size
50474 ** value. Reset it to the correct value for this process.
50476 setSectorSize(pPager);
50477 return rc;
50482 ** Read the content for page pPg out of the database file (or out of
50483 ** the WAL if that is where the most recent copy if found) into
50484 ** pPg->pData. A shared lock or greater must be held on the database
50485 ** file before this function is called.
50487 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
50488 ** the value read from the database file.
50490 ** If an IO error occurs, then the IO error is returned to the caller.
50491 ** Otherwise, SQLITE_OK is returned.
50493 static int readDbPage(PgHdr *pPg){
50494 Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
50495 int rc = SQLITE_OK; /* Return code */
50497 #ifndef SQLITE_OMIT_WAL
50498 u32 iFrame = 0; /* Frame of WAL containing pgno */
50500 assert( pPager->eState>=PAGER_READER && !MEMDB );
50501 assert( isOpen(pPager->fd) );
50503 if( pagerUseWal(pPager) ){
50504 rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
50505 if( rc ) return rc;
50507 if( iFrame ){
50508 rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
50509 }else
50510 #endif
50512 i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
50513 rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
50514 if( rc==SQLITE_IOERR_SHORT_READ ){
50515 rc = SQLITE_OK;
50519 if( pPg->pgno==1 ){
50520 if( rc ){
50521 /* If the read is unsuccessful, set the dbFileVers[] to something
50522 ** that will never be a valid file version. dbFileVers[] is a copy
50523 ** of bytes 24..39 of the database. Bytes 28..31 should always be
50524 ** zero or the size of the database in page. Bytes 32..35 and 35..39
50525 ** should be page numbers which are never 0xffffffff. So filling
50526 ** pPager->dbFileVers[] with all 0xff bytes should suffice.
50528 ** For an encrypted database, the situation is more complex: bytes
50529 ** 24..39 of the database are white noise. But the probability of
50530 ** white noise equaling 16 bytes of 0xff is vanishingly small so
50531 ** we should still be ok.
50533 memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
50534 }else{
50535 u8 *dbFileVers = &((u8*)pPg->pData)[24];
50536 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
50539 CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
50541 PAGER_INCR(sqlite3_pager_readdb_count);
50542 PAGER_INCR(pPager->nRead);
50543 IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
50544 PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
50545 PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
50547 return rc;
50551 ** Update the value of the change-counter at offsets 24 and 92 in
50552 ** the header and the sqlite version number at offset 96.
50554 ** This is an unconditional update. See also the pager_incr_changecounter()
50555 ** routine which only updates the change-counter if the update is actually
50556 ** needed, as determined by the pPager->changeCountDone state variable.
50558 static void pager_write_changecounter(PgHdr *pPg){
50559 u32 change_counter;
50561 /* Increment the value just read and write it back to byte 24. */
50562 change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
50563 put32bits(((char*)pPg->pData)+24, change_counter);
50565 /* Also store the SQLite version number in bytes 96..99 and in
50566 ** bytes 92..95 store the change counter for which the version number
50567 ** is valid. */
50568 put32bits(((char*)pPg->pData)+92, change_counter);
50569 put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
50572 #ifndef SQLITE_OMIT_WAL
50574 ** This function is invoked once for each page that has already been
50575 ** written into the log file when a WAL transaction is rolled back.
50576 ** Parameter iPg is the page number of said page. The pCtx argument
50577 ** is actually a pointer to the Pager structure.
50579 ** If page iPg is present in the cache, and has no outstanding references,
50580 ** it is discarded. Otherwise, if there are one or more outstanding
50581 ** references, the page content is reloaded from the database. If the
50582 ** attempt to reload content from the database is required and fails,
50583 ** return an SQLite error code. Otherwise, SQLITE_OK.
50585 static int pagerUndoCallback(void *pCtx, Pgno iPg){
50586 int rc = SQLITE_OK;
50587 Pager *pPager = (Pager *)pCtx;
50588 PgHdr *pPg;
50590 assert( pagerUseWal(pPager) );
50591 pPg = sqlite3PagerLookup(pPager, iPg);
50592 if( pPg ){
50593 if( sqlite3PcachePageRefcount(pPg)==1 ){
50594 sqlite3PcacheDrop(pPg);
50595 }else{
50596 rc = readDbPage(pPg);
50597 if( rc==SQLITE_OK ){
50598 pPager->xReiniter(pPg);
50600 sqlite3PagerUnrefNotNull(pPg);
50604 /* Normally, if a transaction is rolled back, any backup processes are
50605 ** updated as data is copied out of the rollback journal and into the
50606 ** database. This is not generally possible with a WAL database, as
50607 ** rollback involves simply truncating the log file. Therefore, if one
50608 ** or more frames have already been written to the log (and therefore
50609 ** also copied into the backup databases) as part of this transaction,
50610 ** the backups must be restarted.
50612 sqlite3BackupRestart(pPager->pBackup);
50614 return rc;
50618 ** This function is called to rollback a transaction on a WAL database.
50620 static int pagerRollbackWal(Pager *pPager){
50621 int rc; /* Return Code */
50622 PgHdr *pList; /* List of dirty pages to revert */
50624 /* For all pages in the cache that are currently dirty or have already
50625 ** been written (but not committed) to the log file, do one of the
50626 ** following:
50628 ** + Discard the cached page (if refcount==0), or
50629 ** + Reload page content from the database (if refcount>0).
50631 pPager->dbSize = pPager->dbOrigSize;
50632 rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
50633 pList = sqlite3PcacheDirtyList(pPager->pPCache);
50634 while( pList && rc==SQLITE_OK ){
50635 PgHdr *pNext = pList->pDirty;
50636 rc = pagerUndoCallback((void *)pPager, pList->pgno);
50637 pList = pNext;
50640 return rc;
50644 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
50645 ** the contents of the list of pages headed by pList (connected by pDirty),
50646 ** this function notifies any active backup processes that the pages have
50647 ** changed.
50649 ** The list of pages passed into this routine is always sorted by page number.
50650 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
50652 static int pagerWalFrames(
50653 Pager *pPager, /* Pager object */
50654 PgHdr *pList, /* List of frames to log */
50655 Pgno nTruncate, /* Database size after this commit */
50656 int isCommit /* True if this is a commit */
50658 int rc; /* Return code */
50659 int nList; /* Number of pages in pList */
50660 PgHdr *p; /* For looping over pages */
50662 assert( pPager->pWal );
50663 assert( pList );
50664 #ifdef SQLITE_DEBUG
50665 /* Verify that the page list is in accending order */
50666 for(p=pList; p && p->pDirty; p=p->pDirty){
50667 assert( p->pgno < p->pDirty->pgno );
50669 #endif
50671 assert( pList->pDirty==0 || isCommit );
50672 if( isCommit ){
50673 /* If a WAL transaction is being committed, there is no point in writing
50674 ** any pages with page numbers greater than nTruncate into the WAL file.
50675 ** They will never be read by any client. So remove them from the pDirty
50676 ** list here. */
50677 PgHdr **ppNext = &pList;
50678 nList = 0;
50679 for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
50680 if( p->pgno<=nTruncate ){
50681 ppNext = &p->pDirty;
50682 nList++;
50685 assert( pList );
50686 }else{
50687 nList = 1;
50689 pPager->aStat[PAGER_STAT_WRITE] += nList;
50691 if( pList->pgno==1 ) pager_write_changecounter(pList);
50692 rc = sqlite3WalFrames(pPager->pWal,
50693 pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
50695 if( rc==SQLITE_OK && pPager->pBackup ){
50696 for(p=pList; p; p=p->pDirty){
50697 sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
50701 #ifdef SQLITE_CHECK_PAGES
50702 pList = sqlite3PcacheDirtyList(pPager->pPCache);
50703 for(p=pList; p; p=p->pDirty){
50704 pager_set_pagehash(p);
50706 #endif
50708 return rc;
50712 ** Begin a read transaction on the WAL.
50714 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
50715 ** makes a snapshot of the database at the current point in time and preserves
50716 ** that snapshot for use by the reader in spite of concurrently changes by
50717 ** other writers or checkpointers.
50719 static int pagerBeginReadTransaction(Pager *pPager){
50720 int rc; /* Return code */
50721 int changed = 0; /* True if cache must be reset */
50723 assert( pagerUseWal(pPager) );
50724 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
50726 /* sqlite3WalEndReadTransaction() was not called for the previous
50727 ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
50728 ** are in locking_mode=NORMAL and EndRead() was previously called,
50729 ** the duplicate call is harmless.
50731 sqlite3WalEndReadTransaction(pPager->pWal);
50733 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
50734 if( rc!=SQLITE_OK || changed ){
50735 pager_reset(pPager);
50736 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
50739 return rc;
50741 #endif
50744 ** This function is called as part of the transition from PAGER_OPEN
50745 ** to PAGER_READER state to determine the size of the database file
50746 ** in pages (assuming the page size currently stored in Pager.pageSize).
50748 ** If no error occurs, SQLITE_OK is returned and the size of the database
50749 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
50750 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
50752 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
50753 Pgno nPage; /* Value to return via *pnPage */
50755 /* Query the WAL sub-system for the database size. The WalDbsize()
50756 ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
50757 ** if the database size is not available. The database size is not
50758 ** available from the WAL sub-system if the log file is empty or
50759 ** contains no valid committed transactions.
50761 assert( pPager->eState==PAGER_OPEN );
50762 assert( pPager->eLock>=SHARED_LOCK );
50763 assert( isOpen(pPager->fd) );
50764 assert( pPager->tempFile==0 );
50765 nPage = sqlite3WalDbsize(pPager->pWal);
50767 /* If the number of pages in the database is not available from the
50768 ** WAL sub-system, determine the page count based on the size of
50769 ** the database file. If the size of the database file is not an
50770 ** integer multiple of the page-size, round up the result.
50772 if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
50773 i64 n = 0; /* Size of db file in bytes */
50774 int rc = sqlite3OsFileSize(pPager->fd, &n);
50775 if( rc!=SQLITE_OK ){
50776 return rc;
50778 nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
50781 /* If the current number of pages in the file is greater than the
50782 ** configured maximum pager number, increase the allowed limit so
50783 ** that the file can be read.
50785 if( nPage>pPager->mxPgno ){
50786 pPager->mxPgno = (Pgno)nPage;
50789 *pnPage = nPage;
50790 return SQLITE_OK;
50793 #ifndef SQLITE_OMIT_WAL
50795 ** Check if the *-wal file that corresponds to the database opened by pPager
50796 ** exists if the database is not empy, or verify that the *-wal file does
50797 ** not exist (by deleting it) if the database file is empty.
50799 ** If the database is not empty and the *-wal file exists, open the pager
50800 ** in WAL mode. If the database is empty or if no *-wal file exists and
50801 ** if no error occurs, make sure Pager.journalMode is not set to
50802 ** PAGER_JOURNALMODE_WAL.
50804 ** Return SQLITE_OK or an error code.
50806 ** The caller must hold a SHARED lock on the database file to call this
50807 ** function. Because an EXCLUSIVE lock on the db file is required to delete
50808 ** a WAL on a none-empty database, this ensures there is no race condition
50809 ** between the xAccess() below and an xDelete() being executed by some
50810 ** other connection.
50812 static int pagerOpenWalIfPresent(Pager *pPager){
50813 int rc = SQLITE_OK;
50814 assert( pPager->eState==PAGER_OPEN );
50815 assert( pPager->eLock>=SHARED_LOCK );
50817 if( !pPager->tempFile ){
50818 int isWal; /* True if WAL file exists */
50819 rc = sqlite3OsAccess(
50820 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
50822 if( rc==SQLITE_OK ){
50823 if( isWal ){
50824 Pgno nPage; /* Size of the database file */
50826 rc = pagerPagecount(pPager, &nPage);
50827 if( rc ) return rc;
50828 if( nPage==0 ){
50829 rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
50830 }else{
50831 testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
50832 rc = sqlite3PagerOpenWal(pPager, 0);
50834 }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
50835 pPager->journalMode = PAGER_JOURNALMODE_DELETE;
50839 return rc;
50841 #endif
50844 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
50845 ** the entire master journal file. The case pSavepoint==NULL occurs when
50846 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
50847 ** savepoint.
50849 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
50850 ** being rolled back), then the rollback consists of up to three stages,
50851 ** performed in the order specified:
50853 ** * Pages are played back from the main journal starting at byte
50854 ** offset PagerSavepoint.iOffset and continuing to
50855 ** PagerSavepoint.iHdrOffset, or to the end of the main journal
50856 ** file if PagerSavepoint.iHdrOffset is zero.
50858 ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
50859 ** back starting from the journal header immediately following
50860 ** PagerSavepoint.iHdrOffset to the end of the main journal file.
50862 ** * Pages are then played back from the sub-journal file, starting
50863 ** with the PagerSavepoint.iSubRec and continuing to the end of
50864 ** the journal file.
50866 ** Throughout the rollback process, each time a page is rolled back, the
50867 ** corresponding bit is set in a bitvec structure (variable pDone in the
50868 ** implementation below). This is used to ensure that a page is only
50869 ** rolled back the first time it is encountered in either journal.
50871 ** If pSavepoint is NULL, then pages are only played back from the main
50872 ** journal file. There is no need for a bitvec in this case.
50874 ** In either case, before playback commences the Pager.dbSize variable
50875 ** is reset to the value that it held at the start of the savepoint
50876 ** (or transaction). No page with a page-number greater than this value
50877 ** is played back. If one is encountered it is simply skipped.
50879 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
50880 i64 szJ; /* Effective size of the main journal */
50881 i64 iHdrOff; /* End of first segment of main-journal records */
50882 int rc = SQLITE_OK; /* Return code */
50883 Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
50885 assert( pPager->eState!=PAGER_ERROR );
50886 assert( pPager->eState>=PAGER_WRITER_LOCKED );
50888 /* Allocate a bitvec to use to store the set of pages rolled back */
50889 if( pSavepoint ){
50890 pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
50891 if( !pDone ){
50892 return SQLITE_NOMEM_BKPT;
50896 /* Set the database size back to the value it was before the savepoint
50897 ** being reverted was opened.
50899 pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
50900 pPager->changeCountDone = pPager->tempFile;
50902 if( !pSavepoint && pagerUseWal(pPager) ){
50903 return pagerRollbackWal(pPager);
50906 /* Use pPager->journalOff as the effective size of the main rollback
50907 ** journal. The actual file might be larger than this in
50908 ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
50909 ** past pPager->journalOff is off-limits to us.
50911 szJ = pPager->journalOff;
50912 assert( pagerUseWal(pPager)==0 || szJ==0 );
50914 /* Begin by rolling back records from the main journal starting at
50915 ** PagerSavepoint.iOffset and continuing to the next journal header.
50916 ** There might be records in the main journal that have a page number
50917 ** greater than the current database size (pPager->dbSize) but those
50918 ** will be skipped automatically. Pages are added to pDone as they
50919 ** are played back.
50921 if( pSavepoint && !pagerUseWal(pPager) ){
50922 iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
50923 pPager->journalOff = pSavepoint->iOffset;
50924 while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
50925 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
50927 assert( rc!=SQLITE_DONE );
50928 }else{
50929 pPager->journalOff = 0;
50932 /* Continue rolling back records out of the main journal starting at
50933 ** the first journal header seen and continuing until the effective end
50934 ** of the main journal file. Continue to skip out-of-range pages and
50935 ** continue adding pages rolled back to pDone.
50937 while( rc==SQLITE_OK && pPager->journalOff<szJ ){
50938 u32 ii; /* Loop counter */
50939 u32 nJRec = 0; /* Number of Journal Records */
50940 u32 dummy;
50941 rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
50942 assert( rc!=SQLITE_DONE );
50945 ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
50946 ** test is related to ticket #2565. See the discussion in the
50947 ** pager_playback() function for additional information.
50949 if( nJRec==0
50950 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
50952 nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
50954 for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
50955 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
50957 assert( rc!=SQLITE_DONE );
50959 assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
50961 /* Finally, rollback pages from the sub-journal. Page that were
50962 ** previously rolled back out of the main journal (and are hence in pDone)
50963 ** will be skipped. Out-of-range pages are also skipped.
50965 if( pSavepoint ){
50966 u32 ii; /* Loop counter */
50967 i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
50969 if( pagerUseWal(pPager) ){
50970 rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
50972 for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
50973 assert( offset==(i64)ii*(4+pPager->pageSize) );
50974 rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
50976 assert( rc!=SQLITE_DONE );
50979 sqlite3BitvecDestroy(pDone);
50980 if( rc==SQLITE_OK ){
50981 pPager->journalOff = szJ;
50984 return rc;
50988 ** Change the maximum number of in-memory pages that are allowed
50989 ** before attempting to recycle clean and unused pages.
50991 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
50992 sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
50996 ** Change the maximum number of in-memory pages that are allowed
50997 ** before attempting to spill pages to journal.
50999 SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
51000 return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
51004 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
51006 static void pagerFixMaplimit(Pager *pPager){
51007 #if SQLITE_MAX_MMAP_SIZE>0
51008 sqlite3_file *fd = pPager->fd;
51009 if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
51010 sqlite3_int64 sz;
51011 sz = pPager->szMmap;
51012 pPager->bUseFetch = (sz>0);
51013 setGetterMethod(pPager);
51014 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
51016 #endif
51020 ** Change the maximum size of any memory mapping made of the database file.
51022 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
51023 pPager->szMmap = szMmap;
51024 pagerFixMaplimit(pPager);
51028 ** Free as much memory as possible from the pager.
51030 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
51031 sqlite3PcacheShrink(pPager->pPCache);
51035 ** Adjust settings of the pager to those specified in the pgFlags parameter.
51037 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
51038 ** of the database to damage due to OS crashes or power failures by
51039 ** changing the number of syncs()s when writing the journals.
51040 ** There are four levels:
51042 ** OFF sqlite3OsSync() is never called. This is the default
51043 ** for temporary and transient files.
51045 ** NORMAL The journal is synced once before writes begin on the
51046 ** database. This is normally adequate protection, but
51047 ** it is theoretically possible, though very unlikely,
51048 ** that an inopertune power failure could leave the journal
51049 ** in a state which would cause damage to the database
51050 ** when it is rolled back.
51052 ** FULL The journal is synced twice before writes begin on the
51053 ** database (with some additional information - the nRec field
51054 ** of the journal header - being written in between the two
51055 ** syncs). If we assume that writing a
51056 ** single disk sector is atomic, then this mode provides
51057 ** assurance that the journal will not be corrupted to the
51058 ** point of causing damage to the database during rollback.
51060 ** EXTRA This is like FULL except that is also syncs the directory
51061 ** that contains the rollback journal after the rollback
51062 ** journal is unlinked.
51064 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
51065 ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
51066 ** prior to the start of checkpoint and that the database file is synced
51067 ** at the conclusion of the checkpoint if the entire content of the WAL
51068 ** was written back into the database. But no sync operations occur for
51069 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
51070 ** file is synced following each commit operation, in addition to the
51071 ** syncs associated with NORMAL. There is no difference between FULL
51072 ** and EXTRA for WAL mode.
51074 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
51075 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
51076 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
51077 ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
51078 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
51079 ** synchronous=FULL versus synchronous=NORMAL setting determines when
51080 ** the xSync primitive is called and is relevant to all platforms.
51082 ** Numeric values associated with these states are OFF==1, NORMAL=2,
51083 ** and FULL=3.
51085 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
51086 SQLITE_PRIVATE void sqlite3PagerSetFlags(
51087 Pager *pPager, /* The pager to set safety level for */
51088 unsigned pgFlags /* Various flags */
51090 unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
51091 if( pPager->tempFile ){
51092 pPager->noSync = 1;
51093 pPager->fullSync = 0;
51094 pPager->extraSync = 0;
51095 }else{
51096 pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
51097 pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
51098 pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
51100 if( pPager->noSync ){
51101 pPager->syncFlags = 0;
51102 }else if( pgFlags & PAGER_FULLFSYNC ){
51103 pPager->syncFlags = SQLITE_SYNC_FULL;
51104 }else{
51105 pPager->syncFlags = SQLITE_SYNC_NORMAL;
51107 pPager->walSyncFlags = (pPager->syncFlags<<2);
51108 if( pPager->fullSync ){
51109 pPager->walSyncFlags |= pPager->syncFlags;
51111 if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
51112 pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
51114 if( pgFlags & PAGER_CACHESPILL ){
51115 pPager->doNotSpill &= ~SPILLFLAG_OFF;
51116 }else{
51117 pPager->doNotSpill |= SPILLFLAG_OFF;
51120 #endif
51123 ** The following global variable is incremented whenever the library
51124 ** attempts to open a temporary file. This information is used for
51125 ** testing and analysis only.
51127 #ifdef SQLITE_TEST
51128 SQLITE_API int sqlite3_opentemp_count = 0;
51129 #endif
51132 ** Open a temporary file.
51134 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
51135 ** or some other error code if we fail. The OS will automatically
51136 ** delete the temporary file when it is closed.
51138 ** The flags passed to the VFS layer xOpen() call are those specified
51139 ** by parameter vfsFlags ORed with the following:
51141 ** SQLITE_OPEN_READWRITE
51142 ** SQLITE_OPEN_CREATE
51143 ** SQLITE_OPEN_EXCLUSIVE
51144 ** SQLITE_OPEN_DELETEONCLOSE
51146 static int pagerOpentemp(
51147 Pager *pPager, /* The pager object */
51148 sqlite3_file *pFile, /* Write the file descriptor here */
51149 int vfsFlags /* Flags passed through to the VFS */
51151 int rc; /* Return code */
51153 #ifdef SQLITE_TEST
51154 sqlite3_opentemp_count++; /* Used for testing and analysis only */
51155 #endif
51157 vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
51158 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
51159 rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
51160 assert( rc!=SQLITE_OK || isOpen(pFile) );
51161 return rc;
51165 ** Set the busy handler function.
51167 ** The pager invokes the busy-handler if sqlite3OsLock() returns
51168 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
51169 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
51170 ** lock. It does *not* invoke the busy handler when upgrading from
51171 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
51172 ** (which occurs during hot-journal rollback). Summary:
51174 ** Transition | Invokes xBusyHandler
51175 ** --------------------------------------------------------
51176 ** NO_LOCK -> SHARED_LOCK | Yes
51177 ** SHARED_LOCK -> RESERVED_LOCK | No
51178 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
51179 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
51181 ** If the busy-handler callback returns non-zero, the lock is
51182 ** retried. If it returns zero, then the SQLITE_BUSY error is
51183 ** returned to the caller of the pager API function.
51185 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
51186 Pager *pPager, /* Pager object */
51187 int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
51188 void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
51190 pPager->xBusyHandler = xBusyHandler;
51191 pPager->pBusyHandlerArg = pBusyHandlerArg;
51193 if( isOpen(pPager->fd) ){
51194 void **ap = (void **)&pPager->xBusyHandler;
51195 assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
51196 assert( ap[1]==pBusyHandlerArg );
51197 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
51202 ** Change the page size used by the Pager object. The new page size
51203 ** is passed in *pPageSize.
51205 ** If the pager is in the error state when this function is called, it
51206 ** is a no-op. The value returned is the error state error code (i.e.
51207 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
51209 ** Otherwise, if all of the following are true:
51211 ** * the new page size (value of *pPageSize) is valid (a power
51212 ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
51214 ** * there are no outstanding page references, and
51216 ** * the database is either not an in-memory database or it is
51217 ** an in-memory database that currently consists of zero pages.
51219 ** then the pager object page size is set to *pPageSize.
51221 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
51222 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
51223 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
51224 ** In all other cases, SQLITE_OK is returned.
51226 ** If the page size is not changed, either because one of the enumerated
51227 ** conditions above is not true, the pager was in error state when this
51228 ** function was called, or because the memory allocation attempt failed,
51229 ** then *pPageSize is set to the old, retained page size before returning.
51231 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
51232 int rc = SQLITE_OK;
51234 /* It is not possible to do a full assert_pager_state() here, as this
51235 ** function may be called from within PagerOpen(), before the state
51236 ** of the Pager object is internally consistent.
51238 ** At one point this function returned an error if the pager was in
51239 ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
51240 ** there is at least one outstanding page reference, this function
51241 ** is a no-op for that case anyhow.
51244 u32 pageSize = *pPageSize;
51245 assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
51246 if( (pPager->memDb==0 || pPager->dbSize==0)
51247 && sqlite3PcacheRefCount(pPager->pPCache)==0
51248 && pageSize && pageSize!=(u32)pPager->pageSize
51250 char *pNew = NULL; /* New temp space */
51251 i64 nByte = 0;
51253 if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
51254 rc = sqlite3OsFileSize(pPager->fd, &nByte);
51256 if( rc==SQLITE_OK ){
51257 pNew = (char *)sqlite3PageMalloc(pageSize);
51258 if( !pNew ) rc = SQLITE_NOMEM_BKPT;
51261 if( rc==SQLITE_OK ){
51262 pager_reset(pPager);
51263 rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
51265 if( rc==SQLITE_OK ){
51266 sqlite3PageFree(pPager->pTmpSpace);
51267 pPager->pTmpSpace = pNew;
51268 pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
51269 pPager->pageSize = pageSize;
51270 }else{
51271 sqlite3PageFree(pNew);
51275 *pPageSize = pPager->pageSize;
51276 if( rc==SQLITE_OK ){
51277 if( nReserve<0 ) nReserve = pPager->nReserve;
51278 assert( nReserve>=0 && nReserve<1000 );
51279 pPager->nReserve = (i16)nReserve;
51280 pagerReportSize(pPager);
51281 pagerFixMaplimit(pPager);
51283 return rc;
51287 ** Return a pointer to the "temporary page" buffer held internally
51288 ** by the pager. This is a buffer that is big enough to hold the
51289 ** entire content of a database page. This buffer is used internally
51290 ** during rollback and will be overwritten whenever a rollback
51291 ** occurs. But other modules are free to use it too, as long as
51292 ** no rollbacks are happening.
51294 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
51295 return pPager->pTmpSpace;
51299 ** Attempt to set the maximum database page count if mxPage is positive.
51300 ** Make no changes if mxPage is zero or negative. And never reduce the
51301 ** maximum page count below the current size of the database.
51303 ** Regardless of mxPage, return the current maximum page count.
51305 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
51306 if( mxPage>0 ){
51307 pPager->mxPgno = mxPage;
51309 assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
51310 assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
51311 return pPager->mxPgno;
51315 ** The following set of routines are used to disable the simulated
51316 ** I/O error mechanism. These routines are used to avoid simulated
51317 ** errors in places where we do not care about errors.
51319 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
51320 ** and generate no code.
51322 #ifdef SQLITE_TEST
51323 SQLITE_API extern int sqlite3_io_error_pending;
51324 SQLITE_API extern int sqlite3_io_error_hit;
51325 static int saved_cnt;
51326 void disable_simulated_io_errors(void){
51327 saved_cnt = sqlite3_io_error_pending;
51328 sqlite3_io_error_pending = -1;
51330 void enable_simulated_io_errors(void){
51331 sqlite3_io_error_pending = saved_cnt;
51333 #else
51334 # define disable_simulated_io_errors()
51335 # define enable_simulated_io_errors()
51336 #endif
51339 ** Read the first N bytes from the beginning of the file into memory
51340 ** that pDest points to.
51342 ** If the pager was opened on a transient file (zFilename==""), or
51343 ** opened on a file less than N bytes in size, the output buffer is
51344 ** zeroed and SQLITE_OK returned. The rationale for this is that this
51345 ** function is used to read database headers, and a new transient or
51346 ** zero sized database has a header than consists entirely of zeroes.
51348 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
51349 ** the error code is returned to the caller and the contents of the
51350 ** output buffer undefined.
51352 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
51353 int rc = SQLITE_OK;
51354 memset(pDest, 0, N);
51355 assert( isOpen(pPager->fd) || pPager->tempFile );
51357 /* This routine is only called by btree immediately after creating
51358 ** the Pager object. There has not been an opportunity to transition
51359 ** to WAL mode yet.
51361 assert( !pagerUseWal(pPager) );
51363 if( isOpen(pPager->fd) ){
51364 IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
51365 rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
51366 if( rc==SQLITE_IOERR_SHORT_READ ){
51367 rc = SQLITE_OK;
51370 return rc;
51374 ** This function may only be called when a read-transaction is open on
51375 ** the pager. It returns the total number of pages in the database.
51377 ** However, if the file is between 1 and <page-size> bytes in size, then
51378 ** this is considered a 1 page file.
51380 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
51381 assert( pPager->eState>=PAGER_READER );
51382 assert( pPager->eState!=PAGER_WRITER_FINISHED );
51383 *pnPage = (int)pPager->dbSize;
51388 ** Try to obtain a lock of type locktype on the database file. If
51389 ** a similar or greater lock is already held, this function is a no-op
51390 ** (returning SQLITE_OK immediately).
51392 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
51393 ** the busy callback if the lock is currently not available. Repeat
51394 ** until the busy callback returns false or until the attempt to
51395 ** obtain the lock succeeds.
51397 ** Return SQLITE_OK on success and an error code if we cannot obtain
51398 ** the lock. If the lock is obtained successfully, set the Pager.state
51399 ** variable to locktype before returning.
51401 static int pager_wait_on_lock(Pager *pPager, int locktype){
51402 int rc; /* Return code */
51404 /* Check that this is either a no-op (because the requested lock is
51405 ** already held), or one of the transitions that the busy-handler
51406 ** may be invoked during, according to the comment above
51407 ** sqlite3PagerSetBusyhandler().
51409 assert( (pPager->eLock>=locktype)
51410 || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
51411 || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
51414 do {
51415 rc = pagerLockDb(pPager, locktype);
51416 }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
51417 return rc;
51421 ** Function assertTruncateConstraint(pPager) checks that one of the
51422 ** following is true for all dirty pages currently in the page-cache:
51424 ** a) The page number is less than or equal to the size of the
51425 ** current database image, in pages, OR
51427 ** b) if the page content were written at this time, it would not
51428 ** be necessary to write the current content out to the sub-journal
51429 ** (as determined by function subjRequiresPage()).
51431 ** If the condition asserted by this function were not true, and the
51432 ** dirty page were to be discarded from the cache via the pagerStress()
51433 ** routine, pagerStress() would not write the current page content to
51434 ** the database file. If a savepoint transaction were rolled back after
51435 ** this happened, the correct behavior would be to restore the current
51436 ** content of the page. However, since this content is not present in either
51437 ** the database file or the portion of the rollback journal and
51438 ** sub-journal rolled back the content could not be restored and the
51439 ** database image would become corrupt. It is therefore fortunate that
51440 ** this circumstance cannot arise.
51442 #if defined(SQLITE_DEBUG)
51443 static void assertTruncateConstraintCb(PgHdr *pPg){
51444 assert( pPg->flags&PGHDR_DIRTY );
51445 assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
51447 static void assertTruncateConstraint(Pager *pPager){
51448 sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
51450 #else
51451 # define assertTruncateConstraint(pPager)
51452 #endif
51455 ** Truncate the in-memory database file image to nPage pages. This
51456 ** function does not actually modify the database file on disk. It
51457 ** just sets the internal state of the pager object so that the
51458 ** truncation will be done when the current transaction is committed.
51460 ** This function is only called right before committing a transaction.
51461 ** Once this function has been called, the transaction must either be
51462 ** rolled back or committed. It is not safe to call this function and
51463 ** then continue writing to the database.
51465 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
51466 assert( pPager->dbSize>=nPage );
51467 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
51468 pPager->dbSize = nPage;
51470 /* At one point the code here called assertTruncateConstraint() to
51471 ** ensure that all pages being truncated away by this operation are,
51472 ** if one or more savepoints are open, present in the savepoint
51473 ** journal so that they can be restored if the savepoint is rolled
51474 ** back. This is no longer necessary as this function is now only
51475 ** called right before committing a transaction. So although the
51476 ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
51477 ** they cannot be rolled back. So the assertTruncateConstraint() call
51478 ** is no longer correct. */
51483 ** This function is called before attempting a hot-journal rollback. It
51484 ** syncs the journal file to disk, then sets pPager->journalHdr to the
51485 ** size of the journal file so that the pager_playback() routine knows
51486 ** that the entire journal file has been synced.
51488 ** Syncing a hot-journal to disk before attempting to roll it back ensures
51489 ** that if a power-failure occurs during the rollback, the process that
51490 ** attempts rollback following system recovery sees the same journal
51491 ** content as this process.
51493 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
51494 ** an SQLite error code.
51496 static int pagerSyncHotJournal(Pager *pPager){
51497 int rc = SQLITE_OK;
51498 if( !pPager->noSync ){
51499 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
51501 if( rc==SQLITE_OK ){
51502 rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
51504 return rc;
51507 #if SQLITE_MAX_MMAP_SIZE>0
51509 ** Obtain a reference to a memory mapped page object for page number pgno.
51510 ** The new object will use the pointer pData, obtained from xFetch().
51511 ** If successful, set *ppPage to point to the new page reference
51512 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
51513 ** *ppPage to zero.
51515 ** Page references obtained by calling this function should be released
51516 ** by calling pagerReleaseMapPage().
51518 static int pagerAcquireMapPage(
51519 Pager *pPager, /* Pager object */
51520 Pgno pgno, /* Page number */
51521 void *pData, /* xFetch()'d data for this page */
51522 PgHdr **ppPage /* OUT: Acquired page object */
51524 PgHdr *p; /* Memory mapped page to return */
51526 if( pPager->pMmapFreelist ){
51527 *ppPage = p = pPager->pMmapFreelist;
51528 pPager->pMmapFreelist = p->pDirty;
51529 p->pDirty = 0;
51530 assert( pPager->nExtra>=8 );
51531 memset(p->pExtra, 0, 8);
51532 }else{
51533 *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
51534 if( p==0 ){
51535 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
51536 return SQLITE_NOMEM_BKPT;
51538 p->pExtra = (void *)&p[1];
51539 p->flags = PGHDR_MMAP;
51540 p->nRef = 1;
51541 p->pPager = pPager;
51544 assert( p->pExtra==(void *)&p[1] );
51545 assert( p->pPage==0 );
51546 assert( p->flags==PGHDR_MMAP );
51547 assert( p->pPager==pPager );
51548 assert( p->nRef==1 );
51550 p->pgno = pgno;
51551 p->pData = pData;
51552 pPager->nMmapOut++;
51554 return SQLITE_OK;
51556 #endif
51559 ** Release a reference to page pPg. pPg must have been returned by an
51560 ** earlier call to pagerAcquireMapPage().
51562 static void pagerReleaseMapPage(PgHdr *pPg){
51563 Pager *pPager = pPg->pPager;
51564 pPager->nMmapOut--;
51565 pPg->pDirty = pPager->pMmapFreelist;
51566 pPager->pMmapFreelist = pPg;
51568 assert( pPager->fd->pMethods->iVersion>=3 );
51569 sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
51573 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
51575 static void pagerFreeMapHdrs(Pager *pPager){
51576 PgHdr *p;
51577 PgHdr *pNext;
51578 for(p=pPager->pMmapFreelist; p; p=pNext){
51579 pNext = p->pDirty;
51580 sqlite3_free(p);
51586 ** Shutdown the page cache. Free all memory and close all files.
51588 ** If a transaction was in progress when this routine is called, that
51589 ** transaction is rolled back. All outstanding pages are invalidated
51590 ** and their memory is freed. Any attempt to use a page associated
51591 ** with this page cache after this function returns will likely
51592 ** result in a coredump.
51594 ** This function always succeeds. If a transaction is active an attempt
51595 ** is made to roll it back. If an error occurs during the rollback
51596 ** a hot journal may be left in the filesystem but no error is returned
51597 ** to the caller.
51599 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
51600 u8 *pTmp = (u8 *)pPager->pTmpSpace;
51602 assert( db || pagerUseWal(pPager)==0 );
51603 assert( assert_pager_state(pPager) );
51604 disable_simulated_io_errors();
51605 sqlite3BeginBenignMalloc();
51606 pagerFreeMapHdrs(pPager);
51607 /* pPager->errCode = 0; */
51608 pPager->exclusiveMode = 0;
51609 #ifndef SQLITE_OMIT_WAL
51610 assert( db || pPager->pWal==0 );
51611 sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,
51612 (db && (db->flags & SQLITE_NoCkptOnClose) ? 0 : pTmp)
51614 pPager->pWal = 0;
51615 #endif
51616 pager_reset(pPager);
51617 if( MEMDB ){
51618 pager_unlock(pPager);
51619 }else{
51620 /* If it is open, sync the journal file before calling UnlockAndRollback.
51621 ** If this is not done, then an unsynced portion of the open journal
51622 ** file may be played back into the database. If a power failure occurs
51623 ** while this is happening, the database could become corrupt.
51625 ** If an error occurs while trying to sync the journal, shift the pager
51626 ** into the ERROR state. This causes UnlockAndRollback to unlock the
51627 ** database and close the journal file without attempting to roll it
51628 ** back or finalize it. The next database user will have to do hot-journal
51629 ** rollback before accessing the database file.
51631 if( isOpen(pPager->jfd) ){
51632 pager_error(pPager, pagerSyncHotJournal(pPager));
51634 pagerUnlockAndRollback(pPager);
51636 sqlite3EndBenignMalloc();
51637 enable_simulated_io_errors();
51638 PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
51639 IOTRACE(("CLOSE %p\n", pPager))
51640 sqlite3OsClose(pPager->jfd);
51641 sqlite3OsClose(pPager->fd);
51642 sqlite3PageFree(pTmp);
51643 sqlite3PcacheClose(pPager->pPCache);
51645 #ifdef SQLITE_HAS_CODEC
51646 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
51647 #endif
51649 assert( !pPager->aSavepoint && !pPager->pInJournal );
51650 assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
51652 sqlite3_free(pPager);
51653 return SQLITE_OK;
51656 #if !defined(NDEBUG) || defined(SQLITE_TEST)
51658 ** Return the page number for page pPg.
51660 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
51661 return pPg->pgno;
51663 #endif
51666 ** Increment the reference count for page pPg.
51668 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
51669 sqlite3PcacheRef(pPg);
51673 ** Sync the journal. In other words, make sure all the pages that have
51674 ** been written to the journal have actually reached the surface of the
51675 ** disk and can be restored in the event of a hot-journal rollback.
51677 ** If the Pager.noSync flag is set, then this function is a no-op.
51678 ** Otherwise, the actions required depend on the journal-mode and the
51679 ** device characteristics of the file-system, as follows:
51681 ** * If the journal file is an in-memory journal file, no action need
51682 ** be taken.
51684 ** * Otherwise, if the device does not support the SAFE_APPEND property,
51685 ** then the nRec field of the most recently written journal header
51686 ** is updated to contain the number of journal records that have
51687 ** been written following it. If the pager is operating in full-sync
51688 ** mode, then the journal file is synced before this field is updated.
51690 ** * If the device does not support the SEQUENTIAL property, then
51691 ** journal file is synced.
51693 ** Or, in pseudo-code:
51695 ** if( NOT <in-memory journal> ){
51696 ** if( NOT SAFE_APPEND ){
51697 ** if( <full-sync mode> ) xSync(<journal file>);
51698 ** <update nRec field>
51699 ** }
51700 ** if( NOT SEQUENTIAL ) xSync(<journal file>);
51701 ** }
51703 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
51704 ** page currently held in memory before returning SQLITE_OK. If an IO
51705 ** error is encountered, then the IO error code is returned to the caller.
51707 static int syncJournal(Pager *pPager, int newHdr){
51708 int rc; /* Return code */
51710 assert( pPager->eState==PAGER_WRITER_CACHEMOD
51711 || pPager->eState==PAGER_WRITER_DBMOD
51713 assert( assert_pager_state(pPager) );
51714 assert( !pagerUseWal(pPager) );
51716 rc = sqlite3PagerExclusiveLock(pPager);
51717 if( rc!=SQLITE_OK ) return rc;
51719 if( !pPager->noSync ){
51720 assert( !pPager->tempFile );
51721 if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
51722 const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
51723 assert( isOpen(pPager->jfd) );
51725 if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
51726 /* This block deals with an obscure problem. If the last connection
51727 ** that wrote to this database was operating in persistent-journal
51728 ** mode, then the journal file may at this point actually be larger
51729 ** than Pager.journalOff bytes. If the next thing in the journal
51730 ** file happens to be a journal-header (written as part of the
51731 ** previous connection's transaction), and a crash or power-failure
51732 ** occurs after nRec is updated but before this connection writes
51733 ** anything else to the journal file (or commits/rolls back its
51734 ** transaction), then SQLite may become confused when doing the
51735 ** hot-journal rollback following recovery. It may roll back all
51736 ** of this connections data, then proceed to rolling back the old,
51737 ** out-of-date data that follows it. Database corruption.
51739 ** To work around this, if the journal file does appear to contain
51740 ** a valid header following Pager.journalOff, then write a 0x00
51741 ** byte to the start of it to prevent it from being recognized.
51743 ** Variable iNextHdrOffset is set to the offset at which this
51744 ** problematic header will occur, if it exists. aMagic is used
51745 ** as a temporary buffer to inspect the first couple of bytes of
51746 ** the potential journal header.
51748 i64 iNextHdrOffset;
51749 u8 aMagic[8];
51750 u8 zHeader[sizeof(aJournalMagic)+4];
51752 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
51753 put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
51755 iNextHdrOffset = journalHdrOffset(pPager);
51756 rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
51757 if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
51758 static const u8 zerobyte = 0;
51759 rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
51761 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
51762 return rc;
51765 /* Write the nRec value into the journal file header. If in
51766 ** full-synchronous mode, sync the journal first. This ensures that
51767 ** all data has really hit the disk before nRec is updated to mark
51768 ** it as a candidate for rollback.
51770 ** This is not required if the persistent media supports the
51771 ** SAFE_APPEND property. Because in this case it is not possible
51772 ** for garbage data to be appended to the file, the nRec field
51773 ** is populated with 0xFFFFFFFF when the journal header is written
51774 ** and never needs to be updated.
51776 if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
51777 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
51778 IOTRACE(("JSYNC %p\n", pPager))
51779 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
51780 if( rc!=SQLITE_OK ) return rc;
51782 IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
51783 rc = sqlite3OsWrite(
51784 pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
51786 if( rc!=SQLITE_OK ) return rc;
51788 if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
51789 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
51790 IOTRACE(("JSYNC %p\n", pPager))
51791 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
51792 (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
51794 if( rc!=SQLITE_OK ) return rc;
51797 pPager->journalHdr = pPager->journalOff;
51798 if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
51799 pPager->nRec = 0;
51800 rc = writeJournalHdr(pPager);
51801 if( rc!=SQLITE_OK ) return rc;
51803 }else{
51804 pPager->journalHdr = pPager->journalOff;
51808 /* Unless the pager is in noSync mode, the journal file was just
51809 ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
51810 ** all pages.
51812 sqlite3PcacheClearSyncFlags(pPager->pPCache);
51813 pPager->eState = PAGER_WRITER_DBMOD;
51814 assert( assert_pager_state(pPager) );
51815 return SQLITE_OK;
51819 ** The argument is the first in a linked list of dirty pages connected
51820 ** by the PgHdr.pDirty pointer. This function writes each one of the
51821 ** in-memory pages in the list to the database file. The argument may
51822 ** be NULL, representing an empty list. In this case this function is
51823 ** a no-op.
51825 ** The pager must hold at least a RESERVED lock when this function
51826 ** is called. Before writing anything to the database file, this lock
51827 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
51828 ** SQLITE_BUSY is returned and no data is written to the database file.
51830 ** If the pager is a temp-file pager and the actual file-system file
51831 ** is not yet open, it is created and opened before any data is
51832 ** written out.
51834 ** Once the lock has been upgraded and, if necessary, the file opened,
51835 ** the pages are written out to the database file in list order. Writing
51836 ** a page is skipped if it meets either of the following criteria:
51838 ** * The page number is greater than Pager.dbSize, or
51839 ** * The PGHDR_DONT_WRITE flag is set on the page.
51841 ** If writing out a page causes the database file to grow, Pager.dbFileSize
51842 ** is updated accordingly. If page 1 is written out, then the value cached
51843 ** in Pager.dbFileVers[] is updated to match the new value stored in
51844 ** the database file.
51846 ** If everything is successful, SQLITE_OK is returned. If an IO error
51847 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
51848 ** be obtained, SQLITE_BUSY is returned.
51850 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
51851 int rc = SQLITE_OK; /* Return code */
51853 /* This function is only called for rollback pagers in WRITER_DBMOD state. */
51854 assert( !pagerUseWal(pPager) );
51855 assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
51856 assert( pPager->eLock==EXCLUSIVE_LOCK );
51857 assert( isOpen(pPager->fd) || pList->pDirty==0 );
51859 /* If the file is a temp-file has not yet been opened, open it now. It
51860 ** is not possible for rc to be other than SQLITE_OK if this branch
51861 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
51863 if( !isOpen(pPager->fd) ){
51864 assert( pPager->tempFile && rc==SQLITE_OK );
51865 rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
51868 /* Before the first write, give the VFS a hint of what the final
51869 ** file size will be.
51871 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
51872 if( rc==SQLITE_OK
51873 && pPager->dbHintSize<pPager->dbSize
51874 && (pList->pDirty || pList->pgno>pPager->dbHintSize)
51876 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
51877 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
51878 pPager->dbHintSize = pPager->dbSize;
51881 while( rc==SQLITE_OK && pList ){
51882 Pgno pgno = pList->pgno;
51884 /* If there are dirty pages in the page cache with page numbers greater
51885 ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
51886 ** make the file smaller (presumably by auto-vacuum code). Do not write
51887 ** any such pages to the file.
51889 ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
51890 ** set (set by sqlite3PagerDontWrite()).
51892 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
51893 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
51894 char *pData; /* Data to write */
51896 assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
51897 if( pList->pgno==1 ) pager_write_changecounter(pList);
51899 /* Encode the database */
51900 CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
51902 /* Write out the page data. */
51903 rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
51905 /* If page 1 was just written, update Pager.dbFileVers to match
51906 ** the value now stored in the database file. If writing this
51907 ** page caused the database file to grow, update dbFileSize.
51909 if( pgno==1 ){
51910 memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
51912 if( pgno>pPager->dbFileSize ){
51913 pPager->dbFileSize = pgno;
51915 pPager->aStat[PAGER_STAT_WRITE]++;
51917 /* Update any backup objects copying the contents of this pager. */
51918 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
51920 PAGERTRACE(("STORE %d page %d hash(%08x)\n",
51921 PAGERID(pPager), pgno, pager_pagehash(pList)));
51922 IOTRACE(("PGOUT %p %d\n", pPager, pgno));
51923 PAGER_INCR(sqlite3_pager_writedb_count);
51924 }else{
51925 PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
51927 pager_set_pagehash(pList);
51928 pList = pList->pDirty;
51931 return rc;
51935 ** Ensure that the sub-journal file is open. If it is already open, this
51936 ** function is a no-op.
51938 ** SQLITE_OK is returned if everything goes according to plan. An
51939 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
51940 ** fails.
51942 static int openSubJournal(Pager *pPager){
51943 int rc = SQLITE_OK;
51944 if( !isOpen(pPager->sjfd) ){
51945 const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
51946 | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
51947 | SQLITE_OPEN_DELETEONCLOSE;
51948 int nStmtSpill = sqlite3Config.nStmtSpill;
51949 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
51950 nStmtSpill = -1;
51952 rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
51954 return rc;
51958 ** Append a record of the current state of page pPg to the sub-journal.
51960 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
51961 ** for all open savepoints before returning.
51963 ** This function returns SQLITE_OK if everything is successful, an IO
51964 ** error code if the attempt to write to the sub-journal fails, or
51965 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
51966 ** bitvec.
51968 static int subjournalPage(PgHdr *pPg){
51969 int rc = SQLITE_OK;
51970 Pager *pPager = pPg->pPager;
51971 if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
51973 /* Open the sub-journal, if it has not already been opened */
51974 assert( pPager->useJournal );
51975 assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
51976 assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
51977 assert( pagerUseWal(pPager)
51978 || pageInJournal(pPager, pPg)
51979 || pPg->pgno>pPager->dbOrigSize
51981 rc = openSubJournal(pPager);
51983 /* If the sub-journal was opened successfully (or was already open),
51984 ** write the journal record into the file. */
51985 if( rc==SQLITE_OK ){
51986 void *pData = pPg->pData;
51987 i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
51988 char *pData2;
51990 #if SQLITE_HAS_CODEC
51991 if( !pPager->subjInMemory ){
51992 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
51993 }else
51994 #endif
51995 pData2 = pData;
51996 PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
51997 rc = write32bits(pPager->sjfd, offset, pPg->pgno);
51998 if( rc==SQLITE_OK ){
51999 rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
52003 if( rc==SQLITE_OK ){
52004 pPager->nSubRec++;
52005 assert( pPager->nSavepoint>0 );
52006 rc = addToSavepointBitvecs(pPager, pPg->pgno);
52008 return rc;
52010 static int subjournalPageIfRequired(PgHdr *pPg){
52011 if( subjRequiresPage(pPg) ){
52012 return subjournalPage(pPg);
52013 }else{
52014 return SQLITE_OK;
52019 ** This function is called by the pcache layer when it has reached some
52020 ** soft memory limit. The first argument is a pointer to a Pager object
52021 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
52022 ** database). The second argument is a reference to a page that is
52023 ** currently dirty but has no outstanding references. The page
52024 ** is always associated with the Pager object passed as the first
52025 ** argument.
52027 ** The job of this function is to make pPg clean by writing its contents
52028 ** out to the database file, if possible. This may involve syncing the
52029 ** journal file.
52031 ** If successful, sqlite3PcacheMakeClean() is called on the page and
52032 ** SQLITE_OK returned. If an IO error occurs while trying to make the
52033 ** page clean, the IO error code is returned. If the page cannot be
52034 ** made clean for some other reason, but no error occurs, then SQLITE_OK
52035 ** is returned by sqlite3PcacheMakeClean() is not called.
52037 static int pagerStress(void *p, PgHdr *pPg){
52038 Pager *pPager = (Pager *)p;
52039 int rc = SQLITE_OK;
52041 assert( pPg->pPager==pPager );
52042 assert( pPg->flags&PGHDR_DIRTY );
52044 /* The doNotSpill NOSYNC bit is set during times when doing a sync of
52045 ** journal (and adding a new header) is not allowed. This occurs
52046 ** during calls to sqlite3PagerWrite() while trying to journal multiple
52047 ** pages belonging to the same sector.
52049 ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
52050 ** regardless of whether or not a sync is required. This is set during
52051 ** a rollback or by user request, respectively.
52053 ** Spilling is also prohibited when in an error state since that could
52054 ** lead to database corruption. In the current implementation it
52055 ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
52056 ** while in the error state, hence it is impossible for this routine to
52057 ** be called in the error state. Nevertheless, we include a NEVER()
52058 ** test for the error state as a safeguard against future changes.
52060 if( NEVER(pPager->errCode) ) return SQLITE_OK;
52061 testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
52062 testcase( pPager->doNotSpill & SPILLFLAG_OFF );
52063 testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
52064 if( pPager->doNotSpill
52065 && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
52066 || (pPg->flags & PGHDR_NEED_SYNC)!=0)
52068 return SQLITE_OK;
52071 pPg->pDirty = 0;
52072 if( pagerUseWal(pPager) ){
52073 /* Write a single frame for this page to the log. */
52074 rc = subjournalPageIfRequired(pPg);
52075 if( rc==SQLITE_OK ){
52076 rc = pagerWalFrames(pPager, pPg, 0, 0);
52078 }else{
52080 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
52081 if( pPager->tempFile==0 ){
52082 rc = sqlite3JournalCreate(pPager->jfd);
52083 if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
52085 #endif
52087 /* Sync the journal file if required. */
52088 if( pPg->flags&PGHDR_NEED_SYNC
52089 || pPager->eState==PAGER_WRITER_CACHEMOD
52091 rc = syncJournal(pPager, 1);
52094 /* Write the contents of the page out to the database file. */
52095 if( rc==SQLITE_OK ){
52096 assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
52097 rc = pager_write_pagelist(pPager, pPg);
52101 /* Mark the page as clean. */
52102 if( rc==SQLITE_OK ){
52103 PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
52104 sqlite3PcacheMakeClean(pPg);
52107 return pager_error(pPager, rc);
52111 ** Flush all unreferenced dirty pages to disk.
52113 SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
52114 int rc = pPager->errCode;
52115 if( !MEMDB ){
52116 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
52117 assert( assert_pager_state(pPager) );
52118 while( rc==SQLITE_OK && pList ){
52119 PgHdr *pNext = pList->pDirty;
52120 if( pList->nRef==0 ){
52121 rc = pagerStress((void*)pPager, pList);
52123 pList = pNext;
52127 return rc;
52131 ** Allocate and initialize a new Pager object and put a pointer to it
52132 ** in *ppPager. The pager should eventually be freed by passing it
52133 ** to sqlite3PagerClose().
52135 ** The zFilename argument is the path to the database file to open.
52136 ** If zFilename is NULL then a randomly-named temporary file is created
52137 ** and used as the file to be cached. Temporary files are be deleted
52138 ** automatically when they are closed. If zFilename is ":memory:" then
52139 ** all information is held in cache. It is never written to disk.
52140 ** This can be used to implement an in-memory database.
52142 ** The nExtra parameter specifies the number of bytes of space allocated
52143 ** along with each page reference. This space is available to the user
52144 ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the
52145 ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
52146 ** (The extra space is used by btree as the MemPage object.)
52148 ** The flags argument is used to specify properties that affect the
52149 ** operation of the pager. It should be passed some bitwise combination
52150 ** of the PAGER_* flags.
52152 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
52153 ** of the xOpen() method of the supplied VFS when opening files.
52155 ** If the pager object is allocated and the specified file opened
52156 ** successfully, SQLITE_OK is returned and *ppPager set to point to
52157 ** the new pager object. If an error occurs, *ppPager is set to NULL
52158 ** and error code returned. This function may return SQLITE_NOMEM
52159 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
52160 ** various SQLITE_IO_XXX errors.
52162 SQLITE_PRIVATE int sqlite3PagerOpen(
52163 sqlite3_vfs *pVfs, /* The virtual file system to use */
52164 Pager **ppPager, /* OUT: Return the Pager structure here */
52165 const char *zFilename, /* Name of the database file to open */
52166 int nExtra, /* Extra bytes append to each in-memory page */
52167 int flags, /* flags controlling this file */
52168 int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
52169 void (*xReinit)(DbPage*) /* Function to reinitialize pages */
52171 u8 *pPtr;
52172 Pager *pPager = 0; /* Pager object to allocate and return */
52173 int rc = SQLITE_OK; /* Return code */
52174 int tempFile = 0; /* True for temp files (incl. in-memory files) */
52175 int memDb = 0; /* True if this is an in-memory file */
52176 int readOnly = 0; /* True if this is a read-only file */
52177 int journalFileSize; /* Bytes to allocate for each journal fd */
52178 char *zPathname = 0; /* Full path to database file */
52179 int nPathname = 0; /* Number of bytes in zPathname */
52180 int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
52181 int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
52182 u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
52183 const char *zUri = 0; /* URI args to copy */
52184 int nUri = 0; /* Number of bytes of URI args at *zUri */
52186 /* Figure out how much space is required for each journal file-handle
52187 ** (there are two of them, the main journal and the sub-journal). */
52188 journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
52190 /* Set the output variable to NULL in case an error occurs. */
52191 *ppPager = 0;
52193 #ifndef SQLITE_OMIT_MEMORYDB
52194 if( flags & PAGER_MEMORY ){
52195 memDb = 1;
52196 if( zFilename && zFilename[0] ){
52197 zPathname = sqlite3DbStrDup(0, zFilename);
52198 if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
52199 nPathname = sqlite3Strlen30(zPathname);
52200 zFilename = 0;
52203 #endif
52205 /* Compute and store the full pathname in an allocated buffer pointed
52206 ** to by zPathname, length nPathname. Or, if this is a temporary file,
52207 ** leave both nPathname and zPathname set to 0.
52209 if( zFilename && zFilename[0] ){
52210 const char *z;
52211 nPathname = pVfs->mxPathname+1;
52212 zPathname = sqlite3DbMallocRaw(0, nPathname*2);
52213 if( zPathname==0 ){
52214 return SQLITE_NOMEM_BKPT;
52216 zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
52217 rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
52218 nPathname = sqlite3Strlen30(zPathname);
52219 z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
52220 while( *z ){
52221 z += sqlite3Strlen30(z)+1;
52222 z += sqlite3Strlen30(z)+1;
52224 nUri = (int)(&z[1] - zUri);
52225 assert( nUri>=0 );
52226 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
52227 /* This branch is taken when the journal path required by
52228 ** the database being opened will be more than pVfs->mxPathname
52229 ** bytes in length. This means the database cannot be opened,
52230 ** as it will not be possible to open the journal file or even
52231 ** check for a hot-journal before reading.
52233 rc = SQLITE_CANTOPEN_BKPT;
52235 if( rc!=SQLITE_OK ){
52236 sqlite3DbFree(0, zPathname);
52237 return rc;
52241 /* Allocate memory for the Pager structure, PCache object, the
52242 ** three file descriptors, the database file name and the journal
52243 ** file name. The layout in memory is as follows:
52245 ** Pager object (sizeof(Pager) bytes)
52246 ** PCache object (sqlite3PcacheSize() bytes)
52247 ** Database file handle (pVfs->szOsFile bytes)
52248 ** Sub-journal file handle (journalFileSize bytes)
52249 ** Main journal file handle (journalFileSize bytes)
52250 ** Database file name (nPathname+1 bytes)
52251 ** Journal file name (nPathname+8+1 bytes)
52253 pPtr = (u8 *)sqlite3MallocZero(
52254 ROUND8(sizeof(*pPager)) + /* Pager structure */
52255 ROUND8(pcacheSize) + /* PCache object */
52256 ROUND8(pVfs->szOsFile) + /* The main db file */
52257 journalFileSize * 2 + /* The two journal files */
52258 nPathname + 1 + nUri + /* zFilename */
52259 nPathname + 8 + 2 /* zJournal */
52260 #ifndef SQLITE_OMIT_WAL
52261 + nPathname + 4 + 2 /* zWal */
52262 #endif
52264 assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
52265 if( !pPtr ){
52266 sqlite3DbFree(0, zPathname);
52267 return SQLITE_NOMEM_BKPT;
52269 pPager = (Pager*)(pPtr);
52270 pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
52271 pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
52272 pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
52273 pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
52274 pPager->zFilename = (char*)(pPtr += journalFileSize);
52275 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
52277 /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
52278 if( zPathname ){
52279 assert( nPathname>0 );
52280 pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
52281 memcpy(pPager->zFilename, zPathname, nPathname);
52282 if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
52283 memcpy(pPager->zJournal, zPathname, nPathname);
52284 memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
52285 sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
52286 #ifndef SQLITE_OMIT_WAL
52287 pPager->zWal = &pPager->zJournal[nPathname+8+1];
52288 memcpy(pPager->zWal, zPathname, nPathname);
52289 memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
52290 sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
52291 #endif
52292 sqlite3DbFree(0, zPathname);
52294 pPager->pVfs = pVfs;
52295 pPager->vfsFlags = vfsFlags;
52297 /* Open the pager file.
52299 if( zFilename && zFilename[0] ){
52300 int fout = 0; /* VFS flags returned by xOpen() */
52301 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
52302 assert( !memDb );
52303 readOnly = (fout&SQLITE_OPEN_READONLY);
52305 /* If the file was successfully opened for read/write access,
52306 ** choose a default page size in case we have to create the
52307 ** database file. The default page size is the maximum of:
52309 ** + SQLITE_DEFAULT_PAGE_SIZE,
52310 ** + The value returned by sqlite3OsSectorSize()
52311 ** + The largest page size that can be written atomically.
52313 if( rc==SQLITE_OK ){
52314 int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
52315 if( !readOnly ){
52316 setSectorSize(pPager);
52317 assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
52318 if( szPageDflt<pPager->sectorSize ){
52319 if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
52320 szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
52321 }else{
52322 szPageDflt = (u32)pPager->sectorSize;
52325 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
52327 int ii;
52328 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
52329 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
52330 assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
52331 for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
52332 if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
52333 szPageDflt = ii;
52337 #endif
52339 pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
52340 if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
52341 || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
52342 vfsFlags |= SQLITE_OPEN_READONLY;
52343 goto act_like_temp_file;
52346 }else{
52347 /* If a temporary file is requested, it is not opened immediately.
52348 ** In this case we accept the default page size and delay actually
52349 ** opening the file until the first call to OsWrite().
52351 ** This branch is also run for an in-memory database. An in-memory
52352 ** database is the same as a temp-file that is never written out to
52353 ** disk and uses an in-memory rollback journal.
52355 ** This branch also runs for files marked as immutable.
52357 act_like_temp_file:
52358 tempFile = 1;
52359 pPager->eState = PAGER_READER; /* Pretend we already have a lock */
52360 pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
52361 pPager->noLock = 1; /* Do no locking */
52362 readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
52365 /* The following call to PagerSetPagesize() serves to set the value of
52366 ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
52368 if( rc==SQLITE_OK ){
52369 assert( pPager->memDb==0 );
52370 rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
52371 testcase( rc!=SQLITE_OK );
52374 /* Initialize the PCache object. */
52375 if( rc==SQLITE_OK ){
52376 nExtra = ROUND8(nExtra);
52377 assert( nExtra>=8 && nExtra<1000 );
52378 rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
52379 !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
52382 /* If an error occurred above, free the Pager structure and close the file.
52384 if( rc!=SQLITE_OK ){
52385 sqlite3OsClose(pPager->fd);
52386 sqlite3PageFree(pPager->pTmpSpace);
52387 sqlite3_free(pPager);
52388 return rc;
52391 PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
52392 IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
52394 pPager->useJournal = (u8)useJournal;
52395 /* pPager->stmtOpen = 0; */
52396 /* pPager->stmtInUse = 0; */
52397 /* pPager->nRef = 0; */
52398 /* pPager->stmtSize = 0; */
52399 /* pPager->stmtJSize = 0; */
52400 /* pPager->nPage = 0; */
52401 pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
52402 /* pPager->state = PAGER_UNLOCK; */
52403 /* pPager->errMask = 0; */
52404 pPager->tempFile = (u8)tempFile;
52405 assert( tempFile==PAGER_LOCKINGMODE_NORMAL
52406 || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
52407 assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
52408 pPager->exclusiveMode = (u8)tempFile;
52409 pPager->changeCountDone = pPager->tempFile;
52410 pPager->memDb = (u8)memDb;
52411 pPager->readOnly = (u8)readOnly;
52412 assert( useJournal || pPager->tempFile );
52413 pPager->noSync = pPager->tempFile;
52414 if( pPager->noSync ){
52415 assert( pPager->fullSync==0 );
52416 assert( pPager->extraSync==0 );
52417 assert( pPager->syncFlags==0 );
52418 assert( pPager->walSyncFlags==0 );
52419 }else{
52420 pPager->fullSync = 1;
52421 pPager->extraSync = 0;
52422 pPager->syncFlags = SQLITE_SYNC_NORMAL;
52423 pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
52425 /* pPager->pFirst = 0; */
52426 /* pPager->pFirstSynced = 0; */
52427 /* pPager->pLast = 0; */
52428 pPager->nExtra = (u16)nExtra;
52429 pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
52430 assert( isOpen(pPager->fd) || tempFile );
52431 setSectorSize(pPager);
52432 if( !useJournal ){
52433 pPager->journalMode = PAGER_JOURNALMODE_OFF;
52434 }else if( memDb ){
52435 pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
52437 /* pPager->xBusyHandler = 0; */
52438 /* pPager->pBusyHandlerArg = 0; */
52439 pPager->xReiniter = xReinit;
52440 setGetterMethod(pPager);
52441 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
52442 /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
52444 *ppPager = pPager;
52445 return SQLITE_OK;
52449 /* Verify that the database file has not be deleted or renamed out from
52450 ** under the pager. Return SQLITE_OK if the database is still were it ought
52451 ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
52452 ** code from sqlite3OsAccess()) if the database has gone missing.
52454 static int databaseIsUnmoved(Pager *pPager){
52455 int bHasMoved = 0;
52456 int rc;
52458 if( pPager->tempFile ) return SQLITE_OK;
52459 if( pPager->dbSize==0 ) return SQLITE_OK;
52460 assert( pPager->zFilename && pPager->zFilename[0] );
52461 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
52462 if( rc==SQLITE_NOTFOUND ){
52463 /* If the HAS_MOVED file-control is unimplemented, assume that the file
52464 ** has not been moved. That is the historical behavior of SQLite: prior to
52465 ** version 3.8.3, it never checked */
52466 rc = SQLITE_OK;
52467 }else if( rc==SQLITE_OK && bHasMoved ){
52468 rc = SQLITE_READONLY_DBMOVED;
52470 return rc;
52475 ** This function is called after transitioning from PAGER_UNLOCK to
52476 ** PAGER_SHARED state. It tests if there is a hot journal present in
52477 ** the file-system for the given pager. A hot journal is one that
52478 ** needs to be played back. According to this function, a hot-journal
52479 ** file exists if the following criteria are met:
52481 ** * The journal file exists in the file system, and
52482 ** * No process holds a RESERVED or greater lock on the database file, and
52483 ** * The database file itself is greater than 0 bytes in size, and
52484 ** * The first byte of the journal file exists and is not 0x00.
52486 ** If the current size of the database file is 0 but a journal file
52487 ** exists, that is probably an old journal left over from a prior
52488 ** database with the same name. In this case the journal file is
52489 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
52490 ** is returned.
52492 ** This routine does not check if there is a master journal filename
52493 ** at the end of the file. If there is, and that master journal file
52494 ** does not exist, then the journal file is not really hot. In this
52495 ** case this routine will return a false-positive. The pager_playback()
52496 ** routine will discover that the journal file is not really hot and
52497 ** will not roll it back.
52499 ** If a hot-journal file is found to exist, *pExists is set to 1 and
52500 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
52501 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
52502 ** to determine whether or not a hot-journal file exists, the IO error
52503 ** code is returned and the value of *pExists is undefined.
52505 static int hasHotJournal(Pager *pPager, int *pExists){
52506 sqlite3_vfs * const pVfs = pPager->pVfs;
52507 int rc = SQLITE_OK; /* Return code */
52508 int exists = 1; /* True if a journal file is present */
52509 int jrnlOpen = !!isOpen(pPager->jfd);
52511 assert( pPager->useJournal );
52512 assert( isOpen(pPager->fd) );
52513 assert( pPager->eState==PAGER_OPEN );
52515 assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
52516 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
52519 *pExists = 0;
52520 if( !jrnlOpen ){
52521 rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
52523 if( rc==SQLITE_OK && exists ){
52524 int locked = 0; /* True if some process holds a RESERVED lock */
52526 /* Race condition here: Another process might have been holding the
52527 ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
52528 ** call above, but then delete the journal and drop the lock before
52529 ** we get to the following sqlite3OsCheckReservedLock() call. If that
52530 ** is the case, this routine might think there is a hot journal when
52531 ** in fact there is none. This results in a false-positive which will
52532 ** be dealt with by the playback routine. Ticket #3883.
52534 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
52535 if( rc==SQLITE_OK && !locked ){
52536 Pgno nPage; /* Number of pages in database file */
52538 assert( pPager->tempFile==0 );
52539 rc = pagerPagecount(pPager, &nPage);
52540 if( rc==SQLITE_OK ){
52541 /* If the database is zero pages in size, that means that either (1) the
52542 ** journal is a remnant from a prior database with the same name where
52543 ** the database file but not the journal was deleted, or (2) the initial
52544 ** transaction that populates a new database is being rolled back.
52545 ** In either case, the journal file can be deleted. However, take care
52546 ** not to delete the journal file if it is already open due to
52547 ** journal_mode=PERSIST.
52549 if( nPage==0 && !jrnlOpen ){
52550 sqlite3BeginBenignMalloc();
52551 if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
52552 sqlite3OsDelete(pVfs, pPager->zJournal, 0);
52553 if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
52555 sqlite3EndBenignMalloc();
52556 }else{
52557 /* The journal file exists and no other connection has a reserved
52558 ** or greater lock on the database file. Now check that there is
52559 ** at least one non-zero bytes at the start of the journal file.
52560 ** If there is, then we consider this journal to be hot. If not,
52561 ** it can be ignored.
52563 if( !jrnlOpen ){
52564 int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
52565 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
52567 if( rc==SQLITE_OK ){
52568 u8 first = 0;
52569 rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
52570 if( rc==SQLITE_IOERR_SHORT_READ ){
52571 rc = SQLITE_OK;
52573 if( !jrnlOpen ){
52574 sqlite3OsClose(pPager->jfd);
52576 *pExists = (first!=0);
52577 }else if( rc==SQLITE_CANTOPEN ){
52578 /* If we cannot open the rollback journal file in order to see if
52579 ** it has a zero header, that might be due to an I/O error, or
52580 ** it might be due to the race condition described above and in
52581 ** ticket #3883. Either way, assume that the journal is hot.
52582 ** This might be a false positive. But if it is, then the
52583 ** automatic journal playback and recovery mechanism will deal
52584 ** with it under an EXCLUSIVE lock where we do not need to
52585 ** worry so much with race conditions.
52587 *pExists = 1;
52588 rc = SQLITE_OK;
52595 return rc;
52599 ** This function is called to obtain a shared lock on the database file.
52600 ** It is illegal to call sqlite3PagerGet() until after this function
52601 ** has been successfully called. If a shared-lock is already held when
52602 ** this function is called, it is a no-op.
52604 ** The following operations are also performed by this function.
52606 ** 1) If the pager is currently in PAGER_OPEN state (no lock held
52607 ** on the database file), then an attempt is made to obtain a
52608 ** SHARED lock on the database file. Immediately after obtaining
52609 ** the SHARED lock, the file-system is checked for a hot-journal,
52610 ** which is played back if present. Following any hot-journal
52611 ** rollback, the contents of the cache are validated by checking
52612 ** the 'change-counter' field of the database file header and
52613 ** discarded if they are found to be invalid.
52615 ** 2) If the pager is running in exclusive-mode, and there are currently
52616 ** no outstanding references to any pages, and is in the error state,
52617 ** then an attempt is made to clear the error state by discarding
52618 ** the contents of the page cache and rolling back any open journal
52619 ** file.
52621 ** If everything is successful, SQLITE_OK is returned. If an IO error
52622 ** occurs while locking the database, checking for a hot-journal file or
52623 ** rolling back a journal file, the IO error code is returned.
52625 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
52626 int rc = SQLITE_OK; /* Return code */
52628 /* This routine is only called from b-tree and only when there are no
52629 ** outstanding pages. This implies that the pager state should either
52630 ** be OPEN or READER. READER is only possible if the pager is or was in
52631 ** exclusive access mode. */
52632 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
52633 assert( assert_pager_state(pPager) );
52634 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
52635 assert( pPager->errCode==SQLITE_OK );
52637 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
52638 int bHotJournal = 1; /* True if there exists a hot journal-file */
52640 assert( !MEMDB );
52641 assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
52643 rc = pager_wait_on_lock(pPager, SHARED_LOCK);
52644 if( rc!=SQLITE_OK ){
52645 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
52646 goto failed;
52649 /* If a journal file exists, and there is no RESERVED lock on the
52650 ** database file, then it either needs to be played back or deleted.
52652 if( pPager->eLock<=SHARED_LOCK ){
52653 rc = hasHotJournal(pPager, &bHotJournal);
52655 if( rc!=SQLITE_OK ){
52656 goto failed;
52658 if( bHotJournal ){
52659 if( pPager->readOnly ){
52660 rc = SQLITE_READONLY_ROLLBACK;
52661 goto failed;
52664 /* Get an EXCLUSIVE lock on the database file. At this point it is
52665 ** important that a RESERVED lock is not obtained on the way to the
52666 ** EXCLUSIVE lock. If it were, another process might open the
52667 ** database file, detect the RESERVED lock, and conclude that the
52668 ** database is safe to read while this process is still rolling the
52669 ** hot-journal back.
52671 ** Because the intermediate RESERVED lock is not requested, any
52672 ** other process attempting to access the database file will get to
52673 ** this point in the code and fail to obtain its own EXCLUSIVE lock
52674 ** on the database file.
52676 ** Unless the pager is in locking_mode=exclusive mode, the lock is
52677 ** downgraded to SHARED_LOCK before this function returns.
52679 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
52680 if( rc!=SQLITE_OK ){
52681 goto failed;
52684 /* If it is not already open and the file exists on disk, open the
52685 ** journal for read/write access. Write access is required because
52686 ** in exclusive-access mode the file descriptor will be kept open
52687 ** and possibly used for a transaction later on. Also, write-access
52688 ** is usually required to finalize the journal in journal_mode=persist
52689 ** mode (and also for journal_mode=truncate on some systems).
52691 ** If the journal does not exist, it usually means that some
52692 ** other connection managed to get in and roll it back before
52693 ** this connection obtained the exclusive lock above. Or, it
52694 ** may mean that the pager was in the error-state when this
52695 ** function was called and the journal file does not exist.
52697 if( !isOpen(pPager->jfd) ){
52698 sqlite3_vfs * const pVfs = pPager->pVfs;
52699 int bExists; /* True if journal file exists */
52700 rc = sqlite3OsAccess(
52701 pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
52702 if( rc==SQLITE_OK && bExists ){
52703 int fout = 0;
52704 int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
52705 assert( !pPager->tempFile );
52706 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
52707 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
52708 if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
52709 rc = SQLITE_CANTOPEN_BKPT;
52710 sqlite3OsClose(pPager->jfd);
52715 /* Playback and delete the journal. Drop the database write
52716 ** lock and reacquire the read lock. Purge the cache before
52717 ** playing back the hot-journal so that we don't end up with
52718 ** an inconsistent cache. Sync the hot journal before playing
52719 ** it back since the process that crashed and left the hot journal
52720 ** probably did not sync it and we are required to always sync
52721 ** the journal before playing it back.
52723 if( isOpen(pPager->jfd) ){
52724 assert( rc==SQLITE_OK );
52725 rc = pagerSyncHotJournal(pPager);
52726 if( rc==SQLITE_OK ){
52727 rc = pager_playback(pPager, !pPager->tempFile);
52728 pPager->eState = PAGER_OPEN;
52730 }else if( !pPager->exclusiveMode ){
52731 pagerUnlockDb(pPager, SHARED_LOCK);
52734 if( rc!=SQLITE_OK ){
52735 /* This branch is taken if an error occurs while trying to open
52736 ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
52737 ** pager_unlock() routine will be called before returning to unlock
52738 ** the file. If the unlock attempt fails, then Pager.eLock must be
52739 ** set to UNKNOWN_LOCK (see the comment above the #define for
52740 ** UNKNOWN_LOCK above for an explanation).
52742 ** In order to get pager_unlock() to do this, set Pager.eState to
52743 ** PAGER_ERROR now. This is not actually counted as a transition
52744 ** to ERROR state in the state diagram at the top of this file,
52745 ** since we know that the same call to pager_unlock() will very
52746 ** shortly transition the pager object to the OPEN state. Calling
52747 ** assert_pager_state() would fail now, as it should not be possible
52748 ** to be in ERROR state when there are zero outstanding page
52749 ** references.
52751 pager_error(pPager, rc);
52752 goto failed;
52755 assert( pPager->eState==PAGER_OPEN );
52756 assert( (pPager->eLock==SHARED_LOCK)
52757 || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
52761 if( !pPager->tempFile && pPager->hasHeldSharedLock ){
52762 /* The shared-lock has just been acquired then check to
52763 ** see if the database has been modified. If the database has changed,
52764 ** flush the cache. The hasHeldSharedLock flag prevents this from
52765 ** occurring on the very first access to a file, in order to save a
52766 ** single unnecessary sqlite3OsRead() call at the start-up.
52768 ** Database changes are detected by looking at 15 bytes beginning
52769 ** at offset 24 into the file. The first 4 of these 16 bytes are
52770 ** a 32-bit counter that is incremented with each change. The
52771 ** other bytes change randomly with each file change when
52772 ** a codec is in use.
52774 ** There is a vanishingly small chance that a change will not be
52775 ** detected. The chance of an undetected change is so small that
52776 ** it can be neglected.
52778 char dbFileVers[sizeof(pPager->dbFileVers)];
52780 IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
52781 rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
52782 if( rc!=SQLITE_OK ){
52783 if( rc!=SQLITE_IOERR_SHORT_READ ){
52784 goto failed;
52786 memset(dbFileVers, 0, sizeof(dbFileVers));
52789 if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
52790 pager_reset(pPager);
52792 /* Unmap the database file. It is possible that external processes
52793 ** may have truncated the database file and then extended it back
52794 ** to its original size while this process was not holding a lock.
52795 ** In this case there may exist a Pager.pMap mapping that appears
52796 ** to be the right size but is not actually valid. Avoid this
52797 ** possibility by unmapping the db here. */
52798 if( USEFETCH(pPager) ){
52799 sqlite3OsUnfetch(pPager->fd, 0, 0);
52804 /* If there is a WAL file in the file-system, open this database in WAL
52805 ** mode. Otherwise, the following function call is a no-op.
52807 rc = pagerOpenWalIfPresent(pPager);
52808 #ifndef SQLITE_OMIT_WAL
52809 assert( pPager->pWal==0 || rc==SQLITE_OK );
52810 #endif
52813 if( pagerUseWal(pPager) ){
52814 assert( rc==SQLITE_OK );
52815 rc = pagerBeginReadTransaction(pPager);
52818 if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
52819 rc = pagerPagecount(pPager, &pPager->dbSize);
52822 failed:
52823 if( rc!=SQLITE_OK ){
52824 assert( !MEMDB );
52825 pager_unlock(pPager);
52826 assert( pPager->eState==PAGER_OPEN );
52827 }else{
52828 pPager->eState = PAGER_READER;
52829 pPager->hasHeldSharedLock = 1;
52831 return rc;
52835 ** If the reference count has reached zero, rollback any active
52836 ** transaction and unlock the pager.
52838 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
52839 ** the rollback journal, the unlock is not performed and there is
52840 ** nothing to rollback, so this routine is a no-op.
52842 static void pagerUnlockIfUnused(Pager *pPager){
52843 if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
52844 assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
52845 pagerUnlockAndRollback(pPager);
52850 ** The page getter methods each try to acquire a reference to a
52851 ** page with page number pgno. If the requested reference is
52852 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
52854 ** There are different implementations of the getter method depending
52855 ** on the current state of the pager.
52857 ** getPageNormal() -- The normal getter
52858 ** getPageError() -- Used if the pager is in an error state
52859 ** getPageMmap() -- Used if memory-mapped I/O is enabled
52861 ** If the requested page is already in the cache, it is returned.
52862 ** Otherwise, a new page object is allocated and populated with data
52863 ** read from the database file. In some cases, the pcache module may
52864 ** choose not to allocate a new page object and may reuse an existing
52865 ** object with no outstanding references.
52867 ** The extra data appended to a page is always initialized to zeros the
52868 ** first time a page is loaded into memory. If the page requested is
52869 ** already in the cache when this function is called, then the extra
52870 ** data is left as it was when the page object was last used.
52872 ** If the database image is smaller than the requested page or if
52873 ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
52874 ** requested page is not already stored in the cache, then no
52875 ** actual disk read occurs. In this case the memory image of the
52876 ** page is initialized to all zeros.
52878 ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
52879 ** the contents of the page. This occurs in two scenarios:
52881 ** a) When reading a free-list leaf page from the database, and
52883 ** b) When a savepoint is being rolled back and we need to load
52884 ** a new page into the cache to be filled with the data read
52885 ** from the savepoint journal.
52887 ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
52888 ** of being read from the database. Additionally, the bits corresponding
52889 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
52890 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
52891 ** savepoints are set. This means if the page is made writable at any
52892 ** point in the future, using a call to sqlite3PagerWrite(), its contents
52893 ** will not be journaled. This saves IO.
52895 ** The acquisition might fail for several reasons. In all cases,
52896 ** an appropriate error code is returned and *ppPage is set to NULL.
52898 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
52899 ** to find a page in the in-memory cache first. If the page is not already
52900 ** in memory, this routine goes to disk to read it in whereas Lookup()
52901 ** just returns 0. This routine acquires a read-lock the first time it
52902 ** has to go to disk, and could also playback an old journal if necessary.
52903 ** Since Lookup() never goes to disk, it never has to deal with locks
52904 ** or journal files.
52906 static int getPageNormal(
52907 Pager *pPager, /* The pager open on the database file */
52908 Pgno pgno, /* Page number to fetch */
52909 DbPage **ppPage, /* Write a pointer to the page here */
52910 int flags /* PAGER_GET_XXX flags */
52912 int rc = SQLITE_OK;
52913 PgHdr *pPg;
52914 u8 noContent; /* True if PAGER_GET_NOCONTENT is set */
52915 sqlite3_pcache_page *pBase;
52917 assert( pPager->errCode==SQLITE_OK );
52918 assert( pPager->eState>=PAGER_READER );
52919 assert( assert_pager_state(pPager) );
52920 assert( pPager->hasHeldSharedLock==1 );
52922 if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
52923 pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
52924 if( pBase==0 ){
52925 pPg = 0;
52926 rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
52927 if( rc!=SQLITE_OK ) goto pager_acquire_err;
52928 if( pBase==0 ){
52929 rc = SQLITE_NOMEM_BKPT;
52930 goto pager_acquire_err;
52933 pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
52934 assert( pPg==(*ppPage) );
52935 assert( pPg->pgno==pgno );
52936 assert( pPg->pPager==pPager || pPg->pPager==0 );
52938 noContent = (flags & PAGER_GET_NOCONTENT)!=0;
52939 if( pPg->pPager && !noContent ){
52940 /* In this case the pcache already contains an initialized copy of
52941 ** the page. Return without further ado. */
52942 assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
52943 pPager->aStat[PAGER_STAT_HIT]++;
52944 return SQLITE_OK;
52946 }else{
52947 /* The pager cache has created a new page. Its content needs to
52948 ** be initialized. But first some error checks:
52950 ** (1) The maximum page number is 2^31
52951 ** (2) Never try to fetch the locking page
52953 if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
52954 rc = SQLITE_CORRUPT_BKPT;
52955 goto pager_acquire_err;
52958 pPg->pPager = pPager;
52960 assert( !isOpen(pPager->fd) || !MEMDB );
52961 if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
52962 if( pgno>pPager->mxPgno ){
52963 rc = SQLITE_FULL;
52964 goto pager_acquire_err;
52966 if( noContent ){
52967 /* Failure to set the bits in the InJournal bit-vectors is benign.
52968 ** It merely means that we might do some extra work to journal a
52969 ** page that does not need to be journaled. Nevertheless, be sure
52970 ** to test the case where a malloc error occurs while trying to set
52971 ** a bit in a bit vector.
52973 sqlite3BeginBenignMalloc();
52974 if( pgno<=pPager->dbOrigSize ){
52975 TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
52976 testcase( rc==SQLITE_NOMEM );
52978 TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
52979 testcase( rc==SQLITE_NOMEM );
52980 sqlite3EndBenignMalloc();
52982 memset(pPg->pData, 0, pPager->pageSize);
52983 IOTRACE(("ZERO %p %d\n", pPager, pgno));
52984 }else{
52985 assert( pPg->pPager==pPager );
52986 pPager->aStat[PAGER_STAT_MISS]++;
52987 rc = readDbPage(pPg);
52988 if( rc!=SQLITE_OK ){
52989 goto pager_acquire_err;
52992 pager_set_pagehash(pPg);
52994 return SQLITE_OK;
52996 pager_acquire_err:
52997 assert( rc!=SQLITE_OK );
52998 if( pPg ){
52999 sqlite3PcacheDrop(pPg);
53001 pagerUnlockIfUnused(pPager);
53002 *ppPage = 0;
53003 return rc;
53006 #if SQLITE_MAX_MMAP_SIZE>0
53007 /* The page getter for when memory-mapped I/O is enabled */
53008 static int getPageMMap(
53009 Pager *pPager, /* The pager open on the database file */
53010 Pgno pgno, /* Page number to fetch */
53011 DbPage **ppPage, /* Write a pointer to the page here */
53012 int flags /* PAGER_GET_XXX flags */
53014 int rc = SQLITE_OK;
53015 PgHdr *pPg = 0;
53016 u32 iFrame = 0; /* Frame to read from WAL file */
53018 /* It is acceptable to use a read-only (mmap) page for any page except
53019 ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
53020 ** flag was specified by the caller. And so long as the db is not a
53021 ** temporary or in-memory database. */
53022 const int bMmapOk = (pgno>1
53023 && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
53026 assert( USEFETCH(pPager) );
53027 #ifdef SQLITE_HAS_CODEC
53028 assert( pPager->xCodec==0 );
53029 #endif
53031 /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
53032 ** allows the compiler optimizer to reuse the results of the "pgno>1"
53033 ** test in the previous statement, and avoid testing pgno==0 in the
53034 ** common case where pgno is large. */
53035 if( pgno<=1 && pgno==0 ){
53036 return SQLITE_CORRUPT_BKPT;
53038 assert( pPager->eState>=PAGER_READER );
53039 assert( assert_pager_state(pPager) );
53040 assert( pPager->hasHeldSharedLock==1 );
53041 assert( pPager->errCode==SQLITE_OK );
53043 if( bMmapOk && pagerUseWal(pPager) ){
53044 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
53045 if( rc!=SQLITE_OK ){
53046 *ppPage = 0;
53047 return rc;
53050 if( bMmapOk && iFrame==0 ){
53051 void *pData = 0;
53052 rc = sqlite3OsFetch(pPager->fd,
53053 (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
53055 if( rc==SQLITE_OK && pData ){
53056 if( pPager->eState>PAGER_READER || pPager->tempFile ){
53057 pPg = sqlite3PagerLookup(pPager, pgno);
53059 if( pPg==0 ){
53060 rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
53061 }else{
53062 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
53064 if( pPg ){
53065 assert( rc==SQLITE_OK );
53066 *ppPage = pPg;
53067 return SQLITE_OK;
53070 if( rc!=SQLITE_OK ){
53071 *ppPage = 0;
53072 return rc;
53075 return getPageNormal(pPager, pgno, ppPage, flags);
53077 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
53079 /* The page getter method for when the pager is an error state */
53080 static int getPageError(
53081 Pager *pPager, /* The pager open on the database file */
53082 Pgno pgno, /* Page number to fetch */
53083 DbPage **ppPage, /* Write a pointer to the page here */
53084 int flags /* PAGER_GET_XXX flags */
53086 UNUSED_PARAMETER(pgno);
53087 UNUSED_PARAMETER(flags);
53088 assert( pPager->errCode!=SQLITE_OK );
53089 *ppPage = 0;
53090 return pPager->errCode;
53094 /* Dispatch all page fetch requests to the appropriate getter method.
53096 SQLITE_PRIVATE int sqlite3PagerGet(
53097 Pager *pPager, /* The pager open on the database file */
53098 Pgno pgno, /* Page number to fetch */
53099 DbPage **ppPage, /* Write a pointer to the page here */
53100 int flags /* PAGER_GET_XXX flags */
53102 return pPager->xGet(pPager, pgno, ppPage, flags);
53106 ** Acquire a page if it is already in the in-memory cache. Do
53107 ** not read the page from disk. Return a pointer to the page,
53108 ** or 0 if the page is not in cache.
53110 ** See also sqlite3PagerGet(). The difference between this routine
53111 ** and sqlite3PagerGet() is that _get() will go to the disk and read
53112 ** in the page if the page is not already in cache. This routine
53113 ** returns NULL if the page is not in cache or if a disk I/O error
53114 ** has ever happened.
53116 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
53117 sqlite3_pcache_page *pPage;
53118 assert( pPager!=0 );
53119 assert( pgno!=0 );
53120 assert( pPager->pPCache!=0 );
53121 pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
53122 assert( pPage==0 || pPager->hasHeldSharedLock );
53123 if( pPage==0 ) return 0;
53124 return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
53128 ** Release a page reference.
53130 ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
53131 ** used if we know that the page being released is not the last page.
53132 ** The btree layer always holds page1 open until the end, so these first
53133 ** to routines can be used to release any page other than BtShared.pPage1.
53135 ** Use sqlite3PagerUnrefPageOne() to release page1. This latter routine
53136 ** checks the total number of outstanding pages and if the number of
53137 ** pages reaches zero it drops the database lock.
53139 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
53140 TESTONLY( Pager *pPager = pPg->pPager; )
53141 assert( pPg!=0 );
53142 if( pPg->flags & PGHDR_MMAP ){
53143 assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */
53144 pagerReleaseMapPage(pPg);
53145 }else{
53146 sqlite3PcacheRelease(pPg);
53148 /* Do not use this routine to release the last reference to page1 */
53149 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
53151 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
53152 if( pPg ) sqlite3PagerUnrefNotNull(pPg);
53154 SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
53155 Pager *pPager;
53156 assert( pPg!=0 );
53157 assert( pPg->pgno==1 );
53158 assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
53159 pPager = pPg->pPager;
53160 sqlite3PcacheRelease(pPg);
53161 pagerUnlockIfUnused(pPager);
53165 ** This function is called at the start of every write transaction.
53166 ** There must already be a RESERVED or EXCLUSIVE lock on the database
53167 ** file when this routine is called.
53169 ** Open the journal file for pager pPager and write a journal header
53170 ** to the start of it. If there are active savepoints, open the sub-journal
53171 ** as well. This function is only used when the journal file is being
53172 ** opened to write a rollback log for a transaction. It is not used
53173 ** when opening a hot journal file to roll it back.
53175 ** If the journal file is already open (as it may be in exclusive mode),
53176 ** then this function just writes a journal header to the start of the
53177 ** already open file.
53179 ** Whether or not the journal file is opened by this function, the
53180 ** Pager.pInJournal bitvec structure is allocated.
53182 ** Return SQLITE_OK if everything is successful. Otherwise, return
53183 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
53184 ** an IO error code if opening or writing the journal file fails.
53186 static int pager_open_journal(Pager *pPager){
53187 int rc = SQLITE_OK; /* Return code */
53188 sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
53190 assert( pPager->eState==PAGER_WRITER_LOCKED );
53191 assert( assert_pager_state(pPager) );
53192 assert( pPager->pInJournal==0 );
53194 /* If already in the error state, this function is a no-op. But on
53195 ** the other hand, this routine is never called if we are already in
53196 ** an error state. */
53197 if( NEVER(pPager->errCode) ) return pPager->errCode;
53199 if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
53200 pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
53201 if( pPager->pInJournal==0 ){
53202 return SQLITE_NOMEM_BKPT;
53205 /* Open the journal file if it is not already open. */
53206 if( !isOpen(pPager->jfd) ){
53207 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
53208 sqlite3MemJournalOpen(pPager->jfd);
53209 }else{
53210 int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
53211 int nSpill;
53213 if( pPager->tempFile ){
53214 flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
53215 nSpill = sqlite3Config.nStmtSpill;
53216 }else{
53217 flags |= SQLITE_OPEN_MAIN_JOURNAL;
53218 nSpill = jrnlBufferSize(pPager);
53221 /* Verify that the database still has the same name as it did when
53222 ** it was originally opened. */
53223 rc = databaseIsUnmoved(pPager);
53224 if( rc==SQLITE_OK ){
53225 rc = sqlite3JournalOpen (
53226 pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
53230 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
53234 /* Write the first journal header to the journal file and open
53235 ** the sub-journal if necessary.
53237 if( rc==SQLITE_OK ){
53238 /* TODO: Check if all of these are really required. */
53239 pPager->nRec = 0;
53240 pPager->journalOff = 0;
53241 pPager->setMaster = 0;
53242 pPager->journalHdr = 0;
53243 rc = writeJournalHdr(pPager);
53247 if( rc!=SQLITE_OK ){
53248 sqlite3BitvecDestroy(pPager->pInJournal);
53249 pPager->pInJournal = 0;
53250 }else{
53251 assert( pPager->eState==PAGER_WRITER_LOCKED );
53252 pPager->eState = PAGER_WRITER_CACHEMOD;
53255 return rc;
53259 ** Begin a write-transaction on the specified pager object. If a
53260 ** write-transaction has already been opened, this function is a no-op.
53262 ** If the exFlag argument is false, then acquire at least a RESERVED
53263 ** lock on the database file. If exFlag is true, then acquire at least
53264 ** an EXCLUSIVE lock. If such a lock is already held, no locking
53265 ** functions need be called.
53267 ** If the subjInMemory argument is non-zero, then any sub-journal opened
53268 ** within this transaction will be opened as an in-memory file. This
53269 ** has no effect if the sub-journal is already opened (as it may be when
53270 ** running in exclusive mode) or if the transaction does not require a
53271 ** sub-journal. If the subjInMemory argument is zero, then any required
53272 ** sub-journal is implemented in-memory if pPager is an in-memory database,
53273 ** or using a temporary file otherwise.
53275 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
53276 int rc = SQLITE_OK;
53278 if( pPager->errCode ) return pPager->errCode;
53279 assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
53280 pPager->subjInMemory = (u8)subjInMemory;
53282 if( ALWAYS(pPager->eState==PAGER_READER) ){
53283 assert( pPager->pInJournal==0 );
53285 if( pagerUseWal(pPager) ){
53286 /* If the pager is configured to use locking_mode=exclusive, and an
53287 ** exclusive lock on the database is not already held, obtain it now.
53289 if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
53290 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
53291 if( rc!=SQLITE_OK ){
53292 return rc;
53294 (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
53297 /* Grab the write lock on the log file. If successful, upgrade to
53298 ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
53299 ** The busy-handler is not invoked if another connection already
53300 ** holds the write-lock. If possible, the upper layer will call it.
53302 rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
53303 }else{
53304 /* Obtain a RESERVED lock on the database file. If the exFlag parameter
53305 ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
53306 ** busy-handler callback can be used when upgrading to the EXCLUSIVE
53307 ** lock, but not when obtaining the RESERVED lock.
53309 rc = pagerLockDb(pPager, RESERVED_LOCK);
53310 if( rc==SQLITE_OK && exFlag ){
53311 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
53315 if( rc==SQLITE_OK ){
53316 /* Change to WRITER_LOCKED state.
53318 ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
53319 ** when it has an open transaction, but never to DBMOD or FINISHED.
53320 ** This is because in those states the code to roll back savepoint
53321 ** transactions may copy data from the sub-journal into the database
53322 ** file as well as into the page cache. Which would be incorrect in
53323 ** WAL mode.
53325 pPager->eState = PAGER_WRITER_LOCKED;
53326 pPager->dbHintSize = pPager->dbSize;
53327 pPager->dbFileSize = pPager->dbSize;
53328 pPager->dbOrigSize = pPager->dbSize;
53329 pPager->journalOff = 0;
53332 assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
53333 assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
53334 assert( assert_pager_state(pPager) );
53337 PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
53338 return rc;
53342 ** Write page pPg onto the end of the rollback journal.
53344 static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
53345 Pager *pPager = pPg->pPager;
53346 int rc;
53347 u32 cksum;
53348 char *pData2;
53349 i64 iOff = pPager->journalOff;
53351 /* We should never write to the journal file the page that
53352 ** contains the database locks. The following assert verifies
53353 ** that we do not. */
53354 assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
53356 assert( pPager->journalHdr<=pPager->journalOff );
53357 CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
53358 cksum = pager_cksum(pPager, (u8*)pData2);
53360 /* Even if an IO or diskfull error occurs while journalling the
53361 ** page in the block above, set the need-sync flag for the page.
53362 ** Otherwise, when the transaction is rolled back, the logic in
53363 ** playback_one_page() will think that the page needs to be restored
53364 ** in the database file. And if an IO error occurs while doing so,
53365 ** then corruption may follow.
53367 pPg->flags |= PGHDR_NEED_SYNC;
53369 rc = write32bits(pPager->jfd, iOff, pPg->pgno);
53370 if( rc!=SQLITE_OK ) return rc;
53371 rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
53372 if( rc!=SQLITE_OK ) return rc;
53373 rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
53374 if( rc!=SQLITE_OK ) return rc;
53376 IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
53377 pPager->journalOff, pPager->pageSize));
53378 PAGER_INCR(sqlite3_pager_writej_count);
53379 PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
53380 PAGERID(pPager), pPg->pgno,
53381 ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
53383 pPager->journalOff += 8 + pPager->pageSize;
53384 pPager->nRec++;
53385 assert( pPager->pInJournal!=0 );
53386 rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
53387 testcase( rc==SQLITE_NOMEM );
53388 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
53389 rc |= addToSavepointBitvecs(pPager, pPg->pgno);
53390 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
53391 return rc;
53395 ** Mark a single data page as writeable. The page is written into the
53396 ** main journal or sub-journal as required. If the page is written into
53397 ** one of the journals, the corresponding bit is set in the
53398 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
53399 ** of any open savepoints as appropriate.
53401 static int pager_write(PgHdr *pPg){
53402 Pager *pPager = pPg->pPager;
53403 int rc = SQLITE_OK;
53405 /* This routine is not called unless a write-transaction has already
53406 ** been started. The journal file may or may not be open at this point.
53407 ** It is never called in the ERROR state.
53409 assert( pPager->eState==PAGER_WRITER_LOCKED
53410 || pPager->eState==PAGER_WRITER_CACHEMOD
53411 || pPager->eState==PAGER_WRITER_DBMOD
53413 assert( assert_pager_state(pPager) );
53414 assert( pPager->errCode==0 );
53415 assert( pPager->readOnly==0 );
53416 CHECK_PAGE(pPg);
53418 /* The journal file needs to be opened. Higher level routines have already
53419 ** obtained the necessary locks to begin the write-transaction, but the
53420 ** rollback journal might not yet be open. Open it now if this is the case.
53422 ** This is done before calling sqlite3PcacheMakeDirty() on the page.
53423 ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
53424 ** an error might occur and the pager would end up in WRITER_LOCKED state
53425 ** with pages marked as dirty in the cache.
53427 if( pPager->eState==PAGER_WRITER_LOCKED ){
53428 rc = pager_open_journal(pPager);
53429 if( rc!=SQLITE_OK ) return rc;
53431 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
53432 assert( assert_pager_state(pPager) );
53434 /* Mark the page that is about to be modified as dirty. */
53435 sqlite3PcacheMakeDirty(pPg);
53437 /* If a rollback journal is in use, them make sure the page that is about
53438 ** to change is in the rollback journal, or if the page is a new page off
53439 ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
53441 assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
53442 if( pPager->pInJournal!=0
53443 && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
53445 assert( pagerUseWal(pPager)==0 );
53446 if( pPg->pgno<=pPager->dbOrigSize ){
53447 rc = pagerAddPageToRollbackJournal(pPg);
53448 if( rc!=SQLITE_OK ){
53449 return rc;
53451 }else{
53452 if( pPager->eState!=PAGER_WRITER_DBMOD ){
53453 pPg->flags |= PGHDR_NEED_SYNC;
53455 PAGERTRACE(("APPEND %d page %d needSync=%d\n",
53456 PAGERID(pPager), pPg->pgno,
53457 ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
53461 /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
53462 ** and before writing the page into the rollback journal. Wait until now,
53463 ** after the page has been successfully journalled, before setting the
53464 ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
53466 pPg->flags |= PGHDR_WRITEABLE;
53468 /* If the statement journal is open and the page is not in it,
53469 ** then write the page into the statement journal.
53471 if( pPager->nSavepoint>0 ){
53472 rc = subjournalPageIfRequired(pPg);
53475 /* Update the database size and return. */
53476 if( pPager->dbSize<pPg->pgno ){
53477 pPager->dbSize = pPg->pgno;
53479 return rc;
53483 ** This is a variant of sqlite3PagerWrite() that runs when the sector size
53484 ** is larger than the page size. SQLite makes the (reasonable) assumption that
53485 ** all bytes of a sector are written together by hardware. Hence, all bytes of
53486 ** a sector need to be journalled in case of a power loss in the middle of
53487 ** a write.
53489 ** Usually, the sector size is less than or equal to the page size, in which
53490 ** case pages can be individually written. This routine only runs in the
53491 ** exceptional case where the page size is smaller than the sector size.
53493 static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
53494 int rc = SQLITE_OK; /* Return code */
53495 Pgno nPageCount; /* Total number of pages in database file */
53496 Pgno pg1; /* First page of the sector pPg is located on. */
53497 int nPage = 0; /* Number of pages starting at pg1 to journal */
53498 int ii; /* Loop counter */
53499 int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
53500 Pager *pPager = pPg->pPager; /* The pager that owns pPg */
53501 Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
53503 /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
53504 ** a journal header to be written between the pages journaled by
53505 ** this function.
53507 assert( !MEMDB );
53508 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
53509 pPager->doNotSpill |= SPILLFLAG_NOSYNC;
53511 /* This trick assumes that both the page-size and sector-size are
53512 ** an integer power of 2. It sets variable pg1 to the identifier
53513 ** of the first page of the sector pPg is located on.
53515 pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
53517 nPageCount = pPager->dbSize;
53518 if( pPg->pgno>nPageCount ){
53519 nPage = (pPg->pgno - pg1)+1;
53520 }else if( (pg1+nPagePerSector-1)>nPageCount ){
53521 nPage = nPageCount+1-pg1;
53522 }else{
53523 nPage = nPagePerSector;
53525 assert(nPage>0);
53526 assert(pg1<=pPg->pgno);
53527 assert((pg1+nPage)>pPg->pgno);
53529 for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
53530 Pgno pg = pg1+ii;
53531 PgHdr *pPage;
53532 if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
53533 if( pg!=PAGER_MJ_PGNO(pPager) ){
53534 rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
53535 if( rc==SQLITE_OK ){
53536 rc = pager_write(pPage);
53537 if( pPage->flags&PGHDR_NEED_SYNC ){
53538 needSync = 1;
53540 sqlite3PagerUnrefNotNull(pPage);
53543 }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
53544 if( pPage->flags&PGHDR_NEED_SYNC ){
53545 needSync = 1;
53547 sqlite3PagerUnrefNotNull(pPage);
53551 /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
53552 ** starting at pg1, then it needs to be set for all of them. Because
53553 ** writing to any of these nPage pages may damage the others, the
53554 ** journal file must contain sync()ed copies of all of them
53555 ** before any of them can be written out to the database file.
53557 if( rc==SQLITE_OK && needSync ){
53558 assert( !MEMDB );
53559 for(ii=0; ii<nPage; ii++){
53560 PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
53561 if( pPage ){
53562 pPage->flags |= PGHDR_NEED_SYNC;
53563 sqlite3PagerUnrefNotNull(pPage);
53568 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
53569 pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
53570 return rc;
53574 ** Mark a data page as writeable. This routine must be called before
53575 ** making changes to a page. The caller must check the return value
53576 ** of this function and be careful not to change any page data unless
53577 ** this routine returns SQLITE_OK.
53579 ** The difference between this function and pager_write() is that this
53580 ** function also deals with the special case where 2 or more pages
53581 ** fit on a single disk sector. In this case all co-resident pages
53582 ** must have been written to the journal file before returning.
53584 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
53585 ** as appropriate. Otherwise, SQLITE_OK.
53587 SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
53588 Pager *pPager = pPg->pPager;
53589 assert( (pPg->flags & PGHDR_MMAP)==0 );
53590 assert( pPager->eState>=PAGER_WRITER_LOCKED );
53591 assert( assert_pager_state(pPager) );
53592 if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
53593 if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
53594 return SQLITE_OK;
53595 }else if( pPager->errCode ){
53596 return pPager->errCode;
53597 }else if( pPager->sectorSize > (u32)pPager->pageSize ){
53598 assert( pPager->tempFile==0 );
53599 return pagerWriteLargeSector(pPg);
53600 }else{
53601 return pager_write(pPg);
53606 ** Return TRUE if the page given in the argument was previously passed
53607 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
53608 ** to change the content of the page.
53610 #ifndef NDEBUG
53611 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
53612 return pPg->flags & PGHDR_WRITEABLE;
53614 #endif
53617 ** A call to this routine tells the pager that it is not necessary to
53618 ** write the information on page pPg back to the disk, even though
53619 ** that page might be marked as dirty. This happens, for example, when
53620 ** the page has been added as a leaf of the freelist and so its
53621 ** content no longer matters.
53623 ** The overlying software layer calls this routine when all of the data
53624 ** on the given page is unused. The pager marks the page as clean so
53625 ** that it does not get written to disk.
53627 ** Tests show that this optimization can quadruple the speed of large
53628 ** DELETE operations.
53630 ** This optimization cannot be used with a temp-file, as the page may
53631 ** have been dirty at the start of the transaction. In that case, if
53632 ** memory pressure forces page pPg out of the cache, the data does need
53633 ** to be written out to disk so that it may be read back in if the
53634 ** current transaction is rolled back.
53636 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
53637 Pager *pPager = pPg->pPager;
53638 if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
53639 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
53640 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
53641 pPg->flags |= PGHDR_DONT_WRITE;
53642 pPg->flags &= ~PGHDR_WRITEABLE;
53643 testcase( pPg->flags & PGHDR_NEED_SYNC );
53644 pager_set_pagehash(pPg);
53649 ** This routine is called to increment the value of the database file
53650 ** change-counter, stored as a 4-byte big-endian integer starting at
53651 ** byte offset 24 of the pager file. The secondary change counter at
53652 ** 92 is also updated, as is the SQLite version number at offset 96.
53654 ** But this only happens if the pPager->changeCountDone flag is false.
53655 ** To avoid excess churning of page 1, the update only happens once.
53656 ** See also the pager_write_changecounter() routine that does an
53657 ** unconditional update of the change counters.
53659 ** If the isDirectMode flag is zero, then this is done by calling
53660 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
53661 ** page data. In this case the file will be updated when the current
53662 ** transaction is committed.
53664 ** The isDirectMode flag may only be non-zero if the library was compiled
53665 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
53666 ** if isDirect is non-zero, then the database file is updated directly
53667 ** by writing an updated version of page 1 using a call to the
53668 ** sqlite3OsWrite() function.
53670 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
53671 int rc = SQLITE_OK;
53673 assert( pPager->eState==PAGER_WRITER_CACHEMOD
53674 || pPager->eState==PAGER_WRITER_DBMOD
53676 assert( assert_pager_state(pPager) );
53678 /* Declare and initialize constant integer 'isDirect'. If the
53679 ** atomic-write optimization is enabled in this build, then isDirect
53680 ** is initialized to the value passed as the isDirectMode parameter
53681 ** to this function. Otherwise, it is always set to zero.
53683 ** The idea is that if the atomic-write optimization is not
53684 ** enabled at compile time, the compiler can omit the tests of
53685 ** 'isDirect' below, as well as the block enclosed in the
53686 ** "if( isDirect )" condition.
53688 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
53689 # define DIRECT_MODE 0
53690 assert( isDirectMode==0 );
53691 UNUSED_PARAMETER(isDirectMode);
53692 #else
53693 # define DIRECT_MODE isDirectMode
53694 #endif
53696 if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
53697 PgHdr *pPgHdr; /* Reference to page 1 */
53699 assert( !pPager->tempFile && isOpen(pPager->fd) );
53701 /* Open page 1 of the file for writing. */
53702 rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
53703 assert( pPgHdr==0 || rc==SQLITE_OK );
53705 /* If page one was fetched successfully, and this function is not
53706 ** operating in direct-mode, make page 1 writable. When not in
53707 ** direct mode, page 1 is always held in cache and hence the PagerGet()
53708 ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
53710 if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
53711 rc = sqlite3PagerWrite(pPgHdr);
53714 if( rc==SQLITE_OK ){
53715 /* Actually do the update of the change counter */
53716 pager_write_changecounter(pPgHdr);
53718 /* If running in direct mode, write the contents of page 1 to the file. */
53719 if( DIRECT_MODE ){
53720 const void *zBuf;
53721 assert( pPager->dbFileSize>0 );
53722 CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
53723 if( rc==SQLITE_OK ){
53724 rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
53725 pPager->aStat[PAGER_STAT_WRITE]++;
53727 if( rc==SQLITE_OK ){
53728 /* Update the pager's copy of the change-counter. Otherwise, the
53729 ** next time a read transaction is opened the cache will be
53730 ** flushed (as the change-counter values will not match). */
53731 const void *pCopy = (const void *)&((const char *)zBuf)[24];
53732 memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
53733 pPager->changeCountDone = 1;
53735 }else{
53736 pPager->changeCountDone = 1;
53740 /* Release the page reference. */
53741 sqlite3PagerUnref(pPgHdr);
53743 return rc;
53747 ** Sync the database file to disk. This is a no-op for in-memory databases
53748 ** or pages with the Pager.noSync flag set.
53750 ** If successful, or if called on a pager for which it is a no-op, this
53751 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
53753 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
53754 int rc = SQLITE_OK;
53756 if( isOpen(pPager->fd) ){
53757 void *pArg = (void*)zMaster;
53758 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
53759 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
53761 if( rc==SQLITE_OK && !pPager->noSync ){
53762 assert( !MEMDB );
53763 rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
53765 return rc;
53769 ** This function may only be called while a write-transaction is active in
53770 ** rollback. If the connection is in WAL mode, this call is a no-op.
53771 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
53772 ** the database file, an attempt is made to obtain one.
53774 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
53775 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
53776 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
53777 ** returned.
53779 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
53780 int rc = pPager->errCode;
53781 assert( assert_pager_state(pPager) );
53782 if( rc==SQLITE_OK ){
53783 assert( pPager->eState==PAGER_WRITER_CACHEMOD
53784 || pPager->eState==PAGER_WRITER_DBMOD
53785 || pPager->eState==PAGER_WRITER_LOCKED
53787 assert( assert_pager_state(pPager) );
53788 if( 0==pagerUseWal(pPager) ){
53789 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
53792 return rc;
53796 ** Sync the database file for the pager pPager. zMaster points to the name
53797 ** of a master journal file that should be written into the individual
53798 ** journal file. zMaster may be NULL, which is interpreted as no master
53799 ** journal (a single database transaction).
53801 ** This routine ensures that:
53803 ** * The database file change-counter is updated,
53804 ** * the journal is synced (unless the atomic-write optimization is used),
53805 ** * all dirty pages are written to the database file,
53806 ** * the database file is truncated (if required), and
53807 ** * the database file synced.
53809 ** The only thing that remains to commit the transaction is to finalize
53810 ** (delete, truncate or zero the first part of) the journal file (or
53811 ** delete the master journal file if specified).
53813 ** Note that if zMaster==NULL, this does not overwrite a previous value
53814 ** passed to an sqlite3PagerCommitPhaseOne() call.
53816 ** If the final parameter - noSync - is true, then the database file itself
53817 ** is not synced. The caller must call sqlite3PagerSync() directly to
53818 ** sync the database file before calling CommitPhaseTwo() to delete the
53819 ** journal file in this case.
53821 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
53822 Pager *pPager, /* Pager object */
53823 const char *zMaster, /* If not NULL, the master journal name */
53824 int noSync /* True to omit the xSync on the db file */
53826 int rc = SQLITE_OK; /* Return code */
53828 assert( pPager->eState==PAGER_WRITER_LOCKED
53829 || pPager->eState==PAGER_WRITER_CACHEMOD
53830 || pPager->eState==PAGER_WRITER_DBMOD
53831 || pPager->eState==PAGER_ERROR
53833 assert( assert_pager_state(pPager) );
53835 /* If a prior error occurred, report that error again. */
53836 if( NEVER(pPager->errCode) ) return pPager->errCode;
53838 /* Provide the ability to easily simulate an I/O error during testing */
53839 if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
53841 PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
53842 pPager->zFilename, zMaster, pPager->dbSize));
53844 /* If no database changes have been made, return early. */
53845 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
53847 assert( MEMDB==0 || pPager->tempFile );
53848 assert( isOpen(pPager->fd) || pPager->tempFile );
53849 if( 0==pagerFlushOnCommit(pPager, 1) ){
53850 /* If this is an in-memory db, or no pages have been written to, or this
53851 ** function has already been called, it is mostly a no-op. However, any
53852 ** backup in progress needs to be restarted. */
53853 sqlite3BackupRestart(pPager->pBackup);
53854 }else{
53855 if( pagerUseWal(pPager) ){
53856 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
53857 PgHdr *pPageOne = 0;
53858 if( pList==0 ){
53859 /* Must have at least one page for the WAL commit flag.
53860 ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
53861 rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
53862 pList = pPageOne;
53863 pList->pDirty = 0;
53865 assert( rc==SQLITE_OK );
53866 if( ALWAYS(pList) ){
53867 rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
53869 sqlite3PagerUnref(pPageOne);
53870 if( rc==SQLITE_OK ){
53871 sqlite3PcacheCleanAll(pPager->pPCache);
53873 }else{
53874 /* The bBatch boolean is true if the batch-atomic-write commit method
53875 ** should be used. No rollback journal is created if batch-atomic-write
53876 ** is enabled.
53878 sqlite3_file *fd = pPager->fd;
53879 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
53880 const int bBatch = zMaster==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
53881 && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
53882 && !pPager->noSync
53883 && sqlite3JournalIsInMemory(pPager->jfd);
53884 #else
53885 # define bBatch 0
53886 #endif
53888 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
53889 /* The following block updates the change-counter. Exactly how it
53890 ** does this depends on whether or not the atomic-update optimization
53891 ** was enabled at compile time, and if this transaction meets the
53892 ** runtime criteria to use the operation:
53894 ** * The file-system supports the atomic-write property for
53895 ** blocks of size page-size, and
53896 ** * This commit is not part of a multi-file transaction, and
53897 ** * Exactly one page has been modified and store in the journal file.
53899 ** If the optimization was not enabled at compile time, then the
53900 ** pager_incr_changecounter() function is called to update the change
53901 ** counter in 'indirect-mode'. If the optimization is compiled in but
53902 ** is not applicable to this transaction, call sqlite3JournalCreate()
53903 ** to make sure the journal file has actually been created, then call
53904 ** pager_incr_changecounter() to update the change-counter in indirect
53905 ** mode.
53907 ** Otherwise, if the optimization is both enabled and applicable,
53908 ** then call pager_incr_changecounter() to update the change-counter
53909 ** in 'direct' mode. In this case the journal file will never be
53910 ** created for this transaction.
53912 if( bBatch==0 ){
53913 PgHdr *pPg;
53914 assert( isOpen(pPager->jfd)
53915 || pPager->journalMode==PAGER_JOURNALMODE_OFF
53916 || pPager->journalMode==PAGER_JOURNALMODE_WAL
53918 if( !zMaster && isOpen(pPager->jfd)
53919 && pPager->journalOff==jrnlBufferSize(pPager)
53920 && pPager->dbSize>=pPager->dbOrigSize
53921 && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
53923 /* Update the db file change counter via the direct-write method. The
53924 ** following call will modify the in-memory representation of page 1
53925 ** to include the updated change counter and then write page 1
53926 ** directly to the database file. Because of the atomic-write
53927 ** property of the host file-system, this is safe.
53929 rc = pager_incr_changecounter(pPager, 1);
53930 }else{
53931 rc = sqlite3JournalCreate(pPager->jfd);
53932 if( rc==SQLITE_OK ){
53933 rc = pager_incr_changecounter(pPager, 0);
53937 #else
53938 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
53939 if( zMaster ){
53940 rc = sqlite3JournalCreate(pPager->jfd);
53941 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53943 #endif
53944 rc = pager_incr_changecounter(pPager, 0);
53945 #endif
53946 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53948 /* Write the master journal name into the journal file. If a master
53949 ** journal file name has already been written to the journal file,
53950 ** or if zMaster is NULL (no master journal), then this call is a no-op.
53952 rc = writeMasterJournal(pPager, zMaster);
53953 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53955 /* Sync the journal file and write all dirty pages to the database.
53956 ** If the atomic-update optimization is being used, this sync will not
53957 ** create the journal file or perform any real IO.
53959 ** Because the change-counter page was just modified, unless the
53960 ** atomic-update optimization is used it is almost certain that the
53961 ** journal requires a sync here. However, in locking_mode=exclusive
53962 ** on a system under memory pressure it is just possible that this is
53963 ** not the case. In this case it is likely enough that the redundant
53964 ** xSync() call will be changed to a no-op by the OS anyhow.
53966 rc = syncJournal(pPager, 0);
53967 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53969 if( bBatch ){
53970 /* The pager is now in DBMOD state. But regardless of what happens
53971 ** next, attempting to play the journal back into the database would
53972 ** be unsafe. Close it now to make sure that does not happen. */
53973 sqlite3OsClose(pPager->jfd);
53974 rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
53975 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53977 rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
53978 if( bBatch ){
53979 if( rc==SQLITE_OK ){
53980 rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
53981 }else{
53982 sqlite3OsFileControl(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
53986 if( rc!=SQLITE_OK ){
53987 assert( rc!=SQLITE_IOERR_BLOCKED );
53988 goto commit_phase_one_exit;
53990 sqlite3PcacheCleanAll(pPager->pPCache);
53992 /* If the file on disk is smaller than the database image, use
53993 ** pager_truncate to grow the file here. This can happen if the database
53994 ** image was extended as part of the current transaction and then the
53995 ** last page in the db image moved to the free-list. In this case the
53996 ** last page is never written out to disk, leaving the database file
53997 ** undersized. Fix this now if it is the case. */
53998 if( pPager->dbSize>pPager->dbFileSize ){
53999 Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
54000 assert( pPager->eState==PAGER_WRITER_DBMOD );
54001 rc = pager_truncate(pPager, nNew);
54002 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
54005 /* Finally, sync the database file. */
54006 if( !noSync ){
54007 rc = sqlite3PagerSync(pPager, zMaster);
54009 IOTRACE(("DBSYNC %p\n", pPager))
54013 commit_phase_one_exit:
54014 if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
54015 pPager->eState = PAGER_WRITER_FINISHED;
54017 return rc;
54022 ** When this function is called, the database file has been completely
54023 ** updated to reflect the changes made by the current transaction and
54024 ** synced to disk. The journal file still exists in the file-system
54025 ** though, and if a failure occurs at this point it will eventually
54026 ** be used as a hot-journal and the current transaction rolled back.
54028 ** This function finalizes the journal file, either by deleting,
54029 ** truncating or partially zeroing it, so that it cannot be used
54030 ** for hot-journal rollback. Once this is done the transaction is
54031 ** irrevocably committed.
54033 ** If an error occurs, an IO error code is returned and the pager
54034 ** moves into the error state. Otherwise, SQLITE_OK is returned.
54036 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
54037 int rc = SQLITE_OK; /* Return code */
54039 /* This routine should not be called if a prior error has occurred.
54040 ** But if (due to a coding error elsewhere in the system) it does get
54041 ** called, just return the same error code without doing anything. */
54042 if( NEVER(pPager->errCode) ) return pPager->errCode;
54044 assert( pPager->eState==PAGER_WRITER_LOCKED
54045 || pPager->eState==PAGER_WRITER_FINISHED
54046 || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
54048 assert( assert_pager_state(pPager) );
54050 /* An optimization. If the database was not actually modified during
54051 ** this transaction, the pager is running in exclusive-mode and is
54052 ** using persistent journals, then this function is a no-op.
54054 ** The start of the journal file currently contains a single journal
54055 ** header with the nRec field set to 0. If such a journal is used as
54056 ** a hot-journal during hot-journal rollback, 0 changes will be made
54057 ** to the database file. So there is no need to zero the journal
54058 ** header. Since the pager is in exclusive mode, there is no need
54059 ** to drop any locks either.
54061 if( pPager->eState==PAGER_WRITER_LOCKED
54062 && pPager->exclusiveMode
54063 && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
54065 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
54066 pPager->eState = PAGER_READER;
54067 return SQLITE_OK;
54070 PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
54071 pPager->iDataVersion++;
54072 rc = pager_end_transaction(pPager, pPager->setMaster, 1);
54073 return pager_error(pPager, rc);
54077 ** If a write transaction is open, then all changes made within the
54078 ** transaction are reverted and the current write-transaction is closed.
54079 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
54080 ** state if an error occurs.
54082 ** If the pager is already in PAGER_ERROR state when this function is called,
54083 ** it returns Pager.errCode immediately. No work is performed in this case.
54085 ** Otherwise, in rollback mode, this function performs two functions:
54087 ** 1) It rolls back the journal file, restoring all database file and
54088 ** in-memory cache pages to the state they were in when the transaction
54089 ** was opened, and
54091 ** 2) It finalizes the journal file, so that it is not used for hot
54092 ** rollback at any point in the future.
54094 ** Finalization of the journal file (task 2) is only performed if the
54095 ** rollback is successful.
54097 ** In WAL mode, all cache-entries containing data modified within the
54098 ** current transaction are either expelled from the cache or reverted to
54099 ** their pre-transaction state by re-reading data from the database or
54100 ** WAL files. The WAL transaction is then closed.
54102 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
54103 int rc = SQLITE_OK; /* Return code */
54104 PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
54106 /* PagerRollback() is a no-op if called in READER or OPEN state. If
54107 ** the pager is already in the ERROR state, the rollback is not
54108 ** attempted here. Instead, the error code is returned to the caller.
54110 assert( assert_pager_state(pPager) );
54111 if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
54112 if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
54114 if( pagerUseWal(pPager) ){
54115 int rc2;
54116 rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
54117 rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
54118 if( rc==SQLITE_OK ) rc = rc2;
54119 }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
54120 int eState = pPager->eState;
54121 rc = pager_end_transaction(pPager, 0, 0);
54122 if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
54123 /* This can happen using journal_mode=off. Move the pager to the error
54124 ** state to indicate that the contents of the cache may not be trusted.
54125 ** Any active readers will get SQLITE_ABORT.
54127 pPager->errCode = SQLITE_ABORT;
54128 pPager->eState = PAGER_ERROR;
54129 setGetterMethod(pPager);
54130 return rc;
54132 }else{
54133 rc = pager_playback(pPager, 0);
54136 assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
54137 assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
54138 || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
54139 || rc==SQLITE_CANTOPEN
54142 /* If an error occurs during a ROLLBACK, we can no longer trust the pager
54143 ** cache. So call pager_error() on the way out to make any error persistent.
54145 return pager_error(pPager, rc);
54149 ** Return TRUE if the database file is opened read-only. Return FALSE
54150 ** if the database is (in theory) writable.
54152 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
54153 return pPager->readOnly;
54156 #ifdef SQLITE_DEBUG
54158 ** Return the sum of the reference counts for all pages held by pPager.
54160 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
54161 return sqlite3PcacheRefCount(pPager->pPCache);
54163 #endif
54166 ** Return the approximate number of bytes of memory currently
54167 ** used by the pager and its associated cache.
54169 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
54170 int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
54171 + 5*sizeof(void*);
54172 return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
54173 + sqlite3MallocSize(pPager)
54174 + pPager->pageSize;
54178 ** Return the number of references to the specified page.
54180 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
54181 return sqlite3PcachePageRefcount(pPage);
54184 #ifdef SQLITE_TEST
54186 ** This routine is used for testing and analysis only.
54188 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
54189 static int a[11];
54190 a[0] = sqlite3PcacheRefCount(pPager->pPCache);
54191 a[1] = sqlite3PcachePagecount(pPager->pPCache);
54192 a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
54193 a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
54194 a[4] = pPager->eState;
54195 a[5] = pPager->errCode;
54196 a[6] = pPager->aStat[PAGER_STAT_HIT];
54197 a[7] = pPager->aStat[PAGER_STAT_MISS];
54198 a[8] = 0; /* Used to be pPager->nOvfl */
54199 a[9] = pPager->nRead;
54200 a[10] = pPager->aStat[PAGER_STAT_WRITE];
54201 return a;
54203 #endif
54206 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
54207 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
54208 ** current cache hit or miss count, according to the value of eStat. If the
54209 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
54210 ** returning.
54212 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
54214 assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
54215 || eStat==SQLITE_DBSTATUS_CACHE_MISS
54216 || eStat==SQLITE_DBSTATUS_CACHE_WRITE
54219 assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
54220 assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
54221 assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
54223 *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
54224 if( reset ){
54225 pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
54230 ** Return true if this is an in-memory or temp-file backed pager.
54232 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
54233 return pPager->tempFile;
54237 ** Check that there are at least nSavepoint savepoints open. If there are
54238 ** currently less than nSavepoints open, then open one or more savepoints
54239 ** to make up the difference. If the number of savepoints is already
54240 ** equal to nSavepoint, then this function is a no-op.
54242 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
54243 ** occurs while opening the sub-journal file, then an IO error code is
54244 ** returned. Otherwise, SQLITE_OK.
54246 static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
54247 int rc = SQLITE_OK; /* Return code */
54248 int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
54249 int ii; /* Iterator variable */
54250 PagerSavepoint *aNew; /* New Pager.aSavepoint array */
54252 assert( pPager->eState>=PAGER_WRITER_LOCKED );
54253 assert( assert_pager_state(pPager) );
54254 assert( nSavepoint>nCurrent && pPager->useJournal );
54256 /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
54257 ** if the allocation fails. Otherwise, zero the new portion in case a
54258 ** malloc failure occurs while populating it in the for(...) loop below.
54260 aNew = (PagerSavepoint *)sqlite3Realloc(
54261 pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
54263 if( !aNew ){
54264 return SQLITE_NOMEM_BKPT;
54266 memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
54267 pPager->aSavepoint = aNew;
54269 /* Populate the PagerSavepoint structures just allocated. */
54270 for(ii=nCurrent; ii<nSavepoint; ii++){
54271 aNew[ii].nOrig = pPager->dbSize;
54272 if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
54273 aNew[ii].iOffset = pPager->journalOff;
54274 }else{
54275 aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
54277 aNew[ii].iSubRec = pPager->nSubRec;
54278 aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
54279 if( !aNew[ii].pInSavepoint ){
54280 return SQLITE_NOMEM_BKPT;
54282 if( pagerUseWal(pPager) ){
54283 sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
54285 pPager->nSavepoint = ii+1;
54287 assert( pPager->nSavepoint==nSavepoint );
54288 assertTruncateConstraint(pPager);
54289 return rc;
54291 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
54292 assert( pPager->eState>=PAGER_WRITER_LOCKED );
54293 assert( assert_pager_state(pPager) );
54295 if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
54296 return pagerOpenSavepoint(pPager, nSavepoint);
54297 }else{
54298 return SQLITE_OK;
54304 ** This function is called to rollback or release (commit) a savepoint.
54305 ** The savepoint to release or rollback need not be the most recently
54306 ** created savepoint.
54308 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
54309 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
54310 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
54311 ** that have occurred since the specified savepoint was created.
54313 ** The savepoint to rollback or release is identified by parameter
54314 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
54315 ** (the first created). A value of (Pager.nSavepoint-1) means operate
54316 ** on the most recently created savepoint. If iSavepoint is greater than
54317 ** (Pager.nSavepoint-1), then this function is a no-op.
54319 ** If a negative value is passed to this function, then the current
54320 ** transaction is rolled back. This is different to calling
54321 ** sqlite3PagerRollback() because this function does not terminate
54322 ** the transaction or unlock the database, it just restores the
54323 ** contents of the database to its original state.
54325 ** In any case, all savepoints with an index greater than iSavepoint
54326 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
54327 ** then savepoint iSavepoint is also destroyed.
54329 ** This function may return SQLITE_NOMEM if a memory allocation fails,
54330 ** or an IO error code if an IO error occurs while rolling back a
54331 ** savepoint. If no errors occur, SQLITE_OK is returned.
54333 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
54334 int rc = pPager->errCode;
54336 #ifdef SQLITE_ENABLE_ZIPVFS
54337 if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
54338 #endif
54340 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
54341 assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
54343 if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
54344 int ii; /* Iterator variable */
54345 int nNew; /* Number of remaining savepoints after this op. */
54347 /* Figure out how many savepoints will still be active after this
54348 ** operation. Store this value in nNew. Then free resources associated
54349 ** with any savepoints that are destroyed by this operation.
54351 nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
54352 for(ii=nNew; ii<pPager->nSavepoint; ii++){
54353 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
54355 pPager->nSavepoint = nNew;
54357 /* If this is a release of the outermost savepoint, truncate
54358 ** the sub-journal to zero bytes in size. */
54359 if( op==SAVEPOINT_RELEASE ){
54360 if( nNew==0 && isOpen(pPager->sjfd) ){
54361 /* Only truncate if it is an in-memory sub-journal. */
54362 if( sqlite3JournalIsInMemory(pPager->sjfd) ){
54363 rc = sqlite3OsTruncate(pPager->sjfd, 0);
54364 assert( rc==SQLITE_OK );
54366 pPager->nSubRec = 0;
54369 /* Else this is a rollback operation, playback the specified savepoint.
54370 ** If this is a temp-file, it is possible that the journal file has
54371 ** not yet been opened. In this case there have been no changes to
54372 ** the database file, so the playback operation can be skipped.
54374 else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
54375 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
54376 rc = pagerPlaybackSavepoint(pPager, pSavepoint);
54377 assert(rc!=SQLITE_DONE);
54380 #ifdef SQLITE_ENABLE_ZIPVFS
54381 /* If the cache has been modified but the savepoint cannot be rolled
54382 ** back journal_mode=off, put the pager in the error state. This way,
54383 ** if the VFS used by this pager includes ZipVFS, the entire transaction
54384 ** can be rolled back at the ZipVFS level. */
54385 else if(
54386 pPager->journalMode==PAGER_JOURNALMODE_OFF
54387 && pPager->eState>=PAGER_WRITER_CACHEMOD
54389 pPager->errCode = SQLITE_ABORT;
54390 pPager->eState = PAGER_ERROR;
54391 setGetterMethod(pPager);
54393 #endif
54396 return rc;
54400 ** Return the full pathname of the database file.
54402 ** Except, if the pager is in-memory only, then return an empty string if
54403 ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
54404 ** used to report the filename to the user, for compatibility with legacy
54405 ** behavior. But when the Btree needs to know the filename for matching to
54406 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
54407 ** participate in shared-cache.
54409 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
54410 return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
54414 ** Return the VFS structure for the pager.
54416 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
54417 return pPager->pVfs;
54421 ** Return the file handle for the database file associated
54422 ** with the pager. This might return NULL if the file has
54423 ** not yet been opened.
54425 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
54426 return pPager->fd;
54430 ** Return the file handle for the journal file (if it exists).
54431 ** This will be either the rollback journal or the WAL file.
54433 SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
54434 #if SQLITE_OMIT_WAL
54435 return pPager->jfd;
54436 #else
54437 return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
54438 #endif
54442 ** Return the full pathname of the journal file.
54444 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
54445 return pPager->zJournal;
54448 #ifdef SQLITE_HAS_CODEC
54450 ** Set or retrieve the codec for this pager
54452 SQLITE_PRIVATE void sqlite3PagerSetCodec(
54453 Pager *pPager,
54454 void *(*xCodec)(void*,void*,Pgno,int),
54455 void (*xCodecSizeChng)(void*,int,int),
54456 void (*xCodecFree)(void*),
54457 void *pCodec
54459 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
54460 pPager->xCodec = pPager->memDb ? 0 : xCodec;
54461 pPager->xCodecSizeChng = xCodecSizeChng;
54462 pPager->xCodecFree = xCodecFree;
54463 pPager->pCodec = pCodec;
54464 setGetterMethod(pPager);
54465 pagerReportSize(pPager);
54467 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
54468 return pPager->pCodec;
54472 ** This function is called by the wal module when writing page content
54473 ** into the log file.
54475 ** This function returns a pointer to a buffer containing the encrypted
54476 ** page content. If a malloc fails, this function may return NULL.
54478 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
54479 void *aData = 0;
54480 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
54481 return aData;
54485 ** Return the current pager state
54487 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
54488 return pPager->eState;
54490 #endif /* SQLITE_HAS_CODEC */
54492 #ifndef SQLITE_OMIT_AUTOVACUUM
54494 ** Move the page pPg to location pgno in the file.
54496 ** There must be no references to the page previously located at
54497 ** pgno (which we call pPgOld) though that page is allowed to be
54498 ** in cache. If the page previously located at pgno is not already
54499 ** in the rollback journal, it is not put there by by this routine.
54501 ** References to the page pPg remain valid. Updating any
54502 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
54503 ** allocated along with the page) is the responsibility of the caller.
54505 ** A transaction must be active when this routine is called. It used to be
54506 ** required that a statement transaction was not active, but this restriction
54507 ** has been removed (CREATE INDEX needs to move a page when a statement
54508 ** transaction is active).
54510 ** If the fourth argument, isCommit, is non-zero, then this page is being
54511 ** moved as part of a database reorganization just before the transaction
54512 ** is being committed. In this case, it is guaranteed that the database page
54513 ** pPg refers to will not be written to again within this transaction.
54515 ** This function may return SQLITE_NOMEM or an IO error code if an error
54516 ** occurs. Otherwise, it returns SQLITE_OK.
54518 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
54519 PgHdr *pPgOld; /* The page being overwritten. */
54520 Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
54521 int rc; /* Return code */
54522 Pgno origPgno; /* The original page number */
54524 assert( pPg->nRef>0 );
54525 assert( pPager->eState==PAGER_WRITER_CACHEMOD
54526 || pPager->eState==PAGER_WRITER_DBMOD
54528 assert( assert_pager_state(pPager) );
54530 /* In order to be able to rollback, an in-memory database must journal
54531 ** the page we are moving from.
54533 assert( pPager->tempFile || !MEMDB );
54534 if( pPager->tempFile ){
54535 rc = sqlite3PagerWrite(pPg);
54536 if( rc ) return rc;
54539 /* If the page being moved is dirty and has not been saved by the latest
54540 ** savepoint, then save the current contents of the page into the
54541 ** sub-journal now. This is required to handle the following scenario:
54543 ** BEGIN;
54544 ** <journal page X, then modify it in memory>
54545 ** SAVEPOINT one;
54546 ** <Move page X to location Y>
54547 ** ROLLBACK TO one;
54549 ** If page X were not written to the sub-journal here, it would not
54550 ** be possible to restore its contents when the "ROLLBACK TO one"
54551 ** statement were is processed.
54553 ** subjournalPage() may need to allocate space to store pPg->pgno into
54554 ** one or more savepoint bitvecs. This is the reason this function
54555 ** may return SQLITE_NOMEM.
54557 if( (pPg->flags & PGHDR_DIRTY)!=0
54558 && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
54560 return rc;
54563 PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
54564 PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
54565 IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
54567 /* If the journal needs to be sync()ed before page pPg->pgno can
54568 ** be written to, store pPg->pgno in local variable needSyncPgno.
54570 ** If the isCommit flag is set, there is no need to remember that
54571 ** the journal needs to be sync()ed before database page pPg->pgno
54572 ** can be written to. The caller has already promised not to write to it.
54574 if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
54575 needSyncPgno = pPg->pgno;
54576 assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
54577 pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
54578 assert( pPg->flags&PGHDR_DIRTY );
54581 /* If the cache contains a page with page-number pgno, remove it
54582 ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
54583 ** page pgno before the 'move' operation, it needs to be retained
54584 ** for the page moved there.
54586 pPg->flags &= ~PGHDR_NEED_SYNC;
54587 pPgOld = sqlite3PagerLookup(pPager, pgno);
54588 assert( !pPgOld || pPgOld->nRef==1 );
54589 if( pPgOld ){
54590 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
54591 if( pPager->tempFile ){
54592 /* Do not discard pages from an in-memory database since we might
54593 ** need to rollback later. Just move the page out of the way. */
54594 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
54595 }else{
54596 sqlite3PcacheDrop(pPgOld);
54600 origPgno = pPg->pgno;
54601 sqlite3PcacheMove(pPg, pgno);
54602 sqlite3PcacheMakeDirty(pPg);
54604 /* For an in-memory database, make sure the original page continues
54605 ** to exist, in case the transaction needs to roll back. Use pPgOld
54606 ** as the original page since it has already been allocated.
54608 if( pPager->tempFile && pPgOld ){
54609 sqlite3PcacheMove(pPgOld, origPgno);
54610 sqlite3PagerUnrefNotNull(pPgOld);
54613 if( needSyncPgno ){
54614 /* If needSyncPgno is non-zero, then the journal file needs to be
54615 ** sync()ed before any data is written to database file page needSyncPgno.
54616 ** Currently, no such page exists in the page-cache and the
54617 ** "is journaled" bitvec flag has been set. This needs to be remedied by
54618 ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
54619 ** flag.
54621 ** If the attempt to load the page into the page-cache fails, (due
54622 ** to a malloc() or IO failure), clear the bit in the pInJournal[]
54623 ** array. Otherwise, if the page is loaded and written again in
54624 ** this transaction, it may be written to the database file before
54625 ** it is synced into the journal file. This way, it may end up in
54626 ** the journal file twice, but that is not a problem.
54628 PgHdr *pPgHdr;
54629 rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
54630 if( rc!=SQLITE_OK ){
54631 if( needSyncPgno<=pPager->dbOrigSize ){
54632 assert( pPager->pTmpSpace!=0 );
54633 sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
54635 return rc;
54637 pPgHdr->flags |= PGHDR_NEED_SYNC;
54638 sqlite3PcacheMakeDirty(pPgHdr);
54639 sqlite3PagerUnrefNotNull(pPgHdr);
54642 return SQLITE_OK;
54644 #endif
54647 ** The page handle passed as the first argument refers to a dirty page
54648 ** with a page number other than iNew. This function changes the page's
54649 ** page number to iNew and sets the value of the PgHdr.flags field to
54650 ** the value passed as the third parameter.
54652 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
54653 assert( pPg->pgno!=iNew );
54654 pPg->flags = flags;
54655 sqlite3PcacheMove(pPg, iNew);
54659 ** Return a pointer to the data for the specified page.
54661 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
54662 assert( pPg->nRef>0 || pPg->pPager->memDb );
54663 return pPg->pData;
54667 ** Return a pointer to the Pager.nExtra bytes of "extra" space
54668 ** allocated along with the specified page.
54670 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
54671 return pPg->pExtra;
54675 ** Get/set the locking-mode for this pager. Parameter eMode must be one
54676 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
54677 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
54678 ** the locking-mode is set to the value specified.
54680 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
54681 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
54682 ** locking-mode.
54684 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
54685 assert( eMode==PAGER_LOCKINGMODE_QUERY
54686 || eMode==PAGER_LOCKINGMODE_NORMAL
54687 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
54688 assert( PAGER_LOCKINGMODE_QUERY<0 );
54689 assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
54690 assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
54691 if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
54692 pPager->exclusiveMode = (u8)eMode;
54694 return (int)pPager->exclusiveMode;
54698 ** Set the journal-mode for this pager. Parameter eMode must be one of:
54700 ** PAGER_JOURNALMODE_DELETE
54701 ** PAGER_JOURNALMODE_TRUNCATE
54702 ** PAGER_JOURNALMODE_PERSIST
54703 ** PAGER_JOURNALMODE_OFF
54704 ** PAGER_JOURNALMODE_MEMORY
54705 ** PAGER_JOURNALMODE_WAL
54707 ** The journalmode is set to the value specified if the change is allowed.
54708 ** The change may be disallowed for the following reasons:
54710 ** * An in-memory database can only have its journal_mode set to _OFF
54711 ** or _MEMORY.
54713 ** * Temporary databases cannot have _WAL journalmode.
54715 ** The returned indicate the current (possibly updated) journal-mode.
54717 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
54718 u8 eOld = pPager->journalMode; /* Prior journalmode */
54720 #ifdef SQLITE_DEBUG
54721 /* The print_pager_state() routine is intended to be used by the debugger
54722 ** only. We invoke it once here to suppress a compiler warning. */
54723 print_pager_state(pPager);
54724 #endif
54727 /* The eMode parameter is always valid */
54728 assert( eMode==PAGER_JOURNALMODE_DELETE
54729 || eMode==PAGER_JOURNALMODE_TRUNCATE
54730 || eMode==PAGER_JOURNALMODE_PERSIST
54731 || eMode==PAGER_JOURNALMODE_OFF
54732 || eMode==PAGER_JOURNALMODE_WAL
54733 || eMode==PAGER_JOURNALMODE_MEMORY );
54735 /* This routine is only called from the OP_JournalMode opcode, and
54736 ** the logic there will never allow a temporary file to be changed
54737 ** to WAL mode.
54739 assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
54741 /* Do allow the journalmode of an in-memory database to be set to
54742 ** anything other than MEMORY or OFF
54744 if( MEMDB ){
54745 assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
54746 if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
54747 eMode = eOld;
54751 if( eMode!=eOld ){
54753 /* Change the journal mode. */
54754 assert( pPager->eState!=PAGER_ERROR );
54755 pPager->journalMode = (u8)eMode;
54757 /* When transistioning from TRUNCATE or PERSIST to any other journal
54758 ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
54759 ** delete the journal file.
54761 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
54762 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
54763 assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
54764 assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
54765 assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
54766 assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
54768 assert( isOpen(pPager->fd) || pPager->exclusiveMode );
54769 if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
54771 /* In this case we would like to delete the journal file. If it is
54772 ** not possible, then that is not a problem. Deleting the journal file
54773 ** here is an optimization only.
54775 ** Before deleting the journal file, obtain a RESERVED lock on the
54776 ** database file. This ensures that the journal file is not deleted
54777 ** while it is in use by some other client.
54779 sqlite3OsClose(pPager->jfd);
54780 if( pPager->eLock>=RESERVED_LOCK ){
54781 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
54782 }else{
54783 int rc = SQLITE_OK;
54784 int state = pPager->eState;
54785 assert( state==PAGER_OPEN || state==PAGER_READER );
54786 if( state==PAGER_OPEN ){
54787 rc = sqlite3PagerSharedLock(pPager);
54789 if( pPager->eState==PAGER_READER ){
54790 assert( rc==SQLITE_OK );
54791 rc = pagerLockDb(pPager, RESERVED_LOCK);
54793 if( rc==SQLITE_OK ){
54794 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
54796 if( rc==SQLITE_OK && state==PAGER_READER ){
54797 pagerUnlockDb(pPager, SHARED_LOCK);
54798 }else if( state==PAGER_OPEN ){
54799 pager_unlock(pPager);
54801 assert( state==pPager->eState );
54803 }else if( eMode==PAGER_JOURNALMODE_OFF ){
54804 sqlite3OsClose(pPager->jfd);
54808 /* Return the new journal mode */
54809 return (int)pPager->journalMode;
54813 ** Return the current journal mode.
54815 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
54816 return (int)pPager->journalMode;
54820 ** Return TRUE if the pager is in a state where it is OK to change the
54821 ** journalmode. Journalmode changes can only happen when the database
54822 ** is unmodified.
54824 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
54825 assert( assert_pager_state(pPager) );
54826 if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
54827 if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
54828 return 1;
54832 ** Get/set the size-limit used for persistent journal files.
54834 ** Setting the size limit to -1 means no limit is enforced.
54835 ** An attempt to set a limit smaller than -1 is a no-op.
54837 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
54838 if( iLimit>=-1 ){
54839 pPager->journalSizeLimit = iLimit;
54840 sqlite3WalLimit(pPager->pWal, iLimit);
54842 return pPager->journalSizeLimit;
54846 ** Return a pointer to the pPager->pBackup variable. The backup module
54847 ** in backup.c maintains the content of this variable. This module
54848 ** uses it opaquely as an argument to sqlite3BackupRestart() and
54849 ** sqlite3BackupUpdate() only.
54851 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
54852 return &pPager->pBackup;
54855 #ifndef SQLITE_OMIT_VACUUM
54857 ** Unless this is an in-memory or temporary database, clear the pager cache.
54859 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
54860 assert( MEMDB==0 || pPager->tempFile );
54861 if( pPager->tempFile==0 ) pager_reset(pPager);
54863 #endif
54866 #ifndef SQLITE_OMIT_WAL
54868 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
54869 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
54870 ** or wal_blocking_checkpoint() API functions.
54872 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
54874 SQLITE_PRIVATE int sqlite3PagerCheckpoint(
54875 Pager *pPager, /* Checkpoint on this pager */
54876 sqlite3 *db, /* Db handle used to check for interrupts */
54877 int eMode, /* Type of checkpoint */
54878 int *pnLog, /* OUT: Final number of frames in log */
54879 int *pnCkpt /* OUT: Final number of checkpointed frames */
54881 int rc = SQLITE_OK;
54882 if( pPager->pWal ){
54883 rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
54884 (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
54885 pPager->pBusyHandlerArg,
54886 pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
54887 pnLog, pnCkpt
54890 return rc;
54893 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
54894 return sqlite3WalCallback(pPager->pWal);
54898 ** Return true if the underlying VFS for the given pager supports the
54899 ** primitives necessary for write-ahead logging.
54901 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
54902 const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
54903 if( pPager->noLock ) return 0;
54904 return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
54908 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
54909 ** is obtained instead, immediately release it.
54911 static int pagerExclusiveLock(Pager *pPager){
54912 int rc; /* Return code */
54914 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
54915 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
54916 if( rc!=SQLITE_OK ){
54917 /* If the attempt to grab the exclusive lock failed, release the
54918 ** pending lock that may have been obtained instead. */
54919 pagerUnlockDb(pPager, SHARED_LOCK);
54922 return rc;
54926 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
54927 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
54928 ** lock on the database file and use heap-memory to store the wal-index
54929 ** in. Otherwise, use the normal shared-memory.
54931 static int pagerOpenWal(Pager *pPager){
54932 int rc = SQLITE_OK;
54934 assert( pPager->pWal==0 && pPager->tempFile==0 );
54935 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
54937 /* If the pager is already in exclusive-mode, the WAL module will use
54938 ** heap-memory for the wal-index instead of the VFS shared-memory
54939 ** implementation. Take the exclusive lock now, before opening the WAL
54940 ** file, to make sure this is safe.
54942 if( pPager->exclusiveMode ){
54943 rc = pagerExclusiveLock(pPager);
54946 /* Open the connection to the log file. If this operation fails,
54947 ** (e.g. due to malloc() failure), return an error code.
54949 if( rc==SQLITE_OK ){
54950 rc = sqlite3WalOpen(pPager->pVfs,
54951 pPager->fd, pPager->zWal, pPager->exclusiveMode,
54952 pPager->journalSizeLimit, &pPager->pWal
54955 pagerFixMaplimit(pPager);
54957 return rc;
54962 ** The caller must be holding a SHARED lock on the database file to call
54963 ** this function.
54965 ** If the pager passed as the first argument is open on a real database
54966 ** file (not a temp file or an in-memory database), and the WAL file
54967 ** is not already open, make an attempt to open it now. If successful,
54968 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
54969 ** not support the xShmXXX() methods, return an error code. *pbOpen is
54970 ** not modified in either case.
54972 ** If the pager is open on a temp-file (or in-memory database), or if
54973 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
54974 ** without doing anything.
54976 SQLITE_PRIVATE int sqlite3PagerOpenWal(
54977 Pager *pPager, /* Pager object */
54978 int *pbOpen /* OUT: Set to true if call is a no-op */
54980 int rc = SQLITE_OK; /* Return code */
54982 assert( assert_pager_state(pPager) );
54983 assert( pPager->eState==PAGER_OPEN || pbOpen );
54984 assert( pPager->eState==PAGER_READER || !pbOpen );
54985 assert( pbOpen==0 || *pbOpen==0 );
54986 assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
54988 if( !pPager->tempFile && !pPager->pWal ){
54989 if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
54991 /* Close any rollback journal previously open */
54992 sqlite3OsClose(pPager->jfd);
54994 rc = pagerOpenWal(pPager);
54995 if( rc==SQLITE_OK ){
54996 pPager->journalMode = PAGER_JOURNALMODE_WAL;
54997 pPager->eState = PAGER_OPEN;
54999 }else{
55000 *pbOpen = 1;
55003 return rc;
55007 ** This function is called to close the connection to the log file prior
55008 ** to switching from WAL to rollback mode.
55010 ** Before closing the log file, this function attempts to take an
55011 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
55012 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
55013 ** If successful, the EXCLUSIVE lock is not released before returning.
55015 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
55016 int rc = SQLITE_OK;
55018 assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
55020 /* If the log file is not already open, but does exist in the file-system,
55021 ** it may need to be checkpointed before the connection can switch to
55022 ** rollback mode. Open it now so this can happen.
55024 if( !pPager->pWal ){
55025 int logexists = 0;
55026 rc = pagerLockDb(pPager, SHARED_LOCK);
55027 if( rc==SQLITE_OK ){
55028 rc = sqlite3OsAccess(
55029 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
55032 if( rc==SQLITE_OK && logexists ){
55033 rc = pagerOpenWal(pPager);
55037 /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
55038 ** the database file, the log and log-summary files will be deleted.
55040 if( rc==SQLITE_OK && pPager->pWal ){
55041 rc = pagerExclusiveLock(pPager);
55042 if( rc==SQLITE_OK ){
55043 rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
55044 pPager->pageSize, (u8*)pPager->pTmpSpace);
55045 pPager->pWal = 0;
55046 pagerFixMaplimit(pPager);
55047 if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
55050 return rc;
55053 #ifdef SQLITE_ENABLE_SNAPSHOT
55055 ** If this is a WAL database, obtain a snapshot handle for the snapshot
55056 ** currently open. Otherwise, return an error.
55058 SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
55059 int rc = SQLITE_ERROR;
55060 if( pPager->pWal ){
55061 rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
55063 return rc;
55067 ** If this is a WAL database, store a pointer to pSnapshot. Next time a
55068 ** read transaction is opened, attempt to read from the snapshot it
55069 ** identifies. If this is not a WAL database, return an error.
55071 SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
55072 int rc = SQLITE_OK;
55073 if( pPager->pWal ){
55074 sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
55075 }else{
55076 rc = SQLITE_ERROR;
55078 return rc;
55082 ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
55083 ** is not a WAL database, return an error.
55085 SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
55086 int rc;
55087 if( pPager->pWal ){
55088 rc = sqlite3WalSnapshotRecover(pPager->pWal);
55089 }else{
55090 rc = SQLITE_ERROR;
55092 return rc;
55094 #endif /* SQLITE_ENABLE_SNAPSHOT */
55095 #endif /* !SQLITE_OMIT_WAL */
55097 #ifdef SQLITE_ENABLE_ZIPVFS
55099 ** A read-lock must be held on the pager when this function is called. If
55100 ** the pager is in WAL mode and the WAL file currently contains one or more
55101 ** frames, return the size in bytes of the page images stored within the
55102 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
55103 ** is empty, return 0.
55105 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
55106 assert( pPager->eState>=PAGER_READER );
55107 return sqlite3WalFramesize(pPager->pWal);
55109 #endif
55111 #endif /* SQLITE_OMIT_DISKIO */
55113 /************** End of pager.c ***********************************************/
55114 /************** Begin file wal.c *********************************************/
55116 ** 2010 February 1
55118 ** The author disclaims copyright to this source code. In place of
55119 ** a legal notice, here is a blessing:
55121 ** May you do good and not evil.
55122 ** May you find forgiveness for yourself and forgive others.
55123 ** May you share freely, never taking more than you give.
55125 *************************************************************************
55127 ** This file contains the implementation of a write-ahead log (WAL) used in
55128 ** "journal_mode=WAL" mode.
55130 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
55132 ** A WAL file consists of a header followed by zero or more "frames".
55133 ** Each frame records the revised content of a single page from the
55134 ** database file. All changes to the database are recorded by writing
55135 ** frames into the WAL. Transactions commit when a frame is written that
55136 ** contains a commit marker. A single WAL can and usually does record
55137 ** multiple transactions. Periodically, the content of the WAL is
55138 ** transferred back into the database file in an operation called a
55139 ** "checkpoint".
55141 ** A single WAL file can be used multiple times. In other words, the
55142 ** WAL can fill up with frames and then be checkpointed and then new
55143 ** frames can overwrite the old ones. A WAL always grows from beginning
55144 ** toward the end. Checksums and counters attached to each frame are
55145 ** used to determine which frames within the WAL are valid and which
55146 ** are leftovers from prior checkpoints.
55148 ** The WAL header is 32 bytes in size and consists of the following eight
55149 ** big-endian 32-bit unsigned integer values:
55151 ** 0: Magic number. 0x377f0682 or 0x377f0683
55152 ** 4: File format version. Currently 3007000
55153 ** 8: Database page size. Example: 1024
55154 ** 12: Checkpoint sequence number
55155 ** 16: Salt-1, random integer incremented with each checkpoint
55156 ** 20: Salt-2, a different random integer changing with each ckpt
55157 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
55158 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
55160 ** Immediately following the wal-header are zero or more frames. Each
55161 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
55162 ** of page data. The frame-header is six big-endian 32-bit unsigned
55163 ** integer values, as follows:
55165 ** 0: Page number.
55166 ** 4: For commit records, the size of the database image in pages
55167 ** after the commit. For all other records, zero.
55168 ** 8: Salt-1 (copied from the header)
55169 ** 12: Salt-2 (copied from the header)
55170 ** 16: Checksum-1.
55171 ** 20: Checksum-2.
55173 ** A frame is considered valid if and only if the following conditions are
55174 ** true:
55176 ** (1) The salt-1 and salt-2 values in the frame-header match
55177 ** salt values in the wal-header
55179 ** (2) The checksum values in the final 8 bytes of the frame-header
55180 ** exactly match the checksum computed consecutively on the
55181 ** WAL header and the first 8 bytes and the content of all frames
55182 ** up to and including the current frame.
55184 ** The checksum is computed using 32-bit big-endian integers if the
55185 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
55186 ** is computed using little-endian if the magic number is 0x377f0682.
55187 ** The checksum values are always stored in the frame header in a
55188 ** big-endian format regardless of which byte order is used to compute
55189 ** the checksum. The checksum is computed by interpreting the input as
55190 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
55191 ** algorithm used for the checksum is as follows:
55193 ** for i from 0 to n-1 step 2:
55194 ** s0 += x[i] + s1;
55195 ** s1 += x[i+1] + s0;
55196 ** endfor
55198 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
55199 ** in reverse order (the largest fibonacci weight occurs on the first element
55200 ** of the sequence being summed.) The s1 value spans all 32-bit
55201 ** terms of the sequence whereas s0 omits the final term.
55203 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
55204 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
55205 ** The VFS.xSync operations serve as write barriers - all writes launched
55206 ** before the xSync must complete before any write that launches after the
55207 ** xSync begins.
55209 ** After each checkpoint, the salt-1 value is incremented and the salt-2
55210 ** value is randomized. This prevents old and new frames in the WAL from
55211 ** being considered valid at the same time and being checkpointing together
55212 ** following a crash.
55214 ** READER ALGORITHM
55216 ** To read a page from the database (call it page number P), a reader
55217 ** first checks the WAL to see if it contains page P. If so, then the
55218 ** last valid instance of page P that is a followed by a commit frame
55219 ** or is a commit frame itself becomes the value read. If the WAL
55220 ** contains no copies of page P that are valid and which are a commit
55221 ** frame or are followed by a commit frame, then page P is read from
55222 ** the database file.
55224 ** To start a read transaction, the reader records the index of the last
55225 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
55226 ** for all subsequent read operations. New transactions can be appended
55227 ** to the WAL, but as long as the reader uses its original mxFrame value
55228 ** and ignores the newly appended content, it will see a consistent snapshot
55229 ** of the database from a single point in time. This technique allows
55230 ** multiple concurrent readers to view different versions of the database
55231 ** content simultaneously.
55233 ** The reader algorithm in the previous paragraphs works correctly, but
55234 ** because frames for page P can appear anywhere within the WAL, the
55235 ** reader has to scan the entire WAL looking for page P frames. If the
55236 ** WAL is large (multiple megabytes is typical) that scan can be slow,
55237 ** and read performance suffers. To overcome this problem, a separate
55238 ** data structure called the wal-index is maintained to expedite the
55239 ** search for frames of a particular page.
55241 ** WAL-INDEX FORMAT
55243 ** Conceptually, the wal-index is shared memory, though VFS implementations
55244 ** might choose to implement the wal-index using a mmapped file. Because
55245 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
55246 ** on a network filesystem. All users of the database must be able to
55247 ** share memory.
55249 ** The wal-index is transient. After a crash, the wal-index can (and should
55250 ** be) reconstructed from the original WAL file. In fact, the VFS is required
55251 ** to either truncate or zero the header of the wal-index when the last
55252 ** connection to it closes. Because the wal-index is transient, it can
55253 ** use an architecture-specific format; it does not have to be cross-platform.
55254 ** Hence, unlike the database and WAL file formats which store all values
55255 ** as big endian, the wal-index can store multi-byte values in the native
55256 ** byte order of the host computer.
55258 ** The purpose of the wal-index is to answer this question quickly: Given
55259 ** a page number P and a maximum frame index M, return the index of the
55260 ** last frame in the wal before frame M for page P in the WAL, or return
55261 ** NULL if there are no frames for page P in the WAL prior to M.
55263 ** The wal-index consists of a header region, followed by an one or
55264 ** more index blocks.
55266 ** The wal-index header contains the total number of frames within the WAL
55267 ** in the mxFrame field.
55269 ** Each index block except for the first contains information on
55270 ** HASHTABLE_NPAGE frames. The first index block contains information on
55271 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
55272 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
55273 ** first index block are the same size as all other index blocks in the
55274 ** wal-index.
55276 ** Each index block contains two sections, a page-mapping that contains the
55277 ** database page number associated with each wal frame, and a hash-table
55278 ** that allows readers to query an index block for a specific page number.
55279 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
55280 ** for the first index block) 32-bit page numbers. The first entry in the
55281 ** first index-block contains the database page number corresponding to the
55282 ** first frame in the WAL file. The first entry in the second index block
55283 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
55284 ** the log, and so on.
55286 ** The last index block in a wal-index usually contains less than the full
55287 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
55288 ** depending on the contents of the WAL file. This does not change the
55289 ** allocated size of the page-mapping array - the page-mapping array merely
55290 ** contains unused entries.
55292 ** Even without using the hash table, the last frame for page P
55293 ** can be found by scanning the page-mapping sections of each index block
55294 ** starting with the last index block and moving toward the first, and
55295 ** within each index block, starting at the end and moving toward the
55296 ** beginning. The first entry that equals P corresponds to the frame
55297 ** holding the content for that page.
55299 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
55300 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
55301 ** hash table for each page number in the mapping section, so the hash
55302 ** table is never more than half full. The expected number of collisions
55303 ** prior to finding a match is 1. Each entry of the hash table is an
55304 ** 1-based index of an entry in the mapping section of the same
55305 ** index block. Let K be the 1-based index of the largest entry in
55306 ** the mapping section. (For index blocks other than the last, K will
55307 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
55308 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
55309 ** contain a value of 0.
55311 ** To look for page P in the hash table, first compute a hash iKey on
55312 ** P as follows:
55314 ** iKey = (P * 383) % HASHTABLE_NSLOT
55316 ** Then start scanning entries of the hash table, starting with iKey
55317 ** (wrapping around to the beginning when the end of the hash table is
55318 ** reached) until an unused hash slot is found. Let the first unused slot
55319 ** be at index iUnused. (iUnused might be less than iKey if there was
55320 ** wrap-around.) Because the hash table is never more than half full,
55321 ** the search is guaranteed to eventually hit an unused entry. Let
55322 ** iMax be the value between iKey and iUnused, closest to iUnused,
55323 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
55324 ** no hash slot such that aHash[i]==p) then page P is not in the
55325 ** current index block. Otherwise the iMax-th mapping entry of the
55326 ** current index block corresponds to the last entry that references
55327 ** page P.
55329 ** A hash search begins with the last index block and moves toward the
55330 ** first index block, looking for entries corresponding to page P. On
55331 ** average, only two or three slots in each index block need to be
55332 ** examined in order to either find the last entry for page P, or to
55333 ** establish that no such entry exists in the block. Each index block
55334 ** holds over 4000 entries. So two or three index blocks are sufficient
55335 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
55336 ** comparisons (on average) suffice to either locate a frame in the
55337 ** WAL or to establish that the frame does not exist in the WAL. This
55338 ** is much faster than scanning the entire 10MB WAL.
55340 ** Note that entries are added in order of increasing K. Hence, one
55341 ** reader might be using some value K0 and a second reader that started
55342 ** at a later time (after additional transactions were added to the WAL
55343 ** and to the wal-index) might be using a different value K1, where K1>K0.
55344 ** Both readers can use the same hash table and mapping section to get
55345 ** the correct result. There may be entries in the hash table with
55346 ** K>K0 but to the first reader, those entries will appear to be unused
55347 ** slots in the hash table and so the first reader will get an answer as
55348 ** if no values greater than K0 had ever been inserted into the hash table
55349 ** in the first place - which is what reader one wants. Meanwhile, the
55350 ** second reader using K1 will see additional values that were inserted
55351 ** later, which is exactly what reader two wants.
55353 ** When a rollback occurs, the value of K is decreased. Hash table entries
55354 ** that correspond to frames greater than the new K value are removed
55355 ** from the hash table at this point.
55357 #ifndef SQLITE_OMIT_WAL
55359 /* #include "wal.h" */
55362 ** Trace output macros
55364 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
55365 SQLITE_PRIVATE int sqlite3WalTrace = 0;
55366 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
55367 #else
55368 # define WALTRACE(X)
55369 #endif
55372 ** The maximum (and only) versions of the wal and wal-index formats
55373 ** that may be interpreted by this version of SQLite.
55375 ** If a client begins recovering a WAL file and finds that (a) the checksum
55376 ** values in the wal-header are correct and (b) the version field is not
55377 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
55379 ** Similarly, if a client successfully reads a wal-index header (i.e. the
55380 ** checksum test is successful) and finds that the version field is not
55381 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
55382 ** returns SQLITE_CANTOPEN.
55384 #define WAL_MAX_VERSION 3007000
55385 #define WALINDEX_MAX_VERSION 3007000
55388 ** Indices of various locking bytes. WAL_NREADER is the number
55389 ** of available reader locks and should be at least 3. The default
55390 ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
55392 #define WAL_WRITE_LOCK 0
55393 #define WAL_ALL_BUT_WRITE 1
55394 #define WAL_CKPT_LOCK 1
55395 #define WAL_RECOVER_LOCK 2
55396 #define WAL_READ_LOCK(I) (3+(I))
55397 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
55400 /* Object declarations */
55401 typedef struct WalIndexHdr WalIndexHdr;
55402 typedef struct WalIterator WalIterator;
55403 typedef struct WalCkptInfo WalCkptInfo;
55407 ** The following object holds a copy of the wal-index header content.
55409 ** The actual header in the wal-index consists of two copies of this
55410 ** object followed by one instance of the WalCkptInfo object.
55411 ** For all versions of SQLite through 3.10.0 and probably beyond,
55412 ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
55413 ** the total header size is 136 bytes.
55415 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
55416 ** Or it can be 1 to represent a 65536-byte page. The latter case was
55417 ** added in 3.7.1 when support for 64K pages was added.
55419 struct WalIndexHdr {
55420 u32 iVersion; /* Wal-index version */
55421 u32 unused; /* Unused (padding) field */
55422 u32 iChange; /* Counter incremented each transaction */
55423 u8 isInit; /* 1 when initialized */
55424 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
55425 u16 szPage; /* Database page size in bytes. 1==64K */
55426 u32 mxFrame; /* Index of last valid frame in the WAL */
55427 u32 nPage; /* Size of database in pages */
55428 u32 aFrameCksum[2]; /* Checksum of last frame in log */
55429 u32 aSalt[2]; /* Two salt values copied from WAL header */
55430 u32 aCksum[2]; /* Checksum over all prior fields */
55434 ** A copy of the following object occurs in the wal-index immediately
55435 ** following the second copy of the WalIndexHdr. This object stores
55436 ** information used by checkpoint.
55438 ** nBackfill is the number of frames in the WAL that have been written
55439 ** back into the database. (We call the act of moving content from WAL to
55440 ** database "backfilling".) The nBackfill number is never greater than
55441 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
55442 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
55443 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
55444 ** mxFrame back to zero when the WAL is reset.
55446 ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
55447 ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
55448 ** the nBackfillAttempted is set before any backfilling is done and the
55449 ** nBackfill is only set after all backfilling completes. So if a checkpoint
55450 ** crashes, nBackfillAttempted might be larger than nBackfill. The
55451 ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
55453 ** The aLock[] field is a set of bytes used for locking. These bytes should
55454 ** never be read or written.
55456 ** There is one entry in aReadMark[] for each reader lock. If a reader
55457 ** holds read-lock K, then the value in aReadMark[K] is no greater than
55458 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
55459 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
55460 ** a special case; its value is never used and it exists as a place-holder
55461 ** to avoid having to offset aReadMark[] indexs by one. Readers holding
55462 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
55463 ** directly from the database.
55465 ** The value of aReadMark[K] may only be changed by a thread that
55466 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
55467 ** aReadMark[K] cannot changed while there is a reader is using that mark
55468 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
55470 ** The checkpointer may only transfer frames from WAL to database where
55471 ** the frame numbers are less than or equal to every aReadMark[] that is
55472 ** in use (that is, every aReadMark[j] for which there is a corresponding
55473 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
55474 ** largest value and will increase an unused aReadMark[] to mxFrame if there
55475 ** is not already an aReadMark[] equal to mxFrame. The exception to the
55476 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
55477 ** in the WAL has been backfilled into the database) then new readers
55478 ** will choose aReadMark[0] which has value 0 and hence such reader will
55479 ** get all their all content directly from the database file and ignore
55480 ** the WAL.
55482 ** Writers normally append new frames to the end of the WAL. However,
55483 ** if nBackfill equals mxFrame (meaning that all WAL content has been
55484 ** written back into the database) and if no readers are using the WAL
55485 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
55486 ** the writer will first "reset" the WAL back to the beginning and start
55487 ** writing new content beginning at frame 1.
55489 ** We assume that 32-bit loads are atomic and so no locks are needed in
55490 ** order to read from any aReadMark[] entries.
55492 struct WalCkptInfo {
55493 u32 nBackfill; /* Number of WAL frames backfilled into DB */
55494 u32 aReadMark[WAL_NREADER]; /* Reader marks */
55495 u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
55496 u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
55497 u32 notUsed0; /* Available for future enhancements */
55499 #define READMARK_NOT_USED 0xffffffff
55502 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
55503 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
55504 ** only support mandatory file-locks, we do not read or write data
55505 ** from the region of the file on which locks are applied.
55507 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
55508 #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
55510 /* Size of header before each frame in wal */
55511 #define WAL_FRAME_HDRSIZE 24
55513 /* Size of write ahead log header, including checksum. */
55514 /* #define WAL_HDRSIZE 24 */
55515 #define WAL_HDRSIZE 32
55517 /* WAL magic value. Either this value, or the same value with the least
55518 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
55519 ** big-endian format in the first 4 bytes of a WAL file.
55521 ** If the LSB is set, then the checksums for each frame within the WAL
55522 ** file are calculated by treating all data as an array of 32-bit
55523 ** big-endian words. Otherwise, they are calculated by interpreting
55524 ** all data as 32-bit little-endian words.
55526 #define WAL_MAGIC 0x377f0682
55529 ** Return the offset of frame iFrame in the write-ahead log file,
55530 ** assuming a database page size of szPage bytes. The offset returned
55531 ** is to the start of the write-ahead log frame-header.
55533 #define walFrameOffset(iFrame, szPage) ( \
55534 WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
55538 ** An open write-ahead log file is represented by an instance of the
55539 ** following object.
55541 struct Wal {
55542 sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
55543 sqlite3_file *pDbFd; /* File handle for the database file */
55544 sqlite3_file *pWalFd; /* File handle for WAL file */
55545 u32 iCallback; /* Value to pass to log callback (or 0) */
55546 i64 mxWalSize; /* Truncate WAL to this size upon reset */
55547 int nWiData; /* Size of array apWiData */
55548 int szFirstBlock; /* Size of first block written to WAL file */
55549 volatile u32 **apWiData; /* Pointer to wal-index content in memory */
55550 u32 szPage; /* Database page size */
55551 i16 readLock; /* Which read lock is being held. -1 for none */
55552 u8 syncFlags; /* Flags to use to sync header writes */
55553 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
55554 u8 writeLock; /* True if in a write transaction */
55555 u8 ckptLock; /* True if holding a checkpoint lock */
55556 u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
55557 u8 truncateOnCommit; /* True to truncate WAL file on commit */
55558 u8 syncHeader; /* Fsync the WAL header if true */
55559 u8 padToSectorBoundary; /* Pad transactions out to the next sector */
55560 WalIndexHdr hdr; /* Wal-index header for current transaction */
55561 u32 minFrame; /* Ignore wal frames before this one */
55562 u32 iReCksum; /* On commit, recalculate checksums from here */
55563 const char *zWalName; /* Name of WAL file */
55564 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
55565 #ifdef SQLITE_DEBUG
55566 u8 lockError; /* True if a locking error has occurred */
55567 #endif
55568 #ifdef SQLITE_ENABLE_SNAPSHOT
55569 WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
55570 #endif
55574 ** Candidate values for Wal.exclusiveMode.
55576 #define WAL_NORMAL_MODE 0
55577 #define WAL_EXCLUSIVE_MODE 1
55578 #define WAL_HEAPMEMORY_MODE 2
55581 ** Possible values for WAL.readOnly
55583 #define WAL_RDWR 0 /* Normal read/write connection */
55584 #define WAL_RDONLY 1 /* The WAL file is readonly */
55585 #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
55588 ** Each page of the wal-index mapping contains a hash-table made up of
55589 ** an array of HASHTABLE_NSLOT elements of the following type.
55591 typedef u16 ht_slot;
55594 ** This structure is used to implement an iterator that loops through
55595 ** all frames in the WAL in database page order. Where two or more frames
55596 ** correspond to the same database page, the iterator visits only the
55597 ** frame most recently written to the WAL (in other words, the frame with
55598 ** the largest index).
55600 ** The internals of this structure are only accessed by:
55602 ** walIteratorInit() - Create a new iterator,
55603 ** walIteratorNext() - Step an iterator,
55604 ** walIteratorFree() - Free an iterator.
55606 ** This functionality is used by the checkpoint code (see walCheckpoint()).
55608 struct WalIterator {
55609 int iPrior; /* Last result returned from the iterator */
55610 int nSegment; /* Number of entries in aSegment[] */
55611 struct WalSegment {
55612 int iNext; /* Next slot in aIndex[] not yet returned */
55613 ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
55614 u32 *aPgno; /* Array of page numbers. */
55615 int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
55616 int iZero; /* Frame number associated with aPgno[0] */
55617 } aSegment[1]; /* One for every 32KB page in the wal-index */
55621 ** Define the parameters of the hash tables in the wal-index file. There
55622 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
55623 ** wal-index.
55625 ** Changing any of these constants will alter the wal-index format and
55626 ** create incompatibilities.
55628 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
55629 #define HASHTABLE_HASH_1 383 /* Should be prime */
55630 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
55633 ** The block of page numbers associated with the first hash-table in a
55634 ** wal-index is smaller than usual. This is so that there is a complete
55635 ** hash-table on each aligned 32KB page of the wal-index.
55637 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
55639 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
55640 #define WALINDEX_PGSZ ( \
55641 sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
55645 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
55646 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
55647 ** numbered from zero.
55649 ** If this call is successful, *ppPage is set to point to the wal-index
55650 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
55651 ** then an SQLite error code is returned and *ppPage is set to 0.
55653 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
55654 int rc = SQLITE_OK;
55656 /* Enlarge the pWal->apWiData[] array if required */
55657 if( pWal->nWiData<=iPage ){
55658 int nByte = sizeof(u32*)*(iPage+1);
55659 volatile u32 **apNew;
55660 apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
55661 if( !apNew ){
55662 *ppPage = 0;
55663 return SQLITE_NOMEM_BKPT;
55665 memset((void*)&apNew[pWal->nWiData], 0,
55666 sizeof(u32*)*(iPage+1-pWal->nWiData));
55667 pWal->apWiData = apNew;
55668 pWal->nWiData = iPage+1;
55671 /* Request a pointer to the required page from the VFS */
55672 if( pWal->apWiData[iPage]==0 ){
55673 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
55674 pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
55675 if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
55676 }else{
55677 rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
55678 pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
55680 if( rc==SQLITE_READONLY ){
55681 pWal->readOnly |= WAL_SHM_RDONLY;
55682 rc = SQLITE_OK;
55687 *ppPage = pWal->apWiData[iPage];
55688 assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
55689 return rc;
55693 ** Return a pointer to the WalCkptInfo structure in the wal-index.
55695 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
55696 assert( pWal->nWiData>0 && pWal->apWiData[0] );
55697 return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
55701 ** Return a pointer to the WalIndexHdr structure in the wal-index.
55703 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
55704 assert( pWal->nWiData>0 && pWal->apWiData[0] );
55705 return (volatile WalIndexHdr*)pWal->apWiData[0];
55709 ** The argument to this macro must be of type u32. On a little-endian
55710 ** architecture, it returns the u32 value that results from interpreting
55711 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
55712 ** returns the value that would be produced by interpreting the 4 bytes
55713 ** of the input value as a little-endian integer.
55715 #define BYTESWAP32(x) ( \
55716 (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
55717 + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
55721 ** Generate or extend an 8 byte checksum based on the data in
55722 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
55723 ** initial values of 0 and 0 if aIn==NULL).
55725 ** The checksum is written back into aOut[] before returning.
55727 ** nByte must be a positive multiple of 8.
55729 static void walChecksumBytes(
55730 int nativeCksum, /* True for native byte-order, false for non-native */
55731 u8 *a, /* Content to be checksummed */
55732 int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
55733 const u32 *aIn, /* Initial checksum value input */
55734 u32 *aOut /* OUT: Final checksum value output */
55736 u32 s1, s2;
55737 u32 *aData = (u32 *)a;
55738 u32 *aEnd = (u32 *)&a[nByte];
55740 if( aIn ){
55741 s1 = aIn[0];
55742 s2 = aIn[1];
55743 }else{
55744 s1 = s2 = 0;
55747 assert( nByte>=8 );
55748 assert( (nByte&0x00000007)==0 );
55750 if( nativeCksum ){
55751 do {
55752 s1 += *aData++ + s2;
55753 s2 += *aData++ + s1;
55754 }while( aData<aEnd );
55755 }else{
55756 do {
55757 s1 += BYTESWAP32(aData[0]) + s2;
55758 s2 += BYTESWAP32(aData[1]) + s1;
55759 aData += 2;
55760 }while( aData<aEnd );
55763 aOut[0] = s1;
55764 aOut[1] = s2;
55767 static void walShmBarrier(Wal *pWal){
55768 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
55769 sqlite3OsShmBarrier(pWal->pDbFd);
55774 ** Write the header information in pWal->hdr into the wal-index.
55776 ** The checksum on pWal->hdr is updated before it is written.
55778 static void walIndexWriteHdr(Wal *pWal){
55779 volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
55780 const int nCksum = offsetof(WalIndexHdr, aCksum);
55782 assert( pWal->writeLock );
55783 pWal->hdr.isInit = 1;
55784 pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
55785 walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
55786 memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
55787 walShmBarrier(pWal);
55788 memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
55792 ** This function encodes a single frame header and writes it to a buffer
55793 ** supplied by the caller. A frame-header is made up of a series of
55794 ** 4-byte big-endian integers, as follows:
55796 ** 0: Page number.
55797 ** 4: For commit records, the size of the database image in pages
55798 ** after the commit. For all other records, zero.
55799 ** 8: Salt-1 (copied from the wal-header)
55800 ** 12: Salt-2 (copied from the wal-header)
55801 ** 16: Checksum-1.
55802 ** 20: Checksum-2.
55804 static void walEncodeFrame(
55805 Wal *pWal, /* The write-ahead log */
55806 u32 iPage, /* Database page number for frame */
55807 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
55808 u8 *aData, /* Pointer to page data */
55809 u8 *aFrame /* OUT: Write encoded frame here */
55811 int nativeCksum; /* True for native byte-order checksums */
55812 u32 *aCksum = pWal->hdr.aFrameCksum;
55813 assert( WAL_FRAME_HDRSIZE==24 );
55814 sqlite3Put4byte(&aFrame[0], iPage);
55815 sqlite3Put4byte(&aFrame[4], nTruncate);
55816 if( pWal->iReCksum==0 ){
55817 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
55819 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
55820 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
55821 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
55823 sqlite3Put4byte(&aFrame[16], aCksum[0]);
55824 sqlite3Put4byte(&aFrame[20], aCksum[1]);
55825 }else{
55826 memset(&aFrame[8], 0, 16);
55831 ** Check to see if the frame with header in aFrame[] and content
55832 ** in aData[] is valid. If it is a valid frame, fill *piPage and
55833 ** *pnTruncate and return true. Return if the frame is not valid.
55835 static int walDecodeFrame(
55836 Wal *pWal, /* The write-ahead log */
55837 u32 *piPage, /* OUT: Database page number for frame */
55838 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
55839 u8 *aData, /* Pointer to page data (for checksum) */
55840 u8 *aFrame /* Frame data */
55842 int nativeCksum; /* True for native byte-order checksums */
55843 u32 *aCksum = pWal->hdr.aFrameCksum;
55844 u32 pgno; /* Page number of the frame */
55845 assert( WAL_FRAME_HDRSIZE==24 );
55847 /* A frame is only valid if the salt values in the frame-header
55848 ** match the salt values in the wal-header.
55850 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
55851 return 0;
55854 /* A frame is only valid if the page number is creater than zero.
55856 pgno = sqlite3Get4byte(&aFrame[0]);
55857 if( pgno==0 ){
55858 return 0;
55861 /* A frame is only valid if a checksum of the WAL header,
55862 ** all prior frams, the first 16 bytes of this frame-header,
55863 ** and the frame-data matches the checksum in the last 8
55864 ** bytes of this frame-header.
55866 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
55867 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
55868 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
55869 if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
55870 || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
55872 /* Checksum failed. */
55873 return 0;
55876 /* If we reach this point, the frame is valid. Return the page number
55877 ** and the new database size.
55879 *piPage = pgno;
55880 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
55881 return 1;
55885 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
55887 ** Names of locks. This routine is used to provide debugging output and is not
55888 ** a part of an ordinary build.
55890 static const char *walLockName(int lockIdx){
55891 if( lockIdx==WAL_WRITE_LOCK ){
55892 return "WRITE-LOCK";
55893 }else if( lockIdx==WAL_CKPT_LOCK ){
55894 return "CKPT-LOCK";
55895 }else if( lockIdx==WAL_RECOVER_LOCK ){
55896 return "RECOVER-LOCK";
55897 }else{
55898 static char zName[15];
55899 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
55900 lockIdx-WAL_READ_LOCK(0));
55901 return zName;
55904 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
55908 ** Set or release locks on the WAL. Locks are either shared or exclusive.
55909 ** A lock cannot be moved directly between shared and exclusive - it must go
55910 ** through the unlocked state first.
55912 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
55914 static int walLockShared(Wal *pWal, int lockIdx){
55915 int rc;
55916 if( pWal->exclusiveMode ) return SQLITE_OK;
55917 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
55918 SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
55919 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
55920 walLockName(lockIdx), rc ? "failed" : "ok"));
55921 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
55922 return rc;
55924 static void walUnlockShared(Wal *pWal, int lockIdx){
55925 if( pWal->exclusiveMode ) return;
55926 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
55927 SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
55928 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
55930 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
55931 int rc;
55932 if( pWal->exclusiveMode ) return SQLITE_OK;
55933 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
55934 SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
55935 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
55936 walLockName(lockIdx), n, rc ? "failed" : "ok"));
55937 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
55938 return rc;
55940 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
55941 if( pWal->exclusiveMode ) return;
55942 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
55943 SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
55944 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
55945 walLockName(lockIdx), n));
55949 ** Compute a hash on a page number. The resulting hash value must land
55950 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
55951 ** the hash to the next value in the event of a collision.
55953 static int walHash(u32 iPage){
55954 assert( iPage>0 );
55955 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
55956 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
55958 static int walNextHash(int iPriorHash){
55959 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
55963 ** Return pointers to the hash table and page number array stored on
55964 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
55965 ** numbered starting from 0.
55967 ** Set output variable *paHash to point to the start of the hash table
55968 ** in the wal-index file. Set *piZero to one less than the frame
55969 ** number of the first frame indexed by this hash table. If a
55970 ** slot in the hash table is set to N, it refers to frame number
55971 ** (*piZero+N) in the log.
55973 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
55974 ** first frame indexed by the hash table, frame (*piZero+1).
55976 static int walHashGet(
55977 Wal *pWal, /* WAL handle */
55978 int iHash, /* Find the iHash'th table */
55979 volatile ht_slot **paHash, /* OUT: Pointer to hash index */
55980 volatile u32 **paPgno, /* OUT: Pointer to page number array */
55981 u32 *piZero /* OUT: Frame associated with *paPgno[0] */
55983 int rc; /* Return code */
55984 volatile u32 *aPgno;
55986 rc = walIndexPage(pWal, iHash, &aPgno);
55987 assert( rc==SQLITE_OK || iHash>0 );
55989 if( rc==SQLITE_OK ){
55990 u32 iZero;
55991 volatile ht_slot *aHash;
55993 aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
55994 if( iHash==0 ){
55995 aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
55996 iZero = 0;
55997 }else{
55998 iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
56001 *paPgno = &aPgno[-1];
56002 *paHash = aHash;
56003 *piZero = iZero;
56005 return rc;
56009 ** Return the number of the wal-index page that contains the hash-table
56010 ** and page-number array that contain entries corresponding to WAL frame
56011 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
56012 ** are numbered starting from 0.
56014 static int walFramePage(u32 iFrame){
56015 int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
56016 assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
56017 && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
56018 && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
56019 && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
56020 && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
56022 return iHash;
56026 ** Return the page number associated with frame iFrame in this WAL.
56028 static u32 walFramePgno(Wal *pWal, u32 iFrame){
56029 int iHash = walFramePage(iFrame);
56030 if( iHash==0 ){
56031 return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
56033 return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
56037 ** Remove entries from the hash table that point to WAL slots greater
56038 ** than pWal->hdr.mxFrame.
56040 ** This function is called whenever pWal->hdr.mxFrame is decreased due
56041 ** to a rollback or savepoint.
56043 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
56044 ** updated. Any later hash tables will be automatically cleared when
56045 ** pWal->hdr.mxFrame advances to the point where those hash tables are
56046 ** actually needed.
56048 static void walCleanupHash(Wal *pWal){
56049 volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
56050 volatile u32 *aPgno = 0; /* Page number array for hash table */
56051 u32 iZero = 0; /* frame == (aHash[x]+iZero) */
56052 int iLimit = 0; /* Zero values greater than this */
56053 int nByte; /* Number of bytes to zero in aPgno[] */
56054 int i; /* Used to iterate through aHash[] */
56056 assert( pWal->writeLock );
56057 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
56058 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
56059 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
56061 if( pWal->hdr.mxFrame==0 ) return;
56063 /* Obtain pointers to the hash-table and page-number array containing
56064 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
56065 ** that the page said hash-table and array reside on is already mapped.
56067 assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
56068 assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
56069 walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
56071 /* Zero all hash-table entries that correspond to frame numbers greater
56072 ** than pWal->hdr.mxFrame.
56074 iLimit = pWal->hdr.mxFrame - iZero;
56075 assert( iLimit>0 );
56076 for(i=0; i<HASHTABLE_NSLOT; i++){
56077 if( aHash[i]>iLimit ){
56078 aHash[i] = 0;
56082 /* Zero the entries in the aPgno array that correspond to frames with
56083 ** frame numbers greater than pWal->hdr.mxFrame.
56085 nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
56086 memset((void *)&aPgno[iLimit+1], 0, nByte);
56088 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
56089 /* Verify that the every entry in the mapping region is still reachable
56090 ** via the hash table even after the cleanup.
56092 if( iLimit ){
56093 int j; /* Loop counter */
56094 int iKey; /* Hash key */
56095 for(j=1; j<=iLimit; j++){
56096 for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
56097 if( aHash[iKey]==j ) break;
56099 assert( aHash[iKey]==j );
56102 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
56107 ** Set an entry in the wal-index that will map database page number
56108 ** pPage into WAL frame iFrame.
56110 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
56111 int rc; /* Return code */
56112 u32 iZero = 0; /* One less than frame number of aPgno[1] */
56113 volatile u32 *aPgno = 0; /* Page number array */
56114 volatile ht_slot *aHash = 0; /* Hash table */
56116 rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
56118 /* Assuming the wal-index file was successfully mapped, populate the
56119 ** page number array and hash table entry.
56121 if( rc==SQLITE_OK ){
56122 int iKey; /* Hash table key */
56123 int idx; /* Value to write to hash-table slot */
56124 int nCollide; /* Number of hash collisions */
56126 idx = iFrame - iZero;
56127 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
56129 /* If this is the first entry to be added to this hash-table, zero the
56130 ** entire hash table and aPgno[] array before proceeding.
56132 if( idx==1 ){
56133 int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
56134 memset((void*)&aPgno[1], 0, nByte);
56137 /* If the entry in aPgno[] is already set, then the previous writer
56138 ** must have exited unexpectedly in the middle of a transaction (after
56139 ** writing one or more dirty pages to the WAL to free up memory).
56140 ** Remove the remnants of that writers uncommitted transaction from
56141 ** the hash-table before writing any new entries.
56143 if( aPgno[idx] ){
56144 walCleanupHash(pWal);
56145 assert( !aPgno[idx] );
56148 /* Write the aPgno[] array entry and the hash-table slot. */
56149 nCollide = idx;
56150 for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
56151 if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
56153 aPgno[idx] = iPage;
56154 aHash[iKey] = (ht_slot)idx;
56156 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
56157 /* Verify that the number of entries in the hash table exactly equals
56158 ** the number of entries in the mapping region.
56161 int i; /* Loop counter */
56162 int nEntry = 0; /* Number of entries in the hash table */
56163 for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
56164 assert( nEntry==idx );
56167 /* Verify that the every entry in the mapping region is reachable
56168 ** via the hash table. This turns out to be a really, really expensive
56169 ** thing to check, so only do this occasionally - not on every
56170 ** iteration.
56172 if( (idx&0x3ff)==0 ){
56173 int i; /* Loop counter */
56174 for(i=1; i<=idx; i++){
56175 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
56176 if( aHash[iKey]==i ) break;
56178 assert( aHash[iKey]==i );
56181 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
56185 return rc;
56190 ** Recover the wal-index by reading the write-ahead log file.
56192 ** This routine first tries to establish an exclusive lock on the
56193 ** wal-index to prevent other threads/processes from doing anything
56194 ** with the WAL or wal-index while recovery is running. The
56195 ** WAL_RECOVER_LOCK is also held so that other threads will know
56196 ** that this thread is running recovery. If unable to establish
56197 ** the necessary locks, this routine returns SQLITE_BUSY.
56199 static int walIndexRecover(Wal *pWal){
56200 int rc; /* Return Code */
56201 i64 nSize; /* Size of log file */
56202 u32 aFrameCksum[2] = {0, 0};
56203 int iLock; /* Lock offset to lock for checkpoint */
56204 int nLock; /* Number of locks to hold */
56206 /* Obtain an exclusive lock on all byte in the locking range not already
56207 ** locked by the caller. The caller is guaranteed to have locked the
56208 ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
56209 ** If successful, the same bytes that are locked here are unlocked before
56210 ** this function returns.
56212 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
56213 assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
56214 assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
56215 assert( pWal->writeLock );
56216 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
56217 nLock = SQLITE_SHM_NLOCK - iLock;
56218 rc = walLockExclusive(pWal, iLock, nLock);
56219 if( rc ){
56220 return rc;
56222 WALTRACE(("WAL%p: recovery begin...\n", pWal));
56224 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
56226 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
56227 if( rc!=SQLITE_OK ){
56228 goto recovery_error;
56231 if( nSize>WAL_HDRSIZE ){
56232 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
56233 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
56234 int szFrame; /* Number of bytes in buffer aFrame[] */
56235 u8 *aData; /* Pointer to data part of aFrame buffer */
56236 int iFrame; /* Index of last frame read */
56237 i64 iOffset; /* Next offset to read from log file */
56238 int szPage; /* Page size according to the log */
56239 u32 magic; /* Magic value read from WAL header */
56240 u32 version; /* Magic value read from WAL header */
56241 int isValid; /* True if this frame is valid */
56243 /* Read in the WAL header. */
56244 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
56245 if( rc!=SQLITE_OK ){
56246 goto recovery_error;
56249 /* If the database page size is not a power of two, or is greater than
56250 ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
56251 ** data. Similarly, if the 'magic' value is invalid, ignore the whole
56252 ** WAL file.
56254 magic = sqlite3Get4byte(&aBuf[0]);
56255 szPage = sqlite3Get4byte(&aBuf[8]);
56256 if( (magic&0xFFFFFFFE)!=WAL_MAGIC
56257 || szPage&(szPage-1)
56258 || szPage>SQLITE_MAX_PAGE_SIZE
56259 || szPage<512
56261 goto finished;
56263 pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
56264 pWal->szPage = szPage;
56265 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
56266 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
56268 /* Verify that the WAL header checksum is correct */
56269 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
56270 aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
56272 if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
56273 || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
56275 goto finished;
56278 /* Verify that the version number on the WAL format is one that
56279 ** are able to understand */
56280 version = sqlite3Get4byte(&aBuf[4]);
56281 if( version!=WAL_MAX_VERSION ){
56282 rc = SQLITE_CANTOPEN_BKPT;
56283 goto finished;
56286 /* Malloc a buffer to read frames into. */
56287 szFrame = szPage + WAL_FRAME_HDRSIZE;
56288 aFrame = (u8 *)sqlite3_malloc64(szFrame);
56289 if( !aFrame ){
56290 rc = SQLITE_NOMEM_BKPT;
56291 goto recovery_error;
56293 aData = &aFrame[WAL_FRAME_HDRSIZE];
56295 /* Read all frames from the log file. */
56296 iFrame = 0;
56297 for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
56298 u32 pgno; /* Database page number for frame */
56299 u32 nTruncate; /* dbsize field from frame header */
56301 /* Read and decode the next log frame. */
56302 iFrame++;
56303 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
56304 if( rc!=SQLITE_OK ) break;
56305 isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
56306 if( !isValid ) break;
56307 rc = walIndexAppend(pWal, iFrame, pgno);
56308 if( rc!=SQLITE_OK ) break;
56310 /* If nTruncate is non-zero, this is a commit record. */
56311 if( nTruncate ){
56312 pWal->hdr.mxFrame = iFrame;
56313 pWal->hdr.nPage = nTruncate;
56314 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
56315 testcase( szPage<=32768 );
56316 testcase( szPage>=65536 );
56317 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
56318 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
56322 sqlite3_free(aFrame);
56325 finished:
56326 if( rc==SQLITE_OK ){
56327 volatile WalCkptInfo *pInfo;
56328 int i;
56329 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
56330 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
56331 walIndexWriteHdr(pWal);
56333 /* Reset the checkpoint-header. This is safe because this thread is
56334 ** currently holding locks that exclude all other readers, writers and
56335 ** checkpointers.
56337 pInfo = walCkptInfo(pWal);
56338 pInfo->nBackfill = 0;
56339 pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
56340 pInfo->aReadMark[0] = 0;
56341 for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
56342 if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
56344 /* If more than one frame was recovered from the log file, report an
56345 ** event via sqlite3_log(). This is to help with identifying performance
56346 ** problems caused by applications routinely shutting down without
56347 ** checkpointing the log file.
56349 if( pWal->hdr.nPage ){
56350 sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
56351 "recovered %d frames from WAL file %s",
56352 pWal->hdr.mxFrame, pWal->zWalName
56357 recovery_error:
56358 WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
56359 walUnlockExclusive(pWal, iLock, nLock);
56360 return rc;
56364 ** Close an open wal-index.
56366 static void walIndexClose(Wal *pWal, int isDelete){
56367 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
56368 int i;
56369 for(i=0; i<pWal->nWiData; i++){
56370 sqlite3_free((void *)pWal->apWiData[i]);
56371 pWal->apWiData[i] = 0;
56373 }else{
56374 sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
56379 ** Open a connection to the WAL file zWalName. The database file must
56380 ** already be opened on connection pDbFd. The buffer that zWalName points
56381 ** to must remain valid for the lifetime of the returned Wal* handle.
56383 ** A SHARED lock should be held on the database file when this function
56384 ** is called. The purpose of this SHARED lock is to prevent any other
56385 ** client from unlinking the WAL or wal-index file. If another process
56386 ** were to do this just after this client opened one of these files, the
56387 ** system would be badly broken.
56389 ** If the log file is successfully opened, SQLITE_OK is returned and
56390 ** *ppWal is set to point to a new WAL handle. If an error occurs,
56391 ** an SQLite error code is returned and *ppWal is left unmodified.
56393 SQLITE_PRIVATE int sqlite3WalOpen(
56394 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
56395 sqlite3_file *pDbFd, /* The open database file */
56396 const char *zWalName, /* Name of the WAL file */
56397 int bNoShm, /* True to run in heap-memory mode */
56398 i64 mxWalSize, /* Truncate WAL to this size on reset */
56399 Wal **ppWal /* OUT: Allocated Wal handle */
56401 int rc; /* Return Code */
56402 Wal *pRet; /* Object to allocate and return */
56403 int flags; /* Flags passed to OsOpen() */
56405 assert( zWalName && zWalName[0] );
56406 assert( pDbFd );
56408 /* In the amalgamation, the os_unix.c and os_win.c source files come before
56409 ** this source file. Verify that the #defines of the locking byte offsets
56410 ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
56411 ** For that matter, if the lock offset ever changes from its initial design
56412 ** value of 120, we need to know that so there is an assert() to check it.
56414 assert( 120==WALINDEX_LOCK_OFFSET );
56415 assert( 136==WALINDEX_HDR_SIZE );
56416 #ifdef WIN_SHM_BASE
56417 assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
56418 #endif
56419 #ifdef UNIX_SHM_BASE
56420 assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
56421 #endif
56424 /* Allocate an instance of struct Wal to return. */
56425 *ppWal = 0;
56426 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
56427 if( !pRet ){
56428 return SQLITE_NOMEM_BKPT;
56431 pRet->pVfs = pVfs;
56432 pRet->pWalFd = (sqlite3_file *)&pRet[1];
56433 pRet->pDbFd = pDbFd;
56434 pRet->readLock = -1;
56435 pRet->mxWalSize = mxWalSize;
56436 pRet->zWalName = zWalName;
56437 pRet->syncHeader = 1;
56438 pRet->padToSectorBoundary = 1;
56439 pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
56441 /* Open file handle on the write-ahead log file. */
56442 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
56443 rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
56444 if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
56445 pRet->readOnly = WAL_RDONLY;
56448 if( rc!=SQLITE_OK ){
56449 walIndexClose(pRet, 0);
56450 sqlite3OsClose(pRet->pWalFd);
56451 sqlite3_free(pRet);
56452 }else{
56453 int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
56454 if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
56455 if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
56456 pRet->padToSectorBoundary = 0;
56458 *ppWal = pRet;
56459 WALTRACE(("WAL%d: opened\n", pRet));
56461 return rc;
56465 ** Change the size to which the WAL file is trucated on each reset.
56467 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
56468 if( pWal ) pWal->mxWalSize = iLimit;
56472 ** Find the smallest page number out of all pages held in the WAL that
56473 ** has not been returned by any prior invocation of this method on the
56474 ** same WalIterator object. Write into *piFrame the frame index where
56475 ** that page was last written into the WAL. Write into *piPage the page
56476 ** number.
56478 ** Return 0 on success. If there are no pages in the WAL with a page
56479 ** number larger than *piPage, then return 1.
56481 static int walIteratorNext(
56482 WalIterator *p, /* Iterator */
56483 u32 *piPage, /* OUT: The page number of the next page */
56484 u32 *piFrame /* OUT: Wal frame index of next page */
56486 u32 iMin; /* Result pgno must be greater than iMin */
56487 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
56488 int i; /* For looping through segments */
56490 iMin = p->iPrior;
56491 assert( iMin<0xffffffff );
56492 for(i=p->nSegment-1; i>=0; i--){
56493 struct WalSegment *pSegment = &p->aSegment[i];
56494 while( pSegment->iNext<pSegment->nEntry ){
56495 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
56496 if( iPg>iMin ){
56497 if( iPg<iRet ){
56498 iRet = iPg;
56499 *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
56501 break;
56503 pSegment->iNext++;
56507 *piPage = p->iPrior = iRet;
56508 return (iRet==0xFFFFFFFF);
56512 ** This function merges two sorted lists into a single sorted list.
56514 ** aLeft[] and aRight[] are arrays of indices. The sort key is
56515 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
56516 ** is guaranteed for all J<K:
56518 ** aContent[aLeft[J]] < aContent[aLeft[K]]
56519 ** aContent[aRight[J]] < aContent[aRight[K]]
56521 ** This routine overwrites aRight[] with a new (probably longer) sequence
56522 ** of indices such that the aRight[] contains every index that appears in
56523 ** either aLeft[] or the old aRight[] and such that the second condition
56524 ** above is still met.
56526 ** The aContent[aLeft[X]] values will be unique for all X. And the
56527 ** aContent[aRight[X]] values will be unique too. But there might be
56528 ** one or more combinations of X and Y such that
56530 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
56532 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
56534 static void walMerge(
56535 const u32 *aContent, /* Pages in wal - keys for the sort */
56536 ht_slot *aLeft, /* IN: Left hand input list */
56537 int nLeft, /* IN: Elements in array *paLeft */
56538 ht_slot **paRight, /* IN/OUT: Right hand input list */
56539 int *pnRight, /* IN/OUT: Elements in *paRight */
56540 ht_slot *aTmp /* Temporary buffer */
56542 int iLeft = 0; /* Current index in aLeft */
56543 int iRight = 0; /* Current index in aRight */
56544 int iOut = 0; /* Current index in output buffer */
56545 int nRight = *pnRight;
56546 ht_slot *aRight = *paRight;
56548 assert( nLeft>0 && nRight>0 );
56549 while( iRight<nRight || iLeft<nLeft ){
56550 ht_slot logpage;
56551 Pgno dbpage;
56553 if( (iLeft<nLeft)
56554 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
56556 logpage = aLeft[iLeft++];
56557 }else{
56558 logpage = aRight[iRight++];
56560 dbpage = aContent[logpage];
56562 aTmp[iOut++] = logpage;
56563 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
56565 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
56566 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
56569 *paRight = aLeft;
56570 *pnRight = iOut;
56571 memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
56575 ** Sort the elements in list aList using aContent[] as the sort key.
56576 ** Remove elements with duplicate keys, preferring to keep the
56577 ** larger aList[] values.
56579 ** The aList[] entries are indices into aContent[]. The values in
56580 ** aList[] are to be sorted so that for all J<K:
56582 ** aContent[aList[J]] < aContent[aList[K]]
56584 ** For any X and Y such that
56586 ** aContent[aList[X]] == aContent[aList[Y]]
56588 ** Keep the larger of the two values aList[X] and aList[Y] and discard
56589 ** the smaller.
56591 static void walMergesort(
56592 const u32 *aContent, /* Pages in wal */
56593 ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
56594 ht_slot *aList, /* IN/OUT: List to sort */
56595 int *pnList /* IN/OUT: Number of elements in aList[] */
56597 struct Sublist {
56598 int nList; /* Number of elements in aList */
56599 ht_slot *aList; /* Pointer to sub-list content */
56602 const int nList = *pnList; /* Size of input list */
56603 int nMerge = 0; /* Number of elements in list aMerge */
56604 ht_slot *aMerge = 0; /* List to be merged */
56605 int iList; /* Index into input list */
56606 u32 iSub = 0; /* Index into aSub array */
56607 struct Sublist aSub[13]; /* Array of sub-lists */
56609 memset(aSub, 0, sizeof(aSub));
56610 assert( nList<=HASHTABLE_NPAGE && nList>0 );
56611 assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
56613 for(iList=0; iList<nList; iList++){
56614 nMerge = 1;
56615 aMerge = &aList[iList];
56616 for(iSub=0; iList & (1<<iSub); iSub++){
56617 struct Sublist *p;
56618 assert( iSub<ArraySize(aSub) );
56619 p = &aSub[iSub];
56620 assert( p->aList && p->nList<=(1<<iSub) );
56621 assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
56622 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
56624 aSub[iSub].aList = aMerge;
56625 aSub[iSub].nList = nMerge;
56628 for(iSub++; iSub<ArraySize(aSub); iSub++){
56629 if( nList & (1<<iSub) ){
56630 struct Sublist *p;
56631 assert( iSub<ArraySize(aSub) );
56632 p = &aSub[iSub];
56633 assert( p->nList<=(1<<iSub) );
56634 assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
56635 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
56638 assert( aMerge==aList );
56639 *pnList = nMerge;
56641 #ifdef SQLITE_DEBUG
56643 int i;
56644 for(i=1; i<*pnList; i++){
56645 assert( aContent[aList[i]] > aContent[aList[i-1]] );
56648 #endif
56652 ** Free an iterator allocated by walIteratorInit().
56654 static void walIteratorFree(WalIterator *p){
56655 sqlite3_free(p);
56659 ** Construct a WalInterator object that can be used to loop over all
56660 ** pages in the WAL in ascending order. The caller must hold the checkpoint
56661 ** lock.
56663 ** On success, make *pp point to the newly allocated WalInterator object
56664 ** return SQLITE_OK. Otherwise, return an error code. If this routine
56665 ** returns an error, the value of *pp is undefined.
56667 ** The calling routine should invoke walIteratorFree() to destroy the
56668 ** WalIterator object when it has finished with it.
56670 static int walIteratorInit(Wal *pWal, WalIterator **pp){
56671 WalIterator *p; /* Return value */
56672 int nSegment; /* Number of segments to merge */
56673 u32 iLast; /* Last frame in log */
56674 int nByte; /* Number of bytes to allocate */
56675 int i; /* Iterator variable */
56676 ht_slot *aTmp; /* Temp space used by merge-sort */
56677 int rc = SQLITE_OK; /* Return Code */
56679 /* This routine only runs while holding the checkpoint lock. And
56680 ** it only runs if there is actually content in the log (mxFrame>0).
56682 assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
56683 iLast = pWal->hdr.mxFrame;
56685 /* Allocate space for the WalIterator object. */
56686 nSegment = walFramePage(iLast) + 1;
56687 nByte = sizeof(WalIterator)
56688 + (nSegment-1)*sizeof(struct WalSegment)
56689 + iLast*sizeof(ht_slot);
56690 p = (WalIterator *)sqlite3_malloc64(nByte);
56691 if( !p ){
56692 return SQLITE_NOMEM_BKPT;
56694 memset(p, 0, nByte);
56695 p->nSegment = nSegment;
56697 /* Allocate temporary space used by the merge-sort routine. This block
56698 ** of memory will be freed before this function returns.
56700 aTmp = (ht_slot *)sqlite3_malloc64(
56701 sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
56703 if( !aTmp ){
56704 rc = SQLITE_NOMEM_BKPT;
56707 for(i=0; rc==SQLITE_OK && i<nSegment; i++){
56708 volatile ht_slot *aHash;
56709 u32 iZero;
56710 volatile u32 *aPgno;
56712 rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
56713 if( rc==SQLITE_OK ){
56714 int j; /* Counter variable */
56715 int nEntry; /* Number of entries in this segment */
56716 ht_slot *aIndex; /* Sorted index for this segment */
56718 aPgno++;
56719 if( (i+1)==nSegment ){
56720 nEntry = (int)(iLast - iZero);
56721 }else{
56722 nEntry = (int)((u32*)aHash - (u32*)aPgno);
56724 aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
56725 iZero++;
56727 for(j=0; j<nEntry; j++){
56728 aIndex[j] = (ht_slot)j;
56730 walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
56731 p->aSegment[i].iZero = iZero;
56732 p->aSegment[i].nEntry = nEntry;
56733 p->aSegment[i].aIndex = aIndex;
56734 p->aSegment[i].aPgno = (u32 *)aPgno;
56737 sqlite3_free(aTmp);
56739 if( rc!=SQLITE_OK ){
56740 walIteratorFree(p);
56742 *pp = p;
56743 return rc;
56747 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
56748 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
56749 ** busy-handler function. Invoke it and retry the lock until either the
56750 ** lock is successfully obtained or the busy-handler returns 0.
56752 static int walBusyLock(
56753 Wal *pWal, /* WAL connection */
56754 int (*xBusy)(void*), /* Function to call when busy */
56755 void *pBusyArg, /* Context argument for xBusyHandler */
56756 int lockIdx, /* Offset of first byte to lock */
56757 int n /* Number of bytes to lock */
56759 int rc;
56760 do {
56761 rc = walLockExclusive(pWal, lockIdx, n);
56762 }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
56763 return rc;
56767 ** The cache of the wal-index header must be valid to call this function.
56768 ** Return the page-size in bytes used by the database.
56770 static int walPagesize(Wal *pWal){
56771 return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
56775 ** The following is guaranteed when this function is called:
56777 ** a) the WRITER lock is held,
56778 ** b) the entire log file has been checkpointed, and
56779 ** c) any existing readers are reading exclusively from the database
56780 ** file - there are no readers that may attempt to read a frame from
56781 ** the log file.
56783 ** This function updates the shared-memory structures so that the next
56784 ** client to write to the database (which may be this one) does so by
56785 ** writing frames into the start of the log file.
56787 ** The value of parameter salt1 is used as the aSalt[1] value in the
56788 ** new wal-index header. It should be passed a pseudo-random value (i.e.
56789 ** one obtained from sqlite3_randomness()).
56791 static void walRestartHdr(Wal *pWal, u32 salt1){
56792 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56793 int i; /* Loop counter */
56794 u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
56795 pWal->nCkpt++;
56796 pWal->hdr.mxFrame = 0;
56797 sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
56798 memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
56799 walIndexWriteHdr(pWal);
56800 pInfo->nBackfill = 0;
56801 pInfo->nBackfillAttempted = 0;
56802 pInfo->aReadMark[1] = 0;
56803 for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
56804 assert( pInfo->aReadMark[0]==0 );
56808 ** Copy as much content as we can from the WAL back into the database file
56809 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
56811 ** The amount of information copies from WAL to database might be limited
56812 ** by active readers. This routine will never overwrite a database page
56813 ** that a concurrent reader might be using.
56815 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
56816 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
56817 ** checkpoints are always run by a background thread or background
56818 ** process, foreground threads will never block on a lengthy fsync call.
56820 ** Fsync is called on the WAL before writing content out of the WAL and
56821 ** into the database. This ensures that if the new content is persistent
56822 ** in the WAL and can be recovered following a power-loss or hard reset.
56824 ** Fsync is also called on the database file if (and only if) the entire
56825 ** WAL content is copied into the database file. This second fsync makes
56826 ** it safe to delete the WAL since the new content will persist in the
56827 ** database file.
56829 ** This routine uses and updates the nBackfill field of the wal-index header.
56830 ** This is the only routine that will increase the value of nBackfill.
56831 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
56832 ** its value.)
56834 ** The caller must be holding sufficient locks to ensure that no other
56835 ** checkpoint is running (in any other thread or process) at the same
56836 ** time.
56838 static int walCheckpoint(
56839 Wal *pWal, /* Wal connection */
56840 sqlite3 *db, /* Check for interrupts on this handle */
56841 int eMode, /* One of PASSIVE, FULL or RESTART */
56842 int (*xBusy)(void*), /* Function to call when busy */
56843 void *pBusyArg, /* Context argument for xBusyHandler */
56844 int sync_flags, /* Flags for OsSync() (or 0) */
56845 u8 *zBuf /* Temporary buffer to use */
56847 int rc = SQLITE_OK; /* Return code */
56848 int szPage; /* Database page-size */
56849 WalIterator *pIter = 0; /* Wal iterator context */
56850 u32 iDbpage = 0; /* Next database page to write */
56851 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
56852 u32 mxSafeFrame; /* Max frame that can be backfilled */
56853 u32 mxPage; /* Max database page to write */
56854 int i; /* Loop counter */
56855 volatile WalCkptInfo *pInfo; /* The checkpoint status information */
56857 szPage = walPagesize(pWal);
56858 testcase( szPage<=32768 );
56859 testcase( szPage>=65536 );
56860 pInfo = walCkptInfo(pWal);
56861 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
56863 /* Allocate the iterator */
56864 rc = walIteratorInit(pWal, &pIter);
56865 if( rc!=SQLITE_OK ){
56866 return rc;
56868 assert( pIter );
56870 /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
56871 ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
56872 assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
56874 /* Compute in mxSafeFrame the index of the last frame of the WAL that is
56875 ** safe to write into the database. Frames beyond mxSafeFrame might
56876 ** overwrite database pages that are in use by active readers and thus
56877 ** cannot be backfilled from the WAL.
56879 mxSafeFrame = pWal->hdr.mxFrame;
56880 mxPage = pWal->hdr.nPage;
56881 for(i=1; i<WAL_NREADER; i++){
56882 /* Thread-sanitizer reports that the following is an unsafe read,
56883 ** as some other thread may be in the process of updating the value
56884 ** of the aReadMark[] slot. The assumption here is that if that is
56885 ** happening, the other client may only be increasing the value,
56886 ** not decreasing it. So assuming either that either the "old" or
56887 ** "new" version of the value is read, and not some arbitrary value
56888 ** that would never be written by a real client, things are still
56889 ** safe. */
56890 u32 y = pInfo->aReadMark[i];
56891 if( mxSafeFrame>y ){
56892 assert( y<=pWal->hdr.mxFrame );
56893 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
56894 if( rc==SQLITE_OK ){
56895 pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
56896 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
56897 }else if( rc==SQLITE_BUSY ){
56898 mxSafeFrame = y;
56899 xBusy = 0;
56900 }else{
56901 goto walcheckpoint_out;
56906 if( pInfo->nBackfill<mxSafeFrame
56907 && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
56909 i64 nSize; /* Current size of database file */
56910 u32 nBackfill = pInfo->nBackfill;
56912 pInfo->nBackfillAttempted = mxSafeFrame;
56914 /* Sync the WAL to disk */
56915 rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
56917 /* If the database may grow as a result of this checkpoint, hint
56918 ** about the eventual size of the db file to the VFS layer.
56920 if( rc==SQLITE_OK ){
56921 i64 nReq = ((i64)mxPage * szPage);
56922 rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
56923 if( rc==SQLITE_OK && nSize<nReq ){
56924 sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
56929 /* Iterate through the contents of the WAL, copying data to the db file */
56930 while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
56931 i64 iOffset;
56932 assert( walFramePgno(pWal, iFrame)==iDbpage );
56933 if( db->u1.isInterrupted ){
56934 rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
56935 break;
56937 if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
56938 continue;
56940 iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
56941 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
56942 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
56943 if( rc!=SQLITE_OK ) break;
56944 iOffset = (iDbpage-1)*(i64)szPage;
56945 testcase( IS_BIG_INT(iOffset) );
56946 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
56947 if( rc!=SQLITE_OK ) break;
56950 /* If work was actually accomplished... */
56951 if( rc==SQLITE_OK ){
56952 if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
56953 i64 szDb = pWal->hdr.nPage*(i64)szPage;
56954 testcase( IS_BIG_INT(szDb) );
56955 rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
56956 if( rc==SQLITE_OK ){
56957 rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
56960 if( rc==SQLITE_OK ){
56961 pInfo->nBackfill = mxSafeFrame;
56965 /* Release the reader lock held while backfilling */
56966 walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
56969 if( rc==SQLITE_BUSY ){
56970 /* Reset the return code so as not to report a checkpoint failure
56971 ** just because there are active readers. */
56972 rc = SQLITE_OK;
56976 /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
56977 ** entire wal file has been copied into the database file, then block
56978 ** until all readers have finished using the wal file. This ensures that
56979 ** the next process to write to the database restarts the wal file.
56981 if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
56982 assert( pWal->writeLock );
56983 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
56984 rc = SQLITE_BUSY;
56985 }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
56986 u32 salt1;
56987 sqlite3_randomness(4, &salt1);
56988 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
56989 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
56990 if( rc==SQLITE_OK ){
56991 if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
56992 /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
56993 ** SQLITE_CHECKPOINT_RESTART with the addition that it also
56994 ** truncates the log file to zero bytes just prior to a
56995 ** successful return.
56997 ** In theory, it might be safe to do this without updating the
56998 ** wal-index header in shared memory, as all subsequent reader or
56999 ** writer clients should see that the entire log file has been
57000 ** checkpointed and behave accordingly. This seems unsafe though,
57001 ** as it would leave the system in a state where the contents of
57002 ** the wal-index header do not match the contents of the
57003 ** file-system. To avoid this, update the wal-index header to
57004 ** indicate that the log file contains zero valid frames. */
57005 walRestartHdr(pWal, salt1);
57006 rc = sqlite3OsTruncate(pWal->pWalFd, 0);
57008 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
57013 walcheckpoint_out:
57014 walIteratorFree(pIter);
57015 return rc;
57019 ** If the WAL file is currently larger than nMax bytes in size, truncate
57020 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
57022 static void walLimitSize(Wal *pWal, i64 nMax){
57023 i64 sz;
57024 int rx;
57025 sqlite3BeginBenignMalloc();
57026 rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
57027 if( rx==SQLITE_OK && (sz > nMax ) ){
57028 rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
57030 sqlite3EndBenignMalloc();
57031 if( rx ){
57032 sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
57037 ** Close a connection to a log file.
57039 SQLITE_PRIVATE int sqlite3WalClose(
57040 Wal *pWal, /* Wal to close */
57041 sqlite3 *db, /* For interrupt flag */
57042 int sync_flags, /* Flags to pass to OsSync() (or 0) */
57043 int nBuf,
57044 u8 *zBuf /* Buffer of at least nBuf bytes */
57046 int rc = SQLITE_OK;
57047 if( pWal ){
57048 int isDelete = 0; /* True to unlink wal and wal-index files */
57050 /* If an EXCLUSIVE lock can be obtained on the database file (using the
57051 ** ordinary, rollback-mode locking methods, this guarantees that the
57052 ** connection associated with this log file is the only connection to
57053 ** the database. In this case checkpoint the database and unlink both
57054 ** the wal and wal-index files.
57056 ** The EXCLUSIVE lock is not released before returning.
57058 if( zBuf!=0
57059 && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
57061 if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
57062 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
57064 rc = sqlite3WalCheckpoint(pWal, db,
57065 SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
57067 if( rc==SQLITE_OK ){
57068 int bPersist = -1;
57069 sqlite3OsFileControlHint(
57070 pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
57072 if( bPersist!=1 ){
57073 /* Try to delete the WAL file if the checkpoint completed and
57074 ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
57075 ** mode (!bPersist) */
57076 isDelete = 1;
57077 }else if( pWal->mxWalSize>=0 ){
57078 /* Try to truncate the WAL file to zero bytes if the checkpoint
57079 ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
57080 ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
57081 ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
57082 ** to zero bytes as truncating to the journal_size_limit might
57083 ** leave a corrupt WAL file on disk. */
57084 walLimitSize(pWal, 0);
57089 walIndexClose(pWal, isDelete);
57090 sqlite3OsClose(pWal->pWalFd);
57091 if( isDelete ){
57092 sqlite3BeginBenignMalloc();
57093 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
57094 sqlite3EndBenignMalloc();
57096 WALTRACE(("WAL%p: closed\n", pWal));
57097 sqlite3_free((void *)pWal->apWiData);
57098 sqlite3_free(pWal);
57100 return rc;
57104 ** Try to read the wal-index header. Return 0 on success and 1 if
57105 ** there is a problem.
57107 ** The wal-index is in shared memory. Another thread or process might
57108 ** be writing the header at the same time this procedure is trying to
57109 ** read it, which might result in inconsistency. A dirty read is detected
57110 ** by verifying that both copies of the header are the same and also by
57111 ** a checksum on the header.
57113 ** If and only if the read is consistent and the header is different from
57114 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
57115 ** and *pChanged is set to 1.
57117 ** If the checksum cannot be verified return non-zero. If the header
57118 ** is read successfully and the checksum verified, return zero.
57120 static int walIndexTryHdr(Wal *pWal, int *pChanged){
57121 u32 aCksum[2]; /* Checksum on the header content */
57122 WalIndexHdr h1, h2; /* Two copies of the header content */
57123 WalIndexHdr volatile *aHdr; /* Header in shared memory */
57125 /* The first page of the wal-index must be mapped at this point. */
57126 assert( pWal->nWiData>0 && pWal->apWiData[0] );
57128 /* Read the header. This might happen concurrently with a write to the
57129 ** same area of shared memory on a different CPU in a SMP,
57130 ** meaning it is possible that an inconsistent snapshot is read
57131 ** from the file. If this happens, return non-zero.
57133 ** There are two copies of the header at the beginning of the wal-index.
57134 ** When reading, read [0] first then [1]. Writes are in the reverse order.
57135 ** Memory barriers are used to prevent the compiler or the hardware from
57136 ** reordering the reads and writes.
57138 aHdr = walIndexHdr(pWal);
57139 memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
57140 walShmBarrier(pWal);
57141 memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
57143 if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
57144 return 1; /* Dirty read */
57146 if( h1.isInit==0 ){
57147 return 1; /* Malformed header - probably all zeros */
57149 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
57150 if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
57151 return 1; /* Checksum does not match */
57154 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
57155 *pChanged = 1;
57156 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
57157 pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
57158 testcase( pWal->szPage<=32768 );
57159 testcase( pWal->szPage>=65536 );
57162 /* The header was successfully read. Return zero. */
57163 return 0;
57167 ** Read the wal-index header from the wal-index and into pWal->hdr.
57168 ** If the wal-header appears to be corrupt, try to reconstruct the
57169 ** wal-index from the WAL before returning.
57171 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
57172 ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
57173 ** to 0.
57175 ** If the wal-index header is successfully read, return SQLITE_OK.
57176 ** Otherwise an SQLite error code.
57178 static int walIndexReadHdr(Wal *pWal, int *pChanged){
57179 int rc; /* Return code */
57180 int badHdr; /* True if a header read failed */
57181 volatile u32 *page0; /* Chunk of wal-index containing header */
57183 /* Ensure that page 0 of the wal-index (the page that contains the
57184 ** wal-index header) is mapped. Return early if an error occurs here.
57186 assert( pChanged );
57187 rc = walIndexPage(pWal, 0, &page0);
57188 if( rc!=SQLITE_OK ){
57189 return rc;
57191 assert( page0 || pWal->writeLock==0 );
57193 /* If the first page of the wal-index has been mapped, try to read the
57194 ** wal-index header immediately, without holding any lock. This usually
57195 ** works, but may fail if the wal-index header is corrupt or currently
57196 ** being modified by another thread or process.
57198 badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
57200 /* If the first attempt failed, it might have been due to a race
57201 ** with a writer. So get a WRITE lock and try again.
57203 assert( badHdr==0 || pWal->writeLock==0 );
57204 if( badHdr ){
57205 if( pWal->readOnly & WAL_SHM_RDONLY ){
57206 if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
57207 walUnlockShared(pWal, WAL_WRITE_LOCK);
57208 rc = SQLITE_READONLY_RECOVERY;
57210 }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
57211 pWal->writeLock = 1;
57212 if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
57213 badHdr = walIndexTryHdr(pWal, pChanged);
57214 if( badHdr ){
57215 /* If the wal-index header is still malformed even while holding
57216 ** a WRITE lock, it can only mean that the header is corrupted and
57217 ** needs to be reconstructed. So run recovery to do exactly that.
57219 rc = walIndexRecover(pWal);
57220 *pChanged = 1;
57223 pWal->writeLock = 0;
57224 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
57228 /* If the header is read successfully, check the version number to make
57229 ** sure the wal-index was not constructed with some future format that
57230 ** this version of SQLite cannot understand.
57232 if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
57233 rc = SQLITE_CANTOPEN_BKPT;
57236 return rc;
57240 ** This is the value that walTryBeginRead returns when it needs to
57241 ** be retried.
57243 #define WAL_RETRY (-1)
57246 ** Attempt to start a read transaction. This might fail due to a race or
57247 ** other transient condition. When that happens, it returns WAL_RETRY to
57248 ** indicate to the caller that it is safe to retry immediately.
57250 ** On success return SQLITE_OK. On a permanent failure (such an
57251 ** I/O error or an SQLITE_BUSY because another process is running
57252 ** recovery) return a positive error code.
57254 ** The useWal parameter is true to force the use of the WAL and disable
57255 ** the case where the WAL is bypassed because it has been completely
57256 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
57257 ** to make a copy of the wal-index header into pWal->hdr. If the
57258 ** wal-index header has changed, *pChanged is set to 1 (as an indication
57259 ** to the caller that the local paget cache is obsolete and needs to be
57260 ** flushed.) When useWal==1, the wal-index header is assumed to already
57261 ** be loaded and the pChanged parameter is unused.
57263 ** The caller must set the cnt parameter to the number of prior calls to
57264 ** this routine during the current read attempt that returned WAL_RETRY.
57265 ** This routine will start taking more aggressive measures to clear the
57266 ** race conditions after multiple WAL_RETRY returns, and after an excessive
57267 ** number of errors will ultimately return SQLITE_PROTOCOL. The
57268 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
57269 ** and is not honoring the locking protocol. There is a vanishingly small
57270 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
57271 ** bad luck when there is lots of contention for the wal-index, but that
57272 ** possibility is so small that it can be safely neglected, we believe.
57274 ** On success, this routine obtains a read lock on
57275 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
57276 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
57277 ** that means the Wal does not hold any read lock. The reader must not
57278 ** access any database page that is modified by a WAL frame up to and
57279 ** including frame number aReadMark[pWal->readLock]. The reader will
57280 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
57281 ** Or if pWal->readLock==0, then the reader will ignore the WAL
57282 ** completely and get all content directly from the database file.
57283 ** If the useWal parameter is 1 then the WAL will never be ignored and
57284 ** this routine will always set pWal->readLock>0 on success.
57285 ** When the read transaction is completed, the caller must release the
57286 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
57288 ** This routine uses the nBackfill and aReadMark[] fields of the header
57289 ** to select a particular WAL_READ_LOCK() that strives to let the
57290 ** checkpoint process do as much work as possible. This routine might
57291 ** update values of the aReadMark[] array in the header, but if it does
57292 ** so it takes care to hold an exclusive lock on the corresponding
57293 ** WAL_READ_LOCK() while changing values.
57295 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
57296 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
57297 u32 mxReadMark; /* Largest aReadMark[] value */
57298 int mxI; /* Index of largest aReadMark[] value */
57299 int i; /* Loop counter */
57300 int rc = SQLITE_OK; /* Return code */
57301 u32 mxFrame; /* Wal frame to lock to */
57303 assert( pWal->readLock<0 ); /* Not currently locked */
57305 /* Take steps to avoid spinning forever if there is a protocol error.
57307 ** Circumstances that cause a RETRY should only last for the briefest
57308 ** instances of time. No I/O or other system calls are done while the
57309 ** locks are held, so the locks should not be held for very long. But
57310 ** if we are unlucky, another process that is holding a lock might get
57311 ** paged out or take a page-fault that is time-consuming to resolve,
57312 ** during the few nanoseconds that it is holding the lock. In that case,
57313 ** it might take longer than normal for the lock to free.
57315 ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
57316 ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
57317 ** is more of a scheduler yield than an actual delay. But on the 10th
57318 ** an subsequent retries, the delays start becoming longer and longer,
57319 ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
57320 ** The total delay time before giving up is less than 10 seconds.
57322 if( cnt>5 ){
57323 int nDelay = 1; /* Pause time in microseconds */
57324 if( cnt>100 ){
57325 VVA_ONLY( pWal->lockError = 1; )
57326 return SQLITE_PROTOCOL;
57328 if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
57329 sqlite3OsSleep(pWal->pVfs, nDelay);
57332 if( !useWal ){
57333 rc = walIndexReadHdr(pWal, pChanged);
57334 if( rc==SQLITE_BUSY ){
57335 /* If there is not a recovery running in another thread or process
57336 ** then convert BUSY errors to WAL_RETRY. If recovery is known to
57337 ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
57338 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
57339 ** would be technically correct. But the race is benign since with
57340 ** WAL_RETRY this routine will be called again and will probably be
57341 ** right on the second iteration.
57343 if( pWal->apWiData[0]==0 ){
57344 /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
57345 ** We assume this is a transient condition, so return WAL_RETRY. The
57346 ** xShmMap() implementation used by the default unix and win32 VFS
57347 ** modules may return SQLITE_BUSY due to a race condition in the
57348 ** code that determines whether or not the shared-memory region
57349 ** must be zeroed before the requested page is returned.
57351 rc = WAL_RETRY;
57352 }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
57353 walUnlockShared(pWal, WAL_RECOVER_LOCK);
57354 rc = WAL_RETRY;
57355 }else if( rc==SQLITE_BUSY ){
57356 rc = SQLITE_BUSY_RECOVERY;
57359 if( rc!=SQLITE_OK ){
57360 return rc;
57364 pInfo = walCkptInfo(pWal);
57365 if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
57366 #ifdef SQLITE_ENABLE_SNAPSHOT
57367 && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
57368 || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
57369 #endif
57371 /* The WAL has been completely backfilled (or it is empty).
57372 ** and can be safely ignored.
57374 rc = walLockShared(pWal, WAL_READ_LOCK(0));
57375 walShmBarrier(pWal);
57376 if( rc==SQLITE_OK ){
57377 if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
57378 /* It is not safe to allow the reader to continue here if frames
57379 ** may have been appended to the log before READ_LOCK(0) was obtained.
57380 ** When holding READ_LOCK(0), the reader ignores the entire log file,
57381 ** which implies that the database file contains a trustworthy
57382 ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
57383 ** happening, this is usually correct.
57385 ** However, if frames have been appended to the log (or if the log
57386 ** is wrapped and written for that matter) before the READ_LOCK(0)
57387 ** is obtained, that is not necessarily true. A checkpointer may
57388 ** have started to backfill the appended frames but crashed before
57389 ** it finished. Leaving a corrupt image in the database file.
57391 walUnlockShared(pWal, WAL_READ_LOCK(0));
57392 return WAL_RETRY;
57394 pWal->readLock = 0;
57395 return SQLITE_OK;
57396 }else if( rc!=SQLITE_BUSY ){
57397 return rc;
57401 /* If we get this far, it means that the reader will want to use
57402 ** the WAL to get at content from recent commits. The job now is
57403 ** to select one of the aReadMark[] entries that is closest to
57404 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
57406 mxReadMark = 0;
57407 mxI = 0;
57408 mxFrame = pWal->hdr.mxFrame;
57409 #ifdef SQLITE_ENABLE_SNAPSHOT
57410 if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
57411 mxFrame = pWal->pSnapshot->mxFrame;
57413 #endif
57414 for(i=1; i<WAL_NREADER; i++){
57415 u32 thisMark = pInfo->aReadMark[i];
57416 if( mxReadMark<=thisMark && thisMark<=mxFrame ){
57417 assert( thisMark!=READMARK_NOT_USED );
57418 mxReadMark = thisMark;
57419 mxI = i;
57422 if( (pWal->readOnly & WAL_SHM_RDONLY)==0
57423 && (mxReadMark<mxFrame || mxI==0)
57425 for(i=1; i<WAL_NREADER; i++){
57426 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
57427 if( rc==SQLITE_OK ){
57428 mxReadMark = pInfo->aReadMark[i] = mxFrame;
57429 mxI = i;
57430 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
57431 break;
57432 }else if( rc!=SQLITE_BUSY ){
57433 return rc;
57437 if( mxI==0 ){
57438 assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
57439 return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
57442 rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
57443 if( rc ){
57444 return rc==SQLITE_BUSY ? WAL_RETRY : rc;
57446 /* Now that the read-lock has been obtained, check that neither the
57447 ** value in the aReadMark[] array or the contents of the wal-index
57448 ** header have changed.
57450 ** It is necessary to check that the wal-index header did not change
57451 ** between the time it was read and when the shared-lock was obtained
57452 ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
57453 ** that the log file may have been wrapped by a writer, or that frames
57454 ** that occur later in the log than pWal->hdr.mxFrame may have been
57455 ** copied into the database by a checkpointer. If either of these things
57456 ** happened, then reading the database with the current value of
57457 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
57458 ** instead.
57460 ** Before checking that the live wal-index header has not changed
57461 ** since it was read, set Wal.minFrame to the first frame in the wal
57462 ** file that has not yet been checkpointed. This client will not need
57463 ** to read any frames earlier than minFrame from the wal file - they
57464 ** can be safely read directly from the database file.
57466 ** Because a ShmBarrier() call is made between taking the copy of
57467 ** nBackfill and checking that the wal-header in shared-memory still
57468 ** matches the one cached in pWal->hdr, it is guaranteed that the
57469 ** checkpointer that set nBackfill was not working with a wal-index
57470 ** header newer than that cached in pWal->hdr. If it were, that could
57471 ** cause a problem. The checkpointer could omit to checkpoint
57472 ** a version of page X that lies before pWal->minFrame (call that version
57473 ** A) on the basis that there is a newer version (version B) of the same
57474 ** page later in the wal file. But if version B happens to like past
57475 ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
57476 ** that it can read version A from the database file. However, since
57477 ** we can guarantee that the checkpointer that set nBackfill could not
57478 ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
57480 pWal->minFrame = pInfo->nBackfill+1;
57481 walShmBarrier(pWal);
57482 if( pInfo->aReadMark[mxI]!=mxReadMark
57483 || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
57485 walUnlockShared(pWal, WAL_READ_LOCK(mxI));
57486 return WAL_RETRY;
57487 }else{
57488 assert( mxReadMark<=pWal->hdr.mxFrame );
57489 pWal->readLock = (i16)mxI;
57491 return rc;
57494 #ifdef SQLITE_ENABLE_SNAPSHOT
57496 ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
57497 ** variable so that older snapshots can be accessed. To do this, loop
57498 ** through all wal frames from nBackfillAttempted to (nBackfill+1),
57499 ** comparing their content to the corresponding page with the database
57500 ** file, if any. Set nBackfillAttempted to the frame number of the
57501 ** first frame for which the wal file content matches the db file.
57503 ** This is only really safe if the file-system is such that any page
57504 ** writes made by earlier checkpointers were atomic operations, which
57505 ** is not always true. It is also possible that nBackfillAttempted
57506 ** may be left set to a value larger than expected, if a wal frame
57507 ** contains content that duplicate of an earlier version of the same
57508 ** page.
57510 ** SQLITE_OK is returned if successful, or an SQLite error code if an
57511 ** error occurs. It is not an error if nBackfillAttempted cannot be
57512 ** decreased at all.
57514 SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
57515 int rc;
57517 assert( pWal->readLock>=0 );
57518 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
57519 if( rc==SQLITE_OK ){
57520 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
57521 int szPage = (int)pWal->szPage;
57522 i64 szDb; /* Size of db file in bytes */
57524 rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
57525 if( rc==SQLITE_OK ){
57526 void *pBuf1 = sqlite3_malloc(szPage);
57527 void *pBuf2 = sqlite3_malloc(szPage);
57528 if( pBuf1==0 || pBuf2==0 ){
57529 rc = SQLITE_NOMEM;
57530 }else{
57531 u32 i = pInfo->nBackfillAttempted;
57532 for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
57533 volatile ht_slot *dummy;
57534 volatile u32 *aPgno; /* Array of page numbers */
57535 u32 iZero; /* Frame corresponding to aPgno[0] */
57536 u32 pgno; /* Page number in db file */
57537 i64 iDbOff; /* Offset of db file entry */
57538 i64 iWalOff; /* Offset of wal file entry */
57540 rc = walHashGet(pWal, walFramePage(i), &dummy, &aPgno, &iZero);
57541 if( rc!=SQLITE_OK ) break;
57542 pgno = aPgno[i-iZero];
57543 iDbOff = (i64)(pgno-1) * szPage;
57545 if( iDbOff+szPage<=szDb ){
57546 iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
57547 rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
57549 if( rc==SQLITE_OK ){
57550 rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
57553 if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
57554 break;
57558 pInfo->nBackfillAttempted = i-1;
57562 sqlite3_free(pBuf1);
57563 sqlite3_free(pBuf2);
57565 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
57568 return rc;
57570 #endif /* SQLITE_ENABLE_SNAPSHOT */
57573 ** Begin a read transaction on the database.
57575 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
57576 ** it takes a snapshot of the state of the WAL and wal-index for the current
57577 ** instant in time. The current thread will continue to use this snapshot.
57578 ** Other threads might append new content to the WAL and wal-index but
57579 ** that extra content is ignored by the current thread.
57581 ** If the database contents have changes since the previous read
57582 ** transaction, then *pChanged is set to 1 before returning. The
57583 ** Pager layer will use this to know that is cache is stale and
57584 ** needs to be flushed.
57586 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
57587 int rc; /* Return code */
57588 int cnt = 0; /* Number of TryBeginRead attempts */
57590 #ifdef SQLITE_ENABLE_SNAPSHOT
57591 int bChanged = 0;
57592 WalIndexHdr *pSnapshot = pWal->pSnapshot;
57593 if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
57594 bChanged = 1;
57596 #endif
57599 rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
57600 }while( rc==WAL_RETRY );
57601 testcase( (rc&0xff)==SQLITE_BUSY );
57602 testcase( (rc&0xff)==SQLITE_IOERR );
57603 testcase( rc==SQLITE_PROTOCOL );
57604 testcase( rc==SQLITE_OK );
57606 #ifdef SQLITE_ENABLE_SNAPSHOT
57607 if( rc==SQLITE_OK ){
57608 if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
57609 /* At this point the client has a lock on an aReadMark[] slot holding
57610 ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
57611 ** is populated with the wal-index header corresponding to the head
57612 ** of the wal file. Verify that pSnapshot is still valid before
57613 ** continuing. Reasons why pSnapshot might no longer be valid:
57615 ** (1) The WAL file has been reset since the snapshot was taken.
57616 ** In this case, the salt will have changed.
57618 ** (2) A checkpoint as been attempted that wrote frames past
57619 ** pSnapshot->mxFrame into the database file. Note that the
57620 ** checkpoint need not have completed for this to cause problems.
57622 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
57624 assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
57625 assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
57627 /* It is possible that there is a checkpointer thread running
57628 ** concurrent with this code. If this is the case, it may be that the
57629 ** checkpointer has already determined that it will checkpoint
57630 ** snapshot X, where X is later in the wal file than pSnapshot, but
57631 ** has not yet set the pInfo->nBackfillAttempted variable to indicate
57632 ** its intent. To avoid the race condition this leads to, ensure that
57633 ** there is no checkpointer process by taking a shared CKPT lock
57634 ** before checking pInfo->nBackfillAttempted.
57636 ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
57637 ** this already?
57639 rc = walLockShared(pWal, WAL_CKPT_LOCK);
57641 if( rc==SQLITE_OK ){
57642 /* Check that the wal file has not been wrapped. Assuming that it has
57643 ** not, also check that no checkpointer has attempted to checkpoint any
57644 ** frames beyond pSnapshot->mxFrame. If either of these conditions are
57645 ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
57646 ** with *pSnapshot and set *pChanged as appropriate for opening the
57647 ** snapshot. */
57648 if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
57649 && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
57651 assert( pWal->readLock>0 );
57652 memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
57653 *pChanged = bChanged;
57654 }else{
57655 rc = SQLITE_BUSY_SNAPSHOT;
57658 /* Release the shared CKPT lock obtained above. */
57659 walUnlockShared(pWal, WAL_CKPT_LOCK);
57663 if( rc!=SQLITE_OK ){
57664 sqlite3WalEndReadTransaction(pWal);
57668 #endif
57669 return rc;
57673 ** Finish with a read transaction. All this does is release the
57674 ** read-lock.
57676 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
57677 sqlite3WalEndWriteTransaction(pWal);
57678 if( pWal->readLock>=0 ){
57679 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
57680 pWal->readLock = -1;
57685 ** Search the wal file for page pgno. If found, set *piRead to the frame that
57686 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
57687 ** to zero.
57689 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
57690 ** error does occur, the final value of *piRead is undefined.
57692 SQLITE_PRIVATE int sqlite3WalFindFrame(
57693 Wal *pWal, /* WAL handle */
57694 Pgno pgno, /* Database page number to read data for */
57695 u32 *piRead /* OUT: Frame number (or zero) */
57697 u32 iRead = 0; /* If !=0, WAL frame to return data from */
57698 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
57699 int iHash; /* Used to loop through N hash tables */
57700 int iMinHash;
57702 /* This routine is only be called from within a read transaction. */
57703 assert( pWal->readLock>=0 || pWal->lockError );
57705 /* If the "last page" field of the wal-index header snapshot is 0, then
57706 ** no data will be read from the wal under any circumstances. Return early
57707 ** in this case as an optimization. Likewise, if pWal->readLock==0,
57708 ** then the WAL is ignored by the reader so return early, as if the
57709 ** WAL were empty.
57711 if( iLast==0 || pWal->readLock==0 ){
57712 *piRead = 0;
57713 return SQLITE_OK;
57716 /* Search the hash table or tables for an entry matching page number
57717 ** pgno. Each iteration of the following for() loop searches one
57718 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
57720 ** This code might run concurrently to the code in walIndexAppend()
57721 ** that adds entries to the wal-index (and possibly to this hash
57722 ** table). This means the value just read from the hash
57723 ** slot (aHash[iKey]) may have been added before or after the
57724 ** current read transaction was opened. Values added after the
57725 ** read transaction was opened may have been written incorrectly -
57726 ** i.e. these slots may contain garbage data. However, we assume
57727 ** that any slots written before the current read transaction was
57728 ** opened remain unmodified.
57730 ** For the reasons above, the if(...) condition featured in the inner
57731 ** loop of the following block is more stringent that would be required
57732 ** if we had exclusive access to the hash-table:
57734 ** (aPgno[iFrame]==pgno):
57735 ** This condition filters out normal hash-table collisions.
57737 ** (iFrame<=iLast):
57738 ** This condition filters out entries that were added to the hash
57739 ** table after the current read-transaction had started.
57741 iMinHash = walFramePage(pWal->minFrame);
57742 for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
57743 volatile ht_slot *aHash; /* Pointer to hash table */
57744 volatile u32 *aPgno; /* Pointer to array of page numbers */
57745 u32 iZero; /* Frame number corresponding to aPgno[0] */
57746 int iKey; /* Hash slot index */
57747 int nCollide; /* Number of hash collisions remaining */
57748 int rc; /* Error code */
57750 rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
57751 if( rc!=SQLITE_OK ){
57752 return rc;
57754 nCollide = HASHTABLE_NSLOT;
57755 for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
57756 u32 iFrame = aHash[iKey] + iZero;
57757 if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
57758 assert( iFrame>iRead || CORRUPT_DB );
57759 iRead = iFrame;
57761 if( (nCollide--)==0 ){
57762 return SQLITE_CORRUPT_BKPT;
57767 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
57768 /* If expensive assert() statements are available, do a linear search
57769 ** of the wal-index file content. Make sure the results agree with the
57770 ** result obtained using the hash indexes above. */
57772 u32 iRead2 = 0;
57773 u32 iTest;
57774 assert( pWal->minFrame>0 );
57775 for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
57776 if( walFramePgno(pWal, iTest)==pgno ){
57777 iRead2 = iTest;
57778 break;
57781 assert( iRead==iRead2 );
57783 #endif
57785 *piRead = iRead;
57786 return SQLITE_OK;
57790 ** Read the contents of frame iRead from the wal file into buffer pOut
57791 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
57792 ** error code otherwise.
57794 SQLITE_PRIVATE int sqlite3WalReadFrame(
57795 Wal *pWal, /* WAL handle */
57796 u32 iRead, /* Frame to read */
57797 int nOut, /* Size of buffer pOut in bytes */
57798 u8 *pOut /* Buffer to write page data to */
57800 int sz;
57801 i64 iOffset;
57802 sz = pWal->hdr.szPage;
57803 sz = (sz&0xfe00) + ((sz&0x0001)<<16);
57804 testcase( sz<=32768 );
57805 testcase( sz>=65536 );
57806 iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
57807 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
57808 return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
57812 ** Return the size of the database in pages (or zero, if unknown).
57814 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
57815 if( pWal && ALWAYS(pWal->readLock>=0) ){
57816 return pWal->hdr.nPage;
57818 return 0;
57823 ** This function starts a write transaction on the WAL.
57825 ** A read transaction must have already been started by a prior call
57826 ** to sqlite3WalBeginReadTransaction().
57828 ** If another thread or process has written into the database since
57829 ** the read transaction was started, then it is not possible for this
57830 ** thread to write as doing so would cause a fork. So this routine
57831 ** returns SQLITE_BUSY in that case and no write transaction is started.
57833 ** There can only be a single writer active at a time.
57835 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
57836 int rc;
57838 /* Cannot start a write transaction without first holding a read
57839 ** transaction. */
57840 assert( pWal->readLock>=0 );
57841 assert( pWal->writeLock==0 && pWal->iReCksum==0 );
57843 if( pWal->readOnly ){
57844 return SQLITE_READONLY;
57847 /* Only one writer allowed at a time. Get the write lock. Return
57848 ** SQLITE_BUSY if unable.
57850 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
57851 if( rc ){
57852 return rc;
57854 pWal->writeLock = 1;
57856 /* If another connection has written to the database file since the
57857 ** time the read transaction on this connection was started, then
57858 ** the write is disallowed.
57860 if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
57861 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
57862 pWal->writeLock = 0;
57863 rc = SQLITE_BUSY_SNAPSHOT;
57866 return rc;
57870 ** End a write transaction. The commit has already been done. This
57871 ** routine merely releases the lock.
57873 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
57874 if( pWal->writeLock ){
57875 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
57876 pWal->writeLock = 0;
57877 pWal->iReCksum = 0;
57878 pWal->truncateOnCommit = 0;
57880 return SQLITE_OK;
57884 ** If any data has been written (but not committed) to the log file, this
57885 ** function moves the write-pointer back to the start of the transaction.
57887 ** Additionally, the callback function is invoked for each frame written
57888 ** to the WAL since the start of the transaction. If the callback returns
57889 ** other than SQLITE_OK, it is not invoked again and the error code is
57890 ** returned to the caller.
57892 ** Otherwise, if the callback function does not return an error, this
57893 ** function returns SQLITE_OK.
57895 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
57896 int rc = SQLITE_OK;
57897 if( ALWAYS(pWal->writeLock) ){
57898 Pgno iMax = pWal->hdr.mxFrame;
57899 Pgno iFrame;
57901 /* Restore the clients cache of the wal-index header to the state it
57902 ** was in before the client began writing to the database.
57904 memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
57906 for(iFrame=pWal->hdr.mxFrame+1;
57907 ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
57908 iFrame++
57910 /* This call cannot fail. Unless the page for which the page number
57911 ** is passed as the second argument is (a) in the cache and
57912 ** (b) has an outstanding reference, then xUndo is either a no-op
57913 ** (if (a) is false) or simply expels the page from the cache (if (b)
57914 ** is false).
57916 ** If the upper layer is doing a rollback, it is guaranteed that there
57917 ** are no outstanding references to any page other than page 1. And
57918 ** page 1 is never written to the log until the transaction is
57919 ** committed. As a result, the call to xUndo may not fail.
57921 assert( walFramePgno(pWal, iFrame)!=1 );
57922 rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
57924 if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
57926 return rc;
57930 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
57931 ** values. This function populates the array with values required to
57932 ** "rollback" the write position of the WAL handle back to the current
57933 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
57935 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
57936 assert( pWal->writeLock );
57937 aWalData[0] = pWal->hdr.mxFrame;
57938 aWalData[1] = pWal->hdr.aFrameCksum[0];
57939 aWalData[2] = pWal->hdr.aFrameCksum[1];
57940 aWalData[3] = pWal->nCkpt;
57944 ** Move the write position of the WAL back to the point identified by
57945 ** the values in the aWalData[] array. aWalData must point to an array
57946 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
57947 ** by a call to WalSavepoint().
57949 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
57950 int rc = SQLITE_OK;
57952 assert( pWal->writeLock );
57953 assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
57955 if( aWalData[3]!=pWal->nCkpt ){
57956 /* This savepoint was opened immediately after the write-transaction
57957 ** was started. Right after that, the writer decided to wrap around
57958 ** to the start of the log. Update the savepoint values to match.
57960 aWalData[0] = 0;
57961 aWalData[3] = pWal->nCkpt;
57964 if( aWalData[0]<pWal->hdr.mxFrame ){
57965 pWal->hdr.mxFrame = aWalData[0];
57966 pWal->hdr.aFrameCksum[0] = aWalData[1];
57967 pWal->hdr.aFrameCksum[1] = aWalData[2];
57968 walCleanupHash(pWal);
57971 return rc;
57975 ** This function is called just before writing a set of frames to the log
57976 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
57977 ** to the current log file, it is possible to overwrite the start of the
57978 ** existing log file with the new frames (i.e. "reset" the log). If so,
57979 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
57980 ** unchanged.
57982 ** SQLITE_OK is returned if no error is encountered (regardless of whether
57983 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
57984 ** if an error occurs.
57986 static int walRestartLog(Wal *pWal){
57987 int rc = SQLITE_OK;
57988 int cnt;
57990 if( pWal->readLock==0 ){
57991 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
57992 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
57993 if( pInfo->nBackfill>0 ){
57994 u32 salt1;
57995 sqlite3_randomness(4, &salt1);
57996 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
57997 if( rc==SQLITE_OK ){
57998 /* If all readers are using WAL_READ_LOCK(0) (in other words if no
57999 ** readers are currently using the WAL), then the transactions
58000 ** frames will overwrite the start of the existing log. Update the
58001 ** wal-index header to reflect this.
58003 ** In theory it would be Ok to update the cache of the header only
58004 ** at this point. But updating the actual wal-index header is also
58005 ** safe and means there is no special case for sqlite3WalUndo()
58006 ** to handle if this transaction is rolled back. */
58007 walRestartHdr(pWal, salt1);
58008 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
58009 }else if( rc!=SQLITE_BUSY ){
58010 return rc;
58013 walUnlockShared(pWal, WAL_READ_LOCK(0));
58014 pWal->readLock = -1;
58015 cnt = 0;
58017 int notUsed;
58018 rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
58019 }while( rc==WAL_RETRY );
58020 assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
58021 testcase( (rc&0xff)==SQLITE_IOERR );
58022 testcase( rc==SQLITE_PROTOCOL );
58023 testcase( rc==SQLITE_OK );
58025 return rc;
58029 ** Information about the current state of the WAL file and where
58030 ** the next fsync should occur - passed from sqlite3WalFrames() into
58031 ** walWriteToLog().
58033 typedef struct WalWriter {
58034 Wal *pWal; /* The complete WAL information */
58035 sqlite3_file *pFd; /* The WAL file to which we write */
58036 sqlite3_int64 iSyncPoint; /* Fsync at this offset */
58037 int syncFlags; /* Flags for the fsync */
58038 int szPage; /* Size of one page */
58039 } WalWriter;
58042 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
58043 ** Do a sync when crossing the p->iSyncPoint boundary.
58045 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
58046 ** first write the part before iSyncPoint, then sync, then write the
58047 ** rest.
58049 static int walWriteToLog(
58050 WalWriter *p, /* WAL to write to */
58051 void *pContent, /* Content to be written */
58052 int iAmt, /* Number of bytes to write */
58053 sqlite3_int64 iOffset /* Start writing at this offset */
58055 int rc;
58056 if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
58057 int iFirstAmt = (int)(p->iSyncPoint - iOffset);
58058 rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
58059 if( rc ) return rc;
58060 iOffset += iFirstAmt;
58061 iAmt -= iFirstAmt;
58062 pContent = (void*)(iFirstAmt + (char*)pContent);
58063 assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
58064 rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
58065 if( iAmt==0 || rc ) return rc;
58067 rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
58068 return rc;
58072 ** Write out a single frame of the WAL
58074 static int walWriteOneFrame(
58075 WalWriter *p, /* Where to write the frame */
58076 PgHdr *pPage, /* The page of the frame to be written */
58077 int nTruncate, /* The commit flag. Usually 0. >0 for commit */
58078 sqlite3_int64 iOffset /* Byte offset at which to write */
58080 int rc; /* Result code from subfunctions */
58081 void *pData; /* Data actually written */
58082 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
58083 #if defined(SQLITE_HAS_CODEC)
58084 if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
58085 #else
58086 pData = pPage->pData;
58087 #endif
58088 walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
58089 rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
58090 if( rc ) return rc;
58091 /* Write the page data */
58092 rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
58093 return rc;
58097 ** This function is called as part of committing a transaction within which
58098 ** one or more frames have been overwritten. It updates the checksums for
58099 ** all frames written to the wal file by the current transaction starting
58100 ** with the earliest to have been overwritten.
58102 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
58104 static int walRewriteChecksums(Wal *pWal, u32 iLast){
58105 const int szPage = pWal->szPage;/* Database page size */
58106 int rc = SQLITE_OK; /* Return code */
58107 u8 *aBuf; /* Buffer to load data from wal file into */
58108 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
58109 u32 iRead; /* Next frame to read from wal file */
58110 i64 iCksumOff;
58112 aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
58113 if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
58115 /* Find the checksum values to use as input for the recalculating the
58116 ** first checksum. If the first frame is frame 1 (implying that the current
58117 ** transaction restarted the wal file), these values must be read from the
58118 ** wal-file header. Otherwise, read them from the frame header of the
58119 ** previous frame. */
58120 assert( pWal->iReCksum>0 );
58121 if( pWal->iReCksum==1 ){
58122 iCksumOff = 24;
58123 }else{
58124 iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
58126 rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
58127 pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
58128 pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
58130 iRead = pWal->iReCksum;
58131 pWal->iReCksum = 0;
58132 for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
58133 i64 iOff = walFrameOffset(iRead, szPage);
58134 rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
58135 if( rc==SQLITE_OK ){
58136 u32 iPgno, nDbSize;
58137 iPgno = sqlite3Get4byte(aBuf);
58138 nDbSize = sqlite3Get4byte(&aBuf[4]);
58140 walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
58141 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
58145 sqlite3_free(aBuf);
58146 return rc;
58150 ** Write a set of frames to the log. The caller must hold the write-lock
58151 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
58153 SQLITE_PRIVATE int sqlite3WalFrames(
58154 Wal *pWal, /* Wal handle to write to */
58155 int szPage, /* Database page-size in bytes */
58156 PgHdr *pList, /* List of dirty pages to write */
58157 Pgno nTruncate, /* Database size after this commit */
58158 int isCommit, /* True if this is a commit */
58159 int sync_flags /* Flags to pass to OsSync() (or 0) */
58161 int rc; /* Used to catch return codes */
58162 u32 iFrame; /* Next frame address */
58163 PgHdr *p; /* Iterator to run through pList with. */
58164 PgHdr *pLast = 0; /* Last frame in list */
58165 int nExtra = 0; /* Number of extra copies of last page */
58166 int szFrame; /* The size of a single frame */
58167 i64 iOffset; /* Next byte to write in WAL file */
58168 WalWriter w; /* The writer */
58169 u32 iFirst = 0; /* First frame that may be overwritten */
58170 WalIndexHdr *pLive; /* Pointer to shared header */
58172 assert( pList );
58173 assert( pWal->writeLock );
58175 /* If this frame set completes a transaction, then nTruncate>0. If
58176 ** nTruncate==0 then this frame set does not complete the transaction. */
58177 assert( (isCommit!=0)==(nTruncate!=0) );
58179 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
58180 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
58181 WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
58182 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
58184 #endif
58186 pLive = (WalIndexHdr*)walIndexHdr(pWal);
58187 if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
58188 iFirst = pLive->mxFrame+1;
58191 /* See if it is possible to write these frames into the start of the
58192 ** log file, instead of appending to it at pWal->hdr.mxFrame.
58194 if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
58195 return rc;
58198 /* If this is the first frame written into the log, write the WAL
58199 ** header to the start of the WAL file. See comments at the top of
58200 ** this source file for a description of the WAL header format.
58202 iFrame = pWal->hdr.mxFrame;
58203 if( iFrame==0 ){
58204 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
58205 u32 aCksum[2]; /* Checksum for wal-header */
58207 sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
58208 sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
58209 sqlite3Put4byte(&aWalHdr[8], szPage);
58210 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
58211 if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
58212 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
58213 walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
58214 sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
58215 sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
58217 pWal->szPage = szPage;
58218 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
58219 pWal->hdr.aFrameCksum[0] = aCksum[0];
58220 pWal->hdr.aFrameCksum[1] = aCksum[1];
58221 pWal->truncateOnCommit = 1;
58223 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
58224 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
58225 if( rc!=SQLITE_OK ){
58226 return rc;
58229 /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
58230 ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
58231 ** an out-of-order write following a WAL restart could result in
58232 ** database corruption. See the ticket:
58234 ** https://sqlite.org/src/info/ff5be73dee
58236 if( pWal->syncHeader ){
58237 rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
58238 if( rc ) return rc;
58241 assert( (int)pWal->szPage==szPage );
58243 /* Setup information needed to write frames into the WAL */
58244 w.pWal = pWal;
58245 w.pFd = pWal->pWalFd;
58246 w.iSyncPoint = 0;
58247 w.syncFlags = sync_flags;
58248 w.szPage = szPage;
58249 iOffset = walFrameOffset(iFrame+1, szPage);
58250 szFrame = szPage + WAL_FRAME_HDRSIZE;
58252 /* Write all frames into the log file exactly once */
58253 for(p=pList; p; p=p->pDirty){
58254 int nDbSize; /* 0 normally. Positive == commit flag */
58256 /* Check if this page has already been written into the wal file by
58257 ** the current transaction. If so, overwrite the existing frame and
58258 ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
58259 ** checksums must be recomputed when the transaction is committed. */
58260 if( iFirst && (p->pDirty || isCommit==0) ){
58261 u32 iWrite = 0;
58262 VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
58263 assert( rc==SQLITE_OK || iWrite==0 );
58264 if( iWrite>=iFirst ){
58265 i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
58266 void *pData;
58267 if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
58268 pWal->iReCksum = iWrite;
58270 #if defined(SQLITE_HAS_CODEC)
58271 if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
58272 #else
58273 pData = p->pData;
58274 #endif
58275 rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
58276 if( rc ) return rc;
58277 p->flags &= ~PGHDR_WAL_APPEND;
58278 continue;
58282 iFrame++;
58283 assert( iOffset==walFrameOffset(iFrame, szPage) );
58284 nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
58285 rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
58286 if( rc ) return rc;
58287 pLast = p;
58288 iOffset += szFrame;
58289 p->flags |= PGHDR_WAL_APPEND;
58292 /* Recalculate checksums within the wal file if required. */
58293 if( isCommit && pWal->iReCksum ){
58294 rc = walRewriteChecksums(pWal, iFrame);
58295 if( rc ) return rc;
58298 /* If this is the end of a transaction, then we might need to pad
58299 ** the transaction and/or sync the WAL file.
58301 ** Padding and syncing only occur if this set of frames complete a
58302 ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
58303 ** or synchronous==OFF, then no padding or syncing are needed.
58305 ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
58306 ** needed and only the sync is done. If padding is needed, then the
58307 ** final frame is repeated (with its commit mark) until the next sector
58308 ** boundary is crossed. Only the part of the WAL prior to the last
58309 ** sector boundary is synced; the part of the last frame that extends
58310 ** past the sector boundary is written after the sync.
58312 if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
58313 int bSync = 1;
58314 if( pWal->padToSectorBoundary ){
58315 int sectorSize = sqlite3SectorSize(pWal->pWalFd);
58316 w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
58317 bSync = (w.iSyncPoint==iOffset);
58318 testcase( bSync );
58319 while( iOffset<w.iSyncPoint ){
58320 rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
58321 if( rc ) return rc;
58322 iOffset += szFrame;
58323 nExtra++;
58326 if( bSync ){
58327 assert( rc==SQLITE_OK );
58328 rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
58332 /* If this frame set completes the first transaction in the WAL and
58333 ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
58334 ** journal size limit, if possible.
58336 if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
58337 i64 sz = pWal->mxWalSize;
58338 if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
58339 sz = walFrameOffset(iFrame+nExtra+1, szPage);
58341 walLimitSize(pWal, sz);
58342 pWal->truncateOnCommit = 0;
58345 /* Append data to the wal-index. It is not necessary to lock the
58346 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
58347 ** guarantees that there are no other writers, and no data that may
58348 ** be in use by existing readers is being overwritten.
58350 iFrame = pWal->hdr.mxFrame;
58351 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
58352 if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
58353 iFrame++;
58354 rc = walIndexAppend(pWal, iFrame, p->pgno);
58356 while( rc==SQLITE_OK && nExtra>0 ){
58357 iFrame++;
58358 nExtra--;
58359 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
58362 if( rc==SQLITE_OK ){
58363 /* Update the private copy of the header. */
58364 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
58365 testcase( szPage<=32768 );
58366 testcase( szPage>=65536 );
58367 pWal->hdr.mxFrame = iFrame;
58368 if( isCommit ){
58369 pWal->hdr.iChange++;
58370 pWal->hdr.nPage = nTruncate;
58372 /* If this is a commit, update the wal-index header too. */
58373 if( isCommit ){
58374 walIndexWriteHdr(pWal);
58375 pWal->iCallback = iFrame;
58379 WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
58380 return rc;
58384 ** This routine is called to implement sqlite3_wal_checkpoint() and
58385 ** related interfaces.
58387 ** Obtain a CHECKPOINT lock and then backfill as much information as
58388 ** we can from WAL into the database.
58390 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
58391 ** callback. In this case this function runs a blocking checkpoint.
58393 SQLITE_PRIVATE int sqlite3WalCheckpoint(
58394 Wal *pWal, /* Wal connection */
58395 sqlite3 *db, /* Check this handle's interrupt flag */
58396 int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
58397 int (*xBusy)(void*), /* Function to call when busy */
58398 void *pBusyArg, /* Context argument for xBusyHandler */
58399 int sync_flags, /* Flags to sync db file with (or 0) */
58400 int nBuf, /* Size of temporary buffer */
58401 u8 *zBuf, /* Temporary buffer to use */
58402 int *pnLog, /* OUT: Number of frames in WAL */
58403 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
58405 int rc; /* Return code */
58406 int isChanged = 0; /* True if a new wal-index header is loaded */
58407 int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
58408 int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
58410 assert( pWal->ckptLock==0 );
58411 assert( pWal->writeLock==0 );
58413 /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
58414 ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
58415 assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
58417 if( pWal->readOnly ) return SQLITE_READONLY;
58418 WALTRACE(("WAL%p: checkpoint begins\n", pWal));
58420 /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
58421 ** "checkpoint" lock on the database file. */
58422 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
58423 if( rc ){
58424 /* EVIDENCE-OF: R-10421-19736 If any other process is running a
58425 ** checkpoint operation at the same time, the lock cannot be obtained and
58426 ** SQLITE_BUSY is returned.
58427 ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
58428 ** it will not be invoked in this case.
58430 testcase( rc==SQLITE_BUSY );
58431 testcase( xBusy!=0 );
58432 return rc;
58434 pWal->ckptLock = 1;
58436 /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
58437 ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
58438 ** file.
58440 ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
58441 ** immediately, and a busy-handler is configured, it is invoked and the
58442 ** writer lock retried until either the busy-handler returns 0 or the
58443 ** lock is successfully obtained.
58445 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
58446 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
58447 if( rc==SQLITE_OK ){
58448 pWal->writeLock = 1;
58449 }else if( rc==SQLITE_BUSY ){
58450 eMode2 = SQLITE_CHECKPOINT_PASSIVE;
58451 xBusy2 = 0;
58452 rc = SQLITE_OK;
58456 /* Read the wal-index header. */
58457 if( rc==SQLITE_OK ){
58458 rc = walIndexReadHdr(pWal, &isChanged);
58459 if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
58460 sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
58464 /* Copy data from the log to the database file. */
58465 if( rc==SQLITE_OK ){
58467 if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
58468 rc = SQLITE_CORRUPT_BKPT;
58469 }else{
58470 rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
58473 /* If no error occurred, set the output variables. */
58474 if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
58475 if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
58476 if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
58480 if( isChanged ){
58481 /* If a new wal-index header was loaded before the checkpoint was
58482 ** performed, then the pager-cache associated with pWal is now
58483 ** out of date. So zero the cached wal-index header to ensure that
58484 ** next time the pager opens a snapshot on this database it knows that
58485 ** the cache needs to be reset.
58487 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
58490 /* Release the locks. */
58491 sqlite3WalEndWriteTransaction(pWal);
58492 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
58493 pWal->ckptLock = 0;
58494 WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
58495 return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
58498 /* Return the value to pass to a sqlite3_wal_hook callback, the
58499 ** number of frames in the WAL at the point of the last commit since
58500 ** sqlite3WalCallback() was called. If no commits have occurred since
58501 ** the last call, then return 0.
58503 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
58504 u32 ret = 0;
58505 if( pWal ){
58506 ret = pWal->iCallback;
58507 pWal->iCallback = 0;
58509 return (int)ret;
58513 ** This function is called to change the WAL subsystem into or out
58514 ** of locking_mode=EXCLUSIVE.
58516 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
58517 ** into locking_mode=NORMAL. This means that we must acquire a lock
58518 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
58519 ** or if the acquisition of the lock fails, then return 0. If the
58520 ** transition out of exclusive-mode is successful, return 1. This
58521 ** operation must occur while the pager is still holding the exclusive
58522 ** lock on the main database file.
58524 ** If op is one, then change from locking_mode=NORMAL into
58525 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
58526 ** be released. Return 1 if the transition is made and 0 if the
58527 ** WAL is already in exclusive-locking mode - meaning that this
58528 ** routine is a no-op. The pager must already hold the exclusive lock
58529 ** on the main database file before invoking this operation.
58531 ** If op is negative, then do a dry-run of the op==1 case but do
58532 ** not actually change anything. The pager uses this to see if it
58533 ** should acquire the database exclusive lock prior to invoking
58534 ** the op==1 case.
58536 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
58537 int rc;
58538 assert( pWal->writeLock==0 );
58539 assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
58541 /* pWal->readLock is usually set, but might be -1 if there was a
58542 ** prior error while attempting to acquire are read-lock. This cannot
58543 ** happen if the connection is actually in exclusive mode (as no xShmLock
58544 ** locks are taken in this case). Nor should the pager attempt to
58545 ** upgrade to exclusive-mode following such an error.
58547 assert( pWal->readLock>=0 || pWal->lockError );
58548 assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
58550 if( op==0 ){
58551 if( pWal->exclusiveMode ){
58552 pWal->exclusiveMode = 0;
58553 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
58554 pWal->exclusiveMode = 1;
58556 rc = pWal->exclusiveMode==0;
58557 }else{
58558 /* Already in locking_mode=NORMAL */
58559 rc = 0;
58561 }else if( op>0 ){
58562 assert( pWal->exclusiveMode==0 );
58563 assert( pWal->readLock>=0 );
58564 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
58565 pWal->exclusiveMode = 1;
58566 rc = 1;
58567 }else{
58568 rc = pWal->exclusiveMode==0;
58570 return rc;
58574 ** Return true if the argument is non-NULL and the WAL module is using
58575 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
58576 ** WAL module is using shared-memory, return false.
58578 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
58579 return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
58582 #ifdef SQLITE_ENABLE_SNAPSHOT
58583 /* Create a snapshot object. The content of a snapshot is opaque to
58584 ** every other subsystem, so the WAL module can put whatever it needs
58585 ** in the object.
58587 SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
58588 int rc = SQLITE_OK;
58589 WalIndexHdr *pRet;
58590 static const u32 aZero[4] = { 0, 0, 0, 0 };
58592 assert( pWal->readLock>=0 && pWal->writeLock==0 );
58594 if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
58595 *ppSnapshot = 0;
58596 return SQLITE_ERROR;
58598 pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
58599 if( pRet==0 ){
58600 rc = SQLITE_NOMEM_BKPT;
58601 }else{
58602 memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
58603 *ppSnapshot = (sqlite3_snapshot*)pRet;
58606 return rc;
58609 /* Try to open on pSnapshot when the next read-transaction starts
58611 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
58612 pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
58616 ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
58617 ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
58619 SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
58620 WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
58621 WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
58623 /* aSalt[0] is a copy of the value stored in the wal file header. It
58624 ** is incremented each time the wal file is restarted. */
58625 if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
58626 if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
58627 if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
58628 if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
58629 return 0;
58631 #endif /* SQLITE_ENABLE_SNAPSHOT */
58633 #ifdef SQLITE_ENABLE_ZIPVFS
58635 ** If the argument is not NULL, it points to a Wal object that holds a
58636 ** read-lock. This function returns the database page-size if it is known,
58637 ** or zero if it is not (or if pWal is NULL).
58639 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
58640 assert( pWal==0 || pWal->readLock>=0 );
58641 return (pWal ? pWal->szPage : 0);
58643 #endif
58645 /* Return the sqlite3_file object for the WAL file
58647 SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
58648 return pWal->pWalFd;
58651 #endif /* #ifndef SQLITE_OMIT_WAL */
58653 /************** End of wal.c *************************************************/
58654 /************** Begin file btmutex.c *****************************************/
58656 ** 2007 August 27
58658 ** The author disclaims copyright to this source code. In place of
58659 ** a legal notice, here is a blessing:
58661 ** May you do good and not evil.
58662 ** May you find forgiveness for yourself and forgive others.
58663 ** May you share freely, never taking more than you give.
58665 *************************************************************************
58667 ** This file contains code used to implement mutexes on Btree objects.
58668 ** This code really belongs in btree.c. But btree.c is getting too
58669 ** big and we want to break it down some. This packaged seemed like
58670 ** a good breakout.
58672 /************** Include btreeInt.h in the middle of btmutex.c ****************/
58673 /************** Begin file btreeInt.h ****************************************/
58675 ** 2004 April 6
58677 ** The author disclaims copyright to this source code. In place of
58678 ** a legal notice, here is a blessing:
58680 ** May you do good and not evil.
58681 ** May you find forgiveness for yourself and forgive others.
58682 ** May you share freely, never taking more than you give.
58684 *************************************************************************
58685 ** This file implements an external (disk-based) database using BTrees.
58686 ** For a detailed discussion of BTrees, refer to
58688 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
58689 ** "Sorting And Searching", pages 473-480. Addison-Wesley
58690 ** Publishing Company, Reading, Massachusetts.
58692 ** The basic idea is that each page of the file contains N database
58693 ** entries and N+1 pointers to subpages.
58695 ** ----------------------------------------------------------------
58696 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
58697 ** ----------------------------------------------------------------
58699 ** All of the keys on the page that Ptr(0) points to have values less
58700 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
58701 ** values greater than Key(0) and less than Key(1). All of the keys
58702 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
58703 ** so forth.
58705 ** Finding a particular key requires reading O(log(M)) pages from the
58706 ** disk where M is the number of entries in the tree.
58708 ** In this implementation, a single file can hold one or more separate
58709 ** BTrees. Each BTree is identified by the index of its root page. The
58710 ** key and data for any entry are combined to form the "payload". A
58711 ** fixed amount of payload can be carried directly on the database
58712 ** page. If the payload is larger than the preset amount then surplus
58713 ** bytes are stored on overflow pages. The payload for an entry
58714 ** and the preceding pointer are combined to form a "Cell". Each
58715 ** page has a small header which contains the Ptr(N) pointer and other
58716 ** information such as the size of key and data.
58718 ** FORMAT DETAILS
58720 ** The file is divided into pages. The first page is called page 1,
58721 ** the second is page 2, and so forth. A page number of zero indicates
58722 ** "no such page". The page size can be any power of 2 between 512 and 65536.
58723 ** Each page can be either a btree page, a freelist page, an overflow
58724 ** page, or a pointer-map page.
58726 ** The first page is always a btree page. The first 100 bytes of the first
58727 ** page contain a special header (the "file header") that describes the file.
58728 ** The format of the file header is as follows:
58730 ** OFFSET SIZE DESCRIPTION
58731 ** 0 16 Header string: "SQLite format 3\000"
58732 ** 16 2 Page size in bytes. (1 means 65536)
58733 ** 18 1 File format write version
58734 ** 19 1 File format read version
58735 ** 20 1 Bytes of unused space at the end of each page
58736 ** 21 1 Max embedded payload fraction (must be 64)
58737 ** 22 1 Min embedded payload fraction (must be 32)
58738 ** 23 1 Min leaf payload fraction (must be 32)
58739 ** 24 4 File change counter
58740 ** 28 4 Reserved for future use
58741 ** 32 4 First freelist page
58742 ** 36 4 Number of freelist pages in the file
58743 ** 40 60 15 4-byte meta values passed to higher layers
58745 ** 40 4 Schema cookie
58746 ** 44 4 File format of schema layer
58747 ** 48 4 Size of page cache
58748 ** 52 4 Largest root-page (auto/incr_vacuum)
58749 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
58750 ** 60 4 User version
58751 ** 64 4 Incremental vacuum mode
58752 ** 68 4 Application-ID
58753 ** 72 20 unused
58754 ** 92 4 The version-valid-for number
58755 ** 96 4 SQLITE_VERSION_NUMBER
58757 ** All of the integer values are big-endian (most significant byte first).
58759 ** The file change counter is incremented when the database is changed
58760 ** This counter allows other processes to know when the file has changed
58761 ** and thus when they need to flush their cache.
58763 ** The max embedded payload fraction is the amount of the total usable
58764 ** space in a page that can be consumed by a single cell for standard
58765 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
58766 ** is to limit the maximum cell size so that at least 4 cells will fit
58767 ** on one page. Thus the default max embedded payload fraction is 64.
58769 ** If the payload for a cell is larger than the max payload, then extra
58770 ** payload is spilled to overflow pages. Once an overflow page is allocated,
58771 ** as many bytes as possible are moved into the overflow pages without letting
58772 ** the cell size drop below the min embedded payload fraction.
58774 ** The min leaf payload fraction is like the min embedded payload fraction
58775 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
58776 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
58777 ** not specified in the header.
58779 ** Each btree pages is divided into three sections: The header, the
58780 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
58781 ** file header that occurs before the page header.
58783 ** |----------------|
58784 ** | file header | 100 bytes. Page 1 only.
58785 ** |----------------|
58786 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
58787 ** |----------------|
58788 ** | cell pointer | | 2 bytes per cell. Sorted order.
58789 ** | array | | Grows downward
58790 ** | | v
58791 ** |----------------|
58792 ** | unallocated |
58793 ** | space |
58794 ** |----------------| ^ Grows upwards
58795 ** | cell content | | Arbitrary order interspersed with freeblocks.
58796 ** | area | | and free space fragments.
58797 ** |----------------|
58799 ** The page headers looks like this:
58801 ** OFFSET SIZE DESCRIPTION
58802 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
58803 ** 1 2 byte offset to the first freeblock
58804 ** 3 2 number of cells on this page
58805 ** 5 2 first byte of the cell content area
58806 ** 7 1 number of fragmented free bytes
58807 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
58809 ** The flags define the format of this btree page. The leaf flag means that
58810 ** this page has no children. The zerodata flag means that this page carries
58811 ** only keys and no data. The intkey flag means that the key is an integer
58812 ** which is stored in the key size entry of the cell header rather than in
58813 ** the payload area.
58815 ** The cell pointer array begins on the first byte after the page header.
58816 ** The cell pointer array contains zero or more 2-byte numbers which are
58817 ** offsets from the beginning of the page to the cell content in the cell
58818 ** content area. The cell pointers occur in sorted order. The system strives
58819 ** to keep free space after the last cell pointer so that new cells can
58820 ** be easily added without having to defragment the page.
58822 ** Cell content is stored at the very end of the page and grows toward the
58823 ** beginning of the page.
58825 ** Unused space within the cell content area is collected into a linked list of
58826 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
58827 ** to the first freeblock is given in the header. Freeblocks occur in
58828 ** increasing order. Because a freeblock must be at least 4 bytes in size,
58829 ** any group of 3 or fewer unused bytes in the cell content area cannot
58830 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
58831 ** a fragment. The total number of bytes in all fragments is recorded.
58832 ** in the page header at offset 7.
58834 ** SIZE DESCRIPTION
58835 ** 2 Byte offset of the next freeblock
58836 ** 2 Bytes in this freeblock
58838 ** Cells are of variable length. Cells are stored in the cell content area at
58839 ** the end of the page. Pointers to the cells are in the cell pointer array
58840 ** that immediately follows the page header. Cells is not necessarily
58841 ** contiguous or in order, but cell pointers are contiguous and in order.
58843 ** Cell content makes use of variable length integers. A variable
58844 ** length integer is 1 to 9 bytes where the lower 7 bits of each
58845 ** byte are used. The integer consists of all bytes that have bit 8 set and
58846 ** the first byte with bit 8 clear. The most significant byte of the integer
58847 ** appears first. A variable-length integer may not be more than 9 bytes long.
58848 ** As a special case, all 8 bytes of the 9th byte are used as data. This
58849 ** allows a 64-bit integer to be encoded in 9 bytes.
58851 ** 0x00 becomes 0x00000000
58852 ** 0x7f becomes 0x0000007f
58853 ** 0x81 0x00 becomes 0x00000080
58854 ** 0x82 0x00 becomes 0x00000100
58855 ** 0x80 0x7f becomes 0x0000007f
58856 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
58857 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
58859 ** Variable length integers are used for rowids and to hold the number of
58860 ** bytes of key and data in a btree cell.
58862 ** The content of a cell looks like this:
58864 ** SIZE DESCRIPTION
58865 ** 4 Page number of the left child. Omitted if leaf flag is set.
58866 ** var Number of bytes of data. Omitted if the zerodata flag is set.
58867 ** var Number of bytes of key. Or the key itself if intkey flag is set.
58868 ** * Payload
58869 ** 4 First page of the overflow chain. Omitted if no overflow
58871 ** Overflow pages form a linked list. Each page except the last is completely
58872 ** filled with data (pagesize - 4 bytes). The last page can have as little
58873 ** as 1 byte of data.
58875 ** SIZE DESCRIPTION
58876 ** 4 Page number of next overflow page
58877 ** * Data
58879 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
58880 ** file header points to the first in a linked list of trunk page. Each trunk
58881 ** page points to multiple leaf pages. The content of a leaf page is
58882 ** unspecified. A trunk page looks like this:
58884 ** SIZE DESCRIPTION
58885 ** 4 Page number of next trunk page
58886 ** 4 Number of leaf pointers on this page
58887 ** * zero or more pages numbers of leaves
58889 /* #include "sqliteInt.h" */
58892 /* The following value is the maximum cell size assuming a maximum page
58893 ** size give above.
58895 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
58897 /* The maximum number of cells on a single page of the database. This
58898 ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
58899 ** plus 2 bytes for the index to the cell in the page header). Such
58900 ** small cells will be rare, but they are possible.
58902 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
58904 /* Forward declarations */
58905 typedef struct MemPage MemPage;
58906 typedef struct BtLock BtLock;
58907 typedef struct CellInfo CellInfo;
58910 ** This is a magic string that appears at the beginning of every
58911 ** SQLite database in order to identify the file as a real database.
58913 ** You can change this value at compile-time by specifying a
58914 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
58915 ** header must be exactly 16 bytes including the zero-terminator so
58916 ** the string itself should be 15 characters long. If you change
58917 ** the header, then your custom library will not be able to read
58918 ** databases generated by the standard tools and the standard tools
58919 ** will not be able to read databases created by your custom library.
58921 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
58922 # define SQLITE_FILE_HEADER "SQLite format 3"
58923 #endif
58926 ** Page type flags. An ORed combination of these flags appear as the
58927 ** first byte of on-disk image of every BTree page.
58929 #define PTF_INTKEY 0x01
58930 #define PTF_ZERODATA 0x02
58931 #define PTF_LEAFDATA 0x04
58932 #define PTF_LEAF 0x08
58935 ** An instance of this object stores information about each a single database
58936 ** page that has been loaded into memory. The information in this object
58937 ** is derived from the raw on-disk page content.
58939 ** As each database page is loaded into memory, the pager allocats an
58940 ** instance of this object and zeros the first 8 bytes. (This is the
58941 ** "extra" information associated with each page of the pager.)
58943 ** Access to all fields of this structure is controlled by the mutex
58944 ** stored in MemPage.pBt->mutex.
58946 struct MemPage {
58947 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
58948 u8 bBusy; /* Prevent endless loops on corrupt database files */
58949 u8 intKey; /* True if table b-trees. False for index b-trees */
58950 u8 intKeyLeaf; /* True if the leaf of an intKey table */
58951 Pgno pgno; /* Page number for this page */
58952 /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
58953 ** is allocated. All fields that follow must be initialized before use */
58954 u8 leaf; /* True if a leaf page */
58955 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
58956 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
58957 u8 max1bytePayload; /* min(maxLocal,127) */
58958 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
58959 u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
58960 u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
58961 u16 cellOffset; /* Index in aData of first cell pointer */
58962 u16 nFree; /* Number of free bytes on the page */
58963 u16 nCell; /* Number of cells on this page, local and ovfl */
58964 u16 maskPage; /* Mask for page offset */
58965 u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
58966 ** non-overflow cell */
58967 u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
58968 BtShared *pBt; /* Pointer to BtShared that this page is part of */
58969 u8 *aData; /* Pointer to disk image of the page data */
58970 u8 *aDataEnd; /* One byte past the end of usable data */
58971 u8 *aCellIdx; /* The cell index area */
58972 u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
58973 DbPage *pDbPage; /* Pager page handle */
58974 u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
58975 void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
58979 ** A linked list of the following structures is stored at BtShared.pLock.
58980 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
58981 ** is opened on the table with root page BtShared.iTable. Locks are removed
58982 ** from this list when a transaction is committed or rolled back, or when
58983 ** a btree handle is closed.
58985 struct BtLock {
58986 Btree *pBtree; /* Btree handle holding this lock */
58987 Pgno iTable; /* Root page of table */
58988 u8 eLock; /* READ_LOCK or WRITE_LOCK */
58989 BtLock *pNext; /* Next in BtShared.pLock list */
58992 /* Candidate values for BtLock.eLock */
58993 #define READ_LOCK 1
58994 #define WRITE_LOCK 2
58996 /* A Btree handle
58998 ** A database connection contains a pointer to an instance of
58999 ** this object for every database file that it has open. This structure
59000 ** is opaque to the database connection. The database connection cannot
59001 ** see the internals of this structure and only deals with pointers to
59002 ** this structure.
59004 ** For some database files, the same underlying database cache might be
59005 ** shared between multiple connections. In that case, each connection
59006 ** has it own instance of this object. But each instance of this object
59007 ** points to the same BtShared object. The database cache and the
59008 ** schema associated with the database file are all contained within
59009 ** the BtShared object.
59011 ** All fields in this structure are accessed under sqlite3.mutex.
59012 ** The pBt pointer itself may not be changed while there exists cursors
59013 ** in the referenced BtShared that point back to this Btree since those
59014 ** cursors have to go through this Btree to find their BtShared and
59015 ** they often do so without holding sqlite3.mutex.
59017 struct Btree {
59018 sqlite3 *db; /* The database connection holding this btree */
59019 BtShared *pBt; /* Sharable content of this btree */
59020 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
59021 u8 sharable; /* True if we can share pBt with another db */
59022 u8 locked; /* True if db currently has pBt locked */
59023 u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
59024 int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
59025 int nBackup; /* Number of backup operations reading this btree */
59026 u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
59027 Btree *pNext; /* List of other sharable Btrees from the same db */
59028 Btree *pPrev; /* Back pointer of the same list */
59029 #ifndef SQLITE_OMIT_SHARED_CACHE
59030 BtLock lock; /* Object used to lock page 1 */
59031 #endif
59035 ** Btree.inTrans may take one of the following values.
59037 ** If the shared-data extension is enabled, there may be multiple users
59038 ** of the Btree structure. At most one of these may open a write transaction,
59039 ** but any number may have active read transactions.
59041 #define TRANS_NONE 0
59042 #define TRANS_READ 1
59043 #define TRANS_WRITE 2
59046 ** An instance of this object represents a single database file.
59048 ** A single database file can be in use at the same time by two
59049 ** or more database connections. When two or more connections are
59050 ** sharing the same database file, each connection has it own
59051 ** private Btree object for the file and each of those Btrees points
59052 ** to this one BtShared object. BtShared.nRef is the number of
59053 ** connections currently sharing this database file.
59055 ** Fields in this structure are accessed under the BtShared.mutex
59056 ** mutex, except for nRef and pNext which are accessed under the
59057 ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
59058 ** may not be modified once it is initially set as long as nRef>0.
59059 ** The pSchema field may be set once under BtShared.mutex and
59060 ** thereafter is unchanged as long as nRef>0.
59062 ** isPending:
59064 ** If a BtShared client fails to obtain a write-lock on a database
59065 ** table (because there exists one or more read-locks on the table),
59066 ** the shared-cache enters 'pending-lock' state and isPending is
59067 ** set to true.
59069 ** The shared-cache leaves the 'pending lock' state when either of
59070 ** the following occur:
59072 ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
59073 ** 2) The number of locks held by other connections drops to zero.
59075 ** while in the 'pending-lock' state, no connection may start a new
59076 ** transaction.
59078 ** This feature is included to help prevent writer-starvation.
59080 struct BtShared {
59081 Pager *pPager; /* The page cache */
59082 sqlite3 *db; /* Database connection currently using this Btree */
59083 BtCursor *pCursor; /* A list of all open cursors */
59084 MemPage *pPage1; /* First page of the database */
59085 u8 openFlags; /* Flags to sqlite3BtreeOpen() */
59086 #ifndef SQLITE_OMIT_AUTOVACUUM
59087 u8 autoVacuum; /* True if auto-vacuum is enabled */
59088 u8 incrVacuum; /* True if incr-vacuum is enabled */
59089 u8 bDoTruncate; /* True to truncate db on commit */
59090 #endif
59091 u8 inTransaction; /* Transaction state */
59092 u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
59093 #ifdef SQLITE_HAS_CODEC
59094 u8 optimalReserve; /* Desired amount of reserved space per page */
59095 #endif
59096 u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
59097 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
59098 u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
59099 u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
59100 u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
59101 u32 pageSize; /* Total number of bytes on a page */
59102 u32 usableSize; /* Number of usable bytes on each page */
59103 int nTransaction; /* Number of open transactions (read + write) */
59104 u32 nPage; /* Number of pages in the database */
59105 void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
59106 void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
59107 sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
59108 Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
59109 #ifndef SQLITE_OMIT_SHARED_CACHE
59110 int nRef; /* Number of references to this structure */
59111 BtShared *pNext; /* Next on a list of sharable BtShared structs */
59112 BtLock *pLock; /* List of locks held on this shared-btree struct */
59113 Btree *pWriter; /* Btree with currently open write transaction */
59114 #endif
59115 u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
59119 ** Allowed values for BtShared.btsFlags
59121 #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
59122 #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
59123 #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
59124 #define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */
59125 #define BTS_FAST_SECURE 0x000c /* Combination of the previous two */
59126 #define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */
59127 #define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
59128 #define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */
59129 #define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
59132 ** An instance of the following structure is used to hold information
59133 ** about a cell. The parseCellPtr() function fills in this structure
59134 ** based on information extract from the raw disk page.
59136 struct CellInfo {
59137 i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
59138 u8 *pPayload; /* Pointer to the start of payload */
59139 u32 nPayload; /* Bytes of payload */
59140 u16 nLocal; /* Amount of payload held locally, not on overflow */
59141 u16 nSize; /* Size of the cell content on the main b-tree page */
59145 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
59146 ** this will be declared corrupt. This value is calculated based on a
59147 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
59148 ** root-node and 3 for all other internal nodes.
59150 ** If a tree that appears to be taller than this is encountered, it is
59151 ** assumed that the database is corrupt.
59153 #define BTCURSOR_MAX_DEPTH 20
59156 ** A cursor is a pointer to a particular entry within a particular
59157 ** b-tree within a database file.
59159 ** The entry is identified by its MemPage and the index in
59160 ** MemPage.aCell[] of the entry.
59162 ** A single database file can be shared by two more database connections,
59163 ** but cursors cannot be shared. Each cursor is associated with a
59164 ** particular database connection identified BtCursor.pBtree.db.
59166 ** Fields in this structure are accessed under the BtShared.mutex
59167 ** found at self->pBt->mutex.
59169 ** skipNext meaning:
59170 ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
59171 ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
59172 ** eState==FAULT: Cursor fault with skipNext as error code.
59174 struct BtCursor {
59175 u8 eState; /* One of the CURSOR_XXX constants (see below) */
59176 u8 curFlags; /* zero or more BTCF_* flags defined below */
59177 u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
59178 u8 hints; /* As configured by CursorSetHints() */
59179 int nOvflAlloc; /* Allocated size of aOverflow[] array */
59180 Btree *pBtree; /* The Btree to which this cursor belongs */
59181 BtShared *pBt; /* The BtShared this cursor points to */
59182 BtCursor *pNext; /* Forms a linked list of all cursors */
59183 Pgno *aOverflow; /* Cache of overflow page locations */
59184 CellInfo info; /* A parse of the cell we are pointing at */
59185 i64 nKey; /* Size of pKey, or last integer key */
59186 void *pKey; /* Saved key that was cursor last known position */
59187 Pgno pgnoRoot; /* The root page of this tree */
59188 int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
59189 ** Error code if eState==CURSOR_FAULT */
59190 /* All fields above are zeroed when the cursor is allocated. See
59191 ** sqlite3BtreeCursorZero(). Fields that follow must be manually
59192 ** initialized. */
59193 i8 iPage; /* Index of current page in apPage */
59194 u8 curIntKey; /* Value of apPage[0]->intKey */
59195 u16 ix; /* Current index for apPage[iPage] */
59196 u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
59197 struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
59198 MemPage *pPage; /* Current page */
59199 MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
59203 ** Legal values for BtCursor.curFlags
59205 #define BTCF_WriteFlag 0x01 /* True if a write cursor */
59206 #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
59207 #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
59208 #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
59209 #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
59210 #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
59213 ** Potential values for BtCursor.eState.
59215 ** CURSOR_INVALID:
59216 ** Cursor does not point to a valid entry. This can happen (for example)
59217 ** because the table is empty or because BtreeCursorFirst() has not been
59218 ** called.
59220 ** CURSOR_VALID:
59221 ** Cursor points to a valid entry. getPayload() etc. may be called.
59223 ** CURSOR_SKIPNEXT:
59224 ** Cursor is valid except that the Cursor.skipNext field is non-zero
59225 ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
59226 ** operation should be a no-op.
59228 ** CURSOR_REQUIRESEEK:
59229 ** The table that this cursor was opened on still exists, but has been
59230 ** modified since the cursor was last used. The cursor position is saved
59231 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
59232 ** this state, restoreCursorPosition() can be called to attempt to
59233 ** seek the cursor to the saved position.
59235 ** CURSOR_FAULT:
59236 ** An unrecoverable error (an I/O error or a malloc failure) has occurred
59237 ** on a different connection that shares the BtShared cache with this
59238 ** cursor. The error has left the cache in an inconsistent state.
59239 ** Do nothing else with this cursor. Any attempt to use the cursor
59240 ** should return the error code stored in BtCursor.skipNext
59242 #define CURSOR_INVALID 0
59243 #define CURSOR_VALID 1
59244 #define CURSOR_SKIPNEXT 2
59245 #define CURSOR_REQUIRESEEK 3
59246 #define CURSOR_FAULT 4
59249 ** The database page the PENDING_BYTE occupies. This page is never used.
59251 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
59254 ** These macros define the location of the pointer-map entry for a
59255 ** database page. The first argument to each is the number of usable
59256 ** bytes on each page of the database (often 1024). The second is the
59257 ** page number to look up in the pointer map.
59259 ** PTRMAP_PAGENO returns the database page number of the pointer-map
59260 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
59261 ** the offset of the requested map entry.
59263 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
59264 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
59265 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
59266 ** this test.
59268 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
59269 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
59270 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
59273 ** The pointer map is a lookup table that identifies the parent page for
59274 ** each child page in the database file. The parent page is the page that
59275 ** contains a pointer to the child. Every page in the database contains
59276 ** 0 or 1 parent pages. (In this context 'database page' refers
59277 ** to any page that is not part of the pointer map itself.) Each pointer map
59278 ** entry consists of a single byte 'type' and a 4 byte parent page number.
59279 ** The PTRMAP_XXX identifiers below are the valid types.
59281 ** The purpose of the pointer map is to facility moving pages from one
59282 ** position in the file to another as part of autovacuum. When a page
59283 ** is moved, the pointer in its parent must be updated to point to the
59284 ** new location. The pointer map is used to locate the parent page quickly.
59286 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
59287 ** used in this case.
59289 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
59290 ** is not used in this case.
59292 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
59293 ** overflow pages. The page number identifies the page that
59294 ** contains the cell with a pointer to this overflow page.
59296 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
59297 ** overflow pages. The page-number identifies the previous
59298 ** page in the overflow page list.
59300 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
59301 ** identifies the parent page in the btree.
59303 #define PTRMAP_ROOTPAGE 1
59304 #define PTRMAP_FREEPAGE 2
59305 #define PTRMAP_OVERFLOW1 3
59306 #define PTRMAP_OVERFLOW2 4
59307 #define PTRMAP_BTREE 5
59309 /* A bunch of assert() statements to check the transaction state variables
59310 ** of handle p (type Btree*) are internally consistent.
59312 #define btreeIntegrity(p) \
59313 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
59314 assert( p->pBt->inTransaction>=p->inTrans );
59318 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
59319 ** if the database supports auto-vacuum or not. Because it is used
59320 ** within an expression that is an argument to another macro
59321 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
59322 ** So, this macro is defined instead.
59324 #ifndef SQLITE_OMIT_AUTOVACUUM
59325 #define ISAUTOVACUUM (pBt->autoVacuum)
59326 #else
59327 #define ISAUTOVACUUM 0
59328 #endif
59332 ** This structure is passed around through all the sanity checking routines
59333 ** in order to keep track of some global state information.
59335 ** The aRef[] array is allocated so that there is 1 bit for each page in
59336 ** the database. As the integrity-check proceeds, for each page used in
59337 ** the database the corresponding bit is set. This allows integrity-check to
59338 ** detect pages that are used twice and orphaned pages (both of which
59339 ** indicate corruption).
59341 typedef struct IntegrityCk IntegrityCk;
59342 struct IntegrityCk {
59343 BtShared *pBt; /* The tree being checked out */
59344 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
59345 u8 *aPgRef; /* 1 bit per page in the db (see above) */
59346 Pgno nPage; /* Number of pages in the database */
59347 int mxErr; /* Stop accumulating errors when this reaches zero */
59348 int nErr; /* Number of messages written to zErrMsg so far */
59349 int mallocFailed; /* A memory allocation error has occurred */
59350 const char *zPfx; /* Error message prefix */
59351 int v1, v2; /* Values for up to two %d fields in zPfx */
59352 StrAccum errMsg; /* Accumulate the error message text here */
59353 u32 *heap; /* Min-heap used for analyzing cell coverage */
59357 ** Routines to read or write a two- and four-byte big-endian integer values.
59359 #define get2byte(x) ((x)[0]<<8 | (x)[1])
59360 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
59361 #define get4byte sqlite3Get4byte
59362 #define put4byte sqlite3Put4byte
59365 ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
59366 ** two-byte aligned address. get2bytea() is only used for accessing the
59367 ** cell addresses in a btree header.
59369 #if SQLITE_BYTEORDER==4321
59370 # define get2byteAligned(x) (*(u16*)(x))
59371 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
59372 # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
59373 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
59374 # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
59375 #else
59376 # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
59377 #endif
59379 /************** End of btreeInt.h ********************************************/
59380 /************** Continuing where we left off in btmutex.c ********************/
59381 #ifndef SQLITE_OMIT_SHARED_CACHE
59382 #if SQLITE_THREADSAFE
59385 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
59386 ** set BtShared.db to the database handle associated with p and the
59387 ** p->locked boolean to true.
59389 static void lockBtreeMutex(Btree *p){
59390 assert( p->locked==0 );
59391 assert( sqlite3_mutex_notheld(p->pBt->mutex) );
59392 assert( sqlite3_mutex_held(p->db->mutex) );
59394 sqlite3_mutex_enter(p->pBt->mutex);
59395 p->pBt->db = p->db;
59396 p->locked = 1;
59400 ** Release the BtShared mutex associated with B-Tree handle p and
59401 ** clear the p->locked boolean.
59403 static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
59404 BtShared *pBt = p->pBt;
59405 assert( p->locked==1 );
59406 assert( sqlite3_mutex_held(pBt->mutex) );
59407 assert( sqlite3_mutex_held(p->db->mutex) );
59408 assert( p->db==pBt->db );
59410 sqlite3_mutex_leave(pBt->mutex);
59411 p->locked = 0;
59414 /* Forward reference */
59415 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
59418 ** Enter a mutex on the given BTree object.
59420 ** If the object is not sharable, then no mutex is ever required
59421 ** and this routine is a no-op. The underlying mutex is non-recursive.
59422 ** But we keep a reference count in Btree.wantToLock so the behavior
59423 ** of this interface is recursive.
59425 ** To avoid deadlocks, multiple Btrees are locked in the same order
59426 ** by all database connections. The p->pNext is a list of other
59427 ** Btrees belonging to the same database connection as the p Btree
59428 ** which need to be locked after p. If we cannot get a lock on
59429 ** p, then first unlock all of the others on p->pNext, then wait
59430 ** for the lock to become available on p, then relock all of the
59431 ** subsequent Btrees that desire a lock.
59433 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
59434 /* Some basic sanity checking on the Btree. The list of Btrees
59435 ** connected by pNext and pPrev should be in sorted order by
59436 ** Btree.pBt value. All elements of the list should belong to
59437 ** the same connection. Only shared Btrees are on the list. */
59438 assert( p->pNext==0 || p->pNext->pBt>p->pBt );
59439 assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
59440 assert( p->pNext==0 || p->pNext->db==p->db );
59441 assert( p->pPrev==0 || p->pPrev->db==p->db );
59442 assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
59444 /* Check for locking consistency */
59445 assert( !p->locked || p->wantToLock>0 );
59446 assert( p->sharable || p->wantToLock==0 );
59448 /* We should already hold a lock on the database connection */
59449 assert( sqlite3_mutex_held(p->db->mutex) );
59451 /* Unless the database is sharable and unlocked, then BtShared.db
59452 ** should already be set correctly. */
59453 assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
59455 if( !p->sharable ) return;
59456 p->wantToLock++;
59457 if( p->locked ) return;
59458 btreeLockCarefully(p);
59461 /* This is a helper function for sqlite3BtreeLock(). By moving
59462 ** complex, but seldom used logic, out of sqlite3BtreeLock() and
59463 ** into this routine, we avoid unnecessary stack pointer changes
59464 ** and thus help the sqlite3BtreeLock() routine to run much faster
59465 ** in the common case.
59467 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
59468 Btree *pLater;
59470 /* In most cases, we should be able to acquire the lock we
59471 ** want without having to go through the ascending lock
59472 ** procedure that follows. Just be sure not to block.
59474 if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
59475 p->pBt->db = p->db;
59476 p->locked = 1;
59477 return;
59480 /* To avoid deadlock, first release all locks with a larger
59481 ** BtShared address. Then acquire our lock. Then reacquire
59482 ** the other BtShared locks that we used to hold in ascending
59483 ** order.
59485 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
59486 assert( pLater->sharable );
59487 assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
59488 assert( !pLater->locked || pLater->wantToLock>0 );
59489 if( pLater->locked ){
59490 unlockBtreeMutex(pLater);
59493 lockBtreeMutex(p);
59494 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
59495 if( pLater->wantToLock ){
59496 lockBtreeMutex(pLater);
59503 ** Exit the recursive mutex on a Btree.
59505 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
59506 assert( sqlite3_mutex_held(p->db->mutex) );
59507 if( p->sharable ){
59508 assert( p->wantToLock>0 );
59509 p->wantToLock--;
59510 if( p->wantToLock==0 ){
59511 unlockBtreeMutex(p);
59516 #ifndef NDEBUG
59518 ** Return true if the BtShared mutex is held on the btree, or if the
59519 ** B-Tree is not marked as sharable.
59521 ** This routine is used only from within assert() statements.
59523 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
59524 assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
59525 assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
59526 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
59527 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
59529 return (p->sharable==0 || p->locked);
59531 #endif
59535 ** Enter the mutex on every Btree associated with a database
59536 ** connection. This is needed (for example) prior to parsing
59537 ** a statement since we will be comparing table and column names
59538 ** against all schemas and we do not want those schemas being
59539 ** reset out from under us.
59541 ** There is a corresponding leave-all procedures.
59543 ** Enter the mutexes in accending order by BtShared pointer address
59544 ** to avoid the possibility of deadlock when two threads with
59545 ** two or more btrees in common both try to lock all their btrees
59546 ** at the same instant.
59548 static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
59549 int i;
59550 int skipOk = 1;
59551 Btree *p;
59552 assert( sqlite3_mutex_held(db->mutex) );
59553 for(i=0; i<db->nDb; i++){
59554 p = db->aDb[i].pBt;
59555 if( p && p->sharable ){
59556 sqlite3BtreeEnter(p);
59557 skipOk = 0;
59560 db->skipBtreeMutex = skipOk;
59562 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
59563 if( db->skipBtreeMutex==0 ) btreeEnterAll(db);
59565 static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
59566 int i;
59567 Btree *p;
59568 assert( sqlite3_mutex_held(db->mutex) );
59569 for(i=0; i<db->nDb; i++){
59570 p = db->aDb[i].pBt;
59571 if( p ) sqlite3BtreeLeave(p);
59574 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
59575 if( db->skipBtreeMutex==0 ) btreeLeaveAll(db);
59578 #ifndef NDEBUG
59580 ** Return true if the current thread holds the database connection
59581 ** mutex and all required BtShared mutexes.
59583 ** This routine is used inside assert() statements only.
59585 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
59586 int i;
59587 if( !sqlite3_mutex_held(db->mutex) ){
59588 return 0;
59590 for(i=0; i<db->nDb; i++){
59591 Btree *p;
59592 p = db->aDb[i].pBt;
59593 if( p && p->sharable &&
59594 (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
59595 return 0;
59598 return 1;
59600 #endif /* NDEBUG */
59602 #ifndef NDEBUG
59604 ** Return true if the correct mutexes are held for accessing the
59605 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
59606 ** access are:
59608 ** (1) The mutex on db
59609 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
59611 ** If pSchema is not NULL, then iDb is computed from pSchema and
59612 ** db using sqlite3SchemaToIndex().
59614 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
59615 Btree *p;
59616 assert( db!=0 );
59617 if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
59618 assert( iDb>=0 && iDb<db->nDb );
59619 if( !sqlite3_mutex_held(db->mutex) ) return 0;
59620 if( iDb==1 ) return 1;
59621 p = db->aDb[iDb].pBt;
59622 assert( p!=0 );
59623 return p->sharable==0 || p->locked==1;
59625 #endif /* NDEBUG */
59627 #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
59629 ** The following are special cases for mutex enter routines for use
59630 ** in single threaded applications that use shared cache. Except for
59631 ** these two routines, all mutex operations are no-ops in that case and
59632 ** are null #defines in btree.h.
59634 ** If shared cache is disabled, then all btree mutex routines, including
59635 ** the ones below, are no-ops and are null #defines in btree.h.
59638 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
59639 p->pBt->db = p->db;
59641 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
59642 int i;
59643 for(i=0; i<db->nDb; i++){
59644 Btree *p = db->aDb[i].pBt;
59645 if( p ){
59646 p->pBt->db = p->db;
59650 #endif /* if SQLITE_THREADSAFE */
59652 #ifndef SQLITE_OMIT_INCRBLOB
59654 ** Enter a mutex on a Btree given a cursor owned by that Btree.
59656 ** These entry points are used by incremental I/O only. Enter() is required
59657 ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
59658 ** the build is threadsafe. Leave() is only required by threadsafe builds.
59660 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
59661 sqlite3BtreeEnter(pCur->pBtree);
59663 # if SQLITE_THREADSAFE
59664 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
59665 sqlite3BtreeLeave(pCur->pBtree);
59667 # endif
59668 #endif /* ifndef SQLITE_OMIT_INCRBLOB */
59670 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
59672 /************** End of btmutex.c *********************************************/
59673 /************** Begin file btree.c *******************************************/
59675 ** 2004 April 6
59677 ** The author disclaims copyright to this source code. In place of
59678 ** a legal notice, here is a blessing:
59680 ** May you do good and not evil.
59681 ** May you find forgiveness for yourself and forgive others.
59682 ** May you share freely, never taking more than you give.
59684 *************************************************************************
59685 ** This file implements an external (disk-based) database using BTrees.
59686 ** See the header comment on "btreeInt.h" for additional information.
59687 ** Including a description of file format and an overview of operation.
59689 /* #include "btreeInt.h" */
59692 ** The header string that appears at the beginning of every
59693 ** SQLite database.
59695 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
59698 ** Set this global variable to 1 to enable tracing using the TRACE
59699 ** macro.
59701 #if 0
59702 int sqlite3BtreeTrace=1; /* True to enable tracing */
59703 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
59704 #else
59705 # define TRACE(X)
59706 #endif
59709 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
59710 ** But if the value is zero, make it 65536.
59712 ** This routine is used to extract the "offset to cell content area" value
59713 ** from the header of a btree page. If the page size is 65536 and the page
59714 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
59715 ** This routine makes the necessary adjustment to 65536.
59717 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
59720 ** Values passed as the 5th argument to allocateBtreePage()
59722 #define BTALLOC_ANY 0 /* Allocate any page */
59723 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
59724 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
59727 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
59728 ** defined, or 0 if it is. For example:
59730 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
59732 #ifndef SQLITE_OMIT_AUTOVACUUM
59733 #define IfNotOmitAV(expr) (expr)
59734 #else
59735 #define IfNotOmitAV(expr) 0
59736 #endif
59738 #ifndef SQLITE_OMIT_SHARED_CACHE
59740 ** A list of BtShared objects that are eligible for participation
59741 ** in shared cache. This variable has file scope during normal builds,
59742 ** but the test harness needs to access it so we make it global for
59743 ** test builds.
59745 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
59747 #ifdef SQLITE_TEST
59748 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
59749 #else
59750 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
59751 #endif
59752 #endif /* SQLITE_OMIT_SHARED_CACHE */
59754 #ifndef SQLITE_OMIT_SHARED_CACHE
59756 ** Enable or disable the shared pager and schema features.
59758 ** This routine has no effect on existing database connections.
59759 ** The shared cache setting effects only future calls to
59760 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
59762 SQLITE_API int sqlite3_enable_shared_cache(int enable){
59763 sqlite3GlobalConfig.sharedCacheEnabled = enable;
59764 return SQLITE_OK;
59766 #endif
59770 #ifdef SQLITE_OMIT_SHARED_CACHE
59772 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
59773 ** and clearAllSharedCacheTableLocks()
59774 ** manipulate entries in the BtShared.pLock linked list used to store
59775 ** shared-cache table level locks. If the library is compiled with the
59776 ** shared-cache feature disabled, then there is only ever one user
59777 ** of each BtShared structure and so this locking is not necessary.
59778 ** So define the lock related functions as no-ops.
59780 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
59781 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
59782 #define clearAllSharedCacheTableLocks(a)
59783 #define downgradeAllSharedCacheTableLocks(a)
59784 #define hasSharedCacheTableLock(a,b,c,d) 1
59785 #define hasReadConflicts(a, b) 0
59786 #endif
59788 #ifndef SQLITE_OMIT_SHARED_CACHE
59790 #ifdef SQLITE_DEBUG
59792 **** This function is only used as part of an assert() statement. ***
59794 ** Check to see if pBtree holds the required locks to read or write to the
59795 ** table with root page iRoot. Return 1 if it does and 0 if not.
59797 ** For example, when writing to a table with root-page iRoot via
59798 ** Btree connection pBtree:
59800 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
59802 ** When writing to an index that resides in a sharable database, the
59803 ** caller should have first obtained a lock specifying the root page of
59804 ** the corresponding table. This makes things a bit more complicated,
59805 ** as this module treats each table as a separate structure. To determine
59806 ** the table corresponding to the index being written, this
59807 ** function has to search through the database schema.
59809 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
59810 ** hold a write-lock on the schema table (root page 1). This is also
59811 ** acceptable.
59813 static int hasSharedCacheTableLock(
59814 Btree *pBtree, /* Handle that must hold lock */
59815 Pgno iRoot, /* Root page of b-tree */
59816 int isIndex, /* True if iRoot is the root of an index b-tree */
59817 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
59819 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
59820 Pgno iTab = 0;
59821 BtLock *pLock;
59823 /* If this database is not shareable, or if the client is reading
59824 ** and has the read-uncommitted flag set, then no lock is required.
59825 ** Return true immediately.
59827 if( (pBtree->sharable==0)
59828 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
59830 return 1;
59833 /* If the client is reading or writing an index and the schema is
59834 ** not loaded, then it is too difficult to actually check to see if
59835 ** the correct locks are held. So do not bother - just return true.
59836 ** This case does not come up very often anyhow.
59838 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
59839 return 1;
59842 /* Figure out the root-page that the lock should be held on. For table
59843 ** b-trees, this is just the root page of the b-tree being read or
59844 ** written. For index b-trees, it is the root page of the associated
59845 ** table. */
59846 if( isIndex ){
59847 HashElem *p;
59848 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
59849 Index *pIdx = (Index *)sqliteHashData(p);
59850 if( pIdx->tnum==(int)iRoot ){
59851 if( iTab ){
59852 /* Two or more indexes share the same root page. There must
59853 ** be imposter tables. So just return true. The assert is not
59854 ** useful in that case. */
59855 return 1;
59857 iTab = pIdx->pTable->tnum;
59860 }else{
59861 iTab = iRoot;
59864 /* Search for the required lock. Either a write-lock on root-page iTab, a
59865 ** write-lock on the schema table, or (if the client is reading) a
59866 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
59867 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
59868 if( pLock->pBtree==pBtree
59869 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
59870 && pLock->eLock>=eLockType
59872 return 1;
59876 /* Failed to find the required lock. */
59877 return 0;
59879 #endif /* SQLITE_DEBUG */
59881 #ifdef SQLITE_DEBUG
59883 **** This function may be used as part of assert() statements only. ****
59885 ** Return true if it would be illegal for pBtree to write into the
59886 ** table or index rooted at iRoot because other shared connections are
59887 ** simultaneously reading that same table or index.
59889 ** It is illegal for pBtree to write if some other Btree object that
59890 ** shares the same BtShared object is currently reading or writing
59891 ** the iRoot table. Except, if the other Btree object has the
59892 ** read-uncommitted flag set, then it is OK for the other object to
59893 ** have a read cursor.
59895 ** For example, before writing to any part of the table or index
59896 ** rooted at page iRoot, one should call:
59898 ** assert( !hasReadConflicts(pBtree, iRoot) );
59900 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
59901 BtCursor *p;
59902 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
59903 if( p->pgnoRoot==iRoot
59904 && p->pBtree!=pBtree
59905 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
59907 return 1;
59910 return 0;
59912 #endif /* #ifdef SQLITE_DEBUG */
59915 ** Query to see if Btree handle p may obtain a lock of type eLock
59916 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
59917 ** SQLITE_OK if the lock may be obtained (by calling
59918 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
59920 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
59921 BtShared *pBt = p->pBt;
59922 BtLock *pIter;
59924 assert( sqlite3BtreeHoldsMutex(p) );
59925 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
59926 assert( p->db!=0 );
59927 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
59929 /* If requesting a write-lock, then the Btree must have an open write
59930 ** transaction on this file. And, obviously, for this to be so there
59931 ** must be an open write transaction on the file itself.
59933 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
59934 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
59936 /* This routine is a no-op if the shared-cache is not enabled */
59937 if( !p->sharable ){
59938 return SQLITE_OK;
59941 /* If some other connection is holding an exclusive lock, the
59942 ** requested lock may not be obtained.
59944 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
59945 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
59946 return SQLITE_LOCKED_SHAREDCACHE;
59949 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
59950 /* The condition (pIter->eLock!=eLock) in the following if(...)
59951 ** statement is a simplification of:
59953 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
59955 ** since we know that if eLock==WRITE_LOCK, then no other connection
59956 ** may hold a WRITE_LOCK on any table in this file (since there can
59957 ** only be a single writer).
59959 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
59960 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
59961 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
59962 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
59963 if( eLock==WRITE_LOCK ){
59964 assert( p==pBt->pWriter );
59965 pBt->btsFlags |= BTS_PENDING;
59967 return SQLITE_LOCKED_SHAREDCACHE;
59970 return SQLITE_OK;
59972 #endif /* !SQLITE_OMIT_SHARED_CACHE */
59974 #ifndef SQLITE_OMIT_SHARED_CACHE
59976 ** Add a lock on the table with root-page iTable to the shared-btree used
59977 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
59978 ** WRITE_LOCK.
59980 ** This function assumes the following:
59982 ** (a) The specified Btree object p is connected to a sharable
59983 ** database (one with the BtShared.sharable flag set), and
59985 ** (b) No other Btree objects hold a lock that conflicts
59986 ** with the requested lock (i.e. querySharedCacheTableLock() has
59987 ** already been called and returned SQLITE_OK).
59989 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
59990 ** is returned if a malloc attempt fails.
59992 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
59993 BtShared *pBt = p->pBt;
59994 BtLock *pLock = 0;
59995 BtLock *pIter;
59997 assert( sqlite3BtreeHoldsMutex(p) );
59998 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
59999 assert( p->db!=0 );
60001 /* A connection with the read-uncommitted flag set will never try to
60002 ** obtain a read-lock using this function. The only read-lock obtained
60003 ** by a connection in read-uncommitted mode is on the sqlite_master
60004 ** table, and that lock is obtained in BtreeBeginTrans(). */
60005 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
60007 /* This function should only be called on a sharable b-tree after it
60008 ** has been determined that no other b-tree holds a conflicting lock. */
60009 assert( p->sharable );
60010 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
60012 /* First search the list for an existing lock on this table. */
60013 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
60014 if( pIter->iTable==iTable && pIter->pBtree==p ){
60015 pLock = pIter;
60016 break;
60020 /* If the above search did not find a BtLock struct associating Btree p
60021 ** with table iTable, allocate one and link it into the list.
60023 if( !pLock ){
60024 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
60025 if( !pLock ){
60026 return SQLITE_NOMEM_BKPT;
60028 pLock->iTable = iTable;
60029 pLock->pBtree = p;
60030 pLock->pNext = pBt->pLock;
60031 pBt->pLock = pLock;
60034 /* Set the BtLock.eLock variable to the maximum of the current lock
60035 ** and the requested lock. This means if a write-lock was already held
60036 ** and a read-lock requested, we don't incorrectly downgrade the lock.
60038 assert( WRITE_LOCK>READ_LOCK );
60039 if( eLock>pLock->eLock ){
60040 pLock->eLock = eLock;
60043 return SQLITE_OK;
60045 #endif /* !SQLITE_OMIT_SHARED_CACHE */
60047 #ifndef SQLITE_OMIT_SHARED_CACHE
60049 ** Release all the table locks (locks obtained via calls to
60050 ** the setSharedCacheTableLock() procedure) held by Btree object p.
60052 ** This function assumes that Btree p has an open read or write
60053 ** transaction. If it does not, then the BTS_PENDING flag
60054 ** may be incorrectly cleared.
60056 static void clearAllSharedCacheTableLocks(Btree *p){
60057 BtShared *pBt = p->pBt;
60058 BtLock **ppIter = &pBt->pLock;
60060 assert( sqlite3BtreeHoldsMutex(p) );
60061 assert( p->sharable || 0==*ppIter );
60062 assert( p->inTrans>0 );
60064 while( *ppIter ){
60065 BtLock *pLock = *ppIter;
60066 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
60067 assert( pLock->pBtree->inTrans>=pLock->eLock );
60068 if( pLock->pBtree==p ){
60069 *ppIter = pLock->pNext;
60070 assert( pLock->iTable!=1 || pLock==&p->lock );
60071 if( pLock->iTable!=1 ){
60072 sqlite3_free(pLock);
60074 }else{
60075 ppIter = &pLock->pNext;
60079 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
60080 if( pBt->pWriter==p ){
60081 pBt->pWriter = 0;
60082 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
60083 }else if( pBt->nTransaction==2 ){
60084 /* This function is called when Btree p is concluding its
60085 ** transaction. If there currently exists a writer, and p is not
60086 ** that writer, then the number of locks held by connections other
60087 ** than the writer must be about to drop to zero. In this case
60088 ** set the BTS_PENDING flag to 0.
60090 ** If there is not currently a writer, then BTS_PENDING must
60091 ** be zero already. So this next line is harmless in that case.
60093 pBt->btsFlags &= ~BTS_PENDING;
60098 ** This function changes all write-locks held by Btree p into read-locks.
60100 static void downgradeAllSharedCacheTableLocks(Btree *p){
60101 BtShared *pBt = p->pBt;
60102 if( pBt->pWriter==p ){
60103 BtLock *pLock;
60104 pBt->pWriter = 0;
60105 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
60106 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
60107 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
60108 pLock->eLock = READ_LOCK;
60113 #endif /* SQLITE_OMIT_SHARED_CACHE */
60115 static void releasePage(MemPage *pPage); /* Forward reference */
60116 static void releasePageOne(MemPage *pPage); /* Forward reference */
60117 static void releasePageNotNull(MemPage *pPage); /* Forward reference */
60120 ***** This routine is used inside of assert() only ****
60122 ** Verify that the cursor holds the mutex on its BtShared
60124 #ifdef SQLITE_DEBUG
60125 static int cursorHoldsMutex(BtCursor *p){
60126 return sqlite3_mutex_held(p->pBt->mutex);
60129 /* Verify that the cursor and the BtShared agree about what is the current
60130 ** database connetion. This is important in shared-cache mode. If the database
60131 ** connection pointers get out-of-sync, it is possible for routines like
60132 ** btreeInitPage() to reference an stale connection pointer that references a
60133 ** a connection that has already closed. This routine is used inside assert()
60134 ** statements only and for the purpose of double-checking that the btree code
60135 ** does keep the database connection pointers up-to-date.
60137 static int cursorOwnsBtShared(BtCursor *p){
60138 assert( cursorHoldsMutex(p) );
60139 return (p->pBtree->db==p->pBt->db);
60141 #endif
60144 ** Invalidate the overflow cache of the cursor passed as the first argument.
60145 ** on the shared btree structure pBt.
60147 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
60150 ** Invalidate the overflow page-list cache for all cursors opened
60151 ** on the shared btree structure pBt.
60153 static void invalidateAllOverflowCache(BtShared *pBt){
60154 BtCursor *p;
60155 assert( sqlite3_mutex_held(pBt->mutex) );
60156 for(p=pBt->pCursor; p; p=p->pNext){
60157 invalidateOverflowCache(p);
60161 #ifndef SQLITE_OMIT_INCRBLOB
60163 ** This function is called before modifying the contents of a table
60164 ** to invalidate any incrblob cursors that are open on the
60165 ** row or one of the rows being modified.
60167 ** If argument isClearTable is true, then the entire contents of the
60168 ** table is about to be deleted. In this case invalidate all incrblob
60169 ** cursors open on any row within the table with root-page pgnoRoot.
60171 ** Otherwise, if argument isClearTable is false, then the row with
60172 ** rowid iRow is being replaced or deleted. In this case invalidate
60173 ** only those incrblob cursors open on that specific row.
60175 static void invalidateIncrblobCursors(
60176 Btree *pBtree, /* The database file to check */
60177 Pgno pgnoRoot, /* The table that might be changing */
60178 i64 iRow, /* The rowid that might be changing */
60179 int isClearTable /* True if all rows are being deleted */
60181 BtCursor *p;
60182 if( pBtree->hasIncrblobCur==0 ) return;
60183 assert( sqlite3BtreeHoldsMutex(pBtree) );
60184 pBtree->hasIncrblobCur = 0;
60185 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
60186 if( (p->curFlags & BTCF_Incrblob)!=0 ){
60187 pBtree->hasIncrblobCur = 1;
60188 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
60189 p->eState = CURSOR_INVALID;
60195 #else
60196 /* Stub function when INCRBLOB is omitted */
60197 #define invalidateIncrblobCursors(w,x,y,z)
60198 #endif /* SQLITE_OMIT_INCRBLOB */
60201 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
60202 ** when a page that previously contained data becomes a free-list leaf
60203 ** page.
60205 ** The BtShared.pHasContent bitvec exists to work around an obscure
60206 ** bug caused by the interaction of two useful IO optimizations surrounding
60207 ** free-list leaf pages:
60209 ** 1) When all data is deleted from a page and the page becomes
60210 ** a free-list leaf page, the page is not written to the database
60211 ** (as free-list leaf pages contain no meaningful data). Sometimes
60212 ** such a page is not even journalled (as it will not be modified,
60213 ** why bother journalling it?).
60215 ** 2) When a free-list leaf page is reused, its content is not read
60216 ** from the database or written to the journal file (why should it
60217 ** be, if it is not at all meaningful?).
60219 ** By themselves, these optimizations work fine and provide a handy
60220 ** performance boost to bulk delete or insert operations. However, if
60221 ** a page is moved to the free-list and then reused within the same
60222 ** transaction, a problem comes up. If the page is not journalled when
60223 ** it is moved to the free-list and it is also not journalled when it
60224 ** is extracted from the free-list and reused, then the original data
60225 ** may be lost. In the event of a rollback, it may not be possible
60226 ** to restore the database to its original configuration.
60228 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
60229 ** moved to become a free-list leaf page, the corresponding bit is
60230 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
60231 ** optimization 2 above is omitted if the corresponding bit is already
60232 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
60233 ** at the end of every transaction.
60235 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
60236 int rc = SQLITE_OK;
60237 if( !pBt->pHasContent ){
60238 assert( pgno<=pBt->nPage );
60239 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
60240 if( !pBt->pHasContent ){
60241 rc = SQLITE_NOMEM_BKPT;
60244 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
60245 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
60247 return rc;
60251 ** Query the BtShared.pHasContent vector.
60253 ** This function is called when a free-list leaf page is removed from the
60254 ** free-list for reuse. It returns false if it is safe to retrieve the
60255 ** page from the pager layer with the 'no-content' flag set. True otherwise.
60257 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
60258 Bitvec *p = pBt->pHasContent;
60259 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
60263 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
60264 ** invoked at the conclusion of each write-transaction.
60266 static void btreeClearHasContent(BtShared *pBt){
60267 sqlite3BitvecDestroy(pBt->pHasContent);
60268 pBt->pHasContent = 0;
60272 ** Release all of the apPage[] pages for a cursor.
60274 static void btreeReleaseAllCursorPages(BtCursor *pCur){
60275 int i;
60276 if( pCur->iPage>=0 ){
60277 for(i=0; i<pCur->iPage; i++){
60278 releasePageNotNull(pCur->apPage[i]);
60280 releasePageNotNull(pCur->pPage);
60281 pCur->iPage = -1;
60286 ** The cursor passed as the only argument must point to a valid entry
60287 ** when this function is called (i.e. have eState==CURSOR_VALID). This
60288 ** function saves the current cursor key in variables pCur->nKey and
60289 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
60290 ** code otherwise.
60292 ** If the cursor is open on an intkey table, then the integer key
60293 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
60294 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
60295 ** set to point to a malloced buffer pCur->nKey bytes in size containing
60296 ** the key.
60298 static int saveCursorKey(BtCursor *pCur){
60299 int rc = SQLITE_OK;
60300 assert( CURSOR_VALID==pCur->eState );
60301 assert( 0==pCur->pKey );
60302 assert( cursorHoldsMutex(pCur) );
60304 if( pCur->curIntKey ){
60305 /* Only the rowid is required for a table btree */
60306 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
60307 }else{
60308 /* For an index btree, save the complete key content */
60309 void *pKey;
60310 pCur->nKey = sqlite3BtreePayloadSize(pCur);
60311 pKey = sqlite3Malloc( pCur->nKey );
60312 if( pKey ){
60313 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
60314 if( rc==SQLITE_OK ){
60315 pCur->pKey = pKey;
60316 }else{
60317 sqlite3_free(pKey);
60319 }else{
60320 rc = SQLITE_NOMEM_BKPT;
60323 assert( !pCur->curIntKey || !pCur->pKey );
60324 return rc;
60328 ** Save the current cursor position in the variables BtCursor.nKey
60329 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
60331 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
60332 ** prior to calling this routine.
60334 static int saveCursorPosition(BtCursor *pCur){
60335 int rc;
60337 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
60338 assert( 0==pCur->pKey );
60339 assert( cursorHoldsMutex(pCur) );
60341 if( pCur->eState==CURSOR_SKIPNEXT ){
60342 pCur->eState = CURSOR_VALID;
60343 }else{
60344 pCur->skipNext = 0;
60347 rc = saveCursorKey(pCur);
60348 if( rc==SQLITE_OK ){
60349 btreeReleaseAllCursorPages(pCur);
60350 pCur->eState = CURSOR_REQUIRESEEK;
60353 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
60354 return rc;
60357 /* Forward reference */
60358 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
60361 ** Save the positions of all cursors (except pExcept) that are open on
60362 ** the table with root-page iRoot. "Saving the cursor position" means that
60363 ** the location in the btree is remembered in such a way that it can be
60364 ** moved back to the same spot after the btree has been modified. This
60365 ** routine is called just before cursor pExcept is used to modify the
60366 ** table, for example in BtreeDelete() or BtreeInsert().
60368 ** If there are two or more cursors on the same btree, then all such
60369 ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
60370 ** routine enforces that rule. This routine only needs to be called in
60371 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
60373 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
60374 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
60375 ** pointless call to this routine.
60377 ** Implementation note: This routine merely checks to see if any cursors
60378 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
60379 ** event that cursors are in need to being saved.
60381 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
60382 BtCursor *p;
60383 assert( sqlite3_mutex_held(pBt->mutex) );
60384 assert( pExcept==0 || pExcept->pBt==pBt );
60385 for(p=pBt->pCursor; p; p=p->pNext){
60386 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
60388 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
60389 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
60390 return SQLITE_OK;
60393 /* This helper routine to saveAllCursors does the actual work of saving
60394 ** the cursors if and when a cursor is found that actually requires saving.
60395 ** The common case is that no cursors need to be saved, so this routine is
60396 ** broken out from its caller to avoid unnecessary stack pointer movement.
60398 static int SQLITE_NOINLINE saveCursorsOnList(
60399 BtCursor *p, /* The first cursor that needs saving */
60400 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
60401 BtCursor *pExcept /* Do not save this cursor */
60404 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
60405 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
60406 int rc = saveCursorPosition(p);
60407 if( SQLITE_OK!=rc ){
60408 return rc;
60410 }else{
60411 testcase( p->iPage>=0 );
60412 btreeReleaseAllCursorPages(p);
60415 p = p->pNext;
60416 }while( p );
60417 return SQLITE_OK;
60421 ** Clear the current cursor position.
60423 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
60424 assert( cursorHoldsMutex(pCur) );
60425 sqlite3_free(pCur->pKey);
60426 pCur->pKey = 0;
60427 pCur->eState = CURSOR_INVALID;
60431 ** In this version of BtreeMoveto, pKey is a packed index record
60432 ** such as is generated by the OP_MakeRecord opcode. Unpack the
60433 ** record and then call BtreeMovetoUnpacked() to do the work.
60435 static int btreeMoveto(
60436 BtCursor *pCur, /* Cursor open on the btree to be searched */
60437 const void *pKey, /* Packed key if the btree is an index */
60438 i64 nKey, /* Integer key for tables. Size of pKey for indices */
60439 int bias, /* Bias search to the high end */
60440 int *pRes /* Write search results here */
60442 int rc; /* Status code */
60443 UnpackedRecord *pIdxKey; /* Unpacked index key */
60445 if( pKey ){
60446 assert( nKey==(i64)(int)nKey );
60447 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
60448 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
60449 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
60450 if( pIdxKey->nField==0 ){
60451 rc = SQLITE_CORRUPT_BKPT;
60452 goto moveto_done;
60454 }else{
60455 pIdxKey = 0;
60457 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
60458 moveto_done:
60459 if( pIdxKey ){
60460 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
60462 return rc;
60466 ** Restore the cursor to the position it was in (or as close to as possible)
60467 ** when saveCursorPosition() was called. Note that this call deletes the
60468 ** saved position info stored by saveCursorPosition(), so there can be
60469 ** at most one effective restoreCursorPosition() call after each
60470 ** saveCursorPosition().
60472 static int btreeRestoreCursorPosition(BtCursor *pCur){
60473 int rc;
60474 int skipNext;
60475 assert( cursorOwnsBtShared(pCur) );
60476 assert( pCur->eState>=CURSOR_REQUIRESEEK );
60477 if( pCur->eState==CURSOR_FAULT ){
60478 return pCur->skipNext;
60480 pCur->eState = CURSOR_INVALID;
60481 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
60482 if( rc==SQLITE_OK ){
60483 sqlite3_free(pCur->pKey);
60484 pCur->pKey = 0;
60485 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
60486 pCur->skipNext |= skipNext;
60487 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
60488 pCur->eState = CURSOR_SKIPNEXT;
60491 return rc;
60494 #define restoreCursorPosition(p) \
60495 (p->eState>=CURSOR_REQUIRESEEK ? \
60496 btreeRestoreCursorPosition(p) : \
60497 SQLITE_OK)
60500 ** Determine whether or not a cursor has moved from the position where
60501 ** it was last placed, or has been invalidated for any other reason.
60502 ** Cursors can move when the row they are pointing at is deleted out
60503 ** from under them, for example. Cursor might also move if a btree
60504 ** is rebalanced.
60506 ** Calling this routine with a NULL cursor pointer returns false.
60508 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
60509 ** back to where it ought to be if this routine returns true.
60511 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
60512 return pCur->eState!=CURSOR_VALID;
60516 ** Return a pointer to a fake BtCursor object that will always answer
60517 ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
60518 ** cursor returned must not be used with any other Btree interface.
60520 SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
60521 static u8 fakeCursor = CURSOR_VALID;
60522 assert( offsetof(BtCursor, eState)==0 );
60523 return (BtCursor*)&fakeCursor;
60527 ** This routine restores a cursor back to its original position after it
60528 ** has been moved by some outside activity (such as a btree rebalance or
60529 ** a row having been deleted out from under the cursor).
60531 ** On success, the *pDifferentRow parameter is false if the cursor is left
60532 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
60533 ** was pointing to has been deleted, forcing the cursor to point to some
60534 ** nearby row.
60536 ** This routine should only be called for a cursor that just returned
60537 ** TRUE from sqlite3BtreeCursorHasMoved().
60539 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
60540 int rc;
60542 assert( pCur!=0 );
60543 assert( pCur->eState!=CURSOR_VALID );
60544 rc = restoreCursorPosition(pCur);
60545 if( rc ){
60546 *pDifferentRow = 1;
60547 return rc;
60549 if( pCur->eState!=CURSOR_VALID ){
60550 *pDifferentRow = 1;
60551 }else{
60552 assert( pCur->skipNext==0 );
60553 *pDifferentRow = 0;
60555 return SQLITE_OK;
60558 #ifdef SQLITE_ENABLE_CURSOR_HINTS
60560 ** Provide hints to the cursor. The particular hint given (and the type
60561 ** and number of the varargs parameters) is determined by the eHintType
60562 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
60564 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
60565 /* Used only by system that substitute their own storage engine */
60567 #endif
60570 ** Provide flag hints to the cursor.
60572 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
60573 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
60574 pCur->hints = x;
60578 #ifndef SQLITE_OMIT_AUTOVACUUM
60580 ** Given a page number of a regular database page, return the page
60581 ** number for the pointer-map page that contains the entry for the
60582 ** input page number.
60584 ** Return 0 (not a valid page) for pgno==1 since there is
60585 ** no pointer map associated with page 1. The integrity_check logic
60586 ** requires that ptrmapPageno(*,1)!=1.
60588 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
60589 int nPagesPerMapPage;
60590 Pgno iPtrMap, ret;
60591 assert( sqlite3_mutex_held(pBt->mutex) );
60592 if( pgno<2 ) return 0;
60593 nPagesPerMapPage = (pBt->usableSize/5)+1;
60594 iPtrMap = (pgno-2)/nPagesPerMapPage;
60595 ret = (iPtrMap*nPagesPerMapPage) + 2;
60596 if( ret==PENDING_BYTE_PAGE(pBt) ){
60597 ret++;
60599 return ret;
60603 ** Write an entry into the pointer map.
60605 ** This routine updates the pointer map entry for page number 'key'
60606 ** so that it maps to type 'eType' and parent page number 'pgno'.
60608 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
60609 ** a no-op. If an error occurs, the appropriate error code is written
60610 ** into *pRC.
60612 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
60613 DbPage *pDbPage; /* The pointer map page */
60614 u8 *pPtrmap; /* The pointer map data */
60615 Pgno iPtrmap; /* The pointer map page number */
60616 int offset; /* Offset in pointer map page */
60617 int rc; /* Return code from subfunctions */
60619 if( *pRC ) return;
60621 assert( sqlite3_mutex_held(pBt->mutex) );
60622 /* The master-journal page number must never be used as a pointer map page */
60623 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
60625 assert( pBt->autoVacuum );
60626 if( key==0 ){
60627 *pRC = SQLITE_CORRUPT_BKPT;
60628 return;
60630 iPtrmap = PTRMAP_PAGENO(pBt, key);
60631 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
60632 if( rc!=SQLITE_OK ){
60633 *pRC = rc;
60634 return;
60636 offset = PTRMAP_PTROFFSET(iPtrmap, key);
60637 if( offset<0 ){
60638 *pRC = SQLITE_CORRUPT_BKPT;
60639 goto ptrmap_exit;
60641 assert( offset <= (int)pBt->usableSize-5 );
60642 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
60644 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
60645 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
60646 *pRC= rc = sqlite3PagerWrite(pDbPage);
60647 if( rc==SQLITE_OK ){
60648 pPtrmap[offset] = eType;
60649 put4byte(&pPtrmap[offset+1], parent);
60653 ptrmap_exit:
60654 sqlite3PagerUnref(pDbPage);
60658 ** Read an entry from the pointer map.
60660 ** This routine retrieves the pointer map entry for page 'key', writing
60661 ** the type and parent page number to *pEType and *pPgno respectively.
60662 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
60664 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
60665 DbPage *pDbPage; /* The pointer map page */
60666 int iPtrmap; /* Pointer map page index */
60667 u8 *pPtrmap; /* Pointer map page data */
60668 int offset; /* Offset of entry in pointer map */
60669 int rc;
60671 assert( sqlite3_mutex_held(pBt->mutex) );
60673 iPtrmap = PTRMAP_PAGENO(pBt, key);
60674 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
60675 if( rc!=0 ){
60676 return rc;
60678 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
60680 offset = PTRMAP_PTROFFSET(iPtrmap, key);
60681 if( offset<0 ){
60682 sqlite3PagerUnref(pDbPage);
60683 return SQLITE_CORRUPT_BKPT;
60685 assert( offset <= (int)pBt->usableSize-5 );
60686 assert( pEType!=0 );
60687 *pEType = pPtrmap[offset];
60688 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
60690 sqlite3PagerUnref(pDbPage);
60691 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
60692 return SQLITE_OK;
60695 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
60696 #define ptrmapPut(w,x,y,z,rc)
60697 #define ptrmapGet(w,x,y,z) SQLITE_OK
60698 #define ptrmapPutOvflPtr(x, y, rc)
60699 #endif
60702 ** Given a btree page and a cell index (0 means the first cell on
60703 ** the page, 1 means the second cell, and so forth) return a pointer
60704 ** to the cell content.
60706 ** findCellPastPtr() does the same except it skips past the initial
60707 ** 4-byte child pointer found on interior pages, if there is one.
60709 ** This routine works only for pages that do not contain overflow cells.
60711 #define findCell(P,I) \
60712 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
60713 #define findCellPastPtr(P,I) \
60714 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
60718 ** This is common tail processing for btreeParseCellPtr() and
60719 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
60720 ** on a single B-tree page. Make necessary adjustments to the CellInfo
60721 ** structure.
60723 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
60724 MemPage *pPage, /* Page containing the cell */
60725 u8 *pCell, /* Pointer to the cell text. */
60726 CellInfo *pInfo /* Fill in this structure */
60728 /* If the payload will not fit completely on the local page, we have
60729 ** to decide how much to store locally and how much to spill onto
60730 ** overflow pages. The strategy is to minimize the amount of unused
60731 ** space on overflow pages while keeping the amount of local storage
60732 ** in between minLocal and maxLocal.
60734 ** Warning: changing the way overflow payload is distributed in any
60735 ** way will result in an incompatible file format.
60737 int minLocal; /* Minimum amount of payload held locally */
60738 int maxLocal; /* Maximum amount of payload held locally */
60739 int surplus; /* Overflow payload available for local storage */
60741 minLocal = pPage->minLocal;
60742 maxLocal = pPage->maxLocal;
60743 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
60744 testcase( surplus==maxLocal );
60745 testcase( surplus==maxLocal+1 );
60746 if( surplus <= maxLocal ){
60747 pInfo->nLocal = (u16)surplus;
60748 }else{
60749 pInfo->nLocal = (u16)minLocal;
60751 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
60755 ** The following routines are implementations of the MemPage.xParseCell()
60756 ** method.
60758 ** Parse a cell content block and fill in the CellInfo structure.
60760 ** btreeParseCellPtr() => table btree leaf nodes
60761 ** btreeParseCellNoPayload() => table btree internal nodes
60762 ** btreeParseCellPtrIndex() => index btree nodes
60764 ** There is also a wrapper function btreeParseCell() that works for
60765 ** all MemPage types and that references the cell by index rather than
60766 ** by pointer.
60768 static void btreeParseCellPtrNoPayload(
60769 MemPage *pPage, /* Page containing the cell */
60770 u8 *pCell, /* Pointer to the cell text. */
60771 CellInfo *pInfo /* Fill in this structure */
60773 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60774 assert( pPage->leaf==0 );
60775 assert( pPage->childPtrSize==4 );
60776 #ifndef SQLITE_DEBUG
60777 UNUSED_PARAMETER(pPage);
60778 #endif
60779 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
60780 pInfo->nPayload = 0;
60781 pInfo->nLocal = 0;
60782 pInfo->pPayload = 0;
60783 return;
60785 static void btreeParseCellPtr(
60786 MemPage *pPage, /* Page containing the cell */
60787 u8 *pCell, /* Pointer to the cell text. */
60788 CellInfo *pInfo /* Fill in this structure */
60790 u8 *pIter; /* For scanning through pCell */
60791 u32 nPayload; /* Number of bytes of cell payload */
60792 u64 iKey; /* Extracted Key value */
60794 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60795 assert( pPage->leaf==0 || pPage->leaf==1 );
60796 assert( pPage->intKeyLeaf );
60797 assert( pPage->childPtrSize==0 );
60798 pIter = pCell;
60800 /* The next block of code is equivalent to:
60802 ** pIter += getVarint32(pIter, nPayload);
60804 ** The code is inlined to avoid a function call.
60806 nPayload = *pIter;
60807 if( nPayload>=0x80 ){
60808 u8 *pEnd = &pIter[8];
60809 nPayload &= 0x7f;
60811 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
60812 }while( (*pIter)>=0x80 && pIter<pEnd );
60814 pIter++;
60816 /* The next block of code is equivalent to:
60818 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
60820 ** The code is inlined to avoid a function call.
60822 iKey = *pIter;
60823 if( iKey>=0x80 ){
60824 u8 *pEnd = &pIter[7];
60825 iKey &= 0x7f;
60826 while(1){
60827 iKey = (iKey<<7) | (*++pIter & 0x7f);
60828 if( (*pIter)<0x80 ) break;
60829 if( pIter>=pEnd ){
60830 iKey = (iKey<<8) | *++pIter;
60831 break;
60835 pIter++;
60837 pInfo->nKey = *(i64*)&iKey;
60838 pInfo->nPayload = nPayload;
60839 pInfo->pPayload = pIter;
60840 testcase( nPayload==pPage->maxLocal );
60841 testcase( nPayload==pPage->maxLocal+1 );
60842 if( nPayload<=pPage->maxLocal ){
60843 /* This is the (easy) common case where the entire payload fits
60844 ** on the local page. No overflow is required.
60846 pInfo->nSize = nPayload + (u16)(pIter - pCell);
60847 if( pInfo->nSize<4 ) pInfo->nSize = 4;
60848 pInfo->nLocal = (u16)nPayload;
60849 }else{
60850 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
60853 static void btreeParseCellPtrIndex(
60854 MemPage *pPage, /* Page containing the cell */
60855 u8 *pCell, /* Pointer to the cell text. */
60856 CellInfo *pInfo /* Fill in this structure */
60858 u8 *pIter; /* For scanning through pCell */
60859 u32 nPayload; /* Number of bytes of cell payload */
60861 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60862 assert( pPage->leaf==0 || pPage->leaf==1 );
60863 assert( pPage->intKeyLeaf==0 );
60864 pIter = pCell + pPage->childPtrSize;
60865 nPayload = *pIter;
60866 if( nPayload>=0x80 ){
60867 u8 *pEnd = &pIter[8];
60868 nPayload &= 0x7f;
60870 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
60871 }while( *(pIter)>=0x80 && pIter<pEnd );
60873 pIter++;
60874 pInfo->nKey = nPayload;
60875 pInfo->nPayload = nPayload;
60876 pInfo->pPayload = pIter;
60877 testcase( nPayload==pPage->maxLocal );
60878 testcase( nPayload==pPage->maxLocal+1 );
60879 if( nPayload<=pPage->maxLocal ){
60880 /* This is the (easy) common case where the entire payload fits
60881 ** on the local page. No overflow is required.
60883 pInfo->nSize = nPayload + (u16)(pIter - pCell);
60884 if( pInfo->nSize<4 ) pInfo->nSize = 4;
60885 pInfo->nLocal = (u16)nPayload;
60886 }else{
60887 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
60890 static void btreeParseCell(
60891 MemPage *pPage, /* Page containing the cell */
60892 int iCell, /* The cell index. First cell is 0 */
60893 CellInfo *pInfo /* Fill in this structure */
60895 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
60899 ** The following routines are implementations of the MemPage.xCellSize
60900 ** method.
60902 ** Compute the total number of bytes that a Cell needs in the cell
60903 ** data area of the btree-page. The return number includes the cell
60904 ** data header and the local payload, but not any overflow page or
60905 ** the space used by the cell pointer.
60907 ** cellSizePtrNoPayload() => table internal nodes
60908 ** cellSizePtr() => all index nodes & table leaf nodes
60910 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
60911 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
60912 u8 *pEnd; /* End mark for a varint */
60913 u32 nSize; /* Size value to return */
60915 #ifdef SQLITE_DEBUG
60916 /* The value returned by this function should always be the same as
60917 ** the (CellInfo.nSize) value found by doing a full parse of the
60918 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
60919 ** this function verifies that this invariant is not violated. */
60920 CellInfo debuginfo;
60921 pPage->xParseCell(pPage, pCell, &debuginfo);
60922 #endif
60924 nSize = *pIter;
60925 if( nSize>=0x80 ){
60926 pEnd = &pIter[8];
60927 nSize &= 0x7f;
60929 nSize = (nSize<<7) | (*++pIter & 0x7f);
60930 }while( *(pIter)>=0x80 && pIter<pEnd );
60932 pIter++;
60933 if( pPage->intKey ){
60934 /* pIter now points at the 64-bit integer key value, a variable length
60935 ** integer. The following block moves pIter to point at the first byte
60936 ** past the end of the key value. */
60937 pEnd = &pIter[9];
60938 while( (*pIter++)&0x80 && pIter<pEnd );
60940 testcase( nSize==pPage->maxLocal );
60941 testcase( nSize==pPage->maxLocal+1 );
60942 if( nSize<=pPage->maxLocal ){
60943 nSize += (u32)(pIter - pCell);
60944 if( nSize<4 ) nSize = 4;
60945 }else{
60946 int minLocal = pPage->minLocal;
60947 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
60948 testcase( nSize==pPage->maxLocal );
60949 testcase( nSize==pPage->maxLocal+1 );
60950 if( nSize>pPage->maxLocal ){
60951 nSize = minLocal;
60953 nSize += 4 + (u16)(pIter - pCell);
60955 assert( nSize==debuginfo.nSize || CORRUPT_DB );
60956 return (u16)nSize;
60958 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
60959 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
60960 u8 *pEnd; /* End mark for a varint */
60962 #ifdef SQLITE_DEBUG
60963 /* The value returned by this function should always be the same as
60964 ** the (CellInfo.nSize) value found by doing a full parse of the
60965 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
60966 ** this function verifies that this invariant is not violated. */
60967 CellInfo debuginfo;
60968 pPage->xParseCell(pPage, pCell, &debuginfo);
60969 #else
60970 UNUSED_PARAMETER(pPage);
60971 #endif
60973 assert( pPage->childPtrSize==4 );
60974 pEnd = pIter + 9;
60975 while( (*pIter++)&0x80 && pIter<pEnd );
60976 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
60977 return (u16)(pIter - pCell);
60981 #ifdef SQLITE_DEBUG
60982 /* This variation on cellSizePtr() is used inside of assert() statements
60983 ** only. */
60984 static u16 cellSize(MemPage *pPage, int iCell){
60985 return pPage->xCellSize(pPage, findCell(pPage, iCell));
60987 #endif
60989 #ifndef SQLITE_OMIT_AUTOVACUUM
60991 ** If the cell pCell, part of page pPage contains a pointer
60992 ** to an overflow page, insert an entry into the pointer-map
60993 ** for the overflow page.
60995 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
60996 CellInfo info;
60997 if( *pRC ) return;
60998 assert( pCell!=0 );
60999 pPage->xParseCell(pPage, pCell, &info);
61000 if( info.nLocal<info.nPayload ){
61001 Pgno ovfl = get4byte(&pCell[info.nSize-4]);
61002 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
61005 #endif
61009 ** Defragment the page given. This routine reorganizes cells within the
61010 ** page so that there are no free-blocks on the free-block list.
61012 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
61013 ** present in the page after this routine returns.
61015 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
61016 ** b-tree page so that there are no freeblocks or fragment bytes, all
61017 ** unused bytes are contained in the unallocated space region, and all
61018 ** cells are packed tightly at the end of the page.
61020 static int defragmentPage(MemPage *pPage, int nMaxFrag){
61021 int i; /* Loop counter */
61022 int pc; /* Address of the i-th cell */
61023 int hdr; /* Offset to the page header */
61024 int size; /* Size of a cell */
61025 int usableSize; /* Number of usable bytes on a page */
61026 int cellOffset; /* Offset to the cell pointer array */
61027 int cbrk; /* Offset to the cell content area */
61028 int nCell; /* Number of cells on the page */
61029 unsigned char *data; /* The page data */
61030 unsigned char *temp; /* Temp area for cell content */
61031 unsigned char *src; /* Source of content */
61032 int iCellFirst; /* First allowable cell index */
61033 int iCellLast; /* Last possible cell index */
61035 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61036 assert( pPage->pBt!=0 );
61037 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
61038 assert( pPage->nOverflow==0 );
61039 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61040 temp = 0;
61041 src = data = pPage->aData;
61042 hdr = pPage->hdrOffset;
61043 cellOffset = pPage->cellOffset;
61044 nCell = pPage->nCell;
61045 assert( nCell==get2byte(&data[hdr+3]) );
61046 iCellFirst = cellOffset + 2*nCell;
61047 usableSize = pPage->pBt->usableSize;
61049 /* This block handles pages with two or fewer free blocks and nMaxFrag
61050 ** or fewer fragmented bytes. In this case it is faster to move the
61051 ** two (or one) blocks of cells using memmove() and add the required
61052 ** offsets to each pointer in the cell-pointer array than it is to
61053 ** reconstruct the entire page. */
61054 if( (int)data[hdr+7]<=nMaxFrag ){
61055 int iFree = get2byte(&data[hdr+1]);
61056 if( iFree ){
61057 int iFree2 = get2byte(&data[iFree]);
61059 /* pageFindSlot() has already verified that free blocks are sorted
61060 ** in order of offset within the page, and that no block extends
61061 ** past the end of the page. Provided the two free slots do not
61062 ** overlap, this guarantees that the memmove() calls below will not
61063 ** overwrite the usableSize byte buffer, even if the database page
61064 ** is corrupt. */
61065 assert( iFree2==0 || iFree2>iFree );
61066 assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
61067 assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
61069 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
61070 u8 *pEnd = &data[cellOffset + nCell*2];
61071 u8 *pAddr;
61072 int sz2 = 0;
61073 int sz = get2byte(&data[iFree+2]);
61074 int top = get2byte(&data[hdr+5]);
61075 if( top>=iFree ){
61076 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61078 if( iFree2 ){
61079 assert( iFree+sz<=iFree2 ); /* Verified by pageFindSlot() */
61080 sz2 = get2byte(&data[iFree2+2]);
61081 assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
61082 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
61083 sz += sz2;
61085 cbrk = top+sz;
61086 assert( cbrk+(iFree-top) <= usableSize );
61087 memmove(&data[cbrk], &data[top], iFree-top);
61088 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
61089 pc = get2byte(pAddr);
61090 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
61091 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
61093 goto defragment_out;
61098 cbrk = usableSize;
61099 iCellLast = usableSize - 4;
61100 for(i=0; i<nCell; i++){
61101 u8 *pAddr; /* The i-th cell pointer */
61102 pAddr = &data[cellOffset + i*2];
61103 pc = get2byte(pAddr);
61104 testcase( pc==iCellFirst );
61105 testcase( pc==iCellLast );
61106 /* These conditions have already been verified in btreeInitPage()
61107 ** if PRAGMA cell_size_check=ON.
61109 if( pc<iCellFirst || pc>iCellLast ){
61110 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61112 assert( pc>=iCellFirst && pc<=iCellLast );
61113 size = pPage->xCellSize(pPage, &src[pc]);
61114 cbrk -= size;
61115 if( cbrk<iCellFirst || pc+size>usableSize ){
61116 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61118 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
61119 testcase( cbrk+size==usableSize );
61120 testcase( pc+size==usableSize );
61121 put2byte(pAddr, cbrk);
61122 if( temp==0 ){
61123 int x;
61124 if( cbrk==pc ) continue;
61125 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
61126 x = get2byte(&data[hdr+5]);
61127 memcpy(&temp[x], &data[x], (cbrk+size) - x);
61128 src = temp;
61130 memcpy(&data[cbrk], &src[pc], size);
61132 data[hdr+7] = 0;
61134 defragment_out:
61135 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
61136 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61138 assert( cbrk>=iCellFirst );
61139 put2byte(&data[hdr+5], cbrk);
61140 data[hdr+1] = 0;
61141 data[hdr+2] = 0;
61142 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
61143 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61144 return SQLITE_OK;
61148 ** Search the free-list on page pPg for space to store a cell nByte bytes in
61149 ** size. If one can be found, return a pointer to the space and remove it
61150 ** from the free-list.
61152 ** If no suitable space can be found on the free-list, return NULL.
61154 ** This function may detect corruption within pPg. If corruption is
61155 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
61157 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
61158 ** will be ignored if adding the extra space to the fragmentation count
61159 ** causes the fragmentation count to exceed 60.
61161 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
61162 const int hdr = pPg->hdrOffset;
61163 u8 * const aData = pPg->aData;
61164 int iAddr = hdr + 1;
61165 int pc = get2byte(&aData[iAddr]);
61166 int x;
61167 int usableSize = pPg->pBt->usableSize;
61168 int size; /* Size of the free slot */
61170 assert( pc>0 );
61171 while( pc<=usableSize-4 ){
61172 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
61173 ** freeblock form a big-endian integer which is the size of the freeblock
61174 ** in bytes, including the 4-byte header. */
61175 size = get2byte(&aData[pc+2]);
61176 if( (x = size - nByte)>=0 ){
61177 testcase( x==4 );
61178 testcase( x==3 );
61179 if( size+pc > usableSize ){
61180 *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
61181 return 0;
61182 }else if( x<4 ){
61183 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
61184 ** number of bytes in fragments may not exceed 60. */
61185 if( aData[hdr+7]>57 ) return 0;
61187 /* Remove the slot from the free-list. Update the number of
61188 ** fragmented bytes within the page. */
61189 memcpy(&aData[iAddr], &aData[pc], 2);
61190 aData[hdr+7] += (u8)x;
61191 }else{
61192 /* The slot remains on the free-list. Reduce its size to account
61193 ** for the portion used by the new allocation. */
61194 put2byte(&aData[pc+2], x);
61196 return &aData[pc + x];
61198 iAddr = pc;
61199 pc = get2byte(&aData[pc]);
61200 if( pc<iAddr+size ) break;
61202 if( pc ){
61203 *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
61206 return 0;
61210 ** Allocate nByte bytes of space from within the B-Tree page passed
61211 ** as the first argument. Write into *pIdx the index into pPage->aData[]
61212 ** of the first byte of allocated space. Return either SQLITE_OK or
61213 ** an error code (usually SQLITE_CORRUPT).
61215 ** The caller guarantees that there is sufficient space to make the
61216 ** allocation. This routine might need to defragment in order to bring
61217 ** all the space together, however. This routine will avoid using
61218 ** the first two bytes past the cell pointer area since presumably this
61219 ** allocation is being made in order to insert a new cell, so we will
61220 ** also end up needing a new cell pointer.
61222 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
61223 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
61224 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
61225 int top; /* First byte of cell content area */
61226 int rc = SQLITE_OK; /* Integer return code */
61227 int gap; /* First byte of gap between cell pointers and cell content */
61229 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61230 assert( pPage->pBt );
61231 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61232 assert( nByte>=0 ); /* Minimum cell size is 4 */
61233 assert( pPage->nFree>=nByte );
61234 assert( pPage->nOverflow==0 );
61235 assert( nByte < (int)(pPage->pBt->usableSize-8) );
61237 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
61238 gap = pPage->cellOffset + 2*pPage->nCell;
61239 assert( gap<=65536 );
61240 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
61241 ** and the reserved space is zero (the usual value for reserved space)
61242 ** then the cell content offset of an empty page wants to be 65536.
61243 ** However, that integer is too large to be stored in a 2-byte unsigned
61244 ** integer, so a value of 0 is used in its place. */
61245 top = get2byte(&data[hdr+5]);
61246 assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
61247 if( gap>top ){
61248 if( top==0 && pPage->pBt->usableSize==65536 ){
61249 top = 65536;
61250 }else{
61251 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61255 /* If there is enough space between gap and top for one more cell pointer
61256 ** array entry offset, and if the freelist is not empty, then search the
61257 ** freelist looking for a free slot big enough to satisfy the request.
61259 testcase( gap+2==top );
61260 testcase( gap+1==top );
61261 testcase( gap==top );
61262 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
61263 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
61264 if( pSpace ){
61265 assert( pSpace>=data && (pSpace - data)<65536 );
61266 *pIdx = (int)(pSpace - data);
61267 return SQLITE_OK;
61268 }else if( rc ){
61269 return rc;
61273 /* The request could not be fulfilled using a freelist slot. Check
61274 ** to see if defragmentation is necessary.
61276 testcase( gap+2+nByte==top );
61277 if( gap+2+nByte>top ){
61278 assert( pPage->nCell>0 || CORRUPT_DB );
61279 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
61280 if( rc ) return rc;
61281 top = get2byteNotZero(&data[hdr+5]);
61282 assert( gap+2+nByte<=top );
61286 /* Allocate memory from the gap in between the cell pointer array
61287 ** and the cell content area. The btreeInitPage() call has already
61288 ** validated the freelist. Given that the freelist is valid, there
61289 ** is no way that the allocation can extend off the end of the page.
61290 ** The assert() below verifies the previous sentence.
61292 top -= nByte;
61293 put2byte(&data[hdr+5], top);
61294 assert( top+nByte <= (int)pPage->pBt->usableSize );
61295 *pIdx = top;
61296 return SQLITE_OK;
61300 ** Return a section of the pPage->aData to the freelist.
61301 ** The first byte of the new free block is pPage->aData[iStart]
61302 ** and the size of the block is iSize bytes.
61304 ** Adjacent freeblocks are coalesced.
61306 ** Note that even though the freeblock list was checked by btreeInitPage(),
61307 ** that routine will not detect overlap between cells or freeblocks. Nor
61308 ** does it detect cells or freeblocks that encrouch into the reserved bytes
61309 ** at the end of the page. So do additional corruption checks inside this
61310 ** routine and return SQLITE_CORRUPT if any problems are found.
61312 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
61313 u16 iPtr; /* Address of ptr to next freeblock */
61314 u16 iFreeBlk; /* Address of the next freeblock */
61315 u8 hdr; /* Page header size. 0 or 100 */
61316 u8 nFrag = 0; /* Reduction in fragmentation */
61317 u16 iOrigSize = iSize; /* Original value of iSize */
61318 u16 x; /* Offset to cell content area */
61319 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
61320 unsigned char *data = pPage->aData; /* Page content */
61322 assert( pPage->pBt!=0 );
61323 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61324 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
61325 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
61326 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61327 assert( iSize>=4 ); /* Minimum cell size is 4 */
61328 assert( iStart<=pPage->pBt->usableSize-4 );
61330 /* The list of freeblocks must be in ascending order. Find the
61331 ** spot on the list where iStart should be inserted.
61333 hdr = pPage->hdrOffset;
61334 iPtr = hdr + 1;
61335 if( data[iPtr+1]==0 && data[iPtr]==0 ){
61336 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
61337 }else{
61338 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
61339 if( iFreeBlk<iPtr+4 ){
61340 if( iFreeBlk==0 ) break;
61341 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61343 iPtr = iFreeBlk;
61345 if( iFreeBlk>pPage->pBt->usableSize-4 ){
61346 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61348 assert( iFreeBlk>iPtr || iFreeBlk==0 );
61350 /* At this point:
61351 ** iFreeBlk: First freeblock after iStart, or zero if none
61352 ** iPtr: The address of a pointer to iFreeBlk
61354 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
61356 if( iFreeBlk && iEnd+3>=iFreeBlk ){
61357 nFrag = iFreeBlk - iEnd;
61358 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
61359 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
61360 if( iEnd > pPage->pBt->usableSize ){
61361 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61363 iSize = iEnd - iStart;
61364 iFreeBlk = get2byte(&data[iFreeBlk]);
61367 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
61368 ** pointer in the page header) then check to see if iStart should be
61369 ** coalesced onto the end of iPtr.
61371 if( iPtr>hdr+1 ){
61372 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
61373 if( iPtrEnd+3>=iStart ){
61374 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
61375 nFrag += iStart - iPtrEnd;
61376 iSize = iEnd - iPtr;
61377 iStart = iPtr;
61380 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
61381 data[hdr+7] -= nFrag;
61383 x = get2byte(&data[hdr+5]);
61384 if( iStart<=x ){
61385 /* The new freeblock is at the beginning of the cell content area,
61386 ** so just extend the cell content area rather than create another
61387 ** freelist entry */
61388 if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
61389 put2byte(&data[hdr+1], iFreeBlk);
61390 put2byte(&data[hdr+5], iEnd);
61391 }else{
61392 /* Insert the new freeblock into the freelist */
61393 put2byte(&data[iPtr], iStart);
61395 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
61396 /* Overwrite deleted information with zeros when the secure_delete
61397 ** option is enabled */
61398 memset(&data[iStart], 0, iSize);
61400 put2byte(&data[iStart], iFreeBlk);
61401 put2byte(&data[iStart+2], iSize);
61402 pPage->nFree += iOrigSize;
61403 return SQLITE_OK;
61407 ** Decode the flags byte (the first byte of the header) for a page
61408 ** and initialize fields of the MemPage structure accordingly.
61410 ** Only the following combinations are supported. Anything different
61411 ** indicates a corrupt database files:
61413 ** PTF_ZERODATA
61414 ** PTF_ZERODATA | PTF_LEAF
61415 ** PTF_LEAFDATA | PTF_INTKEY
61416 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
61418 static int decodeFlags(MemPage *pPage, int flagByte){
61419 BtShared *pBt; /* A copy of pPage->pBt */
61421 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
61422 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61423 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
61424 flagByte &= ~PTF_LEAF;
61425 pPage->childPtrSize = 4-4*pPage->leaf;
61426 pPage->xCellSize = cellSizePtr;
61427 pBt = pPage->pBt;
61428 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
61429 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
61430 ** interior table b-tree page. */
61431 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
61432 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
61433 ** leaf table b-tree page. */
61434 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
61435 pPage->intKey = 1;
61436 if( pPage->leaf ){
61437 pPage->intKeyLeaf = 1;
61438 pPage->xParseCell = btreeParseCellPtr;
61439 }else{
61440 pPage->intKeyLeaf = 0;
61441 pPage->xCellSize = cellSizePtrNoPayload;
61442 pPage->xParseCell = btreeParseCellPtrNoPayload;
61444 pPage->maxLocal = pBt->maxLeaf;
61445 pPage->minLocal = pBt->minLeaf;
61446 }else if( flagByte==PTF_ZERODATA ){
61447 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
61448 ** interior index b-tree page. */
61449 assert( (PTF_ZERODATA)==2 );
61450 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
61451 ** leaf index b-tree page. */
61452 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
61453 pPage->intKey = 0;
61454 pPage->intKeyLeaf = 0;
61455 pPage->xParseCell = btreeParseCellPtrIndex;
61456 pPage->maxLocal = pBt->maxLocal;
61457 pPage->minLocal = pBt->minLocal;
61458 }else{
61459 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
61460 ** an error. */
61461 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61463 pPage->max1bytePayload = pBt->max1bytePayload;
61464 return SQLITE_OK;
61468 ** Initialize the auxiliary information for a disk block.
61470 ** Return SQLITE_OK on success. If we see that the page does
61471 ** not contain a well-formed database page, then return
61472 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
61473 ** guarantee that the page is well-formed. It only shows that
61474 ** we failed to detect any corruption.
61476 static int btreeInitPage(MemPage *pPage){
61477 int pc; /* Address of a freeblock within pPage->aData[] */
61478 u8 hdr; /* Offset to beginning of page header */
61479 u8 *data; /* Equal to pPage->aData */
61480 BtShared *pBt; /* The main btree structure */
61481 int usableSize; /* Amount of usable space on each page */
61482 u16 cellOffset; /* Offset from start of page to first cell pointer */
61483 int nFree; /* Number of unused bytes on the page */
61484 int top; /* First byte of the cell content area */
61485 int iCellFirst; /* First allowable cell or freeblock offset */
61486 int iCellLast; /* Last possible cell or freeblock offset */
61488 assert( pPage->pBt!=0 );
61489 assert( pPage->pBt->db!=0 );
61490 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61491 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
61492 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
61493 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
61494 assert( pPage->isInit==0 );
61496 pBt = pPage->pBt;
61497 hdr = pPage->hdrOffset;
61498 data = pPage->aData;
61499 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
61500 ** the b-tree page type. */
61501 if( decodeFlags(pPage, data[hdr]) ){
61502 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61504 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
61505 pPage->maskPage = (u16)(pBt->pageSize - 1);
61506 pPage->nOverflow = 0;
61507 usableSize = pBt->usableSize;
61508 pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
61509 pPage->aDataEnd = &data[usableSize];
61510 pPage->aCellIdx = &data[cellOffset];
61511 pPage->aDataOfst = &data[pPage->childPtrSize];
61512 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
61513 ** the start of the cell content area. A zero value for this integer is
61514 ** interpreted as 65536. */
61515 top = get2byteNotZero(&data[hdr+5]);
61516 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
61517 ** number of cells on the page. */
61518 pPage->nCell = get2byte(&data[hdr+3]);
61519 if( pPage->nCell>MX_CELL(pBt) ){
61520 /* To many cells for a single page. The page must be corrupt */
61521 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61523 testcase( pPage->nCell==MX_CELL(pBt) );
61524 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
61525 ** possible for a root page of a table that contains no rows) then the
61526 ** offset to the cell content area will equal the page size minus the
61527 ** bytes of reserved space. */
61528 assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
61530 /* A malformed database page might cause us to read past the end
61531 ** of page when parsing a cell.
61533 ** The following block of code checks early to see if a cell extends
61534 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
61535 ** returned if it does.
61537 iCellFirst = cellOffset + 2*pPage->nCell;
61538 iCellLast = usableSize - 4;
61539 if( pBt->db->flags & SQLITE_CellSizeCk ){
61540 int i; /* Index into the cell pointer array */
61541 int sz; /* Size of a cell */
61543 if( !pPage->leaf ) iCellLast--;
61544 for(i=0; i<pPage->nCell; i++){
61545 pc = get2byteAligned(&data[cellOffset+i*2]);
61546 testcase( pc==iCellFirst );
61547 testcase( pc==iCellLast );
61548 if( pc<iCellFirst || pc>iCellLast ){
61549 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61551 sz = pPage->xCellSize(pPage, &data[pc]);
61552 testcase( pc+sz==usableSize );
61553 if( pc+sz>usableSize ){
61554 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61557 if( !pPage->leaf ) iCellLast++;
61560 /* Compute the total free space on the page
61561 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
61562 ** start of the first freeblock on the page, or is zero if there are no
61563 ** freeblocks. */
61564 pc = get2byte(&data[hdr+1]);
61565 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
61566 if( pc>0 ){
61567 u32 next, size;
61568 if( pc<iCellFirst ){
61569 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
61570 ** always be at least one cell before the first freeblock.
61572 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61574 while( 1 ){
61575 if( pc>iCellLast ){
61576 /* Freeblock off the end of the page */
61577 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61579 next = get2byte(&data[pc]);
61580 size = get2byte(&data[pc+2]);
61581 nFree = nFree + size;
61582 if( next<=pc+size+3 ) break;
61583 pc = next;
61585 if( next>0 ){
61586 /* Freeblock not in ascending order */
61587 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61589 if( pc+size>(unsigned int)usableSize ){
61590 /* Last freeblock extends past page end */
61591 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61595 /* At this point, nFree contains the sum of the offset to the start
61596 ** of the cell-content area plus the number of free bytes within
61597 ** the cell-content area. If this is greater than the usable-size
61598 ** of the page, then the page must be corrupted. This check also
61599 ** serves to verify that the offset to the start of the cell-content
61600 ** area, according to the page header, lies within the page.
61602 if( nFree>usableSize ){
61603 return SQLITE_CORRUPT_PGNO(pPage->pgno);
61605 pPage->nFree = (u16)(nFree - iCellFirst);
61606 pPage->isInit = 1;
61607 return SQLITE_OK;
61611 ** Set up a raw page so that it looks like a database page holding
61612 ** no entries.
61614 static void zeroPage(MemPage *pPage, int flags){
61615 unsigned char *data = pPage->aData;
61616 BtShared *pBt = pPage->pBt;
61617 u8 hdr = pPage->hdrOffset;
61618 u16 first;
61620 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
61621 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
61622 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
61623 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61624 assert( sqlite3_mutex_held(pBt->mutex) );
61625 if( pBt->btsFlags & BTS_FAST_SECURE ){
61626 memset(&data[hdr], 0, pBt->usableSize - hdr);
61628 data[hdr] = (char)flags;
61629 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
61630 memset(&data[hdr+1], 0, 4);
61631 data[hdr+7] = 0;
61632 put2byte(&data[hdr+5], pBt->usableSize);
61633 pPage->nFree = (u16)(pBt->usableSize - first);
61634 decodeFlags(pPage, flags);
61635 pPage->cellOffset = first;
61636 pPage->aDataEnd = &data[pBt->usableSize];
61637 pPage->aCellIdx = &data[first];
61638 pPage->aDataOfst = &data[pPage->childPtrSize];
61639 pPage->nOverflow = 0;
61640 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
61641 pPage->maskPage = (u16)(pBt->pageSize - 1);
61642 pPage->nCell = 0;
61643 pPage->isInit = 1;
61648 ** Convert a DbPage obtained from the pager into a MemPage used by
61649 ** the btree layer.
61651 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
61652 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
61653 if( pgno!=pPage->pgno ){
61654 pPage->aData = sqlite3PagerGetData(pDbPage);
61655 pPage->pDbPage = pDbPage;
61656 pPage->pBt = pBt;
61657 pPage->pgno = pgno;
61658 pPage->hdrOffset = pgno==1 ? 100 : 0;
61660 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
61661 return pPage;
61665 ** Get a page from the pager. Initialize the MemPage.pBt and
61666 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
61668 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
61669 ** about the content of the page at this time. So do not go to the disk
61670 ** to fetch the content. Just fill in the content with zeros for now.
61671 ** If in the future we call sqlite3PagerWrite() on this page, that
61672 ** means we have started to be concerned about content and the disk
61673 ** read should occur at that point.
61675 static int btreeGetPage(
61676 BtShared *pBt, /* The btree */
61677 Pgno pgno, /* Number of the page to fetch */
61678 MemPage **ppPage, /* Return the page in this parameter */
61679 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
61681 int rc;
61682 DbPage *pDbPage;
61684 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
61685 assert( sqlite3_mutex_held(pBt->mutex) );
61686 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
61687 if( rc ) return rc;
61688 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
61689 return SQLITE_OK;
61693 ** Retrieve a page from the pager cache. If the requested page is not
61694 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
61695 ** MemPage.aData elements if needed.
61697 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
61698 DbPage *pDbPage;
61699 assert( sqlite3_mutex_held(pBt->mutex) );
61700 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
61701 if( pDbPage ){
61702 return btreePageFromDbPage(pDbPage, pgno, pBt);
61704 return 0;
61708 ** Return the size of the database file in pages. If there is any kind of
61709 ** error, return ((unsigned int)-1).
61711 static Pgno btreePagecount(BtShared *pBt){
61712 return pBt->nPage;
61714 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
61715 assert( sqlite3BtreeHoldsMutex(p) );
61716 assert( ((p->pBt->nPage)&0x80000000)==0 );
61717 return btreePagecount(p->pBt);
61721 ** Get a page from the pager and initialize it.
61723 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
61724 ** call. Do additional sanity checking on the page in this case.
61725 ** And if the fetch fails, this routine must decrement pCur->iPage.
61727 ** The page is fetched as read-write unless pCur is not NULL and is
61728 ** a read-only cursor.
61730 ** If an error occurs, then *ppPage is undefined. It
61731 ** may remain unchanged, or it may be set to an invalid value.
61733 static int getAndInitPage(
61734 BtShared *pBt, /* The database file */
61735 Pgno pgno, /* Number of the page to get */
61736 MemPage **ppPage, /* Write the page pointer here */
61737 BtCursor *pCur, /* Cursor to receive the page, or NULL */
61738 int bReadOnly /* True for a read-only page */
61740 int rc;
61741 DbPage *pDbPage;
61742 assert( sqlite3_mutex_held(pBt->mutex) );
61743 assert( pCur==0 || ppPage==&pCur->pPage );
61744 assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
61745 assert( pCur==0 || pCur->iPage>0 );
61747 if( pgno>btreePagecount(pBt) ){
61748 rc = SQLITE_CORRUPT_BKPT;
61749 goto getAndInitPage_error;
61751 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
61752 if( rc ){
61753 goto getAndInitPage_error;
61755 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
61756 if( (*ppPage)->isInit==0 ){
61757 btreePageFromDbPage(pDbPage, pgno, pBt);
61758 rc = btreeInitPage(*ppPage);
61759 if( rc!=SQLITE_OK ){
61760 releasePage(*ppPage);
61761 goto getAndInitPage_error;
61764 assert( (*ppPage)->pgno==pgno );
61765 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
61767 /* If obtaining a child page for a cursor, we must verify that the page is
61768 ** compatible with the root page. */
61769 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
61770 rc = SQLITE_CORRUPT_PGNO(pgno);
61771 releasePage(*ppPage);
61772 goto getAndInitPage_error;
61774 return SQLITE_OK;
61776 getAndInitPage_error:
61777 if( pCur ){
61778 pCur->iPage--;
61779 pCur->pPage = pCur->apPage[pCur->iPage];
61781 testcase( pgno==0 );
61782 assert( pgno!=0 || rc==SQLITE_CORRUPT );
61783 return rc;
61787 ** Release a MemPage. This should be called once for each prior
61788 ** call to btreeGetPage.
61790 ** Page1 is a special case and must be released using releasePageOne().
61792 static void releasePageNotNull(MemPage *pPage){
61793 assert( pPage->aData );
61794 assert( pPage->pBt );
61795 assert( pPage->pDbPage!=0 );
61796 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
61797 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
61798 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61799 sqlite3PagerUnrefNotNull(pPage->pDbPage);
61801 static void releasePage(MemPage *pPage){
61802 if( pPage ) releasePageNotNull(pPage);
61804 static void releasePageOne(MemPage *pPage){
61805 assert( pPage!=0 );
61806 assert( pPage->aData );
61807 assert( pPage->pBt );
61808 assert( pPage->pDbPage!=0 );
61809 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
61810 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
61811 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61812 sqlite3PagerUnrefPageOne(pPage->pDbPage);
61816 ** Get an unused page.
61818 ** This works just like btreeGetPage() with the addition:
61820 ** * If the page is already in use for some other purpose, immediately
61821 ** release it and return an SQLITE_CURRUPT error.
61822 ** * Make sure the isInit flag is clear
61824 static int btreeGetUnusedPage(
61825 BtShared *pBt, /* The btree */
61826 Pgno pgno, /* Number of the page to fetch */
61827 MemPage **ppPage, /* Return the page in this parameter */
61828 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
61830 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
61831 if( rc==SQLITE_OK ){
61832 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
61833 releasePage(*ppPage);
61834 *ppPage = 0;
61835 return SQLITE_CORRUPT_BKPT;
61837 (*ppPage)->isInit = 0;
61838 }else{
61839 *ppPage = 0;
61841 return rc;
61846 ** During a rollback, when the pager reloads information into the cache
61847 ** so that the cache is restored to its original state at the start of
61848 ** the transaction, for each page restored this routine is called.
61850 ** This routine needs to reset the extra data section at the end of the
61851 ** page to agree with the restored data.
61853 static void pageReinit(DbPage *pData){
61854 MemPage *pPage;
61855 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
61856 assert( sqlite3PagerPageRefcount(pData)>0 );
61857 if( pPage->isInit ){
61858 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61859 pPage->isInit = 0;
61860 if( sqlite3PagerPageRefcount(pData)>1 ){
61861 /* pPage might not be a btree page; it might be an overflow page
61862 ** or ptrmap page or a free page. In those cases, the following
61863 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
61864 ** But no harm is done by this. And it is very important that
61865 ** btreeInitPage() be called on every btree page so we make
61866 ** the call for every page that comes in for re-initing. */
61867 btreeInitPage(pPage);
61873 ** Invoke the busy handler for a btree.
61875 static int btreeInvokeBusyHandler(void *pArg){
61876 BtShared *pBt = (BtShared*)pArg;
61877 assert( pBt->db );
61878 assert( sqlite3_mutex_held(pBt->db->mutex) );
61879 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
61883 ** Open a database file.
61885 ** zFilename is the name of the database file. If zFilename is NULL
61886 ** then an ephemeral database is created. The ephemeral database might
61887 ** be exclusively in memory, or it might use a disk-based memory cache.
61888 ** Either way, the ephemeral database will be automatically deleted
61889 ** when sqlite3BtreeClose() is called.
61891 ** If zFilename is ":memory:" then an in-memory database is created
61892 ** that is automatically destroyed when it is closed.
61894 ** The "flags" parameter is a bitmask that might contain bits like
61895 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
61897 ** If the database is already opened in the same database connection
61898 ** and we are in shared cache mode, then the open will fail with an
61899 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
61900 ** objects in the same database connection since doing so will lead
61901 ** to problems with locking.
61903 SQLITE_PRIVATE int sqlite3BtreeOpen(
61904 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
61905 const char *zFilename, /* Name of the file containing the BTree database */
61906 sqlite3 *db, /* Associated database handle */
61907 Btree **ppBtree, /* Pointer to new Btree object written here */
61908 int flags, /* Options */
61909 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
61911 BtShared *pBt = 0; /* Shared part of btree structure */
61912 Btree *p; /* Handle to return */
61913 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
61914 int rc = SQLITE_OK; /* Result code from this function */
61915 u8 nReserve; /* Byte of unused space on each page */
61916 unsigned char zDbHeader[100]; /* Database header content */
61918 /* True if opening an ephemeral, temporary database */
61919 const int isTempDb = zFilename==0 || zFilename[0]==0;
61921 /* Set the variable isMemdb to true for an in-memory database, or
61922 ** false for a file-based database.
61924 #ifdef SQLITE_OMIT_MEMORYDB
61925 const int isMemdb = 0;
61926 #else
61927 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
61928 || (isTempDb && sqlite3TempInMemory(db))
61929 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
61930 #endif
61932 assert( db!=0 );
61933 assert( pVfs!=0 );
61934 assert( sqlite3_mutex_held(db->mutex) );
61935 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
61937 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
61938 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
61940 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
61941 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
61943 if( isMemdb ){
61944 flags |= BTREE_MEMORY;
61946 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
61947 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
61949 p = sqlite3MallocZero(sizeof(Btree));
61950 if( !p ){
61951 return SQLITE_NOMEM_BKPT;
61953 p->inTrans = TRANS_NONE;
61954 p->db = db;
61955 #ifndef SQLITE_OMIT_SHARED_CACHE
61956 p->lock.pBtree = p;
61957 p->lock.iTable = 1;
61958 #endif
61960 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
61962 ** If this Btree is a candidate for shared cache, try to find an
61963 ** existing BtShared object that we can share with
61965 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
61966 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
61967 int nFilename = sqlite3Strlen30(zFilename)+1;
61968 int nFullPathname = pVfs->mxPathname+1;
61969 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
61970 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
61972 p->sharable = 1;
61973 if( !zFullPathname ){
61974 sqlite3_free(p);
61975 return SQLITE_NOMEM_BKPT;
61977 if( isMemdb ){
61978 memcpy(zFullPathname, zFilename, nFilename);
61979 }else{
61980 rc = sqlite3OsFullPathname(pVfs, zFilename,
61981 nFullPathname, zFullPathname);
61982 if( rc ){
61983 sqlite3_free(zFullPathname);
61984 sqlite3_free(p);
61985 return rc;
61988 #if SQLITE_THREADSAFE
61989 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
61990 sqlite3_mutex_enter(mutexOpen);
61991 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
61992 sqlite3_mutex_enter(mutexShared);
61993 #endif
61994 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
61995 assert( pBt->nRef>0 );
61996 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
61997 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
61998 int iDb;
61999 for(iDb=db->nDb-1; iDb>=0; iDb--){
62000 Btree *pExisting = db->aDb[iDb].pBt;
62001 if( pExisting && pExisting->pBt==pBt ){
62002 sqlite3_mutex_leave(mutexShared);
62003 sqlite3_mutex_leave(mutexOpen);
62004 sqlite3_free(zFullPathname);
62005 sqlite3_free(p);
62006 return SQLITE_CONSTRAINT;
62009 p->pBt = pBt;
62010 pBt->nRef++;
62011 break;
62014 sqlite3_mutex_leave(mutexShared);
62015 sqlite3_free(zFullPathname);
62017 #ifdef SQLITE_DEBUG
62018 else{
62019 /* In debug mode, we mark all persistent databases as sharable
62020 ** even when they are not. This exercises the locking code and
62021 ** gives more opportunity for asserts(sqlite3_mutex_held())
62022 ** statements to find locking problems.
62024 p->sharable = 1;
62026 #endif
62028 #endif
62029 if( pBt==0 ){
62031 ** The following asserts make sure that structures used by the btree are
62032 ** the right size. This is to guard against size changes that result
62033 ** when compiling on a different architecture.
62035 assert( sizeof(i64)==8 );
62036 assert( sizeof(u64)==8 );
62037 assert( sizeof(u32)==4 );
62038 assert( sizeof(u16)==2 );
62039 assert( sizeof(Pgno)==4 );
62041 pBt = sqlite3MallocZero( sizeof(*pBt) );
62042 if( pBt==0 ){
62043 rc = SQLITE_NOMEM_BKPT;
62044 goto btree_open_out;
62046 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
62047 sizeof(MemPage), flags, vfsFlags, pageReinit);
62048 if( rc==SQLITE_OK ){
62049 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
62050 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
62052 if( rc!=SQLITE_OK ){
62053 goto btree_open_out;
62055 pBt->openFlags = (u8)flags;
62056 pBt->db = db;
62057 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
62058 p->pBt = pBt;
62060 pBt->pCursor = 0;
62061 pBt->pPage1 = 0;
62062 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
62063 #if defined(SQLITE_SECURE_DELETE)
62064 pBt->btsFlags |= BTS_SECURE_DELETE;
62065 #elif defined(SQLITE_FAST_SECURE_DELETE)
62066 pBt->btsFlags |= BTS_OVERWRITE;
62067 #endif
62068 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
62069 ** determined by the 2-byte integer located at an offset of 16 bytes from
62070 ** the beginning of the database file. */
62071 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
62072 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
62073 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
62074 pBt->pageSize = 0;
62075 #ifndef SQLITE_OMIT_AUTOVACUUM
62076 /* If the magic name ":memory:" will create an in-memory database, then
62077 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
62078 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
62079 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
62080 ** regular file-name. In this case the auto-vacuum applies as per normal.
62082 if( zFilename && !isMemdb ){
62083 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
62084 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
62086 #endif
62087 nReserve = 0;
62088 }else{
62089 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
62090 ** determined by the one-byte unsigned integer found at an offset of 20
62091 ** into the database file header. */
62092 nReserve = zDbHeader[20];
62093 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
62094 #ifndef SQLITE_OMIT_AUTOVACUUM
62095 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
62096 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
62097 #endif
62099 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
62100 if( rc ) goto btree_open_out;
62101 pBt->usableSize = pBt->pageSize - nReserve;
62102 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
62104 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
62105 /* Add the new BtShared object to the linked list sharable BtShareds.
62107 pBt->nRef = 1;
62108 if( p->sharable ){
62109 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
62110 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
62111 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
62112 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
62113 if( pBt->mutex==0 ){
62114 rc = SQLITE_NOMEM_BKPT;
62115 goto btree_open_out;
62118 sqlite3_mutex_enter(mutexShared);
62119 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
62120 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
62121 sqlite3_mutex_leave(mutexShared);
62123 #endif
62126 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
62127 /* If the new Btree uses a sharable pBtShared, then link the new
62128 ** Btree into the list of all sharable Btrees for the same connection.
62129 ** The list is kept in ascending order by pBt address.
62131 if( p->sharable ){
62132 int i;
62133 Btree *pSib;
62134 for(i=0; i<db->nDb; i++){
62135 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
62136 while( pSib->pPrev ){ pSib = pSib->pPrev; }
62137 if( (uptr)p->pBt<(uptr)pSib->pBt ){
62138 p->pNext = pSib;
62139 p->pPrev = 0;
62140 pSib->pPrev = p;
62141 }else{
62142 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
62143 pSib = pSib->pNext;
62145 p->pNext = pSib->pNext;
62146 p->pPrev = pSib;
62147 if( p->pNext ){
62148 p->pNext->pPrev = p;
62150 pSib->pNext = p;
62152 break;
62156 #endif
62157 *ppBtree = p;
62159 btree_open_out:
62160 if( rc!=SQLITE_OK ){
62161 if( pBt && pBt->pPager ){
62162 sqlite3PagerClose(pBt->pPager, 0);
62164 sqlite3_free(pBt);
62165 sqlite3_free(p);
62166 *ppBtree = 0;
62167 }else{
62168 sqlite3_file *pFile;
62170 /* If the B-Tree was successfully opened, set the pager-cache size to the
62171 ** default value. Except, when opening on an existing shared pager-cache,
62172 ** do not change the pager-cache size.
62174 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
62175 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
62178 pFile = sqlite3PagerFile(pBt->pPager);
62179 if( pFile->pMethods ){
62180 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
62183 if( mutexOpen ){
62184 assert( sqlite3_mutex_held(mutexOpen) );
62185 sqlite3_mutex_leave(mutexOpen);
62187 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
62188 return rc;
62192 ** Decrement the BtShared.nRef counter. When it reaches zero,
62193 ** remove the BtShared structure from the sharing list. Return
62194 ** true if the BtShared.nRef counter reaches zero and return
62195 ** false if it is still positive.
62197 static int removeFromSharingList(BtShared *pBt){
62198 #ifndef SQLITE_OMIT_SHARED_CACHE
62199 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
62200 BtShared *pList;
62201 int removed = 0;
62203 assert( sqlite3_mutex_notheld(pBt->mutex) );
62204 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
62205 sqlite3_mutex_enter(pMaster);
62206 pBt->nRef--;
62207 if( pBt->nRef<=0 ){
62208 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
62209 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
62210 }else{
62211 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
62212 while( ALWAYS(pList) && pList->pNext!=pBt ){
62213 pList=pList->pNext;
62215 if( ALWAYS(pList) ){
62216 pList->pNext = pBt->pNext;
62219 if( SQLITE_THREADSAFE ){
62220 sqlite3_mutex_free(pBt->mutex);
62222 removed = 1;
62224 sqlite3_mutex_leave(pMaster);
62225 return removed;
62226 #else
62227 return 1;
62228 #endif
62232 ** Make sure pBt->pTmpSpace points to an allocation of
62233 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
62234 ** pointer.
62236 static void allocateTempSpace(BtShared *pBt){
62237 if( !pBt->pTmpSpace ){
62238 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
62240 /* One of the uses of pBt->pTmpSpace is to format cells before
62241 ** inserting them into a leaf page (function fillInCell()). If
62242 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
62243 ** by the various routines that manipulate binary cells. Which
62244 ** can mean that fillInCell() only initializes the first 2 or 3
62245 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
62246 ** it into a database page. This is not actually a problem, but it
62247 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
62248 ** data is passed to system call write(). So to avoid this error,
62249 ** zero the first 4 bytes of temp space here.
62251 ** Also: Provide four bytes of initialized space before the
62252 ** beginning of pTmpSpace as an area available to prepend the
62253 ** left-child pointer to the beginning of a cell.
62255 if( pBt->pTmpSpace ){
62256 memset(pBt->pTmpSpace, 0, 8);
62257 pBt->pTmpSpace += 4;
62263 ** Free the pBt->pTmpSpace allocation
62265 static void freeTempSpace(BtShared *pBt){
62266 if( pBt->pTmpSpace ){
62267 pBt->pTmpSpace -= 4;
62268 sqlite3PageFree(pBt->pTmpSpace);
62269 pBt->pTmpSpace = 0;
62274 ** Close an open database and invalidate all cursors.
62276 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
62277 BtShared *pBt = p->pBt;
62278 BtCursor *pCur;
62280 /* Close all cursors opened via this handle. */
62281 assert( sqlite3_mutex_held(p->db->mutex) );
62282 sqlite3BtreeEnter(p);
62283 pCur = pBt->pCursor;
62284 while( pCur ){
62285 BtCursor *pTmp = pCur;
62286 pCur = pCur->pNext;
62287 if( pTmp->pBtree==p ){
62288 sqlite3BtreeCloseCursor(pTmp);
62292 /* Rollback any active transaction and free the handle structure.
62293 ** The call to sqlite3BtreeRollback() drops any table-locks held by
62294 ** this handle.
62296 sqlite3BtreeRollback(p, SQLITE_OK, 0);
62297 sqlite3BtreeLeave(p);
62299 /* If there are still other outstanding references to the shared-btree
62300 ** structure, return now. The remainder of this procedure cleans
62301 ** up the shared-btree.
62303 assert( p->wantToLock==0 && p->locked==0 );
62304 if( !p->sharable || removeFromSharingList(pBt) ){
62305 /* The pBt is no longer on the sharing list, so we can access
62306 ** it without having to hold the mutex.
62308 ** Clean out and delete the BtShared object.
62310 assert( !pBt->pCursor );
62311 sqlite3PagerClose(pBt->pPager, p->db);
62312 if( pBt->xFreeSchema && pBt->pSchema ){
62313 pBt->xFreeSchema(pBt->pSchema);
62315 sqlite3DbFree(0, pBt->pSchema);
62316 freeTempSpace(pBt);
62317 sqlite3_free(pBt);
62320 #ifndef SQLITE_OMIT_SHARED_CACHE
62321 assert( p->wantToLock==0 );
62322 assert( p->locked==0 );
62323 if( p->pPrev ) p->pPrev->pNext = p->pNext;
62324 if( p->pNext ) p->pNext->pPrev = p->pPrev;
62325 #endif
62327 sqlite3_free(p);
62328 return SQLITE_OK;
62332 ** Change the "soft" limit on the number of pages in the cache.
62333 ** Unused and unmodified pages will be recycled when the number of
62334 ** pages in the cache exceeds this soft limit. But the size of the
62335 ** cache is allowed to grow larger than this limit if it contains
62336 ** dirty pages or pages still in active use.
62338 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
62339 BtShared *pBt = p->pBt;
62340 assert( sqlite3_mutex_held(p->db->mutex) );
62341 sqlite3BtreeEnter(p);
62342 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
62343 sqlite3BtreeLeave(p);
62344 return SQLITE_OK;
62348 ** Change the "spill" limit on the number of pages in the cache.
62349 ** If the number of pages exceeds this limit during a write transaction,
62350 ** the pager might attempt to "spill" pages to the journal early in
62351 ** order to free up memory.
62353 ** The value returned is the current spill size. If zero is passed
62354 ** as an argument, no changes are made to the spill size setting, so
62355 ** using mxPage of 0 is a way to query the current spill size.
62357 SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
62358 BtShared *pBt = p->pBt;
62359 int res;
62360 assert( sqlite3_mutex_held(p->db->mutex) );
62361 sqlite3BtreeEnter(p);
62362 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
62363 sqlite3BtreeLeave(p);
62364 return res;
62367 #if SQLITE_MAX_MMAP_SIZE>0
62369 ** Change the limit on the amount of the database file that may be
62370 ** memory mapped.
62372 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
62373 BtShared *pBt = p->pBt;
62374 assert( sqlite3_mutex_held(p->db->mutex) );
62375 sqlite3BtreeEnter(p);
62376 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
62377 sqlite3BtreeLeave(p);
62378 return SQLITE_OK;
62380 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
62383 ** Change the way data is synced to disk in order to increase or decrease
62384 ** how well the database resists damage due to OS crashes and power
62385 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
62386 ** there is a high probability of damage) Level 2 is the default. There
62387 ** is a very low but non-zero probability of damage. Level 3 reduces the
62388 ** probability of damage to near zero but with a write performance reduction.
62390 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
62391 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
62392 Btree *p, /* The btree to set the safety level on */
62393 unsigned pgFlags /* Various PAGER_* flags */
62395 BtShared *pBt = p->pBt;
62396 assert( sqlite3_mutex_held(p->db->mutex) );
62397 sqlite3BtreeEnter(p);
62398 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
62399 sqlite3BtreeLeave(p);
62400 return SQLITE_OK;
62402 #endif
62405 ** Change the default pages size and the number of reserved bytes per page.
62406 ** Or, if the page size has already been fixed, return SQLITE_READONLY
62407 ** without changing anything.
62409 ** The page size must be a power of 2 between 512 and 65536. If the page
62410 ** size supplied does not meet this constraint then the page size is not
62411 ** changed.
62413 ** Page sizes are constrained to be a power of two so that the region
62414 ** of the database file used for locking (beginning at PENDING_BYTE,
62415 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
62416 ** at the beginning of a page.
62418 ** If parameter nReserve is less than zero, then the number of reserved
62419 ** bytes per page is left unchanged.
62421 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
62422 ** and autovacuum mode can no longer be changed.
62424 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
62425 int rc = SQLITE_OK;
62426 BtShared *pBt = p->pBt;
62427 assert( nReserve>=-1 && nReserve<=255 );
62428 sqlite3BtreeEnter(p);
62429 #if SQLITE_HAS_CODEC
62430 if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
62431 #endif
62432 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
62433 sqlite3BtreeLeave(p);
62434 return SQLITE_READONLY;
62436 if( nReserve<0 ){
62437 nReserve = pBt->pageSize - pBt->usableSize;
62439 assert( nReserve>=0 && nReserve<=255 );
62440 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
62441 ((pageSize-1)&pageSize)==0 ){
62442 assert( (pageSize & 7)==0 );
62443 assert( !pBt->pCursor );
62444 pBt->pageSize = (u32)pageSize;
62445 freeTempSpace(pBt);
62447 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
62448 pBt->usableSize = pBt->pageSize - (u16)nReserve;
62449 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
62450 sqlite3BtreeLeave(p);
62451 return rc;
62455 ** Return the currently defined page size
62457 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
62458 return p->pBt->pageSize;
62462 ** This function is similar to sqlite3BtreeGetReserve(), except that it
62463 ** may only be called if it is guaranteed that the b-tree mutex is already
62464 ** held.
62466 ** This is useful in one special case in the backup API code where it is
62467 ** known that the shared b-tree mutex is held, but the mutex on the
62468 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
62469 ** were to be called, it might collide with some other operation on the
62470 ** database handle that owns *p, causing undefined behavior.
62472 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
62473 int n;
62474 assert( sqlite3_mutex_held(p->pBt->mutex) );
62475 n = p->pBt->pageSize - p->pBt->usableSize;
62476 return n;
62480 ** Return the number of bytes of space at the end of every page that
62481 ** are intentually left unused. This is the "reserved" space that is
62482 ** sometimes used by extensions.
62484 ** If SQLITE_HAS_MUTEX is defined then the number returned is the
62485 ** greater of the current reserved space and the maximum requested
62486 ** reserve space.
62488 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
62489 int n;
62490 sqlite3BtreeEnter(p);
62491 n = sqlite3BtreeGetReserveNoMutex(p);
62492 #ifdef SQLITE_HAS_CODEC
62493 if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
62494 #endif
62495 sqlite3BtreeLeave(p);
62496 return n;
62501 ** Set the maximum page count for a database if mxPage is positive.
62502 ** No changes are made if mxPage is 0 or negative.
62503 ** Regardless of the value of mxPage, return the maximum page count.
62505 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
62506 int n;
62507 sqlite3BtreeEnter(p);
62508 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
62509 sqlite3BtreeLeave(p);
62510 return n;
62514 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
62516 ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
62517 ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
62518 ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
62519 ** newFlag==(-1) No changes
62521 ** This routine acts as a query if newFlag is less than zero
62523 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
62524 ** freelist leaf pages are not written back to the database. Thus in-page
62525 ** deleted content is cleared, but freelist deleted content is not.
62527 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
62528 ** that freelist leaf pages are written back into the database, increasing
62529 ** the amount of disk I/O.
62531 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
62532 int b;
62533 if( p==0 ) return 0;
62534 sqlite3BtreeEnter(p);
62535 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
62536 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
62537 if( newFlag>=0 ){
62538 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
62539 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
62541 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
62542 sqlite3BtreeLeave(p);
62543 return b;
62547 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
62548 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
62549 ** is disabled. The default value for the auto-vacuum property is
62550 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
62552 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
62553 #ifdef SQLITE_OMIT_AUTOVACUUM
62554 return SQLITE_READONLY;
62555 #else
62556 BtShared *pBt = p->pBt;
62557 int rc = SQLITE_OK;
62558 u8 av = (u8)autoVacuum;
62560 sqlite3BtreeEnter(p);
62561 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
62562 rc = SQLITE_READONLY;
62563 }else{
62564 pBt->autoVacuum = av ?1:0;
62565 pBt->incrVacuum = av==2 ?1:0;
62567 sqlite3BtreeLeave(p);
62568 return rc;
62569 #endif
62573 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
62574 ** enabled 1 is returned. Otherwise 0.
62576 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
62577 #ifdef SQLITE_OMIT_AUTOVACUUM
62578 return BTREE_AUTOVACUUM_NONE;
62579 #else
62580 int rc;
62581 sqlite3BtreeEnter(p);
62582 rc = (
62583 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
62584 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
62585 BTREE_AUTOVACUUM_INCR
62587 sqlite3BtreeLeave(p);
62588 return rc;
62589 #endif
62593 ** If the user has not set the safety-level for this database connection
62594 ** using "PRAGMA synchronous", and if the safety-level is not already
62595 ** set to the value passed to this function as the second parameter,
62596 ** set it so.
62598 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
62599 && !defined(SQLITE_OMIT_WAL)
62600 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
62601 sqlite3 *db;
62602 Db *pDb;
62603 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
62604 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
62605 if( pDb->bSyncSet==0
62606 && pDb->safety_level!=safety_level
62607 && pDb!=&db->aDb[1]
62609 pDb->safety_level = safety_level;
62610 sqlite3PagerSetFlags(pBt->pPager,
62611 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
62615 #else
62616 # define setDefaultSyncFlag(pBt,safety_level)
62617 #endif
62620 ** Get a reference to pPage1 of the database file. This will
62621 ** also acquire a readlock on that file.
62623 ** SQLITE_OK is returned on success. If the file is not a
62624 ** well-formed database file, then SQLITE_CORRUPT is returned.
62625 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
62626 ** is returned if we run out of memory.
62628 static int lockBtree(BtShared *pBt){
62629 int rc; /* Result code from subfunctions */
62630 MemPage *pPage1; /* Page 1 of the database file */
62631 int nPage; /* Number of pages in the database */
62632 int nPageFile = 0; /* Number of pages in the database file */
62633 int nPageHeader; /* Number of pages in the database according to hdr */
62635 assert( sqlite3_mutex_held(pBt->mutex) );
62636 assert( pBt->pPage1==0 );
62637 rc = sqlite3PagerSharedLock(pBt->pPager);
62638 if( rc!=SQLITE_OK ) return rc;
62639 rc = btreeGetPage(pBt, 1, &pPage1, 0);
62640 if( rc!=SQLITE_OK ) return rc;
62642 /* Do some checking to help insure the file we opened really is
62643 ** a valid database file.
62645 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
62646 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
62647 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
62648 nPage = nPageFile;
62650 if( nPage>0 ){
62651 u32 pageSize;
62652 u32 usableSize;
62653 u8 *page1 = pPage1->aData;
62654 rc = SQLITE_NOTADB;
62655 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
62656 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
62657 ** 61 74 20 33 00. */
62658 if( memcmp(page1, zMagicHeader, 16)!=0 ){
62659 goto page1_init_failed;
62662 #ifdef SQLITE_OMIT_WAL
62663 if( page1[18]>1 ){
62664 pBt->btsFlags |= BTS_READ_ONLY;
62666 if( page1[19]>1 ){
62667 goto page1_init_failed;
62669 #else
62670 if( page1[18]>2 ){
62671 pBt->btsFlags |= BTS_READ_ONLY;
62673 if( page1[19]>2 ){
62674 goto page1_init_failed;
62677 /* If the write version is set to 2, this database should be accessed
62678 ** in WAL mode. If the log is not already open, open it now. Then
62679 ** return SQLITE_OK and return without populating BtShared.pPage1.
62680 ** The caller detects this and calls this function again. This is
62681 ** required as the version of page 1 currently in the page1 buffer
62682 ** may not be the latest version - there may be a newer one in the log
62683 ** file.
62685 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
62686 int isOpen = 0;
62687 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
62688 if( rc!=SQLITE_OK ){
62689 goto page1_init_failed;
62690 }else{
62691 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
62692 if( isOpen==0 ){
62693 releasePageOne(pPage1);
62694 return SQLITE_OK;
62697 rc = SQLITE_NOTADB;
62698 }else{
62699 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
62701 #endif
62703 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
62704 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
62706 ** The original design allowed these amounts to vary, but as of
62707 ** version 3.6.0, we require them to be fixed.
62709 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
62710 goto page1_init_failed;
62712 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
62713 ** determined by the 2-byte integer located at an offset of 16 bytes from
62714 ** the beginning of the database file. */
62715 pageSize = (page1[16]<<8) | (page1[17]<<16);
62716 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
62717 ** between 512 and 65536 inclusive. */
62718 if( ((pageSize-1)&pageSize)!=0
62719 || pageSize>SQLITE_MAX_PAGE_SIZE
62720 || pageSize<=256
62722 goto page1_init_failed;
62724 assert( (pageSize & 7)==0 );
62725 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
62726 ** integer at offset 20 is the number of bytes of space at the end of
62727 ** each page to reserve for extensions.
62729 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
62730 ** determined by the one-byte unsigned integer found at an offset of 20
62731 ** into the database file header. */
62732 usableSize = pageSize - page1[20];
62733 if( (u32)pageSize!=pBt->pageSize ){
62734 /* After reading the first page of the database assuming a page size
62735 ** of BtShared.pageSize, we have discovered that the page-size is
62736 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
62737 ** zero and return SQLITE_OK. The caller will call this function
62738 ** again with the correct page-size.
62740 releasePageOne(pPage1);
62741 pBt->usableSize = usableSize;
62742 pBt->pageSize = pageSize;
62743 freeTempSpace(pBt);
62744 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
62745 pageSize-usableSize);
62746 return rc;
62748 if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
62749 rc = SQLITE_CORRUPT_BKPT;
62750 goto page1_init_failed;
62752 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
62753 ** be less than 480. In other words, if the page size is 512, then the
62754 ** reserved space size cannot exceed 32. */
62755 if( usableSize<480 ){
62756 goto page1_init_failed;
62758 pBt->pageSize = pageSize;
62759 pBt->usableSize = usableSize;
62760 #ifndef SQLITE_OMIT_AUTOVACUUM
62761 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
62762 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
62763 #endif
62766 /* maxLocal is the maximum amount of payload to store locally for
62767 ** a cell. Make sure it is small enough so that at least minFanout
62768 ** cells can will fit on one page. We assume a 10-byte page header.
62769 ** Besides the payload, the cell must store:
62770 ** 2-byte pointer to the cell
62771 ** 4-byte child pointer
62772 ** 9-byte nKey value
62773 ** 4-byte nData value
62774 ** 4-byte overflow page pointer
62775 ** So a cell consists of a 2-byte pointer, a header which is as much as
62776 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
62777 ** page pointer.
62779 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
62780 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
62781 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
62782 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
62783 if( pBt->maxLocal>127 ){
62784 pBt->max1bytePayload = 127;
62785 }else{
62786 pBt->max1bytePayload = (u8)pBt->maxLocal;
62788 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
62789 pBt->pPage1 = pPage1;
62790 pBt->nPage = nPage;
62791 return SQLITE_OK;
62793 page1_init_failed:
62794 releasePageOne(pPage1);
62795 pBt->pPage1 = 0;
62796 return rc;
62799 #ifndef NDEBUG
62801 ** Return the number of cursors open on pBt. This is for use
62802 ** in assert() expressions, so it is only compiled if NDEBUG is not
62803 ** defined.
62805 ** Only write cursors are counted if wrOnly is true. If wrOnly is
62806 ** false then all cursors are counted.
62808 ** For the purposes of this routine, a cursor is any cursor that
62809 ** is capable of reading or writing to the database. Cursors that
62810 ** have been tripped into the CURSOR_FAULT state are not counted.
62812 static int countValidCursors(BtShared *pBt, int wrOnly){
62813 BtCursor *pCur;
62814 int r = 0;
62815 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
62816 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
62817 && pCur->eState!=CURSOR_FAULT ) r++;
62819 return r;
62821 #endif
62824 ** If there are no outstanding cursors and we are not in the middle
62825 ** of a transaction but there is a read lock on the database, then
62826 ** this routine unrefs the first page of the database file which
62827 ** has the effect of releasing the read lock.
62829 ** If there is a transaction in progress, this routine is a no-op.
62831 static void unlockBtreeIfUnused(BtShared *pBt){
62832 assert( sqlite3_mutex_held(pBt->mutex) );
62833 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
62834 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
62835 MemPage *pPage1 = pBt->pPage1;
62836 assert( pPage1->aData );
62837 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
62838 pBt->pPage1 = 0;
62839 releasePageOne(pPage1);
62844 ** If pBt points to an empty file then convert that empty file
62845 ** into a new empty database by initializing the first page of
62846 ** the database.
62848 static int newDatabase(BtShared *pBt){
62849 MemPage *pP1;
62850 unsigned char *data;
62851 int rc;
62853 assert( sqlite3_mutex_held(pBt->mutex) );
62854 if( pBt->nPage>0 ){
62855 return SQLITE_OK;
62857 pP1 = pBt->pPage1;
62858 assert( pP1!=0 );
62859 data = pP1->aData;
62860 rc = sqlite3PagerWrite(pP1->pDbPage);
62861 if( rc ) return rc;
62862 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
62863 assert( sizeof(zMagicHeader)==16 );
62864 data[16] = (u8)((pBt->pageSize>>8)&0xff);
62865 data[17] = (u8)((pBt->pageSize>>16)&0xff);
62866 data[18] = 1;
62867 data[19] = 1;
62868 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
62869 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
62870 data[21] = 64;
62871 data[22] = 32;
62872 data[23] = 32;
62873 memset(&data[24], 0, 100-24);
62874 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
62875 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
62876 #ifndef SQLITE_OMIT_AUTOVACUUM
62877 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
62878 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
62879 put4byte(&data[36 + 4*4], pBt->autoVacuum);
62880 put4byte(&data[36 + 7*4], pBt->incrVacuum);
62881 #endif
62882 pBt->nPage = 1;
62883 data[31] = 1;
62884 return SQLITE_OK;
62888 ** Initialize the first page of the database file (creating a database
62889 ** consisting of a single page and no schema objects). Return SQLITE_OK
62890 ** if successful, or an SQLite error code otherwise.
62892 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
62893 int rc;
62894 sqlite3BtreeEnter(p);
62895 p->pBt->nPage = 0;
62896 rc = newDatabase(p->pBt);
62897 sqlite3BtreeLeave(p);
62898 return rc;
62902 ** Attempt to start a new transaction. A write-transaction
62903 ** is started if the second argument is nonzero, otherwise a read-
62904 ** transaction. If the second argument is 2 or more and exclusive
62905 ** transaction is started, meaning that no other process is allowed
62906 ** to access the database. A preexisting transaction may not be
62907 ** upgraded to exclusive by calling this routine a second time - the
62908 ** exclusivity flag only works for a new transaction.
62910 ** A write-transaction must be started before attempting any
62911 ** changes to the database. None of the following routines
62912 ** will work unless a transaction is started first:
62914 ** sqlite3BtreeCreateTable()
62915 ** sqlite3BtreeCreateIndex()
62916 ** sqlite3BtreeClearTable()
62917 ** sqlite3BtreeDropTable()
62918 ** sqlite3BtreeInsert()
62919 ** sqlite3BtreeDelete()
62920 ** sqlite3BtreeUpdateMeta()
62922 ** If an initial attempt to acquire the lock fails because of lock contention
62923 ** and the database was previously unlocked, then invoke the busy handler
62924 ** if there is one. But if there was previously a read-lock, do not
62925 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
62926 ** returned when there is already a read-lock in order to avoid a deadlock.
62928 ** Suppose there are two processes A and B. A has a read lock and B has
62929 ** a reserved lock. B tries to promote to exclusive but is blocked because
62930 ** of A's read lock. A tries to promote to reserved but is blocked by B.
62931 ** One or the other of the two processes must give way or there can be
62932 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
62933 ** when A already has a read lock, we encourage A to give up and let B
62934 ** proceed.
62936 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
62937 BtShared *pBt = p->pBt;
62938 int rc = SQLITE_OK;
62940 sqlite3BtreeEnter(p);
62941 btreeIntegrity(p);
62943 /* If the btree is already in a write-transaction, or it
62944 ** is already in a read-transaction and a read-transaction
62945 ** is requested, this is a no-op.
62947 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
62948 goto trans_begun;
62950 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
62952 /* Write transactions are not possible on a read-only database */
62953 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
62954 rc = SQLITE_READONLY;
62955 goto trans_begun;
62958 #ifndef SQLITE_OMIT_SHARED_CACHE
62960 sqlite3 *pBlock = 0;
62961 /* If another database handle has already opened a write transaction
62962 ** on this shared-btree structure and a second write transaction is
62963 ** requested, return SQLITE_LOCKED.
62965 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
62966 || (pBt->btsFlags & BTS_PENDING)!=0
62968 pBlock = pBt->pWriter->db;
62969 }else if( wrflag>1 ){
62970 BtLock *pIter;
62971 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
62972 if( pIter->pBtree!=p ){
62973 pBlock = pIter->pBtree->db;
62974 break;
62978 if( pBlock ){
62979 sqlite3ConnectionBlocked(p->db, pBlock);
62980 rc = SQLITE_LOCKED_SHAREDCACHE;
62981 goto trans_begun;
62984 #endif
62986 /* Any read-only or read-write transaction implies a read-lock on
62987 ** page 1. So if some other shared-cache client already has a write-lock
62988 ** on page 1, the transaction cannot be opened. */
62989 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
62990 if( SQLITE_OK!=rc ) goto trans_begun;
62992 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
62993 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
62994 do {
62995 /* Call lockBtree() until either pBt->pPage1 is populated or
62996 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
62997 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
62998 ** reading page 1 it discovers that the page-size of the database
62999 ** file is not pBt->pageSize. In this case lockBtree() will update
63000 ** pBt->pageSize to the page-size of the file on disk.
63002 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
63004 if( rc==SQLITE_OK && wrflag ){
63005 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
63006 rc = SQLITE_READONLY;
63007 }else{
63008 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
63009 if( rc==SQLITE_OK ){
63010 rc = newDatabase(pBt);
63015 if( rc!=SQLITE_OK ){
63016 unlockBtreeIfUnused(pBt);
63018 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
63019 btreeInvokeBusyHandler(pBt) );
63021 if( rc==SQLITE_OK ){
63022 if( p->inTrans==TRANS_NONE ){
63023 pBt->nTransaction++;
63024 #ifndef SQLITE_OMIT_SHARED_CACHE
63025 if( p->sharable ){
63026 assert( p->lock.pBtree==p && p->lock.iTable==1 );
63027 p->lock.eLock = READ_LOCK;
63028 p->lock.pNext = pBt->pLock;
63029 pBt->pLock = &p->lock;
63031 #endif
63033 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
63034 if( p->inTrans>pBt->inTransaction ){
63035 pBt->inTransaction = p->inTrans;
63037 if( wrflag ){
63038 MemPage *pPage1 = pBt->pPage1;
63039 #ifndef SQLITE_OMIT_SHARED_CACHE
63040 assert( !pBt->pWriter );
63041 pBt->pWriter = p;
63042 pBt->btsFlags &= ~BTS_EXCLUSIVE;
63043 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
63044 #endif
63046 /* If the db-size header field is incorrect (as it may be if an old
63047 ** client has been writing the database file), update it now. Doing
63048 ** this sooner rather than later means the database size can safely
63049 ** re-read the database size from page 1 if a savepoint or transaction
63050 ** rollback occurs within the transaction.
63052 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
63053 rc = sqlite3PagerWrite(pPage1->pDbPage);
63054 if( rc==SQLITE_OK ){
63055 put4byte(&pPage1->aData[28], pBt->nPage);
63062 trans_begun:
63063 if( rc==SQLITE_OK && wrflag ){
63064 /* This call makes sure that the pager has the correct number of
63065 ** open savepoints. If the second parameter is greater than 0 and
63066 ** the sub-journal is not already open, then it will be opened here.
63068 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
63071 btreeIntegrity(p);
63072 sqlite3BtreeLeave(p);
63073 return rc;
63076 #ifndef SQLITE_OMIT_AUTOVACUUM
63079 ** Set the pointer-map entries for all children of page pPage. Also, if
63080 ** pPage contains cells that point to overflow pages, set the pointer
63081 ** map entries for the overflow pages as well.
63083 static int setChildPtrmaps(MemPage *pPage){
63084 int i; /* Counter variable */
63085 int nCell; /* Number of cells in page pPage */
63086 int rc; /* Return code */
63087 BtShared *pBt = pPage->pBt;
63088 Pgno pgno = pPage->pgno;
63090 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
63091 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
63092 if( rc!=SQLITE_OK ) return rc;
63093 nCell = pPage->nCell;
63095 for(i=0; i<nCell; i++){
63096 u8 *pCell = findCell(pPage, i);
63098 ptrmapPutOvflPtr(pPage, pCell, &rc);
63100 if( !pPage->leaf ){
63101 Pgno childPgno = get4byte(pCell);
63102 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
63106 if( !pPage->leaf ){
63107 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63108 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
63111 return rc;
63115 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
63116 ** that it points to iTo. Parameter eType describes the type of pointer to
63117 ** be modified, as follows:
63119 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
63120 ** page of pPage.
63122 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
63123 ** page pointed to by one of the cells on pPage.
63125 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
63126 ** overflow page in the list.
63128 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
63129 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
63130 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
63131 if( eType==PTRMAP_OVERFLOW2 ){
63132 /* The pointer is always the first 4 bytes of the page in this case. */
63133 if( get4byte(pPage->aData)!=iFrom ){
63134 return SQLITE_CORRUPT_PGNO(pPage->pgno);
63136 put4byte(pPage->aData, iTo);
63137 }else{
63138 int i;
63139 int nCell;
63140 int rc;
63142 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
63143 if( rc ) return rc;
63144 nCell = pPage->nCell;
63146 for(i=0; i<nCell; i++){
63147 u8 *pCell = findCell(pPage, i);
63148 if( eType==PTRMAP_OVERFLOW1 ){
63149 CellInfo info;
63150 pPage->xParseCell(pPage, pCell, &info);
63151 if( info.nLocal<info.nPayload ){
63152 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
63153 return SQLITE_CORRUPT_PGNO(pPage->pgno);
63155 if( iFrom==get4byte(pCell+info.nSize-4) ){
63156 put4byte(pCell+info.nSize-4, iTo);
63157 break;
63160 }else{
63161 if( get4byte(pCell)==iFrom ){
63162 put4byte(pCell, iTo);
63163 break;
63168 if( i==nCell ){
63169 if( eType!=PTRMAP_BTREE ||
63170 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
63171 return SQLITE_CORRUPT_PGNO(pPage->pgno);
63173 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
63176 return SQLITE_OK;
63181 ** Move the open database page pDbPage to location iFreePage in the
63182 ** database. The pDbPage reference remains valid.
63184 ** The isCommit flag indicates that there is no need to remember that
63185 ** the journal needs to be sync()ed before database page pDbPage->pgno
63186 ** can be written to. The caller has already promised not to write to that
63187 ** page.
63189 static int relocatePage(
63190 BtShared *pBt, /* Btree */
63191 MemPage *pDbPage, /* Open page to move */
63192 u8 eType, /* Pointer map 'type' entry for pDbPage */
63193 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
63194 Pgno iFreePage, /* The location to move pDbPage to */
63195 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
63197 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
63198 Pgno iDbPage = pDbPage->pgno;
63199 Pager *pPager = pBt->pPager;
63200 int rc;
63202 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
63203 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
63204 assert( sqlite3_mutex_held(pBt->mutex) );
63205 assert( pDbPage->pBt==pBt );
63207 /* Move page iDbPage from its current location to page number iFreePage */
63208 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
63209 iDbPage, iFreePage, iPtrPage, eType));
63210 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
63211 if( rc!=SQLITE_OK ){
63212 return rc;
63214 pDbPage->pgno = iFreePage;
63216 /* If pDbPage was a btree-page, then it may have child pages and/or cells
63217 ** that point to overflow pages. The pointer map entries for all these
63218 ** pages need to be changed.
63220 ** If pDbPage is an overflow page, then the first 4 bytes may store a
63221 ** pointer to a subsequent overflow page. If this is the case, then
63222 ** the pointer map needs to be updated for the subsequent overflow page.
63224 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
63225 rc = setChildPtrmaps(pDbPage);
63226 if( rc!=SQLITE_OK ){
63227 return rc;
63229 }else{
63230 Pgno nextOvfl = get4byte(pDbPage->aData);
63231 if( nextOvfl!=0 ){
63232 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
63233 if( rc!=SQLITE_OK ){
63234 return rc;
63239 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
63240 ** that it points at iFreePage. Also fix the pointer map entry for
63241 ** iPtrPage.
63243 if( eType!=PTRMAP_ROOTPAGE ){
63244 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
63245 if( rc!=SQLITE_OK ){
63246 return rc;
63248 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
63249 if( rc!=SQLITE_OK ){
63250 releasePage(pPtrPage);
63251 return rc;
63253 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
63254 releasePage(pPtrPage);
63255 if( rc==SQLITE_OK ){
63256 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
63259 return rc;
63262 /* Forward declaration required by incrVacuumStep(). */
63263 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
63266 ** Perform a single step of an incremental-vacuum. If successful, return
63267 ** SQLITE_OK. If there is no work to do (and therefore no point in
63268 ** calling this function again), return SQLITE_DONE. Or, if an error
63269 ** occurs, return some other error code.
63271 ** More specifically, this function attempts to re-organize the database so
63272 ** that the last page of the file currently in use is no longer in use.
63274 ** Parameter nFin is the number of pages that this database would contain
63275 ** were this function called until it returns SQLITE_DONE.
63277 ** If the bCommit parameter is non-zero, this function assumes that the
63278 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
63279 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
63280 ** operation, or false for an incremental vacuum.
63282 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
63283 Pgno nFreeList; /* Number of pages still on the free-list */
63284 int rc;
63286 assert( sqlite3_mutex_held(pBt->mutex) );
63287 assert( iLastPg>nFin );
63289 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
63290 u8 eType;
63291 Pgno iPtrPage;
63293 nFreeList = get4byte(&pBt->pPage1->aData[36]);
63294 if( nFreeList==0 ){
63295 return SQLITE_DONE;
63298 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
63299 if( rc!=SQLITE_OK ){
63300 return rc;
63302 if( eType==PTRMAP_ROOTPAGE ){
63303 return SQLITE_CORRUPT_BKPT;
63306 if( eType==PTRMAP_FREEPAGE ){
63307 if( bCommit==0 ){
63308 /* Remove the page from the files free-list. This is not required
63309 ** if bCommit is non-zero. In that case, the free-list will be
63310 ** truncated to zero after this function returns, so it doesn't
63311 ** matter if it still contains some garbage entries.
63313 Pgno iFreePg;
63314 MemPage *pFreePg;
63315 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
63316 if( rc!=SQLITE_OK ){
63317 return rc;
63319 assert( iFreePg==iLastPg );
63320 releasePage(pFreePg);
63322 } else {
63323 Pgno iFreePg; /* Index of free page to move pLastPg to */
63324 MemPage *pLastPg;
63325 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
63326 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
63328 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
63329 if( rc!=SQLITE_OK ){
63330 return rc;
63333 /* If bCommit is zero, this loop runs exactly once and page pLastPg
63334 ** is swapped with the first free page pulled off the free list.
63336 ** On the other hand, if bCommit is greater than zero, then keep
63337 ** looping until a free-page located within the first nFin pages
63338 ** of the file is found.
63340 if( bCommit==0 ){
63341 eMode = BTALLOC_LE;
63342 iNear = nFin;
63344 do {
63345 MemPage *pFreePg;
63346 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
63347 if( rc!=SQLITE_OK ){
63348 releasePage(pLastPg);
63349 return rc;
63351 releasePage(pFreePg);
63352 }while( bCommit && iFreePg>nFin );
63353 assert( iFreePg<iLastPg );
63355 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
63356 releasePage(pLastPg);
63357 if( rc!=SQLITE_OK ){
63358 return rc;
63363 if( bCommit==0 ){
63364 do {
63365 iLastPg--;
63366 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
63367 pBt->bDoTruncate = 1;
63368 pBt->nPage = iLastPg;
63370 return SQLITE_OK;
63374 ** The database opened by the first argument is an auto-vacuum database
63375 ** nOrig pages in size containing nFree free pages. Return the expected
63376 ** size of the database in pages following an auto-vacuum operation.
63378 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
63379 int nEntry; /* Number of entries on one ptrmap page */
63380 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
63381 Pgno nFin; /* Return value */
63383 nEntry = pBt->usableSize/5;
63384 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
63385 nFin = nOrig - nFree - nPtrmap;
63386 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
63387 nFin--;
63389 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
63390 nFin--;
63393 return nFin;
63397 ** A write-transaction must be opened before calling this function.
63398 ** It performs a single unit of work towards an incremental vacuum.
63400 ** If the incremental vacuum is finished after this function has run,
63401 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
63402 ** SQLITE_OK is returned. Otherwise an SQLite error code.
63404 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
63405 int rc;
63406 BtShared *pBt = p->pBt;
63408 sqlite3BtreeEnter(p);
63409 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
63410 if( !pBt->autoVacuum ){
63411 rc = SQLITE_DONE;
63412 }else{
63413 Pgno nOrig = btreePagecount(pBt);
63414 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
63415 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
63417 if( nOrig<nFin ){
63418 rc = SQLITE_CORRUPT_BKPT;
63419 }else if( nFree>0 ){
63420 rc = saveAllCursors(pBt, 0, 0);
63421 if( rc==SQLITE_OK ){
63422 invalidateAllOverflowCache(pBt);
63423 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
63425 if( rc==SQLITE_OK ){
63426 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
63427 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
63429 }else{
63430 rc = SQLITE_DONE;
63433 sqlite3BtreeLeave(p);
63434 return rc;
63438 ** This routine is called prior to sqlite3PagerCommit when a transaction
63439 ** is committed for an auto-vacuum database.
63441 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
63442 ** the database file should be truncated to during the commit process.
63443 ** i.e. the database has been reorganized so that only the first *pnTrunc
63444 ** pages are in use.
63446 static int autoVacuumCommit(BtShared *pBt){
63447 int rc = SQLITE_OK;
63448 Pager *pPager = pBt->pPager;
63449 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
63451 assert( sqlite3_mutex_held(pBt->mutex) );
63452 invalidateAllOverflowCache(pBt);
63453 assert(pBt->autoVacuum);
63454 if( !pBt->incrVacuum ){
63455 Pgno nFin; /* Number of pages in database after autovacuuming */
63456 Pgno nFree; /* Number of pages on the freelist initially */
63457 Pgno iFree; /* The next page to be freed */
63458 Pgno nOrig; /* Database size before freeing */
63460 nOrig = btreePagecount(pBt);
63461 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
63462 /* It is not possible to create a database for which the final page
63463 ** is either a pointer-map page or the pending-byte page. If one
63464 ** is encountered, this indicates corruption.
63466 return SQLITE_CORRUPT_BKPT;
63469 nFree = get4byte(&pBt->pPage1->aData[36]);
63470 nFin = finalDbSize(pBt, nOrig, nFree);
63471 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
63472 if( nFin<nOrig ){
63473 rc = saveAllCursors(pBt, 0, 0);
63475 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
63476 rc = incrVacuumStep(pBt, nFin, iFree, 1);
63478 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
63479 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
63480 put4byte(&pBt->pPage1->aData[32], 0);
63481 put4byte(&pBt->pPage1->aData[36], 0);
63482 put4byte(&pBt->pPage1->aData[28], nFin);
63483 pBt->bDoTruncate = 1;
63484 pBt->nPage = nFin;
63486 if( rc!=SQLITE_OK ){
63487 sqlite3PagerRollback(pPager);
63491 assert( nRef>=sqlite3PagerRefcount(pPager) );
63492 return rc;
63495 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
63496 # define setChildPtrmaps(x) SQLITE_OK
63497 #endif
63500 ** This routine does the first phase of a two-phase commit. This routine
63501 ** causes a rollback journal to be created (if it does not already exist)
63502 ** and populated with enough information so that if a power loss occurs
63503 ** the database can be restored to its original state by playing back
63504 ** the journal. Then the contents of the journal are flushed out to
63505 ** the disk. After the journal is safely on oxide, the changes to the
63506 ** database are written into the database file and flushed to oxide.
63507 ** At the end of this call, the rollback journal still exists on the
63508 ** disk and we are still holding all locks, so the transaction has not
63509 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
63510 ** commit process.
63512 ** This call is a no-op if no write-transaction is currently active on pBt.
63514 ** Otherwise, sync the database file for the btree pBt. zMaster points to
63515 ** the name of a master journal file that should be written into the
63516 ** individual journal file, or is NULL, indicating no master journal file
63517 ** (single database transaction).
63519 ** When this is called, the master journal should already have been
63520 ** created, populated with this journal pointer and synced to disk.
63522 ** Once this is routine has returned, the only thing required to commit
63523 ** the write-transaction for this database file is to delete the journal.
63525 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
63526 int rc = SQLITE_OK;
63527 if( p->inTrans==TRANS_WRITE ){
63528 BtShared *pBt = p->pBt;
63529 sqlite3BtreeEnter(p);
63530 #ifndef SQLITE_OMIT_AUTOVACUUM
63531 if( pBt->autoVacuum ){
63532 rc = autoVacuumCommit(pBt);
63533 if( rc!=SQLITE_OK ){
63534 sqlite3BtreeLeave(p);
63535 return rc;
63538 if( pBt->bDoTruncate ){
63539 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
63541 #endif
63542 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
63543 sqlite3BtreeLeave(p);
63545 return rc;
63549 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
63550 ** at the conclusion of a transaction.
63552 static void btreeEndTransaction(Btree *p){
63553 BtShared *pBt = p->pBt;
63554 sqlite3 *db = p->db;
63555 assert( sqlite3BtreeHoldsMutex(p) );
63557 #ifndef SQLITE_OMIT_AUTOVACUUM
63558 pBt->bDoTruncate = 0;
63559 #endif
63560 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
63561 /* If there are other active statements that belong to this database
63562 ** handle, downgrade to a read-only transaction. The other statements
63563 ** may still be reading from the database. */
63564 downgradeAllSharedCacheTableLocks(p);
63565 p->inTrans = TRANS_READ;
63566 }else{
63567 /* If the handle had any kind of transaction open, decrement the
63568 ** transaction count of the shared btree. If the transaction count
63569 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
63570 ** call below will unlock the pager. */
63571 if( p->inTrans!=TRANS_NONE ){
63572 clearAllSharedCacheTableLocks(p);
63573 pBt->nTransaction--;
63574 if( 0==pBt->nTransaction ){
63575 pBt->inTransaction = TRANS_NONE;
63579 /* Set the current transaction state to TRANS_NONE and unlock the
63580 ** pager if this call closed the only read or write transaction. */
63581 p->inTrans = TRANS_NONE;
63582 unlockBtreeIfUnused(pBt);
63585 btreeIntegrity(p);
63589 ** Commit the transaction currently in progress.
63591 ** This routine implements the second phase of a 2-phase commit. The
63592 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
63593 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
63594 ** routine did all the work of writing information out to disk and flushing the
63595 ** contents so that they are written onto the disk platter. All this
63596 ** routine has to do is delete or truncate or zero the header in the
63597 ** the rollback journal (which causes the transaction to commit) and
63598 ** drop locks.
63600 ** Normally, if an error occurs while the pager layer is attempting to
63601 ** finalize the underlying journal file, this function returns an error and
63602 ** the upper layer will attempt a rollback. However, if the second argument
63603 ** is non-zero then this b-tree transaction is part of a multi-file
63604 ** transaction. In this case, the transaction has already been committed
63605 ** (by deleting a master journal file) and the caller will ignore this
63606 ** functions return code. So, even if an error occurs in the pager layer,
63607 ** reset the b-tree objects internal state to indicate that the write
63608 ** transaction has been closed. This is quite safe, as the pager will have
63609 ** transitioned to the error state.
63611 ** This will release the write lock on the database file. If there
63612 ** are no active cursors, it also releases the read lock.
63614 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
63616 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
63617 sqlite3BtreeEnter(p);
63618 btreeIntegrity(p);
63620 /* If the handle has a write-transaction open, commit the shared-btrees
63621 ** transaction and set the shared state to TRANS_READ.
63623 if( p->inTrans==TRANS_WRITE ){
63624 int rc;
63625 BtShared *pBt = p->pBt;
63626 assert( pBt->inTransaction==TRANS_WRITE );
63627 assert( pBt->nTransaction>0 );
63628 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
63629 if( rc!=SQLITE_OK && bCleanup==0 ){
63630 sqlite3BtreeLeave(p);
63631 return rc;
63633 p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
63634 pBt->inTransaction = TRANS_READ;
63635 btreeClearHasContent(pBt);
63638 btreeEndTransaction(p);
63639 sqlite3BtreeLeave(p);
63640 return SQLITE_OK;
63644 ** Do both phases of a commit.
63646 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
63647 int rc;
63648 sqlite3BtreeEnter(p);
63649 rc = sqlite3BtreeCommitPhaseOne(p, 0);
63650 if( rc==SQLITE_OK ){
63651 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
63653 sqlite3BtreeLeave(p);
63654 return rc;
63658 ** This routine sets the state to CURSOR_FAULT and the error
63659 ** code to errCode for every cursor on any BtShared that pBtree
63660 ** references. Or if the writeOnly flag is set to 1, then only
63661 ** trip write cursors and leave read cursors unchanged.
63663 ** Every cursor is a candidate to be tripped, including cursors
63664 ** that belong to other database connections that happen to be
63665 ** sharing the cache with pBtree.
63667 ** This routine gets called when a rollback occurs. If the writeOnly
63668 ** flag is true, then only write-cursors need be tripped - read-only
63669 ** cursors save their current positions so that they may continue
63670 ** following the rollback. Or, if writeOnly is false, all cursors are
63671 ** tripped. In general, writeOnly is false if the transaction being
63672 ** rolled back modified the database schema. In this case b-tree root
63673 ** pages may be moved or deleted from the database altogether, making
63674 ** it unsafe for read cursors to continue.
63676 ** If the writeOnly flag is true and an error is encountered while
63677 ** saving the current position of a read-only cursor, all cursors,
63678 ** including all read-cursors are tripped.
63680 ** SQLITE_OK is returned if successful, or if an error occurs while
63681 ** saving a cursor position, an SQLite error code.
63683 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
63684 BtCursor *p;
63685 int rc = SQLITE_OK;
63687 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
63688 if( pBtree ){
63689 sqlite3BtreeEnter(pBtree);
63690 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
63691 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
63692 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
63693 rc = saveCursorPosition(p);
63694 if( rc!=SQLITE_OK ){
63695 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
63696 break;
63699 }else{
63700 sqlite3BtreeClearCursor(p);
63701 p->eState = CURSOR_FAULT;
63702 p->skipNext = errCode;
63704 btreeReleaseAllCursorPages(p);
63706 sqlite3BtreeLeave(pBtree);
63708 return rc;
63712 ** Rollback the transaction in progress.
63714 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
63715 ** Only write cursors are tripped if writeOnly is true but all cursors are
63716 ** tripped if writeOnly is false. Any attempt to use
63717 ** a tripped cursor will result in an error.
63719 ** This will release the write lock on the database file. If there
63720 ** are no active cursors, it also releases the read lock.
63722 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
63723 int rc;
63724 BtShared *pBt = p->pBt;
63725 MemPage *pPage1;
63727 assert( writeOnly==1 || writeOnly==0 );
63728 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
63729 sqlite3BtreeEnter(p);
63730 if( tripCode==SQLITE_OK ){
63731 rc = tripCode = saveAllCursors(pBt, 0, 0);
63732 if( rc ) writeOnly = 0;
63733 }else{
63734 rc = SQLITE_OK;
63736 if( tripCode ){
63737 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
63738 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
63739 if( rc2!=SQLITE_OK ) rc = rc2;
63741 btreeIntegrity(p);
63743 if( p->inTrans==TRANS_WRITE ){
63744 int rc2;
63746 assert( TRANS_WRITE==pBt->inTransaction );
63747 rc2 = sqlite3PagerRollback(pBt->pPager);
63748 if( rc2!=SQLITE_OK ){
63749 rc = rc2;
63752 /* The rollback may have destroyed the pPage1->aData value. So
63753 ** call btreeGetPage() on page 1 again to make
63754 ** sure pPage1->aData is set correctly. */
63755 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
63756 int nPage = get4byte(28+(u8*)pPage1->aData);
63757 testcase( nPage==0 );
63758 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
63759 testcase( pBt->nPage!=nPage );
63760 pBt->nPage = nPage;
63761 releasePageOne(pPage1);
63763 assert( countValidCursors(pBt, 1)==0 );
63764 pBt->inTransaction = TRANS_READ;
63765 btreeClearHasContent(pBt);
63768 btreeEndTransaction(p);
63769 sqlite3BtreeLeave(p);
63770 return rc;
63774 ** Start a statement subtransaction. The subtransaction can be rolled
63775 ** back independently of the main transaction. You must start a transaction
63776 ** before starting a subtransaction. The subtransaction is ended automatically
63777 ** if the main transaction commits or rolls back.
63779 ** Statement subtransactions are used around individual SQL statements
63780 ** that are contained within a BEGIN...COMMIT block. If a constraint
63781 ** error occurs within the statement, the effect of that one statement
63782 ** can be rolled back without having to rollback the entire transaction.
63784 ** A statement sub-transaction is implemented as an anonymous savepoint. The
63785 ** value passed as the second parameter is the total number of savepoints,
63786 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
63787 ** are no active savepoints and no other statement-transactions open,
63788 ** iStatement is 1. This anonymous savepoint can be released or rolled back
63789 ** using the sqlite3BtreeSavepoint() function.
63791 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
63792 int rc;
63793 BtShared *pBt = p->pBt;
63794 sqlite3BtreeEnter(p);
63795 assert( p->inTrans==TRANS_WRITE );
63796 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
63797 assert( iStatement>0 );
63798 assert( iStatement>p->db->nSavepoint );
63799 assert( pBt->inTransaction==TRANS_WRITE );
63800 /* At the pager level, a statement transaction is a savepoint with
63801 ** an index greater than all savepoints created explicitly using
63802 ** SQL statements. It is illegal to open, release or rollback any
63803 ** such savepoints while the statement transaction savepoint is active.
63805 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
63806 sqlite3BtreeLeave(p);
63807 return rc;
63811 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
63812 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
63813 ** savepoint identified by parameter iSavepoint, depending on the value
63814 ** of op.
63816 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
63817 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
63818 ** contents of the entire transaction are rolled back. This is different
63819 ** from a normal transaction rollback, as no locks are released and the
63820 ** transaction remains open.
63822 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
63823 int rc = SQLITE_OK;
63824 if( p && p->inTrans==TRANS_WRITE ){
63825 BtShared *pBt = p->pBt;
63826 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
63827 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
63828 sqlite3BtreeEnter(p);
63829 if( op==SAVEPOINT_ROLLBACK ){
63830 rc = saveAllCursors(pBt, 0, 0);
63832 if( rc==SQLITE_OK ){
63833 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
63835 if( rc==SQLITE_OK ){
63836 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
63837 pBt->nPage = 0;
63839 rc = newDatabase(pBt);
63840 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
63842 /* The database size was written into the offset 28 of the header
63843 ** when the transaction started, so we know that the value at offset
63844 ** 28 is nonzero. */
63845 assert( pBt->nPage>0 );
63847 sqlite3BtreeLeave(p);
63849 return rc;
63853 ** Create a new cursor for the BTree whose root is on the page
63854 ** iTable. If a read-only cursor is requested, it is assumed that
63855 ** the caller already has at least a read-only transaction open
63856 ** on the database already. If a write-cursor is requested, then
63857 ** the caller is assumed to have an open write transaction.
63859 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
63860 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
63861 ** can be used for reading or for writing if other conditions for writing
63862 ** are also met. These are the conditions that must be met in order
63863 ** for writing to be allowed:
63865 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
63867 ** 2: Other database connections that share the same pager cache
63868 ** but which are not in the READ_UNCOMMITTED state may not have
63869 ** cursors open with wrFlag==0 on the same table. Otherwise
63870 ** the changes made by this write cursor would be visible to
63871 ** the read cursors in the other database connection.
63873 ** 3: The database must be writable (not on read-only media)
63875 ** 4: There must be an active transaction.
63877 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
63878 ** is set. If FORDELETE is set, that is a hint to the implementation that
63879 ** this cursor will only be used to seek to and delete entries of an index
63880 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
63881 ** this implementation. But in a hypothetical alternative storage engine
63882 ** in which index entries are automatically deleted when corresponding table
63883 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
63884 ** operations on this cursor can be no-ops and all READ operations can
63885 ** return a null row (2-bytes: 0x01 0x00).
63887 ** No checking is done to make sure that page iTable really is the
63888 ** root page of a b-tree. If it is not, then the cursor acquired
63889 ** will not work correctly.
63891 ** It is assumed that the sqlite3BtreeCursorZero() has been called
63892 ** on pCur to initialize the memory space prior to invoking this routine.
63894 static int btreeCursor(
63895 Btree *p, /* The btree */
63896 int iTable, /* Root page of table to open */
63897 int wrFlag, /* 1 to write. 0 read-only */
63898 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
63899 BtCursor *pCur /* Space for new cursor */
63901 BtShared *pBt = p->pBt; /* Shared b-tree handle */
63902 BtCursor *pX; /* Looping over other all cursors */
63904 assert( sqlite3BtreeHoldsMutex(p) );
63905 assert( wrFlag==0
63906 || wrFlag==BTREE_WRCSR
63907 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
63910 /* The following assert statements verify that if this is a sharable
63911 ** b-tree database, the connection is holding the required table locks,
63912 ** and that no other connection has any open cursor that conflicts with
63913 ** this lock. */
63914 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
63915 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
63917 /* Assert that the caller has opened the required transaction. */
63918 assert( p->inTrans>TRANS_NONE );
63919 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
63920 assert( pBt->pPage1 && pBt->pPage1->aData );
63921 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
63923 if( wrFlag ){
63924 allocateTempSpace(pBt);
63925 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
63927 if( iTable==1 && btreePagecount(pBt)==0 ){
63928 assert( wrFlag==0 );
63929 iTable = 0;
63932 /* Now that no other errors can occur, finish filling in the BtCursor
63933 ** variables and link the cursor into the BtShared list. */
63934 pCur->pgnoRoot = (Pgno)iTable;
63935 pCur->iPage = -1;
63936 pCur->pKeyInfo = pKeyInfo;
63937 pCur->pBtree = p;
63938 pCur->pBt = pBt;
63939 pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
63940 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
63941 /* If there are two or more cursors on the same btree, then all such
63942 ** cursors *must* have the BTCF_Multiple flag set. */
63943 for(pX=pBt->pCursor; pX; pX=pX->pNext){
63944 if( pX->pgnoRoot==(Pgno)iTable ){
63945 pX->curFlags |= BTCF_Multiple;
63946 pCur->curFlags |= BTCF_Multiple;
63949 pCur->pNext = pBt->pCursor;
63950 pBt->pCursor = pCur;
63951 pCur->eState = CURSOR_INVALID;
63952 return SQLITE_OK;
63954 SQLITE_PRIVATE int sqlite3BtreeCursor(
63955 Btree *p, /* The btree */
63956 int iTable, /* Root page of table to open */
63957 int wrFlag, /* 1 to write. 0 read-only */
63958 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
63959 BtCursor *pCur /* Write new cursor here */
63961 int rc;
63962 if( iTable<1 ){
63963 rc = SQLITE_CORRUPT_BKPT;
63964 }else{
63965 sqlite3BtreeEnter(p);
63966 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
63967 sqlite3BtreeLeave(p);
63969 return rc;
63973 ** Return the size of a BtCursor object in bytes.
63975 ** This interfaces is needed so that users of cursors can preallocate
63976 ** sufficient storage to hold a cursor. The BtCursor object is opaque
63977 ** to users so they cannot do the sizeof() themselves - they must call
63978 ** this routine.
63980 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
63981 return ROUND8(sizeof(BtCursor));
63985 ** Initialize memory that will be converted into a BtCursor object.
63987 ** The simple approach here would be to memset() the entire object
63988 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
63989 ** do not need to be zeroed and they are large, so we can save a lot
63990 ** of run-time by skipping the initialization of those elements.
63992 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
63993 memset(p, 0, offsetof(BtCursor, iPage));
63997 ** Close a cursor. The read lock on the database file is released
63998 ** when the last cursor is closed.
64000 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
64001 Btree *pBtree = pCur->pBtree;
64002 if( pBtree ){
64003 BtShared *pBt = pCur->pBt;
64004 sqlite3BtreeEnter(pBtree);
64005 assert( pBt->pCursor!=0 );
64006 if( pBt->pCursor==pCur ){
64007 pBt->pCursor = pCur->pNext;
64008 }else{
64009 BtCursor *pPrev = pBt->pCursor;
64011 if( pPrev->pNext==pCur ){
64012 pPrev->pNext = pCur->pNext;
64013 break;
64015 pPrev = pPrev->pNext;
64016 }while( ALWAYS(pPrev) );
64018 btreeReleaseAllCursorPages(pCur);
64019 unlockBtreeIfUnused(pBt);
64020 sqlite3_free(pCur->aOverflow);
64021 sqlite3_free(pCur->pKey);
64022 sqlite3BtreeLeave(pBtree);
64024 return SQLITE_OK;
64028 ** Make sure the BtCursor* given in the argument has a valid
64029 ** BtCursor.info structure. If it is not already valid, call
64030 ** btreeParseCell() to fill it in.
64032 ** BtCursor.info is a cache of the information in the current cell.
64033 ** Using this cache reduces the number of calls to btreeParseCell().
64035 #ifndef NDEBUG
64036 static void assertCellInfo(BtCursor *pCur){
64037 CellInfo info;
64038 memset(&info, 0, sizeof(info));
64039 btreeParseCell(pCur->pPage, pCur->ix, &info);
64040 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
64042 #else
64043 #define assertCellInfo(x)
64044 #endif
64045 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
64046 if( pCur->info.nSize==0 ){
64047 pCur->curFlags |= BTCF_ValidNKey;
64048 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
64049 }else{
64050 assertCellInfo(pCur);
64054 #ifndef NDEBUG /* The next routine used only within assert() statements */
64056 ** Return true if the given BtCursor is valid. A valid cursor is one
64057 ** that is currently pointing to a row in a (non-empty) table.
64058 ** This is a verification routine is used only within assert() statements.
64060 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
64061 return pCur && pCur->eState==CURSOR_VALID;
64063 #endif /* NDEBUG */
64064 SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
64065 assert( pCur!=0 );
64066 return pCur->eState==CURSOR_VALID;
64070 ** Return the value of the integer key or "rowid" for a table btree.
64071 ** This routine is only valid for a cursor that is pointing into a
64072 ** ordinary table btree. If the cursor points to an index btree or
64073 ** is invalid, the result of this routine is undefined.
64075 SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
64076 assert( cursorHoldsMutex(pCur) );
64077 assert( pCur->eState==CURSOR_VALID );
64078 assert( pCur->curIntKey );
64079 getCellInfo(pCur);
64080 return pCur->info.nKey;
64084 ** Return the number of bytes of payload for the entry that pCur is
64085 ** currently pointing to. For table btrees, this will be the amount
64086 ** of data. For index btrees, this will be the size of the key.
64088 ** The caller must guarantee that the cursor is pointing to a non-NULL
64089 ** valid entry. In other words, the calling procedure must guarantee
64090 ** that the cursor has Cursor.eState==CURSOR_VALID.
64092 SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
64093 assert( cursorHoldsMutex(pCur) );
64094 assert( pCur->eState==CURSOR_VALID );
64095 getCellInfo(pCur);
64096 return pCur->info.nPayload;
64100 ** Given the page number of an overflow page in the database (parameter
64101 ** ovfl), this function finds the page number of the next page in the
64102 ** linked list of overflow pages. If possible, it uses the auto-vacuum
64103 ** pointer-map data instead of reading the content of page ovfl to do so.
64105 ** If an error occurs an SQLite error code is returned. Otherwise:
64107 ** The page number of the next overflow page in the linked list is
64108 ** written to *pPgnoNext. If page ovfl is the last page in its linked
64109 ** list, *pPgnoNext is set to zero.
64111 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
64112 ** to page number pOvfl was obtained, then *ppPage is set to point to that
64113 ** reference. It is the responsibility of the caller to call releasePage()
64114 ** on *ppPage to free the reference. In no reference was obtained (because
64115 ** the pointer-map was used to obtain the value for *pPgnoNext), then
64116 ** *ppPage is set to zero.
64118 static int getOverflowPage(
64119 BtShared *pBt, /* The database file */
64120 Pgno ovfl, /* Current overflow page number */
64121 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
64122 Pgno *pPgnoNext /* OUT: Next overflow page number */
64124 Pgno next = 0;
64125 MemPage *pPage = 0;
64126 int rc = SQLITE_OK;
64128 assert( sqlite3_mutex_held(pBt->mutex) );
64129 assert(pPgnoNext);
64131 #ifndef SQLITE_OMIT_AUTOVACUUM
64132 /* Try to find the next page in the overflow list using the
64133 ** autovacuum pointer-map pages. Guess that the next page in
64134 ** the overflow list is page number (ovfl+1). If that guess turns
64135 ** out to be wrong, fall back to loading the data of page
64136 ** number ovfl to determine the next page number.
64138 if( pBt->autoVacuum ){
64139 Pgno pgno;
64140 Pgno iGuess = ovfl+1;
64141 u8 eType;
64143 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
64144 iGuess++;
64147 if( iGuess<=btreePagecount(pBt) ){
64148 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
64149 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
64150 next = iGuess;
64151 rc = SQLITE_DONE;
64155 #endif
64157 assert( next==0 || rc==SQLITE_DONE );
64158 if( rc==SQLITE_OK ){
64159 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
64160 assert( rc==SQLITE_OK || pPage==0 );
64161 if( rc==SQLITE_OK ){
64162 next = get4byte(pPage->aData);
64166 *pPgnoNext = next;
64167 if( ppPage ){
64168 *ppPage = pPage;
64169 }else{
64170 releasePage(pPage);
64172 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
64176 ** Copy data from a buffer to a page, or from a page to a buffer.
64178 ** pPayload is a pointer to data stored on database page pDbPage.
64179 ** If argument eOp is false, then nByte bytes of data are copied
64180 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
64181 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
64182 ** of data are copied from the buffer pBuf to pPayload.
64184 ** SQLITE_OK is returned on success, otherwise an error code.
64186 static int copyPayload(
64187 void *pPayload, /* Pointer to page data */
64188 void *pBuf, /* Pointer to buffer */
64189 int nByte, /* Number of bytes to copy */
64190 int eOp, /* 0 -> copy from page, 1 -> copy to page */
64191 DbPage *pDbPage /* Page containing pPayload */
64193 if( eOp ){
64194 /* Copy data from buffer to page (a write operation) */
64195 int rc = sqlite3PagerWrite(pDbPage);
64196 if( rc!=SQLITE_OK ){
64197 return rc;
64199 memcpy(pPayload, pBuf, nByte);
64200 }else{
64201 /* Copy data from page to buffer (a read operation) */
64202 memcpy(pBuf, pPayload, nByte);
64204 return SQLITE_OK;
64208 ** This function is used to read or overwrite payload information
64209 ** for the entry that the pCur cursor is pointing to. The eOp
64210 ** argument is interpreted as follows:
64212 ** 0: The operation is a read. Populate the overflow cache.
64213 ** 1: The operation is a write. Populate the overflow cache.
64215 ** A total of "amt" bytes are read or written beginning at "offset".
64216 ** Data is read to or from the buffer pBuf.
64218 ** The content being read or written might appear on the main page
64219 ** or be scattered out on multiple overflow pages.
64221 ** If the current cursor entry uses one or more overflow pages
64222 ** this function may allocate space for and lazily populate
64223 ** the overflow page-list cache array (BtCursor.aOverflow).
64224 ** Subsequent calls use this cache to make seeking to the supplied offset
64225 ** more efficient.
64227 ** Once an overflow page-list cache has been allocated, it must be
64228 ** invalidated if some other cursor writes to the same table, or if
64229 ** the cursor is moved to a different row. Additionally, in auto-vacuum
64230 ** mode, the following events may invalidate an overflow page-list cache.
64232 ** * An incremental vacuum,
64233 ** * A commit in auto_vacuum="full" mode,
64234 ** * Creating a table (may require moving an overflow page).
64236 static int accessPayload(
64237 BtCursor *pCur, /* Cursor pointing to entry to read from */
64238 u32 offset, /* Begin reading this far into payload */
64239 u32 amt, /* Read this many bytes */
64240 unsigned char *pBuf, /* Write the bytes into this buffer */
64241 int eOp /* zero to read. non-zero to write. */
64243 unsigned char *aPayload;
64244 int rc = SQLITE_OK;
64245 int iIdx = 0;
64246 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
64247 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
64248 #ifdef SQLITE_DIRECT_OVERFLOW_READ
64249 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
64250 #endif
64252 assert( pPage );
64253 assert( eOp==0 || eOp==1 );
64254 assert( pCur->eState==CURSOR_VALID );
64255 assert( pCur->ix<pPage->nCell );
64256 assert( cursorHoldsMutex(pCur) );
64258 getCellInfo(pCur);
64259 aPayload = pCur->info.pPayload;
64260 assert( offset+amt <= pCur->info.nPayload );
64262 assert( aPayload > pPage->aData );
64263 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
64264 /* Trying to read or write past the end of the data is an error. The
64265 ** conditional above is really:
64266 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
64267 ** but is recast into its current form to avoid integer overflow problems
64269 return SQLITE_CORRUPT_PGNO(pPage->pgno);
64272 /* Check if data must be read/written to/from the btree page itself. */
64273 if( offset<pCur->info.nLocal ){
64274 int a = amt;
64275 if( a+offset>pCur->info.nLocal ){
64276 a = pCur->info.nLocal - offset;
64278 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
64279 offset = 0;
64280 pBuf += a;
64281 amt -= a;
64282 }else{
64283 offset -= pCur->info.nLocal;
64287 if( rc==SQLITE_OK && amt>0 ){
64288 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
64289 Pgno nextPage;
64291 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
64293 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
64295 ** The aOverflow[] array is sized at one entry for each overflow page
64296 ** in the overflow chain. The page number of the first overflow page is
64297 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
64298 ** means "not yet known" (the cache is lazily populated).
64300 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
64301 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
64302 if( nOvfl>pCur->nOvflAlloc ){
64303 Pgno *aNew = (Pgno*)sqlite3Realloc(
64304 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
64306 if( aNew==0 ){
64307 return SQLITE_NOMEM_BKPT;
64308 }else{
64309 pCur->nOvflAlloc = nOvfl*2;
64310 pCur->aOverflow = aNew;
64313 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
64314 pCur->curFlags |= BTCF_ValidOvfl;
64315 }else{
64316 /* If the overflow page-list cache has been allocated and the
64317 ** entry for the first required overflow page is valid, skip
64318 ** directly to it.
64320 if( pCur->aOverflow[offset/ovflSize] ){
64321 iIdx = (offset/ovflSize);
64322 nextPage = pCur->aOverflow[iIdx];
64323 offset = (offset%ovflSize);
64327 assert( rc==SQLITE_OK && amt>0 );
64328 while( nextPage ){
64329 /* If required, populate the overflow page-list cache. */
64330 assert( pCur->aOverflow[iIdx]==0
64331 || pCur->aOverflow[iIdx]==nextPage
64332 || CORRUPT_DB );
64333 pCur->aOverflow[iIdx] = nextPage;
64335 if( offset>=ovflSize ){
64336 /* The only reason to read this page is to obtain the page
64337 ** number for the next page in the overflow chain. The page
64338 ** data is not required. So first try to lookup the overflow
64339 ** page-list cache, if any, then fall back to the getOverflowPage()
64340 ** function.
64342 assert( pCur->curFlags & BTCF_ValidOvfl );
64343 assert( pCur->pBtree->db==pBt->db );
64344 if( pCur->aOverflow[iIdx+1] ){
64345 nextPage = pCur->aOverflow[iIdx+1];
64346 }else{
64347 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
64349 offset -= ovflSize;
64350 }else{
64351 /* Need to read this page properly. It contains some of the
64352 ** range of data that is being read (eOp==0) or written (eOp!=0).
64354 #ifdef SQLITE_DIRECT_OVERFLOW_READ
64355 sqlite3_file *fd; /* File from which to do direct overflow read */
64356 #endif
64357 int a = amt;
64358 if( a + offset > ovflSize ){
64359 a = ovflSize - offset;
64362 #ifdef SQLITE_DIRECT_OVERFLOW_READ
64363 /* If all the following are true:
64365 ** 1) this is a read operation, and
64366 ** 2) data is required from the start of this overflow page, and
64367 ** 3) there is no open write-transaction, and
64368 ** 4) the database is file-backed, and
64369 ** 5) the page is not in the WAL file
64370 ** 6) at least 4 bytes have already been read into the output buffer
64372 ** then data can be read directly from the database file into the
64373 ** output buffer, bypassing the page-cache altogether. This speeds
64374 ** up loading large records that span many overflow pages.
64376 if( eOp==0 /* (1) */
64377 && offset==0 /* (2) */
64378 && pBt->inTransaction==TRANS_READ /* (3) */
64379 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */
64380 && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */
64381 && &pBuf[-4]>=pBufStart /* (6) */
64383 u8 aSave[4];
64384 u8 *aWrite = &pBuf[-4];
64385 assert( aWrite>=pBufStart ); /* due to (6) */
64386 memcpy(aSave, aWrite, 4);
64387 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
64388 nextPage = get4byte(aWrite);
64389 memcpy(aWrite, aSave, 4);
64390 }else
64391 #endif
64394 DbPage *pDbPage;
64395 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
64396 (eOp==0 ? PAGER_GET_READONLY : 0)
64398 if( rc==SQLITE_OK ){
64399 aPayload = sqlite3PagerGetData(pDbPage);
64400 nextPage = get4byte(aPayload);
64401 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
64402 sqlite3PagerUnref(pDbPage);
64403 offset = 0;
64406 amt -= a;
64407 if( amt==0 ) return rc;
64408 pBuf += a;
64410 if( rc ) break;
64411 iIdx++;
64415 if( rc==SQLITE_OK && amt>0 ){
64416 /* Overflow chain ends prematurely */
64417 return SQLITE_CORRUPT_PGNO(pPage->pgno);
64419 return rc;
64423 ** Read part of the payload for the row at which that cursor pCur is currently
64424 ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
64425 ** begins at "offset".
64427 ** pCur can be pointing to either a table or an index b-tree.
64428 ** If pointing to a table btree, then the content section is read. If
64429 ** pCur is pointing to an index b-tree then the key section is read.
64431 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
64432 ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
64433 ** cursor might be invalid or might need to be restored before being read.
64435 ** Return SQLITE_OK on success or an error code if anything goes
64436 ** wrong. An error is returned if "offset+amt" is larger than
64437 ** the available payload.
64439 SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
64440 assert( cursorHoldsMutex(pCur) );
64441 assert( pCur->eState==CURSOR_VALID );
64442 assert( pCur->iPage>=0 && pCur->pPage );
64443 assert( pCur->ix<pCur->pPage->nCell );
64444 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
64448 ** This variant of sqlite3BtreePayload() works even if the cursor has not
64449 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
64450 ** interface.
64452 #ifndef SQLITE_OMIT_INCRBLOB
64453 static SQLITE_NOINLINE int accessPayloadChecked(
64454 BtCursor *pCur,
64455 u32 offset,
64456 u32 amt,
64457 void *pBuf
64459 int rc;
64460 if ( pCur->eState==CURSOR_INVALID ){
64461 return SQLITE_ABORT;
64463 assert( cursorOwnsBtShared(pCur) );
64464 rc = btreeRestoreCursorPosition(pCur);
64465 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
64467 SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
64468 if( pCur->eState==CURSOR_VALID ){
64469 assert( cursorOwnsBtShared(pCur) );
64470 return accessPayload(pCur, offset, amt, pBuf, 0);
64471 }else{
64472 return accessPayloadChecked(pCur, offset, amt, pBuf);
64475 #endif /* SQLITE_OMIT_INCRBLOB */
64478 ** Return a pointer to payload information from the entry that the
64479 ** pCur cursor is pointing to. The pointer is to the beginning of
64480 ** the key if index btrees (pPage->intKey==0) and is the data for
64481 ** table btrees (pPage->intKey==1). The number of bytes of available
64482 ** key/data is written into *pAmt. If *pAmt==0, then the value
64483 ** returned will not be a valid pointer.
64485 ** This routine is an optimization. It is common for the entire key
64486 ** and data to fit on the local page and for there to be no overflow
64487 ** pages. When that is so, this routine can be used to access the
64488 ** key and data without making a copy. If the key and/or data spills
64489 ** onto overflow pages, then accessPayload() must be used to reassemble
64490 ** the key/data and copy it into a preallocated buffer.
64492 ** The pointer returned by this routine looks directly into the cached
64493 ** page of the database. The data might change or move the next time
64494 ** any btree routine is called.
64496 static const void *fetchPayload(
64497 BtCursor *pCur, /* Cursor pointing to entry to read from */
64498 u32 *pAmt /* Write the number of available bytes here */
64500 int amt;
64501 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
64502 assert( pCur->eState==CURSOR_VALID );
64503 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64504 assert( cursorOwnsBtShared(pCur) );
64505 assert( pCur->ix<pCur->pPage->nCell );
64506 assert( pCur->info.nSize>0 );
64507 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
64508 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
64509 amt = pCur->info.nLocal;
64510 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
64511 /* There is too little space on the page for the expected amount
64512 ** of local content. Database must be corrupt. */
64513 assert( CORRUPT_DB );
64514 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
64516 *pAmt = (u32)amt;
64517 return (void*)pCur->info.pPayload;
64522 ** For the entry that cursor pCur is point to, return as
64523 ** many bytes of the key or data as are available on the local
64524 ** b-tree page. Write the number of available bytes into *pAmt.
64526 ** The pointer returned is ephemeral. The key/data may move
64527 ** or be destroyed on the next call to any Btree routine,
64528 ** including calls from other threads against the same cache.
64529 ** Hence, a mutex on the BtShared should be held prior to calling
64530 ** this routine.
64532 ** These routines is used to get quick access to key and data
64533 ** in the common case where no overflow pages are used.
64535 SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
64536 return fetchPayload(pCur, pAmt);
64541 ** Move the cursor down to a new child page. The newPgno argument is the
64542 ** page number of the child page to move to.
64544 ** This function returns SQLITE_CORRUPT if the page-header flags field of
64545 ** the new child page does not match the flags field of the parent (i.e.
64546 ** if an intkey page appears to be the parent of a non-intkey page, or
64547 ** vice-versa).
64549 static int moveToChild(BtCursor *pCur, u32 newPgno){
64550 BtShared *pBt = pCur->pBt;
64552 assert( cursorOwnsBtShared(pCur) );
64553 assert( pCur->eState==CURSOR_VALID );
64554 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
64555 assert( pCur->iPage>=0 );
64556 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
64557 return SQLITE_CORRUPT_BKPT;
64559 pCur->info.nSize = 0;
64560 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
64561 pCur->aiIdx[pCur->iPage] = pCur->ix;
64562 pCur->apPage[pCur->iPage] = pCur->pPage;
64563 pCur->ix = 0;
64564 pCur->iPage++;
64565 return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
64568 #ifdef SQLITE_DEBUG
64570 ** Page pParent is an internal (non-leaf) tree page. This function
64571 ** asserts that page number iChild is the left-child if the iIdx'th
64572 ** cell in page pParent. Or, if iIdx is equal to the total number of
64573 ** cells in pParent, that page number iChild is the right-child of
64574 ** the page.
64576 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
64577 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
64578 ** in a corrupt database */
64579 assert( iIdx<=pParent->nCell );
64580 if( iIdx==pParent->nCell ){
64581 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
64582 }else{
64583 assert( get4byte(findCell(pParent, iIdx))==iChild );
64586 #else
64587 # define assertParentIndex(x,y,z)
64588 #endif
64591 ** Move the cursor up to the parent page.
64593 ** pCur->idx is set to the cell index that contains the pointer
64594 ** to the page we are coming from. If we are coming from the
64595 ** right-most child page then pCur->idx is set to one more than
64596 ** the largest cell index.
64598 static void moveToParent(BtCursor *pCur){
64599 MemPage *pLeaf;
64600 assert( cursorOwnsBtShared(pCur) );
64601 assert( pCur->eState==CURSOR_VALID );
64602 assert( pCur->iPage>0 );
64603 assert( pCur->pPage );
64604 assertParentIndex(
64605 pCur->apPage[pCur->iPage-1],
64606 pCur->aiIdx[pCur->iPage-1],
64607 pCur->pPage->pgno
64609 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
64610 pCur->info.nSize = 0;
64611 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
64612 pCur->ix = pCur->aiIdx[pCur->iPage-1];
64613 pLeaf = pCur->pPage;
64614 pCur->pPage = pCur->apPage[--pCur->iPage];
64615 releasePageNotNull(pLeaf);
64619 ** Move the cursor to point to the root page of its b-tree structure.
64621 ** If the table has a virtual root page, then the cursor is moved to point
64622 ** to the virtual root page instead of the actual root page. A table has a
64623 ** virtual root page when the actual root page contains no cells and a
64624 ** single child page. This can only happen with the table rooted at page 1.
64626 ** If the b-tree structure is empty, the cursor state is set to
64627 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
64628 ** the cursor is set to point to the first cell located on the root
64629 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
64631 ** If this function returns successfully, it may be assumed that the
64632 ** page-header flags indicate that the [virtual] root-page is the expected
64633 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
64634 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
64635 ** indicating a table b-tree, or if the caller did specify a KeyInfo
64636 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
64637 ** b-tree).
64639 static int moveToRoot(BtCursor *pCur){
64640 MemPage *pRoot;
64641 int rc = SQLITE_OK;
64643 assert( cursorOwnsBtShared(pCur) );
64644 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
64645 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
64646 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
64647 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
64648 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
64650 if( pCur->iPage>=0 ){
64651 if( pCur->iPage ){
64652 releasePageNotNull(pCur->pPage);
64653 while( --pCur->iPage ){
64654 releasePageNotNull(pCur->apPage[pCur->iPage]);
64656 pCur->pPage = pCur->apPage[0];
64657 goto skip_init;
64659 }else if( pCur->pgnoRoot==0 ){
64660 pCur->eState = CURSOR_INVALID;
64661 return SQLITE_EMPTY;
64662 }else{
64663 assert( pCur->iPage==(-1) );
64664 if( pCur->eState>=CURSOR_REQUIRESEEK ){
64665 if( pCur->eState==CURSOR_FAULT ){
64666 assert( pCur->skipNext!=SQLITE_OK );
64667 return pCur->skipNext;
64669 sqlite3BtreeClearCursor(pCur);
64671 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
64672 0, pCur->curPagerFlags);
64673 if( rc!=SQLITE_OK ){
64674 pCur->eState = CURSOR_INVALID;
64675 return rc;
64677 pCur->iPage = 0;
64678 pCur->curIntKey = pCur->pPage->intKey;
64680 pRoot = pCur->pPage;
64681 assert( pRoot->pgno==pCur->pgnoRoot );
64683 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
64684 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
64685 ** NULL, the caller expects a table b-tree. If this is not the case,
64686 ** return an SQLITE_CORRUPT error.
64688 ** Earlier versions of SQLite assumed that this test could not fail
64689 ** if the root page was already loaded when this function was called (i.e.
64690 ** if pCur->iPage>=0). But this is not so if the database is corrupted
64691 ** in such a way that page pRoot is linked into a second b-tree table
64692 ** (or the freelist). */
64693 assert( pRoot->intKey==1 || pRoot->intKey==0 );
64694 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
64695 return SQLITE_CORRUPT_PGNO(pCur->pPage->pgno);
64698 skip_init:
64699 pCur->ix = 0;
64700 pCur->info.nSize = 0;
64701 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
64703 pRoot = pCur->pPage;
64704 if( pRoot->nCell>0 ){
64705 pCur->eState = CURSOR_VALID;
64706 }else if( !pRoot->leaf ){
64707 Pgno subpage;
64708 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
64709 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
64710 pCur->eState = CURSOR_VALID;
64711 rc = moveToChild(pCur, subpage);
64712 }else{
64713 pCur->eState = CURSOR_INVALID;
64714 rc = SQLITE_EMPTY;
64716 return rc;
64720 ** Move the cursor down to the left-most leaf entry beneath the
64721 ** entry to which it is currently pointing.
64723 ** The left-most leaf is the one with the smallest key - the first
64724 ** in ascending order.
64726 static int moveToLeftmost(BtCursor *pCur){
64727 Pgno pgno;
64728 int rc = SQLITE_OK;
64729 MemPage *pPage;
64731 assert( cursorOwnsBtShared(pCur) );
64732 assert( pCur->eState==CURSOR_VALID );
64733 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
64734 assert( pCur->ix<pPage->nCell );
64735 pgno = get4byte(findCell(pPage, pCur->ix));
64736 rc = moveToChild(pCur, pgno);
64738 return rc;
64742 ** Move the cursor down to the right-most leaf entry beneath the
64743 ** page to which it is currently pointing. Notice the difference
64744 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
64745 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
64746 ** finds the right-most entry beneath the *page*.
64748 ** The right-most entry is the one with the largest key - the last
64749 ** key in ascending order.
64751 static int moveToRightmost(BtCursor *pCur){
64752 Pgno pgno;
64753 int rc = SQLITE_OK;
64754 MemPage *pPage = 0;
64756 assert( cursorOwnsBtShared(pCur) );
64757 assert( pCur->eState==CURSOR_VALID );
64758 while( !(pPage = pCur->pPage)->leaf ){
64759 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
64760 pCur->ix = pPage->nCell;
64761 rc = moveToChild(pCur, pgno);
64762 if( rc ) return rc;
64764 pCur->ix = pPage->nCell-1;
64765 assert( pCur->info.nSize==0 );
64766 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
64767 return SQLITE_OK;
64770 /* Move the cursor to the first entry in the table. Return SQLITE_OK
64771 ** on success. Set *pRes to 0 if the cursor actually points to something
64772 ** or set *pRes to 1 if the table is empty.
64774 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
64775 int rc;
64777 assert( cursorOwnsBtShared(pCur) );
64778 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64779 rc = moveToRoot(pCur);
64780 if( rc==SQLITE_OK ){
64781 assert( pCur->pPage->nCell>0 );
64782 *pRes = 0;
64783 rc = moveToLeftmost(pCur);
64784 }else if( rc==SQLITE_EMPTY ){
64785 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
64786 *pRes = 1;
64787 rc = SQLITE_OK;
64789 return rc;
64792 /* Move the cursor to the last entry in the table. Return SQLITE_OK
64793 ** on success. Set *pRes to 0 if the cursor actually points to something
64794 ** or set *pRes to 1 if the table is empty.
64796 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
64797 int rc;
64799 assert( cursorOwnsBtShared(pCur) );
64800 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64802 /* If the cursor already points to the last entry, this is a no-op. */
64803 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
64804 #ifdef SQLITE_DEBUG
64805 /* This block serves to assert() that the cursor really does point
64806 ** to the last entry in the b-tree. */
64807 int ii;
64808 for(ii=0; ii<pCur->iPage; ii++){
64809 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
64811 assert( pCur->ix==pCur->pPage->nCell-1 );
64812 assert( pCur->pPage->leaf );
64813 #endif
64814 return SQLITE_OK;
64817 rc = moveToRoot(pCur);
64818 if( rc==SQLITE_OK ){
64819 assert( pCur->eState==CURSOR_VALID );
64820 *pRes = 0;
64821 rc = moveToRightmost(pCur);
64822 if( rc==SQLITE_OK ){
64823 pCur->curFlags |= BTCF_AtLast;
64824 }else{
64825 pCur->curFlags &= ~BTCF_AtLast;
64827 }else if( rc==SQLITE_EMPTY ){
64828 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
64829 *pRes = 1;
64830 rc = SQLITE_OK;
64832 return rc;
64835 /* Move the cursor so that it points to an entry near the key
64836 ** specified by pIdxKey or intKey. Return a success code.
64838 ** For INTKEY tables, the intKey parameter is used. pIdxKey
64839 ** must be NULL. For index tables, pIdxKey is used and intKey
64840 ** is ignored.
64842 ** If an exact match is not found, then the cursor is always
64843 ** left pointing at a leaf page which would hold the entry if it
64844 ** were present. The cursor might point to an entry that comes
64845 ** before or after the key.
64847 ** An integer is written into *pRes which is the result of
64848 ** comparing the key with the entry to which the cursor is
64849 ** pointing. The meaning of the integer written into
64850 ** *pRes is as follows:
64852 ** *pRes<0 The cursor is left pointing at an entry that
64853 ** is smaller than intKey/pIdxKey or if the table is empty
64854 ** and the cursor is therefore left point to nothing.
64856 ** *pRes==0 The cursor is left pointing at an entry that
64857 ** exactly matches intKey/pIdxKey.
64859 ** *pRes>0 The cursor is left pointing at an entry that
64860 ** is larger than intKey/pIdxKey.
64862 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
64863 ** exists an entry in the table that exactly matches pIdxKey.
64865 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
64866 BtCursor *pCur, /* The cursor to be moved */
64867 UnpackedRecord *pIdxKey, /* Unpacked index key */
64868 i64 intKey, /* The table key */
64869 int biasRight, /* If true, bias the search to the high end */
64870 int *pRes /* Write search results here */
64872 int rc;
64873 RecordCompare xRecordCompare;
64875 assert( cursorOwnsBtShared(pCur) );
64876 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64877 assert( pRes );
64878 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
64879 assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
64881 /* If the cursor is already positioned at the point we are trying
64882 ** to move to, then just return without doing any work */
64883 if( pIdxKey==0
64884 && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
64886 if( pCur->info.nKey==intKey ){
64887 *pRes = 0;
64888 return SQLITE_OK;
64890 if( pCur->info.nKey<intKey ){
64891 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
64892 *pRes = -1;
64893 return SQLITE_OK;
64895 /* If the requested key is one more than the previous key, then
64896 ** try to get there using sqlite3BtreeNext() rather than a full
64897 ** binary search. This is an optimization only. The correct answer
64898 ** is still obtained without this case, only a little more slowely */
64899 if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
64900 *pRes = 0;
64901 rc = sqlite3BtreeNext(pCur, 0);
64902 if( rc==SQLITE_OK ){
64903 getCellInfo(pCur);
64904 if( pCur->info.nKey==intKey ){
64905 return SQLITE_OK;
64907 }else if( rc==SQLITE_DONE ){
64908 rc = SQLITE_OK;
64909 }else{
64910 return rc;
64916 if( pIdxKey ){
64917 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
64918 pIdxKey->errCode = 0;
64919 assert( pIdxKey->default_rc==1
64920 || pIdxKey->default_rc==0
64921 || pIdxKey->default_rc==-1
64923 }else{
64924 xRecordCompare = 0; /* All keys are integers */
64927 rc = moveToRoot(pCur);
64928 if( rc ){
64929 if( rc==SQLITE_EMPTY ){
64930 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
64931 *pRes = -1;
64932 return SQLITE_OK;
64934 return rc;
64936 assert( pCur->pPage );
64937 assert( pCur->pPage->isInit );
64938 assert( pCur->eState==CURSOR_VALID );
64939 assert( pCur->pPage->nCell > 0 );
64940 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
64941 assert( pCur->curIntKey || pIdxKey );
64942 for(;;){
64943 int lwr, upr, idx, c;
64944 Pgno chldPg;
64945 MemPage *pPage = pCur->pPage;
64946 u8 *pCell; /* Pointer to current cell in pPage */
64948 /* pPage->nCell must be greater than zero. If this is the root-page
64949 ** the cursor would have been INVALID above and this for(;;) loop
64950 ** not run. If this is not the root-page, then the moveToChild() routine
64951 ** would have already detected db corruption. Similarly, pPage must
64952 ** be the right kind (index or table) of b-tree page. Otherwise
64953 ** a moveToChild() or moveToRoot() call would have detected corruption. */
64954 assert( pPage->nCell>0 );
64955 assert( pPage->intKey==(pIdxKey==0) );
64956 lwr = 0;
64957 upr = pPage->nCell-1;
64958 assert( biasRight==0 || biasRight==1 );
64959 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
64960 pCur->ix = (u16)idx;
64961 if( xRecordCompare==0 ){
64962 for(;;){
64963 i64 nCellKey;
64964 pCell = findCellPastPtr(pPage, idx);
64965 if( pPage->intKeyLeaf ){
64966 while( 0x80 <= *(pCell++) ){
64967 if( pCell>=pPage->aDataEnd ){
64968 return SQLITE_CORRUPT_PGNO(pPage->pgno);
64972 getVarint(pCell, (u64*)&nCellKey);
64973 if( nCellKey<intKey ){
64974 lwr = idx+1;
64975 if( lwr>upr ){ c = -1; break; }
64976 }else if( nCellKey>intKey ){
64977 upr = idx-1;
64978 if( lwr>upr ){ c = +1; break; }
64979 }else{
64980 assert( nCellKey==intKey );
64981 pCur->ix = (u16)idx;
64982 if( !pPage->leaf ){
64983 lwr = idx;
64984 goto moveto_next_layer;
64985 }else{
64986 pCur->curFlags |= BTCF_ValidNKey;
64987 pCur->info.nKey = nCellKey;
64988 pCur->info.nSize = 0;
64989 *pRes = 0;
64990 return SQLITE_OK;
64993 assert( lwr+upr>=0 );
64994 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
64996 }else{
64997 for(;;){
64998 int nCell; /* Size of the pCell cell in bytes */
64999 pCell = findCellPastPtr(pPage, idx);
65001 /* The maximum supported page-size is 65536 bytes. This means that
65002 ** the maximum number of record bytes stored on an index B-Tree
65003 ** page is less than 16384 bytes and may be stored as a 2-byte
65004 ** varint. This information is used to attempt to avoid parsing
65005 ** the entire cell by checking for the cases where the record is
65006 ** stored entirely within the b-tree page by inspecting the first
65007 ** 2 bytes of the cell.
65009 nCell = pCell[0];
65010 if( nCell<=pPage->max1bytePayload ){
65011 /* This branch runs if the record-size field of the cell is a
65012 ** single byte varint and the record fits entirely on the main
65013 ** b-tree page. */
65014 testcase( pCell+nCell+1==pPage->aDataEnd );
65015 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
65016 }else if( !(pCell[1] & 0x80)
65017 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
65019 /* The record-size field is a 2 byte varint and the record
65020 ** fits entirely on the main b-tree page. */
65021 testcase( pCell+nCell+2==pPage->aDataEnd );
65022 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
65023 }else{
65024 /* The record flows over onto one or more overflow pages. In
65025 ** this case the whole cell needs to be parsed, a buffer allocated
65026 ** and accessPayload() used to retrieve the record into the
65027 ** buffer before VdbeRecordCompare() can be called.
65029 ** If the record is corrupt, the xRecordCompare routine may read
65030 ** up to two varints past the end of the buffer. An extra 18
65031 ** bytes of padding is allocated at the end of the buffer in
65032 ** case this happens. */
65033 void *pCellKey;
65034 u8 * const pCellBody = pCell - pPage->childPtrSize;
65035 pPage->xParseCell(pPage, pCellBody, &pCur->info);
65036 nCell = (int)pCur->info.nKey;
65037 testcase( nCell<0 ); /* True if key size is 2^32 or more */
65038 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
65039 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
65040 testcase( nCell==2 ); /* Minimum legal index key size */
65041 if( nCell<2 ){
65042 rc = SQLITE_CORRUPT_PGNO(pPage->pgno);
65043 goto moveto_finish;
65045 pCellKey = sqlite3Malloc( nCell+18 );
65046 if( pCellKey==0 ){
65047 rc = SQLITE_NOMEM_BKPT;
65048 goto moveto_finish;
65050 pCur->ix = (u16)idx;
65051 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
65052 pCur->curFlags &= ~BTCF_ValidOvfl;
65053 if( rc ){
65054 sqlite3_free(pCellKey);
65055 goto moveto_finish;
65057 c = xRecordCompare(nCell, pCellKey, pIdxKey);
65058 sqlite3_free(pCellKey);
65060 assert(
65061 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
65062 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
65064 if( c<0 ){
65065 lwr = idx+1;
65066 }else if( c>0 ){
65067 upr = idx-1;
65068 }else{
65069 assert( c==0 );
65070 *pRes = 0;
65071 rc = SQLITE_OK;
65072 pCur->ix = (u16)idx;
65073 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
65074 goto moveto_finish;
65076 if( lwr>upr ) break;
65077 assert( lwr+upr>=0 );
65078 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
65081 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
65082 assert( pPage->isInit );
65083 if( pPage->leaf ){
65084 assert( pCur->ix<pCur->pPage->nCell );
65085 pCur->ix = (u16)idx;
65086 *pRes = c;
65087 rc = SQLITE_OK;
65088 goto moveto_finish;
65090 moveto_next_layer:
65091 if( lwr>=pPage->nCell ){
65092 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
65093 }else{
65094 chldPg = get4byte(findCell(pPage, lwr));
65096 pCur->ix = (u16)lwr;
65097 rc = moveToChild(pCur, chldPg);
65098 if( rc ) break;
65100 moveto_finish:
65101 pCur->info.nSize = 0;
65102 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
65103 return rc;
65108 ** Return TRUE if the cursor is not pointing at an entry of the table.
65110 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
65111 ** past the last entry in the table or sqlite3BtreePrev() moves past
65112 ** the first entry. TRUE is also returned if the table is empty.
65114 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
65115 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
65116 ** have been deleted? This API will need to change to return an error code
65117 ** as well as the boolean result value.
65119 return (CURSOR_VALID!=pCur->eState);
65123 ** Return an estimate for the number of rows in the table that pCur is
65124 ** pointing to. Return a negative number if no estimate is currently
65125 ** available.
65127 SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
65128 i64 n;
65129 u8 i;
65131 assert( cursorOwnsBtShared(pCur) );
65132 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
65134 /* Currently this interface is only called by the OP_IfSmaller
65135 ** opcode, and it that case the cursor will always be valid and
65136 ** will always point to a leaf node. */
65137 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
65138 if( NEVER(pCur->pPage->leaf==0) ) return -1;
65140 n = pCur->pPage->nCell;
65141 for(i=0; i<pCur->iPage; i++){
65142 n *= pCur->apPage[i]->nCell;
65144 return n;
65148 ** Advance the cursor to the next entry in the database.
65149 ** Return value:
65151 ** SQLITE_OK success
65152 ** SQLITE_DONE cursor is already pointing at the last element
65153 ** otherwise some kind of error occurred
65155 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
65156 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
65157 ** to the next cell on the current page. The (slower) btreeNext() helper
65158 ** routine is called when it is necessary to move to a different page or
65159 ** to restore the cursor.
65161 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
65162 ** cursor corresponds to an SQL index and this routine could have been
65163 ** skipped if the SQL index had been a unique index. The F argument
65164 ** is a hint to the implement. SQLite btree implementation does not use
65165 ** this hint, but COMDB2 does.
65167 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
65168 int rc;
65169 int idx;
65170 MemPage *pPage;
65172 assert( cursorOwnsBtShared(pCur) );
65173 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
65174 if( pCur->eState!=CURSOR_VALID ){
65175 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
65176 rc = restoreCursorPosition(pCur);
65177 if( rc!=SQLITE_OK ){
65178 return rc;
65180 if( CURSOR_INVALID==pCur->eState ){
65181 return SQLITE_DONE;
65183 if( pCur->skipNext ){
65184 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
65185 pCur->eState = CURSOR_VALID;
65186 if( pCur->skipNext>0 ){
65187 pCur->skipNext = 0;
65188 return SQLITE_OK;
65190 pCur->skipNext = 0;
65194 pPage = pCur->pPage;
65195 idx = ++pCur->ix;
65196 assert( pPage->isInit );
65198 /* If the database file is corrupt, it is possible for the value of idx
65199 ** to be invalid here. This can only occur if a second cursor modifies
65200 ** the page while cursor pCur is holding a reference to it. Which can
65201 ** only happen if the database is corrupt in such a way as to link the
65202 ** page into more than one b-tree structure. */
65203 testcase( idx>pPage->nCell );
65205 if( idx>=pPage->nCell ){
65206 if( !pPage->leaf ){
65207 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
65208 if( rc ) return rc;
65209 return moveToLeftmost(pCur);
65212 if( pCur->iPage==0 ){
65213 pCur->eState = CURSOR_INVALID;
65214 return SQLITE_DONE;
65216 moveToParent(pCur);
65217 pPage = pCur->pPage;
65218 }while( pCur->ix>=pPage->nCell );
65219 if( pPage->intKey ){
65220 return sqlite3BtreeNext(pCur, 0);
65221 }else{
65222 return SQLITE_OK;
65225 if( pPage->leaf ){
65226 return SQLITE_OK;
65227 }else{
65228 return moveToLeftmost(pCur);
65231 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
65232 MemPage *pPage;
65233 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
65234 assert( cursorOwnsBtShared(pCur) );
65235 assert( flags==0 || flags==1 );
65236 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
65237 pCur->info.nSize = 0;
65238 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
65239 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
65240 pPage = pCur->pPage;
65241 if( (++pCur->ix)>=pPage->nCell ){
65242 pCur->ix--;
65243 return btreeNext(pCur);
65245 if( pPage->leaf ){
65246 return SQLITE_OK;
65247 }else{
65248 return moveToLeftmost(pCur);
65253 ** Step the cursor to the back to the previous entry in the database.
65254 ** Return values:
65256 ** SQLITE_OK success
65257 ** SQLITE_DONE the cursor is already on the first element of the table
65258 ** otherwise some kind of error occurred
65260 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
65261 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
65262 ** to the previous cell on the current page. The (slower) btreePrevious()
65263 ** helper routine is called when it is necessary to move to a different page
65264 ** or to restore the cursor.
65266 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
65267 ** the cursor corresponds to an SQL index and this routine could have been
65268 ** skipped if the SQL index had been a unique index. The F argument is a
65269 ** hint to the implement. The native SQLite btree implementation does not
65270 ** use this hint, but COMDB2 does.
65272 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
65273 int rc;
65274 MemPage *pPage;
65276 assert( cursorOwnsBtShared(pCur) );
65277 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
65278 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
65279 assert( pCur->info.nSize==0 );
65280 if( pCur->eState!=CURSOR_VALID ){
65281 rc = restoreCursorPosition(pCur);
65282 if( rc!=SQLITE_OK ){
65283 return rc;
65285 if( CURSOR_INVALID==pCur->eState ){
65286 return SQLITE_DONE;
65288 if( pCur->skipNext ){
65289 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
65290 pCur->eState = CURSOR_VALID;
65291 if( pCur->skipNext<0 ){
65292 pCur->skipNext = 0;
65293 return SQLITE_OK;
65295 pCur->skipNext = 0;
65299 pPage = pCur->pPage;
65300 assert( pPage->isInit );
65301 if( !pPage->leaf ){
65302 int idx = pCur->ix;
65303 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
65304 if( rc ) return rc;
65305 rc = moveToRightmost(pCur);
65306 }else{
65307 while( pCur->ix==0 ){
65308 if( pCur->iPage==0 ){
65309 pCur->eState = CURSOR_INVALID;
65310 return SQLITE_DONE;
65312 moveToParent(pCur);
65314 assert( pCur->info.nSize==0 );
65315 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
65317 pCur->ix--;
65318 pPage = pCur->pPage;
65319 if( pPage->intKey && !pPage->leaf ){
65320 rc = sqlite3BtreePrevious(pCur, 0);
65321 }else{
65322 rc = SQLITE_OK;
65325 return rc;
65327 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
65328 assert( cursorOwnsBtShared(pCur) );
65329 assert( flags==0 || flags==1 );
65330 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
65331 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
65332 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
65333 pCur->info.nSize = 0;
65334 if( pCur->eState!=CURSOR_VALID
65335 || pCur->ix==0
65336 || pCur->pPage->leaf==0
65338 return btreePrevious(pCur);
65340 pCur->ix--;
65341 return SQLITE_OK;
65345 ** Allocate a new page from the database file.
65347 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
65348 ** has already been called on the new page.) The new page has also
65349 ** been referenced and the calling routine is responsible for calling
65350 ** sqlite3PagerUnref() on the new page when it is done.
65352 ** SQLITE_OK is returned on success. Any other return value indicates
65353 ** an error. *ppPage is set to NULL in the event of an error.
65355 ** If the "nearby" parameter is not 0, then an effort is made to
65356 ** locate a page close to the page number "nearby". This can be used in an
65357 ** attempt to keep related pages close to each other in the database file,
65358 ** which in turn can make database access faster.
65360 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
65361 ** anywhere on the free-list, then it is guaranteed to be returned. If
65362 ** eMode is BTALLOC_LT then the page returned will be less than or equal
65363 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
65364 ** are no restrictions on which page is returned.
65366 static int allocateBtreePage(
65367 BtShared *pBt, /* The btree */
65368 MemPage **ppPage, /* Store pointer to the allocated page here */
65369 Pgno *pPgno, /* Store the page number here */
65370 Pgno nearby, /* Search for a page near this one */
65371 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
65373 MemPage *pPage1;
65374 int rc;
65375 u32 n; /* Number of pages on the freelist */
65376 u32 k; /* Number of leaves on the trunk of the freelist */
65377 MemPage *pTrunk = 0;
65378 MemPage *pPrevTrunk = 0;
65379 Pgno mxPage; /* Total size of the database file */
65381 assert( sqlite3_mutex_held(pBt->mutex) );
65382 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
65383 pPage1 = pBt->pPage1;
65384 mxPage = btreePagecount(pBt);
65385 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
65386 ** stores stores the total number of pages on the freelist. */
65387 n = get4byte(&pPage1->aData[36]);
65388 testcase( n==mxPage-1 );
65389 if( n>=mxPage ){
65390 return SQLITE_CORRUPT_BKPT;
65392 if( n>0 ){
65393 /* There are pages on the freelist. Reuse one of those pages. */
65394 Pgno iTrunk;
65395 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
65396 u32 nSearch = 0; /* Count of the number of search attempts */
65398 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
65399 ** shows that the page 'nearby' is somewhere on the free-list, then
65400 ** the entire-list will be searched for that page.
65402 #ifndef SQLITE_OMIT_AUTOVACUUM
65403 if( eMode==BTALLOC_EXACT ){
65404 if( nearby<=mxPage ){
65405 u8 eType;
65406 assert( nearby>0 );
65407 assert( pBt->autoVacuum );
65408 rc = ptrmapGet(pBt, nearby, &eType, 0);
65409 if( rc ) return rc;
65410 if( eType==PTRMAP_FREEPAGE ){
65411 searchList = 1;
65414 }else if( eMode==BTALLOC_LE ){
65415 searchList = 1;
65417 #endif
65419 /* Decrement the free-list count by 1. Set iTrunk to the index of the
65420 ** first free-list trunk page. iPrevTrunk is initially 1.
65422 rc = sqlite3PagerWrite(pPage1->pDbPage);
65423 if( rc ) return rc;
65424 put4byte(&pPage1->aData[36], n-1);
65426 /* The code within this loop is run only once if the 'searchList' variable
65427 ** is not true. Otherwise, it runs once for each trunk-page on the
65428 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
65429 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
65431 do {
65432 pPrevTrunk = pTrunk;
65433 if( pPrevTrunk ){
65434 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
65435 ** is the page number of the next freelist trunk page in the list or
65436 ** zero if this is the last freelist trunk page. */
65437 iTrunk = get4byte(&pPrevTrunk->aData[0]);
65438 }else{
65439 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
65440 ** stores the page number of the first page of the freelist, or zero if
65441 ** the freelist is empty. */
65442 iTrunk = get4byte(&pPage1->aData[32]);
65444 testcase( iTrunk==mxPage );
65445 if( iTrunk>mxPage || nSearch++ > n ){
65446 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
65447 }else{
65448 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
65450 if( rc ){
65451 pTrunk = 0;
65452 goto end_allocate_page;
65454 assert( pTrunk!=0 );
65455 assert( pTrunk->aData!=0 );
65456 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
65457 ** is the number of leaf page pointers to follow. */
65458 k = get4byte(&pTrunk->aData[4]);
65459 if( k==0 && !searchList ){
65460 /* The trunk has no leaves and the list is not being searched.
65461 ** So extract the trunk page itself and use it as the newly
65462 ** allocated page */
65463 assert( pPrevTrunk==0 );
65464 rc = sqlite3PagerWrite(pTrunk->pDbPage);
65465 if( rc ){
65466 goto end_allocate_page;
65468 *pPgno = iTrunk;
65469 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
65470 *ppPage = pTrunk;
65471 pTrunk = 0;
65472 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
65473 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
65474 /* Value of k is out of range. Database corruption */
65475 rc = SQLITE_CORRUPT_PGNO(iTrunk);
65476 goto end_allocate_page;
65477 #ifndef SQLITE_OMIT_AUTOVACUUM
65478 }else if( searchList
65479 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
65481 /* The list is being searched and this trunk page is the page
65482 ** to allocate, regardless of whether it has leaves.
65484 *pPgno = iTrunk;
65485 *ppPage = pTrunk;
65486 searchList = 0;
65487 rc = sqlite3PagerWrite(pTrunk->pDbPage);
65488 if( rc ){
65489 goto end_allocate_page;
65491 if( k==0 ){
65492 if( !pPrevTrunk ){
65493 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
65494 }else{
65495 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
65496 if( rc!=SQLITE_OK ){
65497 goto end_allocate_page;
65499 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
65501 }else{
65502 /* The trunk page is required by the caller but it contains
65503 ** pointers to free-list leaves. The first leaf becomes a trunk
65504 ** page in this case.
65506 MemPage *pNewTrunk;
65507 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
65508 if( iNewTrunk>mxPage ){
65509 rc = SQLITE_CORRUPT_PGNO(iTrunk);
65510 goto end_allocate_page;
65512 testcase( iNewTrunk==mxPage );
65513 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
65514 if( rc!=SQLITE_OK ){
65515 goto end_allocate_page;
65517 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
65518 if( rc!=SQLITE_OK ){
65519 releasePage(pNewTrunk);
65520 goto end_allocate_page;
65522 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
65523 put4byte(&pNewTrunk->aData[4], k-1);
65524 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
65525 releasePage(pNewTrunk);
65526 if( !pPrevTrunk ){
65527 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
65528 put4byte(&pPage1->aData[32], iNewTrunk);
65529 }else{
65530 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
65531 if( rc ){
65532 goto end_allocate_page;
65534 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
65537 pTrunk = 0;
65538 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
65539 #endif
65540 }else if( k>0 ){
65541 /* Extract a leaf from the trunk */
65542 u32 closest;
65543 Pgno iPage;
65544 unsigned char *aData = pTrunk->aData;
65545 if( nearby>0 ){
65546 u32 i;
65547 closest = 0;
65548 if( eMode==BTALLOC_LE ){
65549 for(i=0; i<k; i++){
65550 iPage = get4byte(&aData[8+i*4]);
65551 if( iPage<=nearby ){
65552 closest = i;
65553 break;
65556 }else{
65557 int dist;
65558 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
65559 for(i=1; i<k; i++){
65560 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
65561 if( d2<dist ){
65562 closest = i;
65563 dist = d2;
65567 }else{
65568 closest = 0;
65571 iPage = get4byte(&aData[8+closest*4]);
65572 testcase( iPage==mxPage );
65573 if( iPage>mxPage ){
65574 rc = SQLITE_CORRUPT_PGNO(iTrunk);
65575 goto end_allocate_page;
65577 testcase( iPage==mxPage );
65578 if( !searchList
65579 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
65581 int noContent;
65582 *pPgno = iPage;
65583 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
65584 ": %d more free pages\n",
65585 *pPgno, closest+1, k, pTrunk->pgno, n-1));
65586 rc = sqlite3PagerWrite(pTrunk->pDbPage);
65587 if( rc ) goto end_allocate_page;
65588 if( closest<k-1 ){
65589 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
65591 put4byte(&aData[4], k-1);
65592 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
65593 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
65594 if( rc==SQLITE_OK ){
65595 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
65596 if( rc!=SQLITE_OK ){
65597 releasePage(*ppPage);
65598 *ppPage = 0;
65601 searchList = 0;
65604 releasePage(pPrevTrunk);
65605 pPrevTrunk = 0;
65606 }while( searchList );
65607 }else{
65608 /* There are no pages on the freelist, so append a new page to the
65609 ** database image.
65611 ** Normally, new pages allocated by this block can be requested from the
65612 ** pager layer with the 'no-content' flag set. This prevents the pager
65613 ** from trying to read the pages content from disk. However, if the
65614 ** current transaction has already run one or more incremental-vacuum
65615 ** steps, then the page we are about to allocate may contain content
65616 ** that is required in the event of a rollback. In this case, do
65617 ** not set the no-content flag. This causes the pager to load and journal
65618 ** the current page content before overwriting it.
65620 ** Note that the pager will not actually attempt to load or journal
65621 ** content for any page that really does lie past the end of the database
65622 ** file on disk. So the effects of disabling the no-content optimization
65623 ** here are confined to those pages that lie between the end of the
65624 ** database image and the end of the database file.
65626 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
65628 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
65629 if( rc ) return rc;
65630 pBt->nPage++;
65631 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
65633 #ifndef SQLITE_OMIT_AUTOVACUUM
65634 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
65635 /* If *pPgno refers to a pointer-map page, allocate two new pages
65636 ** at the end of the file instead of one. The first allocated page
65637 ** becomes a new pointer-map page, the second is used by the caller.
65639 MemPage *pPg = 0;
65640 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
65641 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
65642 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
65643 if( rc==SQLITE_OK ){
65644 rc = sqlite3PagerWrite(pPg->pDbPage);
65645 releasePage(pPg);
65647 if( rc ) return rc;
65648 pBt->nPage++;
65649 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
65651 #endif
65652 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
65653 *pPgno = pBt->nPage;
65655 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
65656 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
65657 if( rc ) return rc;
65658 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
65659 if( rc!=SQLITE_OK ){
65660 releasePage(*ppPage);
65661 *ppPage = 0;
65663 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
65666 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
65668 end_allocate_page:
65669 releasePage(pTrunk);
65670 releasePage(pPrevTrunk);
65671 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
65672 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
65673 return rc;
65677 ** This function is used to add page iPage to the database file free-list.
65678 ** It is assumed that the page is not already a part of the free-list.
65680 ** The value passed as the second argument to this function is optional.
65681 ** If the caller happens to have a pointer to the MemPage object
65682 ** corresponding to page iPage handy, it may pass it as the second value.
65683 ** Otherwise, it may pass NULL.
65685 ** If a pointer to a MemPage object is passed as the second argument,
65686 ** its reference count is not altered by this function.
65688 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
65689 MemPage *pTrunk = 0; /* Free-list trunk page */
65690 Pgno iTrunk = 0; /* Page number of free-list trunk page */
65691 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
65692 MemPage *pPage; /* Page being freed. May be NULL. */
65693 int rc; /* Return Code */
65694 int nFree; /* Initial number of pages on free-list */
65696 assert( sqlite3_mutex_held(pBt->mutex) );
65697 assert( CORRUPT_DB || iPage>1 );
65698 assert( !pMemPage || pMemPage->pgno==iPage );
65700 if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
65701 if( pMemPage ){
65702 pPage = pMemPage;
65703 sqlite3PagerRef(pPage->pDbPage);
65704 }else{
65705 pPage = btreePageLookup(pBt, iPage);
65708 /* Increment the free page count on pPage1 */
65709 rc = sqlite3PagerWrite(pPage1->pDbPage);
65710 if( rc ) goto freepage_out;
65711 nFree = get4byte(&pPage1->aData[36]);
65712 put4byte(&pPage1->aData[36], nFree+1);
65714 if( pBt->btsFlags & BTS_SECURE_DELETE ){
65715 /* If the secure_delete option is enabled, then
65716 ** always fully overwrite deleted information with zeros.
65718 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
65719 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
65721 goto freepage_out;
65723 memset(pPage->aData, 0, pPage->pBt->pageSize);
65726 /* If the database supports auto-vacuum, write an entry in the pointer-map
65727 ** to indicate that the page is free.
65729 if( ISAUTOVACUUM ){
65730 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
65731 if( rc ) goto freepage_out;
65734 /* Now manipulate the actual database free-list structure. There are two
65735 ** possibilities. If the free-list is currently empty, or if the first
65736 ** trunk page in the free-list is full, then this page will become a
65737 ** new free-list trunk page. Otherwise, it will become a leaf of the
65738 ** first trunk page in the current free-list. This block tests if it
65739 ** is possible to add the page as a new free-list leaf.
65741 if( nFree!=0 ){
65742 u32 nLeaf; /* Initial number of leaf cells on trunk page */
65744 iTrunk = get4byte(&pPage1->aData[32]);
65745 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
65746 if( rc!=SQLITE_OK ){
65747 goto freepage_out;
65750 nLeaf = get4byte(&pTrunk->aData[4]);
65751 assert( pBt->usableSize>32 );
65752 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
65753 rc = SQLITE_CORRUPT_BKPT;
65754 goto freepage_out;
65756 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
65757 /* In this case there is room on the trunk page to insert the page
65758 ** being freed as a new leaf.
65760 ** Note that the trunk page is not really full until it contains
65761 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
65762 ** coded. But due to a coding error in versions of SQLite prior to
65763 ** 3.6.0, databases with freelist trunk pages holding more than
65764 ** usableSize/4 - 8 entries will be reported as corrupt. In order
65765 ** to maintain backwards compatibility with older versions of SQLite,
65766 ** we will continue to restrict the number of entries to usableSize/4 - 8
65767 ** for now. At some point in the future (once everyone has upgraded
65768 ** to 3.6.0 or later) we should consider fixing the conditional above
65769 ** to read "usableSize/4-2" instead of "usableSize/4-8".
65771 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
65772 ** avoid using the last six entries in the freelist trunk page array in
65773 ** order that database files created by newer versions of SQLite can be
65774 ** read by older versions of SQLite.
65776 rc = sqlite3PagerWrite(pTrunk->pDbPage);
65777 if( rc==SQLITE_OK ){
65778 put4byte(&pTrunk->aData[4], nLeaf+1);
65779 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
65780 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
65781 sqlite3PagerDontWrite(pPage->pDbPage);
65783 rc = btreeSetHasContent(pBt, iPage);
65785 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
65786 goto freepage_out;
65790 /* If control flows to this point, then it was not possible to add the
65791 ** the page being freed as a leaf page of the first trunk in the free-list.
65792 ** Possibly because the free-list is empty, or possibly because the
65793 ** first trunk in the free-list is full. Either way, the page being freed
65794 ** will become the new first trunk page in the free-list.
65796 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
65797 goto freepage_out;
65799 rc = sqlite3PagerWrite(pPage->pDbPage);
65800 if( rc!=SQLITE_OK ){
65801 goto freepage_out;
65803 put4byte(pPage->aData, iTrunk);
65804 put4byte(&pPage->aData[4], 0);
65805 put4byte(&pPage1->aData[32], iPage);
65806 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
65808 freepage_out:
65809 if( pPage ){
65810 pPage->isInit = 0;
65812 releasePage(pPage);
65813 releasePage(pTrunk);
65814 return rc;
65816 static void freePage(MemPage *pPage, int *pRC){
65817 if( (*pRC)==SQLITE_OK ){
65818 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
65823 ** Free any overflow pages associated with the given Cell. Write the
65824 ** local Cell size (the number of bytes on the original page, omitting
65825 ** overflow) into *pnSize.
65827 static int clearCell(
65828 MemPage *pPage, /* The page that contains the Cell */
65829 unsigned char *pCell, /* First byte of the Cell */
65830 CellInfo *pInfo /* Size information about the cell */
65832 BtShared *pBt;
65833 Pgno ovflPgno;
65834 int rc;
65835 int nOvfl;
65836 u32 ovflPageSize;
65838 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65839 pPage->xParseCell(pPage, pCell, pInfo);
65840 if( pInfo->nLocal==pInfo->nPayload ){
65841 return SQLITE_OK; /* No overflow pages. Return without doing anything */
65843 if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
65844 /* Cell extends past end of page */
65845 return SQLITE_CORRUPT_PGNO(pPage->pgno);
65847 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
65848 pBt = pPage->pBt;
65849 assert( pBt->usableSize > 4 );
65850 ovflPageSize = pBt->usableSize - 4;
65851 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
65852 assert( nOvfl>0 ||
65853 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
65855 while( nOvfl-- ){
65856 Pgno iNext = 0;
65857 MemPage *pOvfl = 0;
65858 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
65859 /* 0 is not a legal page number and page 1 cannot be an
65860 ** overflow page. Therefore if ovflPgno<2 or past the end of the
65861 ** file the database must be corrupt. */
65862 return SQLITE_CORRUPT_BKPT;
65864 if( nOvfl ){
65865 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
65866 if( rc ) return rc;
65869 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
65870 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
65872 /* There is no reason any cursor should have an outstanding reference
65873 ** to an overflow page belonging to a cell that is being deleted/updated.
65874 ** So if there exists more than one reference to this page, then it
65875 ** must not really be an overflow page and the database must be corrupt.
65876 ** It is helpful to detect this before calling freePage2(), as
65877 ** freePage2() may zero the page contents if secure-delete mode is
65878 ** enabled. If this 'overflow' page happens to be a page that the
65879 ** caller is iterating through or using in some other way, this
65880 ** can be problematic.
65882 rc = SQLITE_CORRUPT_BKPT;
65883 }else{
65884 rc = freePage2(pBt, pOvfl, ovflPgno);
65887 if( pOvfl ){
65888 sqlite3PagerUnref(pOvfl->pDbPage);
65890 if( rc ) return rc;
65891 ovflPgno = iNext;
65893 return SQLITE_OK;
65897 ** Create the byte sequence used to represent a cell on page pPage
65898 ** and write that byte sequence into pCell[]. Overflow pages are
65899 ** allocated and filled in as necessary. The calling procedure
65900 ** is responsible for making sure sufficient space has been allocated
65901 ** for pCell[].
65903 ** Note that pCell does not necessary need to point to the pPage->aData
65904 ** area. pCell might point to some temporary storage. The cell will
65905 ** be constructed in this temporary area then copied into pPage->aData
65906 ** later.
65908 static int fillInCell(
65909 MemPage *pPage, /* The page that contains the cell */
65910 unsigned char *pCell, /* Complete text of the cell */
65911 const BtreePayload *pX, /* Payload with which to construct the cell */
65912 int *pnSize /* Write cell size here */
65914 int nPayload;
65915 const u8 *pSrc;
65916 int nSrc, n, rc, mn;
65917 int spaceLeft;
65918 MemPage *pToRelease;
65919 unsigned char *pPrior;
65920 unsigned char *pPayload;
65921 BtShared *pBt;
65922 Pgno pgnoOvfl;
65923 int nHeader;
65925 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65927 /* pPage is not necessarily writeable since pCell might be auxiliary
65928 ** buffer space that is separate from the pPage buffer area */
65929 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
65930 || sqlite3PagerIswriteable(pPage->pDbPage) );
65932 /* Fill in the header. */
65933 nHeader = pPage->childPtrSize;
65934 if( pPage->intKey ){
65935 nPayload = pX->nData + pX->nZero;
65936 pSrc = pX->pData;
65937 nSrc = pX->nData;
65938 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
65939 nHeader += putVarint32(&pCell[nHeader], nPayload);
65940 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
65941 }else{
65942 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
65943 nSrc = nPayload = (int)pX->nKey;
65944 pSrc = pX->pKey;
65945 nHeader += putVarint32(&pCell[nHeader], nPayload);
65948 /* Fill in the payload */
65949 pPayload = &pCell[nHeader];
65950 if( nPayload<=pPage->maxLocal ){
65951 /* This is the common case where everything fits on the btree page
65952 ** and no overflow pages are required. */
65953 n = nHeader + nPayload;
65954 testcase( n==3 );
65955 testcase( n==4 );
65956 if( n<4 ) n = 4;
65957 *pnSize = n;
65958 assert( nSrc<=nPayload );
65959 testcase( nSrc<nPayload );
65960 memcpy(pPayload, pSrc, nSrc);
65961 memset(pPayload+nSrc, 0, nPayload-nSrc);
65962 return SQLITE_OK;
65965 /* If we reach this point, it means that some of the content will need
65966 ** to spill onto overflow pages.
65968 mn = pPage->minLocal;
65969 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
65970 testcase( n==pPage->maxLocal );
65971 testcase( n==pPage->maxLocal+1 );
65972 if( n > pPage->maxLocal ) n = mn;
65973 spaceLeft = n;
65974 *pnSize = n + nHeader + 4;
65975 pPrior = &pCell[nHeader+n];
65976 pToRelease = 0;
65977 pgnoOvfl = 0;
65978 pBt = pPage->pBt;
65980 /* At this point variables should be set as follows:
65982 ** nPayload Total payload size in bytes
65983 ** pPayload Begin writing payload here
65984 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
65985 ** that means content must spill into overflow pages.
65986 ** *pnSize Size of the local cell (not counting overflow pages)
65987 ** pPrior Where to write the pgno of the first overflow page
65989 ** Use a call to btreeParseCellPtr() to verify that the values above
65990 ** were computed correctly.
65992 #ifdef SQLITE_DEBUG
65994 CellInfo info;
65995 pPage->xParseCell(pPage, pCell, &info);
65996 assert( nHeader==(int)(info.pPayload - pCell) );
65997 assert( info.nKey==pX->nKey );
65998 assert( *pnSize == info.nSize );
65999 assert( spaceLeft == info.nLocal );
66001 #endif
66003 /* Write the payload into the local Cell and any extra into overflow pages */
66004 while( 1 ){
66005 n = nPayload;
66006 if( n>spaceLeft ) n = spaceLeft;
66008 /* If pToRelease is not zero than pPayload points into the data area
66009 ** of pToRelease. Make sure pToRelease is still writeable. */
66010 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
66012 /* If pPayload is part of the data area of pPage, then make sure pPage
66013 ** is still writeable */
66014 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
66015 || sqlite3PagerIswriteable(pPage->pDbPage) );
66017 if( nSrc>=n ){
66018 memcpy(pPayload, pSrc, n);
66019 }else if( nSrc>0 ){
66020 n = nSrc;
66021 memcpy(pPayload, pSrc, n);
66022 }else{
66023 memset(pPayload, 0, n);
66025 nPayload -= n;
66026 if( nPayload<=0 ) break;
66027 pPayload += n;
66028 pSrc += n;
66029 nSrc -= n;
66030 spaceLeft -= n;
66031 if( spaceLeft==0 ){
66032 MemPage *pOvfl = 0;
66033 #ifndef SQLITE_OMIT_AUTOVACUUM
66034 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
66035 if( pBt->autoVacuum ){
66037 pgnoOvfl++;
66038 } while(
66039 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
66042 #endif
66043 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
66044 #ifndef SQLITE_OMIT_AUTOVACUUM
66045 /* If the database supports auto-vacuum, and the second or subsequent
66046 ** overflow page is being allocated, add an entry to the pointer-map
66047 ** for that page now.
66049 ** If this is the first overflow page, then write a partial entry
66050 ** to the pointer-map. If we write nothing to this pointer-map slot,
66051 ** then the optimistic overflow chain processing in clearCell()
66052 ** may misinterpret the uninitialized values and delete the
66053 ** wrong pages from the database.
66055 if( pBt->autoVacuum && rc==SQLITE_OK ){
66056 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
66057 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
66058 if( rc ){
66059 releasePage(pOvfl);
66062 #endif
66063 if( rc ){
66064 releasePage(pToRelease);
66065 return rc;
66068 /* If pToRelease is not zero than pPrior points into the data area
66069 ** of pToRelease. Make sure pToRelease is still writeable. */
66070 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
66072 /* If pPrior is part of the data area of pPage, then make sure pPage
66073 ** is still writeable */
66074 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
66075 || sqlite3PagerIswriteable(pPage->pDbPage) );
66077 put4byte(pPrior, pgnoOvfl);
66078 releasePage(pToRelease);
66079 pToRelease = pOvfl;
66080 pPrior = pOvfl->aData;
66081 put4byte(pPrior, 0);
66082 pPayload = &pOvfl->aData[4];
66083 spaceLeft = pBt->usableSize - 4;
66086 releasePage(pToRelease);
66087 return SQLITE_OK;
66091 ** Remove the i-th cell from pPage. This routine effects pPage only.
66092 ** The cell content is not freed or deallocated. It is assumed that
66093 ** the cell content has been copied someplace else. This routine just
66094 ** removes the reference to the cell from pPage.
66096 ** "sz" must be the number of bytes in the cell.
66098 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
66099 u32 pc; /* Offset to cell content of cell being deleted */
66100 u8 *data; /* pPage->aData */
66101 u8 *ptr; /* Used to move bytes around within data[] */
66102 int rc; /* The return code */
66103 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
66105 if( *pRC ) return;
66106 assert( idx>=0 && idx<pPage->nCell );
66107 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
66108 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
66109 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
66110 data = pPage->aData;
66111 ptr = &pPage->aCellIdx[2*idx];
66112 pc = get2byte(ptr);
66113 hdr = pPage->hdrOffset;
66114 testcase( pc==get2byte(&data[hdr+5]) );
66115 testcase( pc+sz==pPage->pBt->usableSize );
66116 if( pc+sz > pPage->pBt->usableSize ){
66117 *pRC = SQLITE_CORRUPT_BKPT;
66118 return;
66120 rc = freeSpace(pPage, pc, sz);
66121 if( rc ){
66122 *pRC = rc;
66123 return;
66125 pPage->nCell--;
66126 if( pPage->nCell==0 ){
66127 memset(&data[hdr+1], 0, 4);
66128 data[hdr+7] = 0;
66129 put2byte(&data[hdr+5], pPage->pBt->usableSize);
66130 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
66131 - pPage->childPtrSize - 8;
66132 }else{
66133 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
66134 put2byte(&data[hdr+3], pPage->nCell);
66135 pPage->nFree += 2;
66140 ** Insert a new cell on pPage at cell index "i". pCell points to the
66141 ** content of the cell.
66143 ** If the cell content will fit on the page, then put it there. If it
66144 ** will not fit, then make a copy of the cell content into pTemp if
66145 ** pTemp is not null. Regardless of pTemp, allocate a new entry
66146 ** in pPage->apOvfl[] and make it point to the cell content (either
66147 ** in pTemp or the original pCell) and also record its index.
66148 ** Allocating a new entry in pPage->aCell[] implies that
66149 ** pPage->nOverflow is incremented.
66151 ** *pRC must be SQLITE_OK when this routine is called.
66153 static void insertCell(
66154 MemPage *pPage, /* Page into which we are copying */
66155 int i, /* New cell becomes the i-th cell of the page */
66156 u8 *pCell, /* Content of the new cell */
66157 int sz, /* Bytes of content in pCell */
66158 u8 *pTemp, /* Temp storage space for pCell, if needed */
66159 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
66160 int *pRC /* Read and write return code from here */
66162 int idx = 0; /* Where to write new cell content in data[] */
66163 int j; /* Loop counter */
66164 u8 *data; /* The content of the whole page */
66165 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
66167 assert( *pRC==SQLITE_OK );
66168 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
66169 assert( MX_CELL(pPage->pBt)<=10921 );
66170 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
66171 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
66172 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
66173 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
66174 /* The cell should normally be sized correctly. However, when moving a
66175 ** malformed cell from a leaf page to an interior page, if the cell size
66176 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
66177 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
66178 ** the term after the || in the following assert(). */
66179 assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
66180 if( pPage->nOverflow || sz+2>pPage->nFree ){
66181 if( pTemp ){
66182 memcpy(pTemp, pCell, sz);
66183 pCell = pTemp;
66185 if( iChild ){
66186 put4byte(pCell, iChild);
66188 j = pPage->nOverflow++;
66189 /* Comparison against ArraySize-1 since we hold back one extra slot
66190 ** as a contingency. In other words, never need more than 3 overflow
66191 ** slots but 4 are allocated, just to be safe. */
66192 assert( j < ArraySize(pPage->apOvfl)-1 );
66193 pPage->apOvfl[j] = pCell;
66194 pPage->aiOvfl[j] = (u16)i;
66196 /* When multiple overflows occur, they are always sequential and in
66197 ** sorted order. This invariants arise because multiple overflows can
66198 ** only occur when inserting divider cells into the parent page during
66199 ** balancing, and the dividers are adjacent and sorted.
66201 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
66202 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
66203 }else{
66204 int rc = sqlite3PagerWrite(pPage->pDbPage);
66205 if( rc!=SQLITE_OK ){
66206 *pRC = rc;
66207 return;
66209 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
66210 data = pPage->aData;
66211 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
66212 rc = allocateSpace(pPage, sz, &idx);
66213 if( rc ){ *pRC = rc; return; }
66214 /* The allocateSpace() routine guarantees the following properties
66215 ** if it returns successfully */
66216 assert( idx >= 0 );
66217 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
66218 assert( idx+sz <= (int)pPage->pBt->usableSize );
66219 pPage->nFree -= (u16)(2 + sz);
66220 memcpy(&data[idx], pCell, sz);
66221 if( iChild ){
66222 put4byte(&data[idx], iChild);
66224 pIns = pPage->aCellIdx + i*2;
66225 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
66226 put2byte(pIns, idx);
66227 pPage->nCell++;
66228 /* increment the cell count */
66229 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
66230 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
66231 #ifndef SQLITE_OMIT_AUTOVACUUM
66232 if( pPage->pBt->autoVacuum ){
66233 /* The cell may contain a pointer to an overflow page. If so, write
66234 ** the entry for the overflow page into the pointer map.
66236 ptrmapPutOvflPtr(pPage, pCell, pRC);
66238 #endif
66243 ** A CellArray object contains a cache of pointers and sizes for a
66244 ** consecutive sequence of cells that might be held on multiple pages.
66246 typedef struct CellArray CellArray;
66247 struct CellArray {
66248 int nCell; /* Number of cells in apCell[] */
66249 MemPage *pRef; /* Reference page */
66250 u8 **apCell; /* All cells begin balanced */
66251 u16 *szCell; /* Local size of all cells in apCell[] */
66255 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
66256 ** computed.
66258 static void populateCellCache(CellArray *p, int idx, int N){
66259 assert( idx>=0 && idx+N<=p->nCell );
66260 while( N>0 ){
66261 assert( p->apCell[idx]!=0 );
66262 if( p->szCell[idx]==0 ){
66263 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
66264 }else{
66265 assert( CORRUPT_DB ||
66266 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
66268 idx++;
66269 N--;
66274 ** Return the size of the Nth element of the cell array
66276 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
66277 assert( N>=0 && N<p->nCell );
66278 assert( p->szCell[N]==0 );
66279 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
66280 return p->szCell[N];
66282 static u16 cachedCellSize(CellArray *p, int N){
66283 assert( N>=0 && N<p->nCell );
66284 if( p->szCell[N] ) return p->szCell[N];
66285 return computeCellSize(p, N);
66289 ** Array apCell[] contains pointers to nCell b-tree page cells. The
66290 ** szCell[] array contains the size in bytes of each cell. This function
66291 ** replaces the current contents of page pPg with the contents of the cell
66292 ** array.
66294 ** Some of the cells in apCell[] may currently be stored in pPg. This
66295 ** function works around problems caused by this by making a copy of any
66296 ** such cells before overwriting the page data.
66298 ** The MemPage.nFree field is invalidated by this function. It is the
66299 ** responsibility of the caller to set it correctly.
66301 static int rebuildPage(
66302 MemPage *pPg, /* Edit this page */
66303 int nCell, /* Final number of cells on page */
66304 u8 **apCell, /* Array of cells */
66305 u16 *szCell /* Array of cell sizes */
66307 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
66308 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
66309 const int usableSize = pPg->pBt->usableSize;
66310 u8 * const pEnd = &aData[usableSize];
66311 int i;
66312 u8 *pCellptr = pPg->aCellIdx;
66313 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
66314 u8 *pData;
66316 i = get2byte(&aData[hdr+5]);
66317 memcpy(&pTmp[i], &aData[i], usableSize - i);
66319 pData = pEnd;
66320 for(i=0; i<nCell; i++){
66321 u8 *pCell = apCell[i];
66322 if( SQLITE_WITHIN(pCell,aData,pEnd) ){
66323 pCell = &pTmp[pCell - aData];
66325 pData -= szCell[i];
66326 put2byte(pCellptr, (pData - aData));
66327 pCellptr += 2;
66328 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
66329 memcpy(pData, pCell, szCell[i]);
66330 assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
66331 testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
66334 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
66335 pPg->nCell = nCell;
66336 pPg->nOverflow = 0;
66338 put2byte(&aData[hdr+1], 0);
66339 put2byte(&aData[hdr+3], pPg->nCell);
66340 put2byte(&aData[hdr+5], pData - aData);
66341 aData[hdr+7] = 0x00;
66342 return SQLITE_OK;
66346 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
66347 ** contains the size in bytes of each such cell. This function attempts to
66348 ** add the cells stored in the array to page pPg. If it cannot (because
66349 ** the page needs to be defragmented before the cells will fit), non-zero
66350 ** is returned. Otherwise, if the cells are added successfully, zero is
66351 ** returned.
66353 ** Argument pCellptr points to the first entry in the cell-pointer array
66354 ** (part of page pPg) to populate. After cell apCell[0] is written to the
66355 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
66356 ** cell in the array. It is the responsibility of the caller to ensure
66357 ** that it is safe to overwrite this part of the cell-pointer array.
66359 ** When this function is called, *ppData points to the start of the
66360 ** content area on page pPg. If the size of the content area is extended,
66361 ** *ppData is updated to point to the new start of the content area
66362 ** before returning.
66364 ** Finally, argument pBegin points to the byte immediately following the
66365 ** end of the space required by this page for the cell-pointer area (for
66366 ** all cells - not just those inserted by the current call). If the content
66367 ** area must be extended to before this point in order to accomodate all
66368 ** cells in apCell[], then the cells do not fit and non-zero is returned.
66370 static int pageInsertArray(
66371 MemPage *pPg, /* Page to add cells to */
66372 u8 *pBegin, /* End of cell-pointer array */
66373 u8 **ppData, /* IN/OUT: Page content -area pointer */
66374 u8 *pCellptr, /* Pointer to cell-pointer area */
66375 int iFirst, /* Index of first cell to add */
66376 int nCell, /* Number of cells to add to pPg */
66377 CellArray *pCArray /* Array of cells */
66379 int i;
66380 u8 *aData = pPg->aData;
66381 u8 *pData = *ppData;
66382 int iEnd = iFirst + nCell;
66383 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
66384 for(i=iFirst; i<iEnd; i++){
66385 int sz, rc;
66386 u8 *pSlot;
66387 sz = cachedCellSize(pCArray, i);
66388 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
66389 if( (pData - pBegin)<sz ) return 1;
66390 pData -= sz;
66391 pSlot = pData;
66393 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
66394 ** database. But they might for a corrupt database. Hence use memmove()
66395 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
66396 assert( (pSlot+sz)<=pCArray->apCell[i]
66397 || pSlot>=(pCArray->apCell[i]+sz)
66398 || CORRUPT_DB );
66399 memmove(pSlot, pCArray->apCell[i], sz);
66400 put2byte(pCellptr, (pSlot - aData));
66401 pCellptr += 2;
66403 *ppData = pData;
66404 return 0;
66408 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
66409 ** contains the size in bytes of each such cell. This function adds the
66410 ** space associated with each cell in the array that is currently stored
66411 ** within the body of pPg to the pPg free-list. The cell-pointers and other
66412 ** fields of the page are not updated.
66414 ** This function returns the total number of cells added to the free-list.
66416 static int pageFreeArray(
66417 MemPage *pPg, /* Page to edit */
66418 int iFirst, /* First cell to delete */
66419 int nCell, /* Cells to delete */
66420 CellArray *pCArray /* Array of cells */
66422 u8 * const aData = pPg->aData;
66423 u8 * const pEnd = &aData[pPg->pBt->usableSize];
66424 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
66425 int nRet = 0;
66426 int i;
66427 int iEnd = iFirst + nCell;
66428 u8 *pFree = 0;
66429 int szFree = 0;
66431 for(i=iFirst; i<iEnd; i++){
66432 u8 *pCell = pCArray->apCell[i];
66433 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
66434 int sz;
66435 /* No need to use cachedCellSize() here. The sizes of all cells that
66436 ** are to be freed have already been computing while deciding which
66437 ** cells need freeing */
66438 sz = pCArray->szCell[i]; assert( sz>0 );
66439 if( pFree!=(pCell + sz) ){
66440 if( pFree ){
66441 assert( pFree>aData && (pFree - aData)<65536 );
66442 freeSpace(pPg, (u16)(pFree - aData), szFree);
66444 pFree = pCell;
66445 szFree = sz;
66446 if( pFree+sz>pEnd ) return 0;
66447 }else{
66448 pFree = pCell;
66449 szFree += sz;
66451 nRet++;
66454 if( pFree ){
66455 assert( pFree>aData && (pFree - aData)<65536 );
66456 freeSpace(pPg, (u16)(pFree - aData), szFree);
66458 return nRet;
66462 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
66463 ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
66464 ** with apCell[iOld]. After balancing, this page should hold nNew cells
66465 ** starting at apCell[iNew].
66467 ** This routine makes the necessary adjustments to pPg so that it contains
66468 ** the correct cells after being balanced.
66470 ** The pPg->nFree field is invalid when this function returns. It is the
66471 ** responsibility of the caller to set it correctly.
66473 static int editPage(
66474 MemPage *pPg, /* Edit this page */
66475 int iOld, /* Index of first cell currently on page */
66476 int iNew, /* Index of new first cell on page */
66477 int nNew, /* Final number of cells on page */
66478 CellArray *pCArray /* Array of cells and sizes */
66480 u8 * const aData = pPg->aData;
66481 const int hdr = pPg->hdrOffset;
66482 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
66483 int nCell = pPg->nCell; /* Cells stored on pPg */
66484 u8 *pData;
66485 u8 *pCellptr;
66486 int i;
66487 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
66488 int iNewEnd = iNew + nNew;
66490 #ifdef SQLITE_DEBUG
66491 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
66492 memcpy(pTmp, aData, pPg->pBt->usableSize);
66493 #endif
66495 /* Remove cells from the start and end of the page */
66496 if( iOld<iNew ){
66497 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
66498 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
66499 nCell -= nShift;
66501 if( iNewEnd < iOldEnd ){
66502 nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
66505 pData = &aData[get2byteNotZero(&aData[hdr+5])];
66506 if( pData<pBegin ) goto editpage_fail;
66508 /* Add cells to the start of the page */
66509 if( iNew<iOld ){
66510 int nAdd = MIN(nNew,iOld-iNew);
66511 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
66512 pCellptr = pPg->aCellIdx;
66513 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
66514 if( pageInsertArray(
66515 pPg, pBegin, &pData, pCellptr,
66516 iNew, nAdd, pCArray
66517 ) ) goto editpage_fail;
66518 nCell += nAdd;
66521 /* Add any overflow cells */
66522 for(i=0; i<pPg->nOverflow; i++){
66523 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
66524 if( iCell>=0 && iCell<nNew ){
66525 pCellptr = &pPg->aCellIdx[iCell * 2];
66526 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
66527 nCell++;
66528 if( pageInsertArray(
66529 pPg, pBegin, &pData, pCellptr,
66530 iCell+iNew, 1, pCArray
66531 ) ) goto editpage_fail;
66535 /* Append cells to the end of the page */
66536 pCellptr = &pPg->aCellIdx[nCell*2];
66537 if( pageInsertArray(
66538 pPg, pBegin, &pData, pCellptr,
66539 iNew+nCell, nNew-nCell, pCArray
66540 ) ) goto editpage_fail;
66542 pPg->nCell = nNew;
66543 pPg->nOverflow = 0;
66545 put2byte(&aData[hdr+3], pPg->nCell);
66546 put2byte(&aData[hdr+5], pData - aData);
66548 #ifdef SQLITE_DEBUG
66549 for(i=0; i<nNew && !CORRUPT_DB; i++){
66550 u8 *pCell = pCArray->apCell[i+iNew];
66551 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
66552 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
66553 pCell = &pTmp[pCell - aData];
66555 assert( 0==memcmp(pCell, &aData[iOff],
66556 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
66558 #endif
66560 return SQLITE_OK;
66561 editpage_fail:
66562 /* Unable to edit this page. Rebuild it from scratch instead. */
66563 populateCellCache(pCArray, iNew, nNew);
66564 return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
66568 ** The following parameters determine how many adjacent pages get involved
66569 ** in a balancing operation. NN is the number of neighbors on either side
66570 ** of the page that participate in the balancing operation. NB is the
66571 ** total number of pages that participate, including the target page and
66572 ** NN neighbors on either side.
66574 ** The minimum value of NN is 1 (of course). Increasing NN above 1
66575 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
66576 ** in exchange for a larger degradation in INSERT and UPDATE performance.
66577 ** The value of NN appears to give the best results overall.
66579 #define NN 1 /* Number of neighbors on either side of pPage */
66580 #define NB (NN*2+1) /* Total pages involved in the balance */
66583 #ifndef SQLITE_OMIT_QUICKBALANCE
66585 ** This version of balance() handles the common special case where
66586 ** a new entry is being inserted on the extreme right-end of the
66587 ** tree, in other words, when the new entry will become the largest
66588 ** entry in the tree.
66590 ** Instead of trying to balance the 3 right-most leaf pages, just add
66591 ** a new page to the right-hand side and put the one new entry in
66592 ** that page. This leaves the right side of the tree somewhat
66593 ** unbalanced. But odds are that we will be inserting new entries
66594 ** at the end soon afterwards so the nearly empty page will quickly
66595 ** fill up. On average.
66597 ** pPage is the leaf page which is the right-most page in the tree.
66598 ** pParent is its parent. pPage must have a single overflow entry
66599 ** which is also the right-most entry on the page.
66601 ** The pSpace buffer is used to store a temporary copy of the divider
66602 ** cell that will be inserted into pParent. Such a cell consists of a 4
66603 ** byte page number followed by a variable length integer. In other
66604 ** words, at most 13 bytes. Hence the pSpace buffer must be at
66605 ** least 13 bytes in size.
66607 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
66608 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
66609 MemPage *pNew; /* Newly allocated page */
66610 int rc; /* Return Code */
66611 Pgno pgnoNew; /* Page number of pNew */
66613 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
66614 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
66615 assert( pPage->nOverflow==1 );
66617 /* This error condition is now caught prior to reaching this function */
66618 if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
66620 /* Allocate a new page. This page will become the right-sibling of
66621 ** pPage. Make the parent page writable, so that the new divider cell
66622 ** may be inserted. If both these operations are successful, proceed.
66624 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
66626 if( rc==SQLITE_OK ){
66628 u8 *pOut = &pSpace[4];
66629 u8 *pCell = pPage->apOvfl[0];
66630 u16 szCell = pPage->xCellSize(pPage, pCell);
66631 u8 *pStop;
66633 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
66634 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
66635 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
66636 rc = rebuildPage(pNew, 1, &pCell, &szCell);
66637 if( NEVER(rc) ) return rc;
66638 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
66640 /* If this is an auto-vacuum database, update the pointer map
66641 ** with entries for the new page, and any pointer from the
66642 ** cell on the page to an overflow page. If either of these
66643 ** operations fails, the return code is set, but the contents
66644 ** of the parent page are still manipulated by thh code below.
66645 ** That is Ok, at this point the parent page is guaranteed to
66646 ** be marked as dirty. Returning an error code will cause a
66647 ** rollback, undoing any changes made to the parent page.
66649 if( ISAUTOVACUUM ){
66650 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
66651 if( szCell>pNew->minLocal ){
66652 ptrmapPutOvflPtr(pNew, pCell, &rc);
66656 /* Create a divider cell to insert into pParent. The divider cell
66657 ** consists of a 4-byte page number (the page number of pPage) and
66658 ** a variable length key value (which must be the same value as the
66659 ** largest key on pPage).
66661 ** To find the largest key value on pPage, first find the right-most
66662 ** cell on pPage. The first two fields of this cell are the
66663 ** record-length (a variable length integer at most 32-bits in size)
66664 ** and the key value (a variable length integer, may have any value).
66665 ** The first of the while(...) loops below skips over the record-length
66666 ** field. The second while(...) loop copies the key value from the
66667 ** cell on pPage into the pSpace buffer.
66669 pCell = findCell(pPage, pPage->nCell-1);
66670 pStop = &pCell[9];
66671 while( (*(pCell++)&0x80) && pCell<pStop );
66672 pStop = &pCell[9];
66673 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
66675 /* Insert the new divider cell into pParent. */
66676 if( rc==SQLITE_OK ){
66677 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
66678 0, pPage->pgno, &rc);
66681 /* Set the right-child pointer of pParent to point to the new page. */
66682 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
66684 /* Release the reference to the new page. */
66685 releasePage(pNew);
66688 return rc;
66690 #endif /* SQLITE_OMIT_QUICKBALANCE */
66692 #if 0
66694 ** This function does not contribute anything to the operation of SQLite.
66695 ** it is sometimes activated temporarily while debugging code responsible
66696 ** for setting pointer-map entries.
66698 static int ptrmapCheckPages(MemPage **apPage, int nPage){
66699 int i, j;
66700 for(i=0; i<nPage; i++){
66701 Pgno n;
66702 u8 e;
66703 MemPage *pPage = apPage[i];
66704 BtShared *pBt = pPage->pBt;
66705 assert( pPage->isInit );
66707 for(j=0; j<pPage->nCell; j++){
66708 CellInfo info;
66709 u8 *z;
66711 z = findCell(pPage, j);
66712 pPage->xParseCell(pPage, z, &info);
66713 if( info.nLocal<info.nPayload ){
66714 Pgno ovfl = get4byte(&z[info.nSize-4]);
66715 ptrmapGet(pBt, ovfl, &e, &n);
66716 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
66718 if( !pPage->leaf ){
66719 Pgno child = get4byte(z);
66720 ptrmapGet(pBt, child, &e, &n);
66721 assert( n==pPage->pgno && e==PTRMAP_BTREE );
66724 if( !pPage->leaf ){
66725 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
66726 ptrmapGet(pBt, child, &e, &n);
66727 assert( n==pPage->pgno && e==PTRMAP_BTREE );
66730 return 1;
66732 #endif
66735 ** This function is used to copy the contents of the b-tree node stored
66736 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
66737 ** the pointer-map entries for each child page are updated so that the
66738 ** parent page stored in the pointer map is page pTo. If pFrom contained
66739 ** any cells with overflow page pointers, then the corresponding pointer
66740 ** map entries are also updated so that the parent page is page pTo.
66742 ** If pFrom is currently carrying any overflow cells (entries in the
66743 ** MemPage.apOvfl[] array), they are not copied to pTo.
66745 ** Before returning, page pTo is reinitialized using btreeInitPage().
66747 ** The performance of this function is not critical. It is only used by
66748 ** the balance_shallower() and balance_deeper() procedures, neither of
66749 ** which are called often under normal circumstances.
66751 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
66752 if( (*pRC)==SQLITE_OK ){
66753 BtShared * const pBt = pFrom->pBt;
66754 u8 * const aFrom = pFrom->aData;
66755 u8 * const aTo = pTo->aData;
66756 int const iFromHdr = pFrom->hdrOffset;
66757 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
66758 int rc;
66759 int iData;
66762 assert( pFrom->isInit );
66763 assert( pFrom->nFree>=iToHdr );
66764 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
66766 /* Copy the b-tree node content from page pFrom to page pTo. */
66767 iData = get2byte(&aFrom[iFromHdr+5]);
66768 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
66769 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
66771 /* Reinitialize page pTo so that the contents of the MemPage structure
66772 ** match the new data. The initialization of pTo can actually fail under
66773 ** fairly obscure circumstances, even though it is a copy of initialized
66774 ** page pFrom.
66776 pTo->isInit = 0;
66777 rc = btreeInitPage(pTo);
66778 if( rc!=SQLITE_OK ){
66779 *pRC = rc;
66780 return;
66783 /* If this is an auto-vacuum database, update the pointer-map entries
66784 ** for any b-tree or overflow pages that pTo now contains the pointers to.
66786 if( ISAUTOVACUUM ){
66787 *pRC = setChildPtrmaps(pTo);
66793 ** This routine redistributes cells on the iParentIdx'th child of pParent
66794 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
66795 ** same amount of free space. Usually a single sibling on either side of the
66796 ** page are used in the balancing, though both siblings might come from one
66797 ** side if the page is the first or last child of its parent. If the page
66798 ** has fewer than 2 siblings (something which can only happen if the page
66799 ** is a root page or a child of a root page) then all available siblings
66800 ** participate in the balancing.
66802 ** The number of siblings of the page might be increased or decreased by
66803 ** one or two in an effort to keep pages nearly full but not over full.
66805 ** Note that when this routine is called, some of the cells on the page
66806 ** might not actually be stored in MemPage.aData[]. This can happen
66807 ** if the page is overfull. This routine ensures that all cells allocated
66808 ** to the page and its siblings fit into MemPage.aData[] before returning.
66810 ** In the course of balancing the page and its siblings, cells may be
66811 ** inserted into or removed from the parent page (pParent). Doing so
66812 ** may cause the parent page to become overfull or underfull. If this
66813 ** happens, it is the responsibility of the caller to invoke the correct
66814 ** balancing routine to fix this problem (see the balance() routine).
66816 ** If this routine fails for any reason, it might leave the database
66817 ** in a corrupted state. So if this routine fails, the database should
66818 ** be rolled back.
66820 ** The third argument to this function, aOvflSpace, is a pointer to a
66821 ** buffer big enough to hold one page. If while inserting cells into the parent
66822 ** page (pParent) the parent page becomes overfull, this buffer is
66823 ** used to store the parent's overflow cells. Because this function inserts
66824 ** a maximum of four divider cells into the parent page, and the maximum
66825 ** size of a cell stored within an internal node is always less than 1/4
66826 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
66827 ** enough for all overflow cells.
66829 ** If aOvflSpace is set to a null pointer, this function returns
66830 ** SQLITE_NOMEM.
66832 static int balance_nonroot(
66833 MemPage *pParent, /* Parent page of siblings being balanced */
66834 int iParentIdx, /* Index of "the page" in pParent */
66835 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
66836 int isRoot, /* True if pParent is a root-page */
66837 int bBulk /* True if this call is part of a bulk load */
66839 BtShared *pBt; /* The whole database */
66840 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
66841 int nNew = 0; /* Number of pages in apNew[] */
66842 int nOld; /* Number of pages in apOld[] */
66843 int i, j, k; /* Loop counters */
66844 int nxDiv; /* Next divider slot in pParent->aCell[] */
66845 int rc = SQLITE_OK; /* The return code */
66846 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
66847 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
66848 int usableSpace; /* Bytes in pPage beyond the header */
66849 int pageFlags; /* Value of pPage->aData[0] */
66850 int iSpace1 = 0; /* First unused byte of aSpace1[] */
66851 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
66852 int szScratch; /* Size of scratch memory requested */
66853 MemPage *apOld[NB]; /* pPage and up to two siblings */
66854 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
66855 u8 *pRight; /* Location in parent of right-sibling pointer */
66856 u8 *apDiv[NB-1]; /* Divider cells in pParent */
66857 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
66858 int cntOld[NB+2]; /* Old index in b.apCell[] */
66859 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
66860 u8 *aSpace1; /* Space for copies of dividers cells */
66861 Pgno pgno; /* Temp var to store a page number in */
66862 u8 abDone[NB+2]; /* True after i'th new page is populated */
66863 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
66864 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
66865 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
66866 CellArray b; /* Parsed information on cells being balanced */
66868 memset(abDone, 0, sizeof(abDone));
66869 b.nCell = 0;
66870 b.apCell = 0;
66871 pBt = pParent->pBt;
66872 assert( sqlite3_mutex_held(pBt->mutex) );
66873 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
66875 #if 0
66876 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
66877 #endif
66879 /* At this point pParent may have at most one overflow cell. And if
66880 ** this overflow cell is present, it must be the cell with
66881 ** index iParentIdx. This scenario comes about when this function
66882 ** is called (indirectly) from sqlite3BtreeDelete().
66884 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
66885 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
66887 if( !aOvflSpace ){
66888 return SQLITE_NOMEM_BKPT;
66891 /* Find the sibling pages to balance. Also locate the cells in pParent
66892 ** that divide the siblings. An attempt is made to find NN siblings on
66893 ** either side of pPage. More siblings are taken from one side, however,
66894 ** if there are fewer than NN siblings on the other side. If pParent
66895 ** has NB or fewer children then all children of pParent are taken.
66897 ** This loop also drops the divider cells from the parent page. This
66898 ** way, the remainder of the function does not have to deal with any
66899 ** overflow cells in the parent page, since if any existed they will
66900 ** have already been removed.
66902 i = pParent->nOverflow + pParent->nCell;
66903 if( i<2 ){
66904 nxDiv = 0;
66905 }else{
66906 assert( bBulk==0 || bBulk==1 );
66907 if( iParentIdx==0 ){
66908 nxDiv = 0;
66909 }else if( iParentIdx==i ){
66910 nxDiv = i-2+bBulk;
66911 }else{
66912 nxDiv = iParentIdx-1;
66914 i = 2-bBulk;
66916 nOld = i+1;
66917 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
66918 pRight = &pParent->aData[pParent->hdrOffset+8];
66919 }else{
66920 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
66922 pgno = get4byte(pRight);
66923 while( 1 ){
66924 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
66925 if( rc ){
66926 memset(apOld, 0, (i+1)*sizeof(MemPage*));
66927 goto balance_cleanup;
66929 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
66930 if( (i--)==0 ) break;
66932 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
66933 apDiv[i] = pParent->apOvfl[0];
66934 pgno = get4byte(apDiv[i]);
66935 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
66936 pParent->nOverflow = 0;
66937 }else{
66938 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
66939 pgno = get4byte(apDiv[i]);
66940 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
66942 /* Drop the cell from the parent page. apDiv[i] still points to
66943 ** the cell within the parent, even though it has been dropped.
66944 ** This is safe because dropping a cell only overwrites the first
66945 ** four bytes of it, and this function does not need the first
66946 ** four bytes of the divider cell. So the pointer is safe to use
66947 ** later on.
66949 ** But not if we are in secure-delete mode. In secure-delete mode,
66950 ** the dropCell() routine will overwrite the entire cell with zeroes.
66951 ** In this case, temporarily copy the cell into the aOvflSpace[]
66952 ** buffer. It will be copied out again as soon as the aSpace[] buffer
66953 ** is allocated. */
66954 if( pBt->btsFlags & BTS_FAST_SECURE ){
66955 int iOff;
66957 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
66958 if( (iOff+szNew[i])>(int)pBt->usableSize ){
66959 rc = SQLITE_CORRUPT_BKPT;
66960 memset(apOld, 0, (i+1)*sizeof(MemPage*));
66961 goto balance_cleanup;
66962 }else{
66963 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
66964 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
66967 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
66971 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
66972 ** alignment */
66973 nMaxCells = (nMaxCells + 3)&~3;
66976 ** Allocate space for memory structures
66978 szScratch =
66979 nMaxCells*sizeof(u8*) /* b.apCell */
66980 + nMaxCells*sizeof(u16) /* b.szCell */
66981 + pBt->pageSize; /* aSpace1 */
66983 assert( szScratch<=6*(int)pBt->pageSize );
66984 b.apCell = sqlite3StackAllocRaw(0, szScratch );
66985 if( b.apCell==0 ){
66986 rc = SQLITE_NOMEM_BKPT;
66987 goto balance_cleanup;
66989 b.szCell = (u16*)&b.apCell[nMaxCells];
66990 aSpace1 = (u8*)&b.szCell[nMaxCells];
66991 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
66994 ** Load pointers to all cells on sibling pages and the divider cells
66995 ** into the local b.apCell[] array. Make copies of the divider cells
66996 ** into space obtained from aSpace1[]. The divider cells have already
66997 ** been removed from pParent.
66999 ** If the siblings are on leaf pages, then the child pointers of the
67000 ** divider cells are stripped from the cells before they are copied
67001 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
67002 ** child pointers. If siblings are not leaves, then all cell in
67003 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
67004 ** are alike.
67006 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
67007 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
67009 b.pRef = apOld[0];
67010 leafCorrection = b.pRef->leaf*4;
67011 leafData = b.pRef->intKeyLeaf;
67012 for(i=0; i<nOld; i++){
67013 MemPage *pOld = apOld[i];
67014 int limit = pOld->nCell;
67015 u8 *aData = pOld->aData;
67016 u16 maskPage = pOld->maskPage;
67017 u8 *piCell = aData + pOld->cellOffset;
67018 u8 *piEnd;
67020 /* Verify that all sibling pages are of the same "type" (table-leaf,
67021 ** table-interior, index-leaf, or index-interior).
67023 if( pOld->aData[0]!=apOld[0]->aData[0] ){
67024 rc = SQLITE_CORRUPT_BKPT;
67025 goto balance_cleanup;
67028 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
67029 ** constains overflow cells, include them in the b.apCell[] array
67030 ** in the correct spot.
67032 ** Note that when there are multiple overflow cells, it is always the
67033 ** case that they are sequential and adjacent. This invariant arises
67034 ** because multiple overflows can only occurs when inserting divider
67035 ** cells into a parent on a prior balance, and divider cells are always
67036 ** adjacent and are inserted in order. There is an assert() tagged
67037 ** with "NOTE 1" in the overflow cell insertion loop to prove this
67038 ** invariant.
67040 ** This must be done in advance. Once the balance starts, the cell
67041 ** offset section of the btree page will be overwritten and we will no
67042 ** long be able to find the cells if a pointer to each cell is not saved
67043 ** first.
67045 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
67046 if( pOld->nOverflow>0 ){
67047 limit = pOld->aiOvfl[0];
67048 for(j=0; j<limit; j++){
67049 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
67050 piCell += 2;
67051 b.nCell++;
67053 for(k=0; k<pOld->nOverflow; k++){
67054 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
67055 b.apCell[b.nCell] = pOld->apOvfl[k];
67056 b.nCell++;
67059 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
67060 while( piCell<piEnd ){
67061 assert( b.nCell<nMaxCells );
67062 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
67063 piCell += 2;
67064 b.nCell++;
67067 cntOld[i] = b.nCell;
67068 if( i<nOld-1 && !leafData){
67069 u16 sz = (u16)szNew[i];
67070 u8 *pTemp;
67071 assert( b.nCell<nMaxCells );
67072 b.szCell[b.nCell] = sz;
67073 pTemp = &aSpace1[iSpace1];
67074 iSpace1 += sz;
67075 assert( sz<=pBt->maxLocal+23 );
67076 assert( iSpace1 <= (int)pBt->pageSize );
67077 memcpy(pTemp, apDiv[i], sz);
67078 b.apCell[b.nCell] = pTemp+leafCorrection;
67079 assert( leafCorrection==0 || leafCorrection==4 );
67080 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
67081 if( !pOld->leaf ){
67082 assert( leafCorrection==0 );
67083 assert( pOld->hdrOffset==0 );
67084 /* The right pointer of the child page pOld becomes the left
67085 ** pointer of the divider cell */
67086 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
67087 }else{
67088 assert( leafCorrection==4 );
67089 while( b.szCell[b.nCell]<4 ){
67090 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
67091 ** does exist, pad it with 0x00 bytes. */
67092 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
67093 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
67094 aSpace1[iSpace1++] = 0x00;
67095 b.szCell[b.nCell]++;
67098 b.nCell++;
67103 ** Figure out the number of pages needed to hold all b.nCell cells.
67104 ** Store this number in "k". Also compute szNew[] which is the total
67105 ** size of all cells on the i-th page and cntNew[] which is the index
67106 ** in b.apCell[] of the cell that divides page i from page i+1.
67107 ** cntNew[k] should equal b.nCell.
67109 ** Values computed by this block:
67111 ** k: The total number of sibling pages
67112 ** szNew[i]: Spaced used on the i-th sibling page.
67113 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
67114 ** the right of the i-th sibling page.
67115 ** usableSpace: Number of bytes of space available on each sibling.
67118 usableSpace = pBt->usableSize - 12 + leafCorrection;
67119 for(i=0; i<nOld; i++){
67120 MemPage *p = apOld[i];
67121 szNew[i] = usableSpace - p->nFree;
67122 for(j=0; j<p->nOverflow; j++){
67123 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
67125 cntNew[i] = cntOld[i];
67127 k = nOld;
67128 for(i=0; i<k; i++){
67129 int sz;
67130 while( szNew[i]>usableSpace ){
67131 if( i+1>=k ){
67132 k = i+2;
67133 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
67134 szNew[k-1] = 0;
67135 cntNew[k-1] = b.nCell;
67137 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
67138 szNew[i] -= sz;
67139 if( !leafData ){
67140 if( cntNew[i]<b.nCell ){
67141 sz = 2 + cachedCellSize(&b, cntNew[i]);
67142 }else{
67143 sz = 0;
67146 szNew[i+1] += sz;
67147 cntNew[i]--;
67149 while( cntNew[i]<b.nCell ){
67150 sz = 2 + cachedCellSize(&b, cntNew[i]);
67151 if( szNew[i]+sz>usableSpace ) break;
67152 szNew[i] += sz;
67153 cntNew[i]++;
67154 if( !leafData ){
67155 if( cntNew[i]<b.nCell ){
67156 sz = 2 + cachedCellSize(&b, cntNew[i]);
67157 }else{
67158 sz = 0;
67161 szNew[i+1] -= sz;
67163 if( cntNew[i]>=b.nCell ){
67164 k = i+1;
67165 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
67166 rc = SQLITE_CORRUPT_BKPT;
67167 goto balance_cleanup;
67172 ** The packing computed by the previous block is biased toward the siblings
67173 ** on the left side (siblings with smaller keys). The left siblings are
67174 ** always nearly full, while the right-most sibling might be nearly empty.
67175 ** The next block of code attempts to adjust the packing of siblings to
67176 ** get a better balance.
67178 ** This adjustment is more than an optimization. The packing above might
67179 ** be so out of balance as to be illegal. For example, the right-most
67180 ** sibling might be completely empty. This adjustment is not optional.
67182 for(i=k-1; i>0; i--){
67183 int szRight = szNew[i]; /* Size of sibling on the right */
67184 int szLeft = szNew[i-1]; /* Size of sibling on the left */
67185 int r; /* Index of right-most cell in left sibling */
67186 int d; /* Index of first cell to the left of right sibling */
67188 r = cntNew[i-1] - 1;
67189 d = r + 1 - leafData;
67190 (void)cachedCellSize(&b, d);
67192 assert( d<nMaxCells );
67193 assert( r<nMaxCells );
67194 (void)cachedCellSize(&b, r);
67195 if( szRight!=0
67196 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
67197 break;
67199 szRight += b.szCell[d] + 2;
67200 szLeft -= b.szCell[r] + 2;
67201 cntNew[i-1] = r;
67202 r--;
67203 d--;
67204 }while( r>=0 );
67205 szNew[i] = szRight;
67206 szNew[i-1] = szLeft;
67207 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
67208 rc = SQLITE_CORRUPT_BKPT;
67209 goto balance_cleanup;
67213 /* Sanity check: For a non-corrupt database file one of the follwing
67214 ** must be true:
67215 ** (1) We found one or more cells (cntNew[0])>0), or
67216 ** (2) pPage is a virtual root page. A virtual root page is when
67217 ** the real root page is page 1 and we are the only child of
67218 ** that page.
67220 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
67221 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
67222 apOld[0]->pgno, apOld[0]->nCell,
67223 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
67224 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
67228 ** Allocate k new pages. Reuse old pages where possible.
67230 pageFlags = apOld[0]->aData[0];
67231 for(i=0; i<k; i++){
67232 MemPage *pNew;
67233 if( i<nOld ){
67234 pNew = apNew[i] = apOld[i];
67235 apOld[i] = 0;
67236 rc = sqlite3PagerWrite(pNew->pDbPage);
67237 nNew++;
67238 if( rc ) goto balance_cleanup;
67239 }else{
67240 assert( i>0 );
67241 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
67242 if( rc ) goto balance_cleanup;
67243 zeroPage(pNew, pageFlags);
67244 apNew[i] = pNew;
67245 nNew++;
67246 cntOld[i] = b.nCell;
67248 /* Set the pointer-map entry for the new sibling page. */
67249 if( ISAUTOVACUUM ){
67250 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
67251 if( rc!=SQLITE_OK ){
67252 goto balance_cleanup;
67259 ** Reassign page numbers so that the new pages are in ascending order.
67260 ** This helps to keep entries in the disk file in order so that a scan
67261 ** of the table is closer to a linear scan through the file. That in turn
67262 ** helps the operating system to deliver pages from the disk more rapidly.
67264 ** An O(n^2) insertion sort algorithm is used, but since n is never more
67265 ** than (NB+2) (a small constant), that should not be a problem.
67267 ** When NB==3, this one optimization makes the database about 25% faster
67268 ** for large insertions and deletions.
67270 for(i=0; i<nNew; i++){
67271 aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
67272 aPgFlags[i] = apNew[i]->pDbPage->flags;
67273 for(j=0; j<i; j++){
67274 if( aPgno[j]==aPgno[i] ){
67275 /* This branch is taken if the set of sibling pages somehow contains
67276 ** duplicate entries. This can happen if the database is corrupt.
67277 ** It would be simpler to detect this as part of the loop below, but
67278 ** we do the detection here in order to avoid populating the pager
67279 ** cache with two separate objects associated with the same
67280 ** page number. */
67281 assert( CORRUPT_DB );
67282 rc = SQLITE_CORRUPT_BKPT;
67283 goto balance_cleanup;
67287 for(i=0; i<nNew; i++){
67288 int iBest = 0; /* aPgno[] index of page number to use */
67289 for(j=1; j<nNew; j++){
67290 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
67292 pgno = aPgOrder[iBest];
67293 aPgOrder[iBest] = 0xffffffff;
67294 if( iBest!=i ){
67295 if( iBest>i ){
67296 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
67298 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
67299 apNew[i]->pgno = pgno;
67303 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
67304 "%d(%d nc=%d) %d(%d nc=%d)\n",
67305 apNew[0]->pgno, szNew[0], cntNew[0],
67306 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
67307 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
67308 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
67309 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
67310 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
67311 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
67312 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
67313 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
67316 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
67317 put4byte(pRight, apNew[nNew-1]->pgno);
67319 /* If the sibling pages are not leaves, ensure that the right-child pointer
67320 ** of the right-most new sibling page is set to the value that was
67321 ** originally in the same field of the right-most old sibling page. */
67322 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
67323 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
67324 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
67327 /* Make any required updates to pointer map entries associated with
67328 ** cells stored on sibling pages following the balance operation. Pointer
67329 ** map entries associated with divider cells are set by the insertCell()
67330 ** routine. The associated pointer map entries are:
67332 ** a) if the cell contains a reference to an overflow chain, the
67333 ** entry associated with the first page in the overflow chain, and
67335 ** b) if the sibling pages are not leaves, the child page associated
67336 ** with the cell.
67338 ** If the sibling pages are not leaves, then the pointer map entry
67339 ** associated with the right-child of each sibling may also need to be
67340 ** updated. This happens below, after the sibling pages have been
67341 ** populated, not here.
67343 if( ISAUTOVACUUM ){
67344 MemPage *pNew = apNew[0];
67345 u8 *aOld = pNew->aData;
67346 int cntOldNext = pNew->nCell + pNew->nOverflow;
67347 int usableSize = pBt->usableSize;
67348 int iNew = 0;
67349 int iOld = 0;
67351 for(i=0; i<b.nCell; i++){
67352 u8 *pCell = b.apCell[i];
67353 if( i==cntOldNext ){
67354 MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
67355 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
67356 aOld = pOld->aData;
67358 if( i==cntNew[iNew] ){
67359 pNew = apNew[++iNew];
67360 if( !leafData ) continue;
67363 /* Cell pCell is destined for new sibling page pNew. Originally, it
67364 ** was either part of sibling page iOld (possibly an overflow cell),
67365 ** or else the divider cell to the left of sibling page iOld. So,
67366 ** if sibling page iOld had the same page number as pNew, and if
67367 ** pCell really was a part of sibling page iOld (not a divider or
67368 ** overflow cell), we can skip updating the pointer map entries. */
67369 if( iOld>=nNew
67370 || pNew->pgno!=aPgno[iOld]
67371 || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
67373 if( !leafCorrection ){
67374 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
67376 if( cachedCellSize(&b,i)>pNew->minLocal ){
67377 ptrmapPutOvflPtr(pNew, pCell, &rc);
67379 if( rc ) goto balance_cleanup;
67384 /* Insert new divider cells into pParent. */
67385 for(i=0; i<nNew-1; i++){
67386 u8 *pCell;
67387 u8 *pTemp;
67388 int sz;
67389 MemPage *pNew = apNew[i];
67390 j = cntNew[i];
67392 assert( j<nMaxCells );
67393 assert( b.apCell[j]!=0 );
67394 pCell = b.apCell[j];
67395 sz = b.szCell[j] + leafCorrection;
67396 pTemp = &aOvflSpace[iOvflSpace];
67397 if( !pNew->leaf ){
67398 memcpy(&pNew->aData[8], pCell, 4);
67399 }else if( leafData ){
67400 /* If the tree is a leaf-data tree, and the siblings are leaves,
67401 ** then there is no divider cell in b.apCell[]. Instead, the divider
67402 ** cell consists of the integer key for the right-most cell of
67403 ** the sibling-page assembled above only.
67405 CellInfo info;
67406 j--;
67407 pNew->xParseCell(pNew, b.apCell[j], &info);
67408 pCell = pTemp;
67409 sz = 4 + putVarint(&pCell[4], info.nKey);
67410 pTemp = 0;
67411 }else{
67412 pCell -= 4;
67413 /* Obscure case for non-leaf-data trees: If the cell at pCell was
67414 ** previously stored on a leaf node, and its reported size was 4
67415 ** bytes, then it may actually be smaller than this
67416 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
67417 ** any cell). But it is important to pass the correct size to
67418 ** insertCell(), so reparse the cell now.
67420 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
67421 ** and WITHOUT ROWID tables with exactly one column which is the
67422 ** primary key.
67424 if( b.szCell[j]==4 ){
67425 assert(leafCorrection==4);
67426 sz = pParent->xCellSize(pParent, pCell);
67429 iOvflSpace += sz;
67430 assert( sz<=pBt->maxLocal+23 );
67431 assert( iOvflSpace <= (int)pBt->pageSize );
67432 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
67433 if( rc!=SQLITE_OK ) goto balance_cleanup;
67434 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
67437 /* Now update the actual sibling pages. The order in which they are updated
67438 ** is important, as this code needs to avoid disrupting any page from which
67439 ** cells may still to be read. In practice, this means:
67441 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
67442 ** then it is not safe to update page apNew[iPg] until after
67443 ** the left-hand sibling apNew[iPg-1] has been updated.
67445 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
67446 ** then it is not safe to update page apNew[iPg] until after
67447 ** the right-hand sibling apNew[iPg+1] has been updated.
67449 ** If neither of the above apply, the page is safe to update.
67451 ** The iPg value in the following loop starts at nNew-1 goes down
67452 ** to 0, then back up to nNew-1 again, thus making two passes over
67453 ** the pages. On the initial downward pass, only condition (1) above
67454 ** needs to be tested because (2) will always be true from the previous
67455 ** step. On the upward pass, both conditions are always true, so the
67456 ** upwards pass simply processes pages that were missed on the downward
67457 ** pass.
67459 for(i=1-nNew; i<nNew; i++){
67460 int iPg = i<0 ? -i : i;
67461 assert( iPg>=0 && iPg<nNew );
67462 if( abDone[iPg] ) continue; /* Skip pages already processed */
67463 if( i>=0 /* On the upwards pass, or... */
67464 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
67466 int iNew;
67467 int iOld;
67468 int nNewCell;
67470 /* Verify condition (1): If cells are moving left, update iPg
67471 ** only after iPg-1 has already been updated. */
67472 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
67474 /* Verify condition (2): If cells are moving right, update iPg
67475 ** only after iPg+1 has already been updated. */
67476 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
67478 if( iPg==0 ){
67479 iNew = iOld = 0;
67480 nNewCell = cntNew[0];
67481 }else{
67482 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
67483 iNew = cntNew[iPg-1] + !leafData;
67484 nNewCell = cntNew[iPg] - iNew;
67487 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
67488 if( rc ) goto balance_cleanup;
67489 abDone[iPg]++;
67490 apNew[iPg]->nFree = usableSpace-szNew[iPg];
67491 assert( apNew[iPg]->nOverflow==0 );
67492 assert( apNew[iPg]->nCell==nNewCell );
67496 /* All pages have been processed exactly once */
67497 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
67499 assert( nOld>0 );
67500 assert( nNew>0 );
67502 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
67503 /* The root page of the b-tree now contains no cells. The only sibling
67504 ** page is the right-child of the parent. Copy the contents of the
67505 ** child page into the parent, decreasing the overall height of the
67506 ** b-tree structure by one. This is described as the "balance-shallower"
67507 ** sub-algorithm in some documentation.
67509 ** If this is an auto-vacuum database, the call to copyNodeContent()
67510 ** sets all pointer-map entries corresponding to database image pages
67511 ** for which the pointer is stored within the content being copied.
67513 ** It is critical that the child page be defragmented before being
67514 ** copied into the parent, because if the parent is page 1 then it will
67515 ** by smaller than the child due to the database header, and so all the
67516 ** free space needs to be up front.
67518 assert( nNew==1 || CORRUPT_DB );
67519 rc = defragmentPage(apNew[0], -1);
67520 testcase( rc!=SQLITE_OK );
67521 assert( apNew[0]->nFree ==
67522 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
67523 || rc!=SQLITE_OK
67525 copyNodeContent(apNew[0], pParent, &rc);
67526 freePage(apNew[0], &rc);
67527 }else if( ISAUTOVACUUM && !leafCorrection ){
67528 /* Fix the pointer map entries associated with the right-child of each
67529 ** sibling page. All other pointer map entries have already been taken
67530 ** care of. */
67531 for(i=0; i<nNew; i++){
67532 u32 key = get4byte(&apNew[i]->aData[8]);
67533 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
67537 assert( pParent->isInit );
67538 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
67539 nOld, nNew, b.nCell));
67541 /* Free any old pages that were not reused as new pages.
67543 for(i=nNew; i<nOld; i++){
67544 freePage(apOld[i], &rc);
67547 #if 0
67548 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
67549 /* The ptrmapCheckPages() contains assert() statements that verify that
67550 ** all pointer map pages are set correctly. This is helpful while
67551 ** debugging. This is usually disabled because a corrupt database may
67552 ** cause an assert() statement to fail. */
67553 ptrmapCheckPages(apNew, nNew);
67554 ptrmapCheckPages(&pParent, 1);
67556 #endif
67559 ** Cleanup before returning.
67561 balance_cleanup:
67562 sqlite3StackFree(0, b.apCell);
67563 for(i=0; i<nOld; i++){
67564 releasePage(apOld[i]);
67566 for(i=0; i<nNew; i++){
67567 releasePage(apNew[i]);
67570 return rc;
67575 ** This function is called when the root page of a b-tree structure is
67576 ** overfull (has one or more overflow pages).
67578 ** A new child page is allocated and the contents of the current root
67579 ** page, including overflow cells, are copied into the child. The root
67580 ** page is then overwritten to make it an empty page with the right-child
67581 ** pointer pointing to the new page.
67583 ** Before returning, all pointer-map entries corresponding to pages
67584 ** that the new child-page now contains pointers to are updated. The
67585 ** entry corresponding to the new right-child pointer of the root
67586 ** page is also updated.
67588 ** If successful, *ppChild is set to contain a reference to the child
67589 ** page and SQLITE_OK is returned. In this case the caller is required
67590 ** to call releasePage() on *ppChild exactly once. If an error occurs,
67591 ** an error code is returned and *ppChild is set to 0.
67593 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
67594 int rc; /* Return value from subprocedures */
67595 MemPage *pChild = 0; /* Pointer to a new child page */
67596 Pgno pgnoChild = 0; /* Page number of the new child page */
67597 BtShared *pBt = pRoot->pBt; /* The BTree */
67599 assert( pRoot->nOverflow>0 );
67600 assert( sqlite3_mutex_held(pBt->mutex) );
67602 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
67603 ** page that will become the new right-child of pPage. Copy the contents
67604 ** of the node stored on pRoot into the new child page.
67606 rc = sqlite3PagerWrite(pRoot->pDbPage);
67607 if( rc==SQLITE_OK ){
67608 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
67609 copyNodeContent(pRoot, pChild, &rc);
67610 if( ISAUTOVACUUM ){
67611 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
67614 if( rc ){
67615 *ppChild = 0;
67616 releasePage(pChild);
67617 return rc;
67619 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
67620 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
67621 assert( pChild->nCell==pRoot->nCell );
67623 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
67625 /* Copy the overflow cells from pRoot to pChild */
67626 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
67627 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
67628 memcpy(pChild->apOvfl, pRoot->apOvfl,
67629 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
67630 pChild->nOverflow = pRoot->nOverflow;
67632 /* Zero the contents of pRoot. Then install pChild as the right-child. */
67633 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
67634 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
67636 *ppChild = pChild;
67637 return SQLITE_OK;
67641 ** The page that pCur currently points to has just been modified in
67642 ** some way. This function figures out if this modification means the
67643 ** tree needs to be balanced, and if so calls the appropriate balancing
67644 ** routine. Balancing routines are:
67646 ** balance_quick()
67647 ** balance_deeper()
67648 ** balance_nonroot()
67650 static int balance(BtCursor *pCur){
67651 int rc = SQLITE_OK;
67652 const int nMin = pCur->pBt->usableSize * 2 / 3;
67653 u8 aBalanceQuickSpace[13];
67654 u8 *pFree = 0;
67656 VVA_ONLY( int balance_quick_called = 0 );
67657 VVA_ONLY( int balance_deeper_called = 0 );
67659 do {
67660 int iPage = pCur->iPage;
67661 MemPage *pPage = pCur->pPage;
67663 if( iPage==0 ){
67664 if( pPage->nOverflow ){
67665 /* The root page of the b-tree is overfull. In this case call the
67666 ** balance_deeper() function to create a new child for the root-page
67667 ** and copy the current contents of the root-page to it. The
67668 ** next iteration of the do-loop will balance the child page.
67670 assert( balance_deeper_called==0 );
67671 VVA_ONLY( balance_deeper_called++ );
67672 rc = balance_deeper(pPage, &pCur->apPage[1]);
67673 if( rc==SQLITE_OK ){
67674 pCur->iPage = 1;
67675 pCur->ix = 0;
67676 pCur->aiIdx[0] = 0;
67677 pCur->apPage[0] = pPage;
67678 pCur->pPage = pCur->apPage[1];
67679 assert( pCur->pPage->nOverflow );
67681 }else{
67682 break;
67684 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
67685 break;
67686 }else{
67687 MemPage * const pParent = pCur->apPage[iPage-1];
67688 int const iIdx = pCur->aiIdx[iPage-1];
67690 rc = sqlite3PagerWrite(pParent->pDbPage);
67691 if( rc==SQLITE_OK ){
67692 #ifndef SQLITE_OMIT_QUICKBALANCE
67693 if( pPage->intKeyLeaf
67694 && pPage->nOverflow==1
67695 && pPage->aiOvfl[0]==pPage->nCell
67696 && pParent->pgno!=1
67697 && pParent->nCell==iIdx
67699 /* Call balance_quick() to create a new sibling of pPage on which
67700 ** to store the overflow cell. balance_quick() inserts a new cell
67701 ** into pParent, which may cause pParent overflow. If this
67702 ** happens, the next iteration of the do-loop will balance pParent
67703 ** use either balance_nonroot() or balance_deeper(). Until this
67704 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
67705 ** buffer.
67707 ** The purpose of the following assert() is to check that only a
67708 ** single call to balance_quick() is made for each call to this
67709 ** function. If this were not verified, a subtle bug involving reuse
67710 ** of the aBalanceQuickSpace[] might sneak in.
67712 assert( balance_quick_called==0 );
67713 VVA_ONLY( balance_quick_called++ );
67714 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
67715 }else
67716 #endif
67718 /* In this case, call balance_nonroot() to redistribute cells
67719 ** between pPage and up to 2 of its sibling pages. This involves
67720 ** modifying the contents of pParent, which may cause pParent to
67721 ** become overfull or underfull. The next iteration of the do-loop
67722 ** will balance the parent page to correct this.
67724 ** If the parent page becomes overfull, the overflow cell or cells
67725 ** are stored in the pSpace buffer allocated immediately below.
67726 ** A subsequent iteration of the do-loop will deal with this by
67727 ** calling balance_nonroot() (balance_deeper() may be called first,
67728 ** but it doesn't deal with overflow cells - just moves them to a
67729 ** different page). Once this subsequent call to balance_nonroot()
67730 ** has completed, it is safe to release the pSpace buffer used by
67731 ** the previous call, as the overflow cell data will have been
67732 ** copied either into the body of a database page or into the new
67733 ** pSpace buffer passed to the latter call to balance_nonroot().
67735 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
67736 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
67737 pCur->hints&BTREE_BULKLOAD);
67738 if( pFree ){
67739 /* If pFree is not NULL, it points to the pSpace buffer used
67740 ** by a previous call to balance_nonroot(). Its contents are
67741 ** now stored either on real database pages or within the
67742 ** new pSpace buffer, so it may be safely freed here. */
67743 sqlite3PageFree(pFree);
67746 /* The pSpace buffer will be freed after the next call to
67747 ** balance_nonroot(), or just before this function returns, whichever
67748 ** comes first. */
67749 pFree = pSpace;
67753 pPage->nOverflow = 0;
67755 /* The next iteration of the do-loop balances the parent page. */
67756 releasePage(pPage);
67757 pCur->iPage--;
67758 assert( pCur->iPage>=0 );
67759 pCur->pPage = pCur->apPage[pCur->iPage];
67761 }while( rc==SQLITE_OK );
67763 if( pFree ){
67764 sqlite3PageFree(pFree);
67766 return rc;
67771 ** Insert a new record into the BTree. The content of the new record
67772 ** is described by the pX object. The pCur cursor is used only to
67773 ** define what table the record should be inserted into, and is left
67774 ** pointing at a random location.
67776 ** For a table btree (used for rowid tables), only the pX.nKey value of
67777 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
67778 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
67779 ** hold the content of the row.
67781 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
67782 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
67783 ** pX.pData,nData,nZero fields must be zero.
67785 ** If the seekResult parameter is non-zero, then a successful call to
67786 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
67787 ** been performed. In other words, if seekResult!=0 then the cursor
67788 ** is currently pointing to a cell that will be adjacent to the cell
67789 ** to be inserted. If seekResult<0 then pCur points to a cell that is
67790 ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
67791 ** that is larger than (pKey,nKey).
67793 ** If seekResult==0, that means pCur is pointing at some unknown location.
67794 ** In that case, this routine must seek the cursor to the correct insertion
67795 ** point for (pKey,nKey) before doing the insertion. For index btrees,
67796 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
67797 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
67798 ** to decode the key.
67800 SQLITE_PRIVATE int sqlite3BtreeInsert(
67801 BtCursor *pCur, /* Insert data into the table of this cursor */
67802 const BtreePayload *pX, /* Content of the row to be inserted */
67803 int flags, /* True if this is likely an append */
67804 int seekResult /* Result of prior MovetoUnpacked() call */
67806 int rc;
67807 int loc = seekResult; /* -1: before desired location +1: after */
67808 int szNew = 0;
67809 int idx;
67810 MemPage *pPage;
67811 Btree *p = pCur->pBtree;
67812 BtShared *pBt = p->pBt;
67813 unsigned char *oldCell;
67814 unsigned char *newCell = 0;
67816 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
67818 if( pCur->eState==CURSOR_FAULT ){
67819 assert( pCur->skipNext!=SQLITE_OK );
67820 return pCur->skipNext;
67823 assert( cursorOwnsBtShared(pCur) );
67824 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
67825 && pBt->inTransaction==TRANS_WRITE
67826 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
67827 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
67829 /* Assert that the caller has been consistent. If this cursor was opened
67830 ** expecting an index b-tree, then the caller should be inserting blob
67831 ** keys with no associated data. If the cursor was opened expecting an
67832 ** intkey table, the caller should be inserting integer keys with a
67833 ** blob of associated data. */
67834 assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
67836 /* Save the positions of any other cursors open on this table.
67838 ** In some cases, the call to btreeMoveto() below is a no-op. For
67839 ** example, when inserting data into a table with auto-generated integer
67840 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
67841 ** integer key to use. It then calls this function to actually insert the
67842 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
67843 ** that the cursor is already where it needs to be and returns without
67844 ** doing any work. To avoid thwarting these optimizations, it is important
67845 ** not to clear the cursor here.
67847 if( pCur->curFlags & BTCF_Multiple ){
67848 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
67849 if( rc ) return rc;
67852 if( pCur->pKeyInfo==0 ){
67853 assert( pX->pKey==0 );
67854 /* If this is an insert into a table b-tree, invalidate any incrblob
67855 ** cursors open on the row being replaced */
67856 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
67858 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
67859 ** to a row with the same key as the new entry being inserted. */
67860 assert( (flags & BTREE_SAVEPOSITION)==0 ||
67861 ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
67863 /* If the cursor is currently on the last row and we are appending a
67864 ** new row onto the end, set the "loc" to avoid an unnecessary
67865 ** btreeMoveto() call */
67866 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
67867 loc = 0;
67868 }else if( loc==0 ){
67869 rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
67870 if( rc ) return rc;
67872 }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
67873 if( pX->nMem ){
67874 UnpackedRecord r;
67875 r.pKeyInfo = pCur->pKeyInfo;
67876 r.aMem = pX->aMem;
67877 r.nField = pX->nMem;
67878 r.default_rc = 0;
67879 r.errCode = 0;
67880 r.r1 = 0;
67881 r.r2 = 0;
67882 r.eqSeen = 0;
67883 rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
67884 }else{
67885 rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
67887 if( rc ) return rc;
67889 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
67891 pPage = pCur->pPage;
67892 assert( pPage->intKey || pX->nKey>=0 );
67893 assert( pPage->leaf || !pPage->intKey );
67895 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
67896 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
67897 loc==0 ? "overwrite" : "new entry"));
67898 assert( pPage->isInit );
67899 newCell = pBt->pTmpSpace;
67900 assert( newCell!=0 );
67901 rc = fillInCell(pPage, newCell, pX, &szNew);
67902 if( rc ) goto end_insert;
67903 assert( szNew==pPage->xCellSize(pPage, newCell) );
67904 assert( szNew <= MX_CELL_SIZE(pBt) );
67905 idx = pCur->ix;
67906 if( loc==0 ){
67907 CellInfo info;
67908 assert( idx<pPage->nCell );
67909 rc = sqlite3PagerWrite(pPage->pDbPage);
67910 if( rc ){
67911 goto end_insert;
67913 oldCell = findCell(pPage, idx);
67914 if( !pPage->leaf ){
67915 memcpy(newCell, oldCell, 4);
67917 rc = clearCell(pPage, oldCell, &info);
67918 if( info.nSize==szNew && info.nLocal==info.nPayload
67919 && (!ISAUTOVACUUM || szNew<pPage->minLocal)
67921 /* Overwrite the old cell with the new if they are the same size.
67922 ** We could also try to do this if the old cell is smaller, then add
67923 ** the leftover space to the free list. But experiments show that
67924 ** doing that is no faster then skipping this optimization and just
67925 ** calling dropCell() and insertCell().
67927 ** This optimization cannot be used on an autovacuum database if the
67928 ** new entry uses overflow pages, as the insertCell() call below is
67929 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
67930 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
67931 if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
67932 memcpy(oldCell, newCell, szNew);
67933 return SQLITE_OK;
67935 dropCell(pPage, idx, info.nSize, &rc);
67936 if( rc ) goto end_insert;
67937 }else if( loc<0 && pPage->nCell>0 ){
67938 assert( pPage->leaf );
67939 idx = ++pCur->ix;
67940 pCur->curFlags &= ~BTCF_ValidNKey;
67941 }else{
67942 assert( pPage->leaf );
67944 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
67945 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
67946 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
67948 /* If no error has occurred and pPage has an overflow cell, call balance()
67949 ** to redistribute the cells within the tree. Since balance() may move
67950 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
67951 ** variables.
67953 ** Previous versions of SQLite called moveToRoot() to move the cursor
67954 ** back to the root page as balance() used to invalidate the contents
67955 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
67956 ** set the cursor state to "invalid". This makes common insert operations
67957 ** slightly faster.
67959 ** There is a subtle but important optimization here too. When inserting
67960 ** multiple records into an intkey b-tree using a single cursor (as can
67961 ** happen while processing an "INSERT INTO ... SELECT" statement), it
67962 ** is advantageous to leave the cursor pointing to the last entry in
67963 ** the b-tree if possible. If the cursor is left pointing to the last
67964 ** entry in the table, and the next row inserted has an integer key
67965 ** larger than the largest existing key, it is possible to insert the
67966 ** row without seeking the cursor. This can be a big performance boost.
67968 pCur->info.nSize = 0;
67969 if( pPage->nOverflow ){
67970 assert( rc==SQLITE_OK );
67971 pCur->curFlags &= ~(BTCF_ValidNKey);
67972 rc = balance(pCur);
67974 /* Must make sure nOverflow is reset to zero even if the balance()
67975 ** fails. Internal data structure corruption will result otherwise.
67976 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
67977 ** from trying to save the current position of the cursor. */
67978 pCur->pPage->nOverflow = 0;
67979 pCur->eState = CURSOR_INVALID;
67980 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
67981 btreeReleaseAllCursorPages(pCur);
67982 if( pCur->pKeyInfo ){
67983 assert( pCur->pKey==0 );
67984 pCur->pKey = sqlite3Malloc( pX->nKey );
67985 if( pCur->pKey==0 ){
67986 rc = SQLITE_NOMEM;
67987 }else{
67988 memcpy(pCur->pKey, pX->pKey, pX->nKey);
67991 pCur->eState = CURSOR_REQUIRESEEK;
67992 pCur->nKey = pX->nKey;
67995 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
67997 end_insert:
67998 return rc;
68002 ** Delete the entry that the cursor is pointing to.
68004 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
68005 ** the cursor is left pointing at an arbitrary location after the delete.
68006 ** But if that bit is set, then the cursor is left in a state such that
68007 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
68008 ** as it would have been on if the call to BtreeDelete() had been omitted.
68010 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
68011 ** associated with a single table entry and its indexes. Only one of those
68012 ** deletes is considered the "primary" delete. The primary delete occurs
68013 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
68014 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
68015 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
68016 ** but which might be used by alternative storage engines.
68018 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
68019 Btree *p = pCur->pBtree;
68020 BtShared *pBt = p->pBt;
68021 int rc; /* Return code */
68022 MemPage *pPage; /* Page to delete cell from */
68023 unsigned char *pCell; /* Pointer to cell to delete */
68024 int iCellIdx; /* Index of cell to delete */
68025 int iCellDepth; /* Depth of node containing pCell */
68026 CellInfo info; /* Size of the cell being deleted */
68027 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
68028 u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
68030 assert( cursorOwnsBtShared(pCur) );
68031 assert( pBt->inTransaction==TRANS_WRITE );
68032 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
68033 assert( pCur->curFlags & BTCF_WriteFlag );
68034 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
68035 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
68036 assert( pCur->ix<pCur->pPage->nCell );
68037 assert( pCur->eState==CURSOR_VALID );
68038 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
68040 iCellDepth = pCur->iPage;
68041 iCellIdx = pCur->ix;
68042 pPage = pCur->pPage;
68043 pCell = findCell(pPage, iCellIdx);
68045 /* If the bPreserve flag is set to true, then the cursor position must
68046 ** be preserved following this delete operation. If the current delete
68047 ** will cause a b-tree rebalance, then this is done by saving the cursor
68048 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
68049 ** returning.
68051 ** Or, if the current delete will not cause a rebalance, then the cursor
68052 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
68053 ** before or after the deleted entry. In this case set bSkipnext to true. */
68054 if( bPreserve ){
68055 if( !pPage->leaf
68056 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
68058 /* A b-tree rebalance will be required after deleting this entry.
68059 ** Save the cursor key. */
68060 rc = saveCursorKey(pCur);
68061 if( rc ) return rc;
68062 }else{
68063 bSkipnext = 1;
68067 /* If the page containing the entry to delete is not a leaf page, move
68068 ** the cursor to the largest entry in the tree that is smaller than
68069 ** the entry being deleted. This cell will replace the cell being deleted
68070 ** from the internal node. The 'previous' entry is used for this instead
68071 ** of the 'next' entry, as the previous entry is always a part of the
68072 ** sub-tree headed by the child page of the cell being deleted. This makes
68073 ** balancing the tree following the delete operation easier. */
68074 if( !pPage->leaf ){
68075 rc = sqlite3BtreePrevious(pCur, 0);
68076 assert( rc!=SQLITE_DONE );
68077 if( rc ) return rc;
68080 /* Save the positions of any other cursors open on this table before
68081 ** making any modifications. */
68082 if( pCur->curFlags & BTCF_Multiple ){
68083 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
68084 if( rc ) return rc;
68087 /* If this is a delete operation to remove a row from a table b-tree,
68088 ** invalidate any incrblob cursors open on the row being deleted. */
68089 if( pCur->pKeyInfo==0 ){
68090 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
68093 /* Make the page containing the entry to be deleted writable. Then free any
68094 ** overflow pages associated with the entry and finally remove the cell
68095 ** itself from within the page. */
68096 rc = sqlite3PagerWrite(pPage->pDbPage);
68097 if( rc ) return rc;
68098 rc = clearCell(pPage, pCell, &info);
68099 dropCell(pPage, iCellIdx, info.nSize, &rc);
68100 if( rc ) return rc;
68102 /* If the cell deleted was not located on a leaf page, then the cursor
68103 ** is currently pointing to the largest entry in the sub-tree headed
68104 ** by the child-page of the cell that was just deleted from an internal
68105 ** node. The cell from the leaf node needs to be moved to the internal
68106 ** node to replace the deleted cell. */
68107 if( !pPage->leaf ){
68108 MemPage *pLeaf = pCur->pPage;
68109 int nCell;
68110 Pgno n;
68111 unsigned char *pTmp;
68113 if( iCellDepth<pCur->iPage-1 ){
68114 n = pCur->apPage[iCellDepth+1]->pgno;
68115 }else{
68116 n = pCur->pPage->pgno;
68118 pCell = findCell(pLeaf, pLeaf->nCell-1);
68119 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
68120 nCell = pLeaf->xCellSize(pLeaf, pCell);
68121 assert( MX_CELL_SIZE(pBt) >= nCell );
68122 pTmp = pBt->pTmpSpace;
68123 assert( pTmp!=0 );
68124 rc = sqlite3PagerWrite(pLeaf->pDbPage);
68125 if( rc==SQLITE_OK ){
68126 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
68128 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
68129 if( rc ) return rc;
68132 /* Balance the tree. If the entry deleted was located on a leaf page,
68133 ** then the cursor still points to that page. In this case the first
68134 ** call to balance() repairs the tree, and the if(...) condition is
68135 ** never true.
68137 ** Otherwise, if the entry deleted was on an internal node page, then
68138 ** pCur is pointing to the leaf page from which a cell was removed to
68139 ** replace the cell deleted from the internal node. This is slightly
68140 ** tricky as the leaf node may be underfull, and the internal node may
68141 ** be either under or overfull. In this case run the balancing algorithm
68142 ** on the leaf node first. If the balance proceeds far enough up the
68143 ** tree that we can be sure that any problem in the internal node has
68144 ** been corrected, so be it. Otherwise, after balancing the leaf node,
68145 ** walk the cursor up the tree to the internal node and balance it as
68146 ** well. */
68147 rc = balance(pCur);
68148 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
68149 releasePageNotNull(pCur->pPage);
68150 pCur->iPage--;
68151 while( pCur->iPage>iCellDepth ){
68152 releasePage(pCur->apPage[pCur->iPage--]);
68154 pCur->pPage = pCur->apPage[pCur->iPage];
68155 rc = balance(pCur);
68158 if( rc==SQLITE_OK ){
68159 if( bSkipnext ){
68160 assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
68161 assert( pPage==pCur->pPage || CORRUPT_DB );
68162 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
68163 pCur->eState = CURSOR_SKIPNEXT;
68164 if( iCellIdx>=pPage->nCell ){
68165 pCur->skipNext = -1;
68166 pCur->ix = pPage->nCell-1;
68167 }else{
68168 pCur->skipNext = 1;
68170 }else{
68171 rc = moveToRoot(pCur);
68172 if( bPreserve ){
68173 btreeReleaseAllCursorPages(pCur);
68174 pCur->eState = CURSOR_REQUIRESEEK;
68176 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
68179 return rc;
68183 ** Create a new BTree table. Write into *piTable the page
68184 ** number for the root page of the new table.
68186 ** The type of type is determined by the flags parameter. Only the
68187 ** following values of flags are currently in use. Other values for
68188 ** flags might not work:
68190 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
68191 ** BTREE_ZERODATA Used for SQL indices
68193 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
68194 BtShared *pBt = p->pBt;
68195 MemPage *pRoot;
68196 Pgno pgnoRoot;
68197 int rc;
68198 int ptfFlags; /* Page-type flage for the root page of new table */
68200 assert( sqlite3BtreeHoldsMutex(p) );
68201 assert( pBt->inTransaction==TRANS_WRITE );
68202 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
68204 #ifdef SQLITE_OMIT_AUTOVACUUM
68205 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
68206 if( rc ){
68207 return rc;
68209 #else
68210 if( pBt->autoVacuum ){
68211 Pgno pgnoMove; /* Move a page here to make room for the root-page */
68212 MemPage *pPageMove; /* The page to move to. */
68214 /* Creating a new table may probably require moving an existing database
68215 ** to make room for the new tables root page. In case this page turns
68216 ** out to be an overflow page, delete all overflow page-map caches
68217 ** held by open cursors.
68219 invalidateAllOverflowCache(pBt);
68221 /* Read the value of meta[3] from the database to determine where the
68222 ** root page of the new table should go. meta[3] is the largest root-page
68223 ** created so far, so the new root-page is (meta[3]+1).
68225 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
68226 pgnoRoot++;
68228 /* The new root-page may not be allocated on a pointer-map page, or the
68229 ** PENDING_BYTE page.
68231 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
68232 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
68233 pgnoRoot++;
68235 assert( pgnoRoot>=3 || CORRUPT_DB );
68236 testcase( pgnoRoot<3 );
68238 /* Allocate a page. The page that currently resides at pgnoRoot will
68239 ** be moved to the allocated page (unless the allocated page happens
68240 ** to reside at pgnoRoot).
68242 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
68243 if( rc!=SQLITE_OK ){
68244 return rc;
68247 if( pgnoMove!=pgnoRoot ){
68248 /* pgnoRoot is the page that will be used for the root-page of
68249 ** the new table (assuming an error did not occur). But we were
68250 ** allocated pgnoMove. If required (i.e. if it was not allocated
68251 ** by extending the file), the current page at position pgnoMove
68252 ** is already journaled.
68254 u8 eType = 0;
68255 Pgno iPtrPage = 0;
68257 /* Save the positions of any open cursors. This is required in
68258 ** case they are holding a reference to an xFetch reference
68259 ** corresponding to page pgnoRoot. */
68260 rc = saveAllCursors(pBt, 0, 0);
68261 releasePage(pPageMove);
68262 if( rc!=SQLITE_OK ){
68263 return rc;
68266 /* Move the page currently at pgnoRoot to pgnoMove. */
68267 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
68268 if( rc!=SQLITE_OK ){
68269 return rc;
68271 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
68272 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
68273 rc = SQLITE_CORRUPT_BKPT;
68275 if( rc!=SQLITE_OK ){
68276 releasePage(pRoot);
68277 return rc;
68279 assert( eType!=PTRMAP_ROOTPAGE );
68280 assert( eType!=PTRMAP_FREEPAGE );
68281 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
68282 releasePage(pRoot);
68284 /* Obtain the page at pgnoRoot */
68285 if( rc!=SQLITE_OK ){
68286 return rc;
68288 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
68289 if( rc!=SQLITE_OK ){
68290 return rc;
68292 rc = sqlite3PagerWrite(pRoot->pDbPage);
68293 if( rc!=SQLITE_OK ){
68294 releasePage(pRoot);
68295 return rc;
68297 }else{
68298 pRoot = pPageMove;
68301 /* Update the pointer-map and meta-data with the new root-page number. */
68302 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
68303 if( rc ){
68304 releasePage(pRoot);
68305 return rc;
68308 /* When the new root page was allocated, page 1 was made writable in
68309 ** order either to increase the database filesize, or to decrement the
68310 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
68312 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
68313 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
68314 if( NEVER(rc) ){
68315 releasePage(pRoot);
68316 return rc;
68319 }else{
68320 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
68321 if( rc ) return rc;
68323 #endif
68324 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
68325 if( createTabFlags & BTREE_INTKEY ){
68326 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
68327 }else{
68328 ptfFlags = PTF_ZERODATA | PTF_LEAF;
68330 zeroPage(pRoot, ptfFlags);
68331 sqlite3PagerUnref(pRoot->pDbPage);
68332 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
68333 *piTable = (int)pgnoRoot;
68334 return SQLITE_OK;
68336 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
68337 int rc;
68338 sqlite3BtreeEnter(p);
68339 rc = btreeCreateTable(p, piTable, flags);
68340 sqlite3BtreeLeave(p);
68341 return rc;
68345 ** Erase the given database page and all its children. Return
68346 ** the page to the freelist.
68348 static int clearDatabasePage(
68349 BtShared *pBt, /* The BTree that contains the table */
68350 Pgno pgno, /* Page number to clear */
68351 int freePageFlag, /* Deallocate page if true */
68352 int *pnChange /* Add number of Cells freed to this counter */
68354 MemPage *pPage;
68355 int rc;
68356 unsigned char *pCell;
68357 int i;
68358 int hdr;
68359 CellInfo info;
68361 assert( sqlite3_mutex_held(pBt->mutex) );
68362 if( pgno>btreePagecount(pBt) ){
68363 return SQLITE_CORRUPT_BKPT;
68365 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
68366 if( rc ) return rc;
68367 if( pPage->bBusy ){
68368 rc = SQLITE_CORRUPT_BKPT;
68369 goto cleardatabasepage_out;
68371 pPage->bBusy = 1;
68372 hdr = pPage->hdrOffset;
68373 for(i=0; i<pPage->nCell; i++){
68374 pCell = findCell(pPage, i);
68375 if( !pPage->leaf ){
68376 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
68377 if( rc ) goto cleardatabasepage_out;
68379 rc = clearCell(pPage, pCell, &info);
68380 if( rc ) goto cleardatabasepage_out;
68382 if( !pPage->leaf ){
68383 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
68384 if( rc ) goto cleardatabasepage_out;
68385 }else if( pnChange ){
68386 assert( pPage->intKey || CORRUPT_DB );
68387 testcase( !pPage->intKey );
68388 *pnChange += pPage->nCell;
68390 if( freePageFlag ){
68391 freePage(pPage, &rc);
68392 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
68393 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
68396 cleardatabasepage_out:
68397 pPage->bBusy = 0;
68398 releasePage(pPage);
68399 return rc;
68403 ** Delete all information from a single table in the database. iTable is
68404 ** the page number of the root of the table. After this routine returns,
68405 ** the root page is empty, but still exists.
68407 ** This routine will fail with SQLITE_LOCKED if there are any open
68408 ** read cursors on the table. Open write cursors are moved to the
68409 ** root of the table.
68411 ** If pnChange is not NULL, then table iTable must be an intkey table. The
68412 ** integer value pointed to by pnChange is incremented by the number of
68413 ** entries in the table.
68415 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
68416 int rc;
68417 BtShared *pBt = p->pBt;
68418 sqlite3BtreeEnter(p);
68419 assert( p->inTrans==TRANS_WRITE );
68421 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
68423 if( SQLITE_OK==rc ){
68424 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
68425 ** is the root of a table b-tree - if it is not, the following call is
68426 ** a no-op). */
68427 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
68428 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
68430 sqlite3BtreeLeave(p);
68431 return rc;
68435 ** Delete all information from the single table that pCur is open on.
68437 ** This routine only work for pCur on an ephemeral table.
68439 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
68440 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
68444 ** Erase all information in a table and add the root of the table to
68445 ** the freelist. Except, the root of the principle table (the one on
68446 ** page 1) is never added to the freelist.
68448 ** This routine will fail with SQLITE_LOCKED if there are any open
68449 ** cursors on the table.
68451 ** If AUTOVACUUM is enabled and the page at iTable is not the last
68452 ** root page in the database file, then the last root page
68453 ** in the database file is moved into the slot formerly occupied by
68454 ** iTable and that last slot formerly occupied by the last root page
68455 ** is added to the freelist instead of iTable. In this say, all
68456 ** root pages are kept at the beginning of the database file, which
68457 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
68458 ** page number that used to be the last root page in the file before
68459 ** the move. If no page gets moved, *piMoved is set to 0.
68460 ** The last root page is recorded in meta[3] and the value of
68461 ** meta[3] is updated by this procedure.
68463 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
68464 int rc;
68465 MemPage *pPage = 0;
68466 BtShared *pBt = p->pBt;
68468 assert( sqlite3BtreeHoldsMutex(p) );
68469 assert( p->inTrans==TRANS_WRITE );
68470 assert( iTable>=2 );
68472 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
68473 if( rc ) return rc;
68474 rc = sqlite3BtreeClearTable(p, iTable, 0);
68475 if( rc ){
68476 releasePage(pPage);
68477 return rc;
68480 *piMoved = 0;
68482 #ifdef SQLITE_OMIT_AUTOVACUUM
68483 freePage(pPage, &rc);
68484 releasePage(pPage);
68485 #else
68486 if( pBt->autoVacuum ){
68487 Pgno maxRootPgno;
68488 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
68490 if( iTable==maxRootPgno ){
68491 /* If the table being dropped is the table with the largest root-page
68492 ** number in the database, put the root page on the free list.
68494 freePage(pPage, &rc);
68495 releasePage(pPage);
68496 if( rc!=SQLITE_OK ){
68497 return rc;
68499 }else{
68500 /* The table being dropped does not have the largest root-page
68501 ** number in the database. So move the page that does into the
68502 ** gap left by the deleted root-page.
68504 MemPage *pMove;
68505 releasePage(pPage);
68506 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
68507 if( rc!=SQLITE_OK ){
68508 return rc;
68510 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
68511 releasePage(pMove);
68512 if( rc!=SQLITE_OK ){
68513 return rc;
68515 pMove = 0;
68516 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
68517 freePage(pMove, &rc);
68518 releasePage(pMove);
68519 if( rc!=SQLITE_OK ){
68520 return rc;
68522 *piMoved = maxRootPgno;
68525 /* Set the new 'max-root-page' value in the database header. This
68526 ** is the old value less one, less one more if that happens to
68527 ** be a root-page number, less one again if that is the
68528 ** PENDING_BYTE_PAGE.
68530 maxRootPgno--;
68531 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
68532 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
68533 maxRootPgno--;
68535 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
68537 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
68538 }else{
68539 freePage(pPage, &rc);
68540 releasePage(pPage);
68542 #endif
68543 return rc;
68545 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
68546 int rc;
68547 sqlite3BtreeEnter(p);
68548 rc = btreeDropTable(p, iTable, piMoved);
68549 sqlite3BtreeLeave(p);
68550 return rc;
68555 ** This function may only be called if the b-tree connection already
68556 ** has a read or write transaction open on the database.
68558 ** Read the meta-information out of a database file. Meta[0]
68559 ** is the number of free pages currently in the database. Meta[1]
68560 ** through meta[15] are available for use by higher layers. Meta[0]
68561 ** is read-only, the others are read/write.
68563 ** The schema layer numbers meta values differently. At the schema
68564 ** layer (and the SetCookie and ReadCookie opcodes) the number of
68565 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
68567 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
68568 ** of reading the value out of the header, it instead loads the "DataVersion"
68569 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
68570 ** database file. It is a number computed by the pager. But its access
68571 ** pattern is the same as header meta values, and so it is convenient to
68572 ** read it from this routine.
68574 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
68575 BtShared *pBt = p->pBt;
68577 sqlite3BtreeEnter(p);
68578 assert( p->inTrans>TRANS_NONE );
68579 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
68580 assert( pBt->pPage1 );
68581 assert( idx>=0 && idx<=15 );
68583 if( idx==BTREE_DATA_VERSION ){
68584 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
68585 }else{
68586 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
68589 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
68590 ** database, mark the database as read-only. */
68591 #ifdef SQLITE_OMIT_AUTOVACUUM
68592 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
68593 pBt->btsFlags |= BTS_READ_ONLY;
68595 #endif
68597 sqlite3BtreeLeave(p);
68601 ** Write meta-information back into the database. Meta[0] is
68602 ** read-only and may not be written.
68604 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
68605 BtShared *pBt = p->pBt;
68606 unsigned char *pP1;
68607 int rc;
68608 assert( idx>=1 && idx<=15 );
68609 sqlite3BtreeEnter(p);
68610 assert( p->inTrans==TRANS_WRITE );
68611 assert( pBt->pPage1!=0 );
68612 pP1 = pBt->pPage1->aData;
68613 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
68614 if( rc==SQLITE_OK ){
68615 put4byte(&pP1[36 + idx*4], iMeta);
68616 #ifndef SQLITE_OMIT_AUTOVACUUM
68617 if( idx==BTREE_INCR_VACUUM ){
68618 assert( pBt->autoVacuum || iMeta==0 );
68619 assert( iMeta==0 || iMeta==1 );
68620 pBt->incrVacuum = (u8)iMeta;
68622 #endif
68624 sqlite3BtreeLeave(p);
68625 return rc;
68628 #ifndef SQLITE_OMIT_BTREECOUNT
68630 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
68631 ** number of entries in the b-tree and write the result to *pnEntry.
68633 ** SQLITE_OK is returned if the operation is successfully executed.
68634 ** Otherwise, if an error is encountered (i.e. an IO error or database
68635 ** corruption) an SQLite error code is returned.
68637 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
68638 i64 nEntry = 0; /* Value to return in *pnEntry */
68639 int rc; /* Return code */
68641 rc = moveToRoot(pCur);
68642 if( rc==SQLITE_EMPTY ){
68643 *pnEntry = 0;
68644 return SQLITE_OK;
68647 /* Unless an error occurs, the following loop runs one iteration for each
68648 ** page in the B-Tree structure (not including overflow pages).
68650 while( rc==SQLITE_OK ){
68651 int iIdx; /* Index of child node in parent */
68652 MemPage *pPage; /* Current page of the b-tree */
68654 /* If this is a leaf page or the tree is not an int-key tree, then
68655 ** this page contains countable entries. Increment the entry counter
68656 ** accordingly.
68658 pPage = pCur->pPage;
68659 if( pPage->leaf || !pPage->intKey ){
68660 nEntry += pPage->nCell;
68663 /* pPage is a leaf node. This loop navigates the cursor so that it
68664 ** points to the first interior cell that it points to the parent of
68665 ** the next page in the tree that has not yet been visited. The
68666 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
68667 ** of the page, or to the number of cells in the page if the next page
68668 ** to visit is the right-child of its parent.
68670 ** If all pages in the tree have been visited, return SQLITE_OK to the
68671 ** caller.
68673 if( pPage->leaf ){
68674 do {
68675 if( pCur->iPage==0 ){
68676 /* All pages of the b-tree have been visited. Return successfully. */
68677 *pnEntry = nEntry;
68678 return moveToRoot(pCur);
68680 moveToParent(pCur);
68681 }while ( pCur->ix>=pCur->pPage->nCell );
68683 pCur->ix++;
68684 pPage = pCur->pPage;
68687 /* Descend to the child node of the cell that the cursor currently
68688 ** points at. This is the right-child if (iIdx==pPage->nCell).
68690 iIdx = pCur->ix;
68691 if( iIdx==pPage->nCell ){
68692 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
68693 }else{
68694 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
68698 /* An error has occurred. Return an error code. */
68699 return rc;
68701 #endif
68704 ** Return the pager associated with a BTree. This routine is used for
68705 ** testing and debugging only.
68707 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
68708 return p->pBt->pPager;
68711 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
68713 ** Append a message to the error message string.
68715 static void checkAppendMsg(
68716 IntegrityCk *pCheck,
68717 const char *zFormat,
68720 va_list ap;
68721 if( !pCheck->mxErr ) return;
68722 pCheck->mxErr--;
68723 pCheck->nErr++;
68724 va_start(ap, zFormat);
68725 if( pCheck->errMsg.nChar ){
68726 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
68728 if( pCheck->zPfx ){
68729 sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
68731 sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
68732 va_end(ap);
68733 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
68734 pCheck->mallocFailed = 1;
68737 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
68739 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
68742 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
68743 ** corresponds to page iPg is already set.
68745 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
68746 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
68747 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
68751 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
68753 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
68754 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
68755 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
68760 ** Add 1 to the reference count for page iPage. If this is the second
68761 ** reference to the page, add an error message to pCheck->zErrMsg.
68762 ** Return 1 if there are 2 or more references to the page and 0 if
68763 ** if this is the first reference to the page.
68765 ** Also check that the page number is in bounds.
68767 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
68768 if( iPage==0 ) return 1;
68769 if( iPage>pCheck->nPage ){
68770 checkAppendMsg(pCheck, "invalid page number %d", iPage);
68771 return 1;
68773 if( getPageReferenced(pCheck, iPage) ){
68774 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
68775 return 1;
68777 setPageReferenced(pCheck, iPage);
68778 return 0;
68781 #ifndef SQLITE_OMIT_AUTOVACUUM
68783 ** Check that the entry in the pointer-map for page iChild maps to
68784 ** page iParent, pointer type ptrType. If not, append an error message
68785 ** to pCheck.
68787 static void checkPtrmap(
68788 IntegrityCk *pCheck, /* Integrity check context */
68789 Pgno iChild, /* Child page number */
68790 u8 eType, /* Expected pointer map type */
68791 Pgno iParent /* Expected pointer map parent page number */
68793 int rc;
68794 u8 ePtrmapType;
68795 Pgno iPtrmapParent;
68797 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
68798 if( rc!=SQLITE_OK ){
68799 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
68800 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
68801 return;
68804 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
68805 checkAppendMsg(pCheck,
68806 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
68807 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
68810 #endif
68813 ** Check the integrity of the freelist or of an overflow page list.
68814 ** Verify that the number of pages on the list is N.
68816 static void checkList(
68817 IntegrityCk *pCheck, /* Integrity checking context */
68818 int isFreeList, /* True for a freelist. False for overflow page list */
68819 int iPage, /* Page number for first page in the list */
68820 int N /* Expected number of pages in the list */
68822 int i;
68823 int expected = N;
68824 int iFirst = iPage;
68825 while( N-- > 0 && pCheck->mxErr ){
68826 DbPage *pOvflPage;
68827 unsigned char *pOvflData;
68828 if( iPage<1 ){
68829 checkAppendMsg(pCheck,
68830 "%d of %d pages missing from overflow list starting at %d",
68831 N+1, expected, iFirst);
68832 break;
68834 if( checkRef(pCheck, iPage) ) break;
68835 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
68836 checkAppendMsg(pCheck, "failed to get page %d", iPage);
68837 break;
68839 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
68840 if( isFreeList ){
68841 int n = get4byte(&pOvflData[4]);
68842 #ifndef SQLITE_OMIT_AUTOVACUUM
68843 if( pCheck->pBt->autoVacuum ){
68844 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
68846 #endif
68847 if( n>(int)pCheck->pBt->usableSize/4-2 ){
68848 checkAppendMsg(pCheck,
68849 "freelist leaf count too big on page %d", iPage);
68850 N--;
68851 }else{
68852 for(i=0; i<n; i++){
68853 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
68854 #ifndef SQLITE_OMIT_AUTOVACUUM
68855 if( pCheck->pBt->autoVacuum ){
68856 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
68858 #endif
68859 checkRef(pCheck, iFreePage);
68861 N -= n;
68864 #ifndef SQLITE_OMIT_AUTOVACUUM
68865 else{
68866 /* If this database supports auto-vacuum and iPage is not the last
68867 ** page in this overflow list, check that the pointer-map entry for
68868 ** the following page matches iPage.
68870 if( pCheck->pBt->autoVacuum && N>0 ){
68871 i = get4byte(pOvflData);
68872 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
68875 #endif
68876 iPage = get4byte(pOvflData);
68877 sqlite3PagerUnref(pOvflPage);
68879 if( isFreeList && N<(iPage!=0) ){
68880 checkAppendMsg(pCheck, "free-page count in header is too small");
68884 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
68887 ** An implementation of a min-heap.
68889 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
68890 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
68891 ** and aHeap[N*2+1].
68893 ** The heap property is this: Every node is less than or equal to both
68894 ** of its daughter nodes. A consequence of the heap property is that the
68895 ** root node aHeap[1] is always the minimum value currently in the heap.
68897 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
68898 ** the heap, preserving the heap property. The btreeHeapPull() routine
68899 ** removes the root element from the heap (the minimum value in the heap)
68900 ** and then moves other nodes around as necessary to preserve the heap
68901 ** property.
68903 ** This heap is used for cell overlap and coverage testing. Each u32
68904 ** entry represents the span of a cell or freeblock on a btree page.
68905 ** The upper 16 bits are the index of the first byte of a range and the
68906 ** lower 16 bits are the index of the last byte of that range.
68908 static void btreeHeapInsert(u32 *aHeap, u32 x){
68909 u32 j, i = ++aHeap[0];
68910 aHeap[i] = x;
68911 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
68912 x = aHeap[j];
68913 aHeap[j] = aHeap[i];
68914 aHeap[i] = x;
68915 i = j;
68918 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
68919 u32 j, i, x;
68920 if( (x = aHeap[0])==0 ) return 0;
68921 *pOut = aHeap[1];
68922 aHeap[1] = aHeap[x];
68923 aHeap[x] = 0xffffffff;
68924 aHeap[0]--;
68925 i = 1;
68926 while( (j = i*2)<=aHeap[0] ){
68927 if( aHeap[j]>aHeap[j+1] ) j++;
68928 if( aHeap[i]<aHeap[j] ) break;
68929 x = aHeap[i];
68930 aHeap[i] = aHeap[j];
68931 aHeap[j] = x;
68932 i = j;
68934 return 1;
68937 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
68939 ** Do various sanity checks on a single page of a tree. Return
68940 ** the tree depth. Root pages return 0. Parents of root pages
68941 ** return 1, and so forth.
68943 ** These checks are done:
68945 ** 1. Make sure that cells and freeblocks do not overlap
68946 ** but combine to completely cover the page.
68947 ** 2. Make sure integer cell keys are in order.
68948 ** 3. Check the integrity of overflow pages.
68949 ** 4. Recursively call checkTreePage on all children.
68950 ** 5. Verify that the depth of all children is the same.
68952 static int checkTreePage(
68953 IntegrityCk *pCheck, /* Context for the sanity check */
68954 int iPage, /* Page number of the page to check */
68955 i64 *piMinKey, /* Write minimum integer primary key here */
68956 i64 maxKey /* Error if integer primary key greater than this */
68958 MemPage *pPage = 0; /* The page being analyzed */
68959 int i; /* Loop counter */
68960 int rc; /* Result code from subroutine call */
68961 int depth = -1, d2; /* Depth of a subtree */
68962 int pgno; /* Page number */
68963 int nFrag; /* Number of fragmented bytes on the page */
68964 int hdr; /* Offset to the page header */
68965 int cellStart; /* Offset to the start of the cell pointer array */
68966 int nCell; /* Number of cells */
68967 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
68968 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
68969 ** False if IPK must be strictly less than maxKey */
68970 u8 *data; /* Page content */
68971 u8 *pCell; /* Cell content */
68972 u8 *pCellIdx; /* Next element of the cell pointer array */
68973 BtShared *pBt; /* The BtShared object that owns pPage */
68974 u32 pc; /* Address of a cell */
68975 u32 usableSize; /* Usable size of the page */
68976 u32 contentOffset; /* Offset to the start of the cell content area */
68977 u32 *heap = 0; /* Min-heap used for checking cell coverage */
68978 u32 x, prev = 0; /* Next and previous entry on the min-heap */
68979 const char *saved_zPfx = pCheck->zPfx;
68980 int saved_v1 = pCheck->v1;
68981 int saved_v2 = pCheck->v2;
68982 u8 savedIsInit = 0;
68984 /* Check that the page exists
68986 pBt = pCheck->pBt;
68987 usableSize = pBt->usableSize;
68988 if( iPage==0 ) return 0;
68989 if( checkRef(pCheck, iPage) ) return 0;
68990 pCheck->zPfx = "Page %d: ";
68991 pCheck->v1 = iPage;
68992 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
68993 checkAppendMsg(pCheck,
68994 "unable to get the page. error code=%d", rc);
68995 goto end_of_check;
68998 /* Clear MemPage.isInit to make sure the corruption detection code in
68999 ** btreeInitPage() is executed. */
69000 savedIsInit = pPage->isInit;
69001 pPage->isInit = 0;
69002 if( (rc = btreeInitPage(pPage))!=0 ){
69003 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
69004 checkAppendMsg(pCheck,
69005 "btreeInitPage() returns error code %d", rc);
69006 goto end_of_check;
69008 data = pPage->aData;
69009 hdr = pPage->hdrOffset;
69011 /* Set up for cell analysis */
69012 pCheck->zPfx = "On tree page %d cell %d: ";
69013 contentOffset = get2byteNotZero(&data[hdr+5]);
69014 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
69016 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
69017 ** number of cells on the page. */
69018 nCell = get2byte(&data[hdr+3]);
69019 assert( pPage->nCell==nCell );
69021 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
69022 ** immediately follows the b-tree page header. */
69023 cellStart = hdr + 12 - 4*pPage->leaf;
69024 assert( pPage->aCellIdx==&data[cellStart] );
69025 pCellIdx = &data[cellStart + 2*(nCell-1)];
69027 if( !pPage->leaf ){
69028 /* Analyze the right-child page of internal pages */
69029 pgno = get4byte(&data[hdr+8]);
69030 #ifndef SQLITE_OMIT_AUTOVACUUM
69031 if( pBt->autoVacuum ){
69032 pCheck->zPfx = "On page %d at right child: ";
69033 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
69035 #endif
69036 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
69037 keyCanBeEqual = 0;
69038 }else{
69039 /* For leaf pages, the coverage check will occur in the same loop
69040 ** as the other cell checks, so initialize the heap. */
69041 heap = pCheck->heap;
69042 heap[0] = 0;
69045 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
69046 ** integer offsets to the cell contents. */
69047 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
69048 CellInfo info;
69050 /* Check cell size */
69051 pCheck->v2 = i;
69052 assert( pCellIdx==&data[cellStart + i*2] );
69053 pc = get2byteAligned(pCellIdx);
69054 pCellIdx -= 2;
69055 if( pc<contentOffset || pc>usableSize-4 ){
69056 checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
69057 pc, contentOffset, usableSize-4);
69058 doCoverageCheck = 0;
69059 continue;
69061 pCell = &data[pc];
69062 pPage->xParseCell(pPage, pCell, &info);
69063 if( pc+info.nSize>usableSize ){
69064 checkAppendMsg(pCheck, "Extends off end of page");
69065 doCoverageCheck = 0;
69066 continue;
69069 /* Check for integer primary key out of range */
69070 if( pPage->intKey ){
69071 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
69072 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
69074 maxKey = info.nKey;
69075 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
69078 /* Check the content overflow list */
69079 if( info.nPayload>info.nLocal ){
69080 int nPage; /* Number of pages on the overflow chain */
69081 Pgno pgnoOvfl; /* First page of the overflow chain */
69082 assert( pc + info.nSize - 4 <= usableSize );
69083 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
69084 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
69085 #ifndef SQLITE_OMIT_AUTOVACUUM
69086 if( pBt->autoVacuum ){
69087 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
69089 #endif
69090 checkList(pCheck, 0, pgnoOvfl, nPage);
69093 if( !pPage->leaf ){
69094 /* Check sanity of left child page for internal pages */
69095 pgno = get4byte(pCell);
69096 #ifndef SQLITE_OMIT_AUTOVACUUM
69097 if( pBt->autoVacuum ){
69098 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
69100 #endif
69101 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
69102 keyCanBeEqual = 0;
69103 if( d2!=depth ){
69104 checkAppendMsg(pCheck, "Child page depth differs");
69105 depth = d2;
69107 }else{
69108 /* Populate the coverage-checking heap for leaf pages */
69109 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
69112 *piMinKey = maxKey;
69114 /* Check for complete coverage of the page
69116 pCheck->zPfx = 0;
69117 if( doCoverageCheck && pCheck->mxErr>0 ){
69118 /* For leaf pages, the min-heap has already been initialized and the
69119 ** cells have already been inserted. But for internal pages, that has
69120 ** not yet been done, so do it now */
69121 if( !pPage->leaf ){
69122 heap = pCheck->heap;
69123 heap[0] = 0;
69124 for(i=nCell-1; i>=0; i--){
69125 u32 size;
69126 pc = get2byteAligned(&data[cellStart+i*2]);
69127 size = pPage->xCellSize(pPage, &data[pc]);
69128 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
69131 /* Add the freeblocks to the min-heap
69133 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
69134 ** is the offset of the first freeblock, or zero if there are no
69135 ** freeblocks on the page.
69137 i = get2byte(&data[hdr+1]);
69138 while( i>0 ){
69139 int size, j;
69140 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
69141 size = get2byte(&data[i+2]);
69142 assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
69143 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
69144 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
69145 ** big-endian integer which is the offset in the b-tree page of the next
69146 ** freeblock in the chain, or zero if the freeblock is the last on the
69147 ** chain. */
69148 j = get2byte(&data[i]);
69149 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
69150 ** increasing offset. */
69151 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
69152 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
69153 i = j;
69155 /* Analyze the min-heap looking for overlap between cells and/or
69156 ** freeblocks, and counting the number of untracked bytes in nFrag.
69158 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
69159 ** There is an implied first entry the covers the page header, the cell
69160 ** pointer index, and the gap between the cell pointer index and the start
69161 ** of cell content.
69163 ** The loop below pulls entries from the min-heap in order and compares
69164 ** the start_address against the previous end_address. If there is an
69165 ** overlap, that means bytes are used multiple times. If there is a gap,
69166 ** that gap is added to the fragmentation count.
69168 nFrag = 0;
69169 prev = contentOffset - 1; /* Implied first min-heap entry */
69170 while( btreeHeapPull(heap,&x) ){
69171 if( (prev&0xffff)>=(x>>16) ){
69172 checkAppendMsg(pCheck,
69173 "Multiple uses for byte %u of page %d", x>>16, iPage);
69174 break;
69175 }else{
69176 nFrag += (x>>16) - (prev&0xffff) - 1;
69177 prev = x;
69180 nFrag += usableSize - (prev&0xffff) - 1;
69181 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
69182 ** is stored in the fifth field of the b-tree page header.
69183 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
69184 ** number of fragmented free bytes within the cell content area.
69186 if( heap[0]==0 && nFrag!=data[hdr+7] ){
69187 checkAppendMsg(pCheck,
69188 "Fragmentation of %d bytes reported as %d on page %d",
69189 nFrag, data[hdr+7], iPage);
69193 end_of_check:
69194 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
69195 releasePage(pPage);
69196 pCheck->zPfx = saved_zPfx;
69197 pCheck->v1 = saved_v1;
69198 pCheck->v2 = saved_v2;
69199 return depth+1;
69201 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
69203 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
69205 ** This routine does a complete check of the given BTree file. aRoot[] is
69206 ** an array of pages numbers were each page number is the root page of
69207 ** a table. nRoot is the number of entries in aRoot.
69209 ** A read-only or read-write transaction must be opened before calling
69210 ** this function.
69212 ** Write the number of error seen in *pnErr. Except for some memory
69213 ** allocation errors, an error message held in memory obtained from
69214 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
69215 ** returned. If a memory allocation error occurs, NULL is returned.
69217 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
69218 Btree *p, /* The btree to be checked */
69219 int *aRoot, /* An array of root pages numbers for individual trees */
69220 int nRoot, /* Number of entries in aRoot[] */
69221 int mxErr, /* Stop reporting errors after this many */
69222 int *pnErr /* Write number of errors seen to this variable */
69224 Pgno i;
69225 IntegrityCk sCheck;
69226 BtShared *pBt = p->pBt;
69227 int savedDbFlags = pBt->db->flags;
69228 char zErr[100];
69229 VVA_ONLY( int nRef );
69231 sqlite3BtreeEnter(p);
69232 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
69233 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
69234 assert( nRef>=0 );
69235 sCheck.pBt = pBt;
69236 sCheck.pPager = pBt->pPager;
69237 sCheck.nPage = btreePagecount(sCheck.pBt);
69238 sCheck.mxErr = mxErr;
69239 sCheck.nErr = 0;
69240 sCheck.mallocFailed = 0;
69241 sCheck.zPfx = 0;
69242 sCheck.v1 = 0;
69243 sCheck.v2 = 0;
69244 sCheck.aPgRef = 0;
69245 sCheck.heap = 0;
69246 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
69247 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
69248 if( sCheck.nPage==0 ){
69249 goto integrity_ck_cleanup;
69252 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
69253 if( !sCheck.aPgRef ){
69254 sCheck.mallocFailed = 1;
69255 goto integrity_ck_cleanup;
69257 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
69258 if( sCheck.heap==0 ){
69259 sCheck.mallocFailed = 1;
69260 goto integrity_ck_cleanup;
69263 i = PENDING_BYTE_PAGE(pBt);
69264 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
69266 /* Check the integrity of the freelist
69268 sCheck.zPfx = "Main freelist: ";
69269 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
69270 get4byte(&pBt->pPage1->aData[36]));
69271 sCheck.zPfx = 0;
69273 /* Check all the tables.
69275 testcase( pBt->db->flags & SQLITE_CellSizeCk );
69276 pBt->db->flags &= ~SQLITE_CellSizeCk;
69277 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
69278 i64 notUsed;
69279 if( aRoot[i]==0 ) continue;
69280 #ifndef SQLITE_OMIT_AUTOVACUUM
69281 if( pBt->autoVacuum && aRoot[i]>1 ){
69282 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
69284 #endif
69285 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
69287 pBt->db->flags = savedDbFlags;
69289 /* Make sure every page in the file is referenced
69291 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
69292 #ifdef SQLITE_OMIT_AUTOVACUUM
69293 if( getPageReferenced(&sCheck, i)==0 ){
69294 checkAppendMsg(&sCheck, "Page %d is never used", i);
69296 #else
69297 /* If the database supports auto-vacuum, make sure no tables contain
69298 ** references to pointer-map pages.
69300 if( getPageReferenced(&sCheck, i)==0 &&
69301 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
69302 checkAppendMsg(&sCheck, "Page %d is never used", i);
69304 if( getPageReferenced(&sCheck, i)!=0 &&
69305 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
69306 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
69308 #endif
69311 /* Clean up and report errors.
69313 integrity_ck_cleanup:
69314 sqlite3PageFree(sCheck.heap);
69315 sqlite3_free(sCheck.aPgRef);
69316 if( sCheck.mallocFailed ){
69317 sqlite3StrAccumReset(&sCheck.errMsg);
69318 sCheck.nErr++;
69320 *pnErr = sCheck.nErr;
69321 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
69322 /* Make sure this analysis did not leave any unref() pages. */
69323 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
69324 sqlite3BtreeLeave(p);
69325 return sqlite3StrAccumFinish(&sCheck.errMsg);
69327 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
69330 ** Return the full pathname of the underlying database file. Return
69331 ** an empty string if the database is in-memory or a TEMP database.
69333 ** The pager filename is invariant as long as the pager is
69334 ** open so it is safe to access without the BtShared mutex.
69336 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
69337 assert( p->pBt->pPager!=0 );
69338 return sqlite3PagerFilename(p->pBt->pPager, 1);
69342 ** Return the pathname of the journal file for this database. The return
69343 ** value of this routine is the same regardless of whether the journal file
69344 ** has been created or not.
69346 ** The pager journal filename is invariant as long as the pager is
69347 ** open so it is safe to access without the BtShared mutex.
69349 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
69350 assert( p->pBt->pPager!=0 );
69351 return sqlite3PagerJournalname(p->pBt->pPager);
69355 ** Return non-zero if a transaction is active.
69357 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
69358 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
69359 return (p && (p->inTrans==TRANS_WRITE));
69362 #ifndef SQLITE_OMIT_WAL
69364 ** Run a checkpoint on the Btree passed as the first argument.
69366 ** Return SQLITE_LOCKED if this or any other connection has an open
69367 ** transaction on the shared-cache the argument Btree is connected to.
69369 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
69371 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
69372 int rc = SQLITE_OK;
69373 if( p ){
69374 BtShared *pBt = p->pBt;
69375 sqlite3BtreeEnter(p);
69376 if( pBt->inTransaction!=TRANS_NONE ){
69377 rc = SQLITE_LOCKED;
69378 }else{
69379 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
69381 sqlite3BtreeLeave(p);
69383 return rc;
69385 #endif
69388 ** Return non-zero if a read (or write) transaction is active.
69390 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
69391 assert( p );
69392 assert( sqlite3_mutex_held(p->db->mutex) );
69393 return p->inTrans!=TRANS_NONE;
69396 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
69397 assert( p );
69398 assert( sqlite3_mutex_held(p->db->mutex) );
69399 return p->nBackup!=0;
69403 ** This function returns a pointer to a blob of memory associated with
69404 ** a single shared-btree. The memory is used by client code for its own
69405 ** purposes (for example, to store a high-level schema associated with
69406 ** the shared-btree). The btree layer manages reference counting issues.
69408 ** The first time this is called on a shared-btree, nBytes bytes of memory
69409 ** are allocated, zeroed, and returned to the caller. For each subsequent
69410 ** call the nBytes parameter is ignored and a pointer to the same blob
69411 ** of memory returned.
69413 ** If the nBytes parameter is 0 and the blob of memory has not yet been
69414 ** allocated, a null pointer is returned. If the blob has already been
69415 ** allocated, it is returned as normal.
69417 ** Just before the shared-btree is closed, the function passed as the
69418 ** xFree argument when the memory allocation was made is invoked on the
69419 ** blob of allocated memory. The xFree function should not call sqlite3_free()
69420 ** on the memory, the btree layer does that.
69422 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
69423 BtShared *pBt = p->pBt;
69424 sqlite3BtreeEnter(p);
69425 if( !pBt->pSchema && nBytes ){
69426 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
69427 pBt->xFreeSchema = xFree;
69429 sqlite3BtreeLeave(p);
69430 return pBt->pSchema;
69434 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
69435 ** btree as the argument handle holds an exclusive lock on the
69436 ** sqlite_master table. Otherwise SQLITE_OK.
69438 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
69439 int rc;
69440 assert( sqlite3_mutex_held(p->db->mutex) );
69441 sqlite3BtreeEnter(p);
69442 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
69443 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
69444 sqlite3BtreeLeave(p);
69445 return rc;
69449 #ifndef SQLITE_OMIT_SHARED_CACHE
69451 ** Obtain a lock on the table whose root page is iTab. The
69452 ** lock is a write lock if isWritelock is true or a read lock
69453 ** if it is false.
69455 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
69456 int rc = SQLITE_OK;
69457 assert( p->inTrans!=TRANS_NONE );
69458 if( p->sharable ){
69459 u8 lockType = READ_LOCK + isWriteLock;
69460 assert( READ_LOCK+1==WRITE_LOCK );
69461 assert( isWriteLock==0 || isWriteLock==1 );
69463 sqlite3BtreeEnter(p);
69464 rc = querySharedCacheTableLock(p, iTab, lockType);
69465 if( rc==SQLITE_OK ){
69466 rc = setSharedCacheTableLock(p, iTab, lockType);
69468 sqlite3BtreeLeave(p);
69470 return rc;
69472 #endif
69474 #ifndef SQLITE_OMIT_INCRBLOB
69476 ** Argument pCsr must be a cursor opened for writing on an
69477 ** INTKEY table currently pointing at a valid table entry.
69478 ** This function modifies the data stored as part of that entry.
69480 ** Only the data content may only be modified, it is not possible to
69481 ** change the length of the data stored. If this function is called with
69482 ** parameters that attempt to write past the end of the existing data,
69483 ** no modifications are made and SQLITE_CORRUPT is returned.
69485 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
69486 int rc;
69487 assert( cursorOwnsBtShared(pCsr) );
69488 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
69489 assert( pCsr->curFlags & BTCF_Incrblob );
69491 rc = restoreCursorPosition(pCsr);
69492 if( rc!=SQLITE_OK ){
69493 return rc;
69495 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
69496 if( pCsr->eState!=CURSOR_VALID ){
69497 return SQLITE_ABORT;
69500 /* Save the positions of all other cursors open on this table. This is
69501 ** required in case any of them are holding references to an xFetch
69502 ** version of the b-tree page modified by the accessPayload call below.
69504 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
69505 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
69506 ** saveAllCursors can only return SQLITE_OK.
69508 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
69509 assert( rc==SQLITE_OK );
69511 /* Check some assumptions:
69512 ** (a) the cursor is open for writing,
69513 ** (b) there is a read/write transaction open,
69514 ** (c) the connection holds a write-lock on the table (if required),
69515 ** (d) there are no conflicting read-locks, and
69516 ** (e) the cursor points at a valid row of an intKey table.
69518 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
69519 return SQLITE_READONLY;
69521 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
69522 && pCsr->pBt->inTransaction==TRANS_WRITE );
69523 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
69524 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
69525 assert( pCsr->pPage->intKey );
69527 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
69531 ** Mark this cursor as an incremental blob cursor.
69533 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
69534 pCur->curFlags |= BTCF_Incrblob;
69535 pCur->pBtree->hasIncrblobCur = 1;
69537 #endif
69540 ** Set both the "read version" (single byte at byte offset 18) and
69541 ** "write version" (single byte at byte offset 19) fields in the database
69542 ** header to iVersion.
69544 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
69545 BtShared *pBt = pBtree->pBt;
69546 int rc; /* Return code */
69548 assert( iVersion==1 || iVersion==2 );
69550 /* If setting the version fields to 1, do not automatically open the
69551 ** WAL connection, even if the version fields are currently set to 2.
69553 pBt->btsFlags &= ~BTS_NO_WAL;
69554 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
69556 rc = sqlite3BtreeBeginTrans(pBtree, 0);
69557 if( rc==SQLITE_OK ){
69558 u8 *aData = pBt->pPage1->aData;
69559 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
69560 rc = sqlite3BtreeBeginTrans(pBtree, 2);
69561 if( rc==SQLITE_OK ){
69562 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
69563 if( rc==SQLITE_OK ){
69564 aData[18] = (u8)iVersion;
69565 aData[19] = (u8)iVersion;
69571 pBt->btsFlags &= ~BTS_NO_WAL;
69572 return rc;
69576 ** Return true if the cursor has a hint specified. This routine is
69577 ** only used from within assert() statements
69579 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
69580 return (pCsr->hints & mask)!=0;
69584 ** Return true if the given Btree is read-only.
69586 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
69587 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
69591 ** Return the size of the header added to each page by this module.
69593 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
69595 #if !defined(SQLITE_OMIT_SHARED_CACHE)
69597 ** Return true if the Btree passed as the only argument is sharable.
69599 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
69600 return p->sharable;
69604 ** Return the number of connections to the BtShared object accessed by
69605 ** the Btree handle passed as the only argument. For private caches
69606 ** this is always 1. For shared caches it may be 1 or greater.
69608 SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
69609 testcase( p->sharable );
69610 return p->pBt->nRef;
69612 #endif
69614 /************** End of btree.c ***********************************************/
69615 /************** Begin file backup.c ******************************************/
69617 ** 2009 January 28
69619 ** The author disclaims copyright to this source code. In place of
69620 ** a legal notice, here is a blessing:
69622 ** May you do good and not evil.
69623 ** May you find forgiveness for yourself and forgive others.
69624 ** May you share freely, never taking more than you give.
69626 *************************************************************************
69627 ** This file contains the implementation of the sqlite3_backup_XXX()
69628 ** API functions and the related features.
69630 /* #include "sqliteInt.h" */
69631 /* #include "btreeInt.h" */
69634 ** Structure allocated for each backup operation.
69636 struct sqlite3_backup {
69637 sqlite3* pDestDb; /* Destination database handle */
69638 Btree *pDest; /* Destination b-tree file */
69639 u32 iDestSchema; /* Original schema cookie in destination */
69640 int bDestLocked; /* True once a write-transaction is open on pDest */
69642 Pgno iNext; /* Page number of the next source page to copy */
69643 sqlite3* pSrcDb; /* Source database handle */
69644 Btree *pSrc; /* Source b-tree file */
69646 int rc; /* Backup process error code */
69648 /* These two variables are set by every call to backup_step(). They are
69649 ** read by calls to backup_remaining() and backup_pagecount().
69651 Pgno nRemaining; /* Number of pages left to copy */
69652 Pgno nPagecount; /* Total number of pages to copy */
69654 int isAttached; /* True once backup has been registered with pager */
69655 sqlite3_backup *pNext; /* Next backup associated with source pager */
69659 ** THREAD SAFETY NOTES:
69661 ** Once it has been created using backup_init(), a single sqlite3_backup
69662 ** structure may be accessed via two groups of thread-safe entry points:
69664 ** * Via the sqlite3_backup_XXX() API function backup_step() and
69665 ** backup_finish(). Both these functions obtain the source database
69666 ** handle mutex and the mutex associated with the source BtShared
69667 ** structure, in that order.
69669 ** * Via the BackupUpdate() and BackupRestart() functions, which are
69670 ** invoked by the pager layer to report various state changes in
69671 ** the page cache associated with the source database. The mutex
69672 ** associated with the source database BtShared structure will always
69673 ** be held when either of these functions are invoked.
69675 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
69676 ** backup_pagecount() are not thread-safe functions. If they are called
69677 ** while some other thread is calling backup_step() or backup_finish(),
69678 ** the values returned may be invalid. There is no way for a call to
69679 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
69680 ** or backup_pagecount().
69682 ** Depending on the SQLite configuration, the database handles and/or
69683 ** the Btree objects may have their own mutexes that require locking.
69684 ** Non-sharable Btrees (in-memory databases for example), do not have
69685 ** associated mutexes.
69689 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
69690 ** in connection handle pDb. If such a database cannot be found, return
69691 ** a NULL pointer and write an error message to pErrorDb.
69693 ** If the "temp" database is requested, it may need to be opened by this
69694 ** function. If an error occurs while doing so, return 0 and write an
69695 ** error message to pErrorDb.
69697 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
69698 int i = sqlite3FindDbName(pDb, zDb);
69700 if( i==1 ){
69701 Parse sParse;
69702 int rc = 0;
69703 memset(&sParse, 0, sizeof(sParse));
69704 sParse.db = pDb;
69705 if( sqlite3OpenTempDatabase(&sParse) ){
69706 sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
69707 rc = SQLITE_ERROR;
69709 sqlite3DbFree(pErrorDb, sParse.zErrMsg);
69710 sqlite3ParserReset(&sParse);
69711 if( rc ){
69712 return 0;
69716 if( i<0 ){
69717 sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
69718 return 0;
69721 return pDb->aDb[i].pBt;
69725 ** Attempt to set the page size of the destination to match the page size
69726 ** of the source.
69728 static int setDestPgsz(sqlite3_backup *p){
69729 int rc;
69730 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
69731 return rc;
69735 ** Check that there is no open read-transaction on the b-tree passed as the
69736 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
69737 ** is an open read-transaction, return SQLITE_ERROR and leave an error
69738 ** message in database handle db.
69740 static int checkReadTransaction(sqlite3 *db, Btree *p){
69741 if( sqlite3BtreeIsInReadTrans(p) ){
69742 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
69743 return SQLITE_ERROR;
69745 return SQLITE_OK;
69749 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
69750 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
69751 ** a pointer to the new sqlite3_backup object.
69753 ** If an error occurs, NULL is returned and an error code and error message
69754 ** stored in database handle pDestDb.
69756 SQLITE_API sqlite3_backup *sqlite3_backup_init(
69757 sqlite3* pDestDb, /* Database to write to */
69758 const char *zDestDb, /* Name of database within pDestDb */
69759 sqlite3* pSrcDb, /* Database connection to read from */
69760 const char *zSrcDb /* Name of database within pSrcDb */
69762 sqlite3_backup *p; /* Value to return */
69764 #ifdef SQLITE_ENABLE_API_ARMOR
69765 if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
69766 (void)SQLITE_MISUSE_BKPT;
69767 return 0;
69769 #endif
69771 /* Lock the source database handle. The destination database
69772 ** handle is not locked in this routine, but it is locked in
69773 ** sqlite3_backup_step(). The user is required to ensure that no
69774 ** other thread accesses the destination handle for the duration
69775 ** of the backup operation. Any attempt to use the destination
69776 ** database connection while a backup is in progress may cause
69777 ** a malfunction or a deadlock.
69779 sqlite3_mutex_enter(pSrcDb->mutex);
69780 sqlite3_mutex_enter(pDestDb->mutex);
69782 if( pSrcDb==pDestDb ){
69783 sqlite3ErrorWithMsg(
69784 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
69786 p = 0;
69787 }else {
69788 /* Allocate space for a new sqlite3_backup object...
69789 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
69790 ** call to sqlite3_backup_init() and is destroyed by a call to
69791 ** sqlite3_backup_finish(). */
69792 p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
69793 if( !p ){
69794 sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
69798 /* If the allocation succeeded, populate the new object. */
69799 if( p ){
69800 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
69801 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
69802 p->pDestDb = pDestDb;
69803 p->pSrcDb = pSrcDb;
69804 p->iNext = 1;
69805 p->isAttached = 0;
69807 if( 0==p->pSrc || 0==p->pDest
69808 || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
69810 /* One (or both) of the named databases did not exist or an OOM
69811 ** error was hit. Or there is a transaction open on the destination
69812 ** database. The error has already been written into the pDestDb
69813 ** handle. All that is left to do here is free the sqlite3_backup
69814 ** structure. */
69815 sqlite3_free(p);
69816 p = 0;
69819 if( p ){
69820 p->pSrc->nBackup++;
69823 sqlite3_mutex_leave(pDestDb->mutex);
69824 sqlite3_mutex_leave(pSrcDb->mutex);
69825 return p;
69829 ** Argument rc is an SQLite error code. Return true if this error is
69830 ** considered fatal if encountered during a backup operation. All errors
69831 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
69833 static int isFatalError(int rc){
69834 return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
69838 ** Parameter zSrcData points to a buffer containing the data for
69839 ** page iSrcPg from the source database. Copy this data into the
69840 ** destination database.
69842 static int backupOnePage(
69843 sqlite3_backup *p, /* Backup handle */
69844 Pgno iSrcPg, /* Source database page to backup */
69845 const u8 *zSrcData, /* Source database page data */
69846 int bUpdate /* True for an update, false otherwise */
69848 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
69849 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
69850 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
69851 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
69852 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
69853 #ifdef SQLITE_HAS_CODEC
69854 /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
69855 ** guaranteed that the shared-mutex is held by this thread, handle
69856 ** p->pSrc may not actually be the owner. */
69857 int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
69858 int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
69859 #endif
69860 int rc = SQLITE_OK;
69861 i64 iOff;
69863 assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
69864 assert( p->bDestLocked );
69865 assert( !isFatalError(p->rc) );
69866 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
69867 assert( zSrcData );
69869 /* Catch the case where the destination is an in-memory database and the
69870 ** page sizes of the source and destination differ.
69872 if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
69873 rc = SQLITE_READONLY;
69876 #ifdef SQLITE_HAS_CODEC
69877 /* Backup is not possible if the page size of the destination is changing
69878 ** and a codec is in use.
69880 if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
69881 rc = SQLITE_READONLY;
69884 /* Backup is not possible if the number of bytes of reserve space differ
69885 ** between source and destination. If there is a difference, try to
69886 ** fix the destination to agree with the source. If that is not possible,
69887 ** then the backup cannot proceed.
69889 if( nSrcReserve!=nDestReserve ){
69890 u32 newPgsz = nSrcPgsz;
69891 rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
69892 if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
69894 #endif
69896 /* This loop runs once for each destination page spanned by the source
69897 ** page. For each iteration, variable iOff is set to the byte offset
69898 ** of the destination page.
69900 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
69901 DbPage *pDestPg = 0;
69902 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
69903 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
69904 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
69905 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
69907 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
69908 u8 *zDestData = sqlite3PagerGetData(pDestPg);
69909 u8 *zOut = &zDestData[iOff%nDestPgsz];
69911 /* Copy the data from the source page into the destination page.
69912 ** Then clear the Btree layer MemPage.isInit flag. Both this module
69913 ** and the pager code use this trick (clearing the first byte
69914 ** of the page 'extra' space to invalidate the Btree layers
69915 ** cached parse of the page). MemPage.isInit is marked
69916 ** "MUST BE FIRST" for this purpose.
69918 memcpy(zOut, zIn, nCopy);
69919 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
69920 if( iOff==0 && bUpdate==0 ){
69921 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
69924 sqlite3PagerUnref(pDestPg);
69927 return rc;
69931 ** If pFile is currently larger than iSize bytes, then truncate it to
69932 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
69933 ** this function is a no-op.
69935 ** Return SQLITE_OK if everything is successful, or an SQLite error
69936 ** code if an error occurs.
69938 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
69939 i64 iCurrent;
69940 int rc = sqlite3OsFileSize(pFile, &iCurrent);
69941 if( rc==SQLITE_OK && iCurrent>iSize ){
69942 rc = sqlite3OsTruncate(pFile, iSize);
69944 return rc;
69948 ** Register this backup object with the associated source pager for
69949 ** callbacks when pages are changed or the cache invalidated.
69951 static void attachBackupObject(sqlite3_backup *p){
69952 sqlite3_backup **pp;
69953 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
69954 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
69955 p->pNext = *pp;
69956 *pp = p;
69957 p->isAttached = 1;
69961 ** Copy nPage pages from the source b-tree to the destination.
69963 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
69964 int rc;
69965 int destMode; /* Destination journal mode */
69966 int pgszSrc = 0; /* Source page size */
69967 int pgszDest = 0; /* Destination page size */
69969 #ifdef SQLITE_ENABLE_API_ARMOR
69970 if( p==0 ) return SQLITE_MISUSE_BKPT;
69971 #endif
69972 sqlite3_mutex_enter(p->pSrcDb->mutex);
69973 sqlite3BtreeEnter(p->pSrc);
69974 if( p->pDestDb ){
69975 sqlite3_mutex_enter(p->pDestDb->mutex);
69978 rc = p->rc;
69979 if( !isFatalError(rc) ){
69980 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
69981 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
69982 int ii; /* Iterator variable */
69983 int nSrcPage = -1; /* Size of source db in pages */
69984 int bCloseTrans = 0; /* True if src db requires unlocking */
69986 /* If the source pager is currently in a write-transaction, return
69987 ** SQLITE_BUSY immediately.
69989 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
69990 rc = SQLITE_BUSY;
69991 }else{
69992 rc = SQLITE_OK;
69995 /* If there is no open read-transaction on the source database, open
69996 ** one now. If a transaction is opened here, then it will be closed
69997 ** before this function exits.
69999 if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
70000 rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
70001 bCloseTrans = 1;
70004 /* If the destination database has not yet been locked (i.e. if this
70005 ** is the first call to backup_step() for the current backup operation),
70006 ** try to set its page size to the same as the source database. This
70007 ** is especially important on ZipVFS systems, as in that case it is
70008 ** not possible to create a database file that uses one page size by
70009 ** writing to it with another. */
70010 if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
70011 rc = SQLITE_NOMEM;
70014 /* Lock the destination database, if it is not locked already. */
70015 if( SQLITE_OK==rc && p->bDestLocked==0
70016 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
70018 p->bDestLocked = 1;
70019 sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
70022 /* Do not allow backup if the destination database is in WAL mode
70023 ** and the page sizes are different between source and destination */
70024 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
70025 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
70026 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
70027 if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
70028 rc = SQLITE_READONLY;
70031 /* Now that there is a read-lock on the source database, query the
70032 ** source pager for the number of pages in the database.
70034 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
70035 assert( nSrcPage>=0 );
70036 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
70037 const Pgno iSrcPg = p->iNext; /* Source page number */
70038 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
70039 DbPage *pSrcPg; /* Source page object */
70040 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
70041 if( rc==SQLITE_OK ){
70042 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
70043 sqlite3PagerUnref(pSrcPg);
70046 p->iNext++;
70048 if( rc==SQLITE_OK ){
70049 p->nPagecount = nSrcPage;
70050 p->nRemaining = nSrcPage+1-p->iNext;
70051 if( p->iNext>(Pgno)nSrcPage ){
70052 rc = SQLITE_DONE;
70053 }else if( !p->isAttached ){
70054 attachBackupObject(p);
70058 /* Update the schema version field in the destination database. This
70059 ** is to make sure that the schema-version really does change in
70060 ** the case where the source and destination databases have the
70061 ** same schema version.
70063 if( rc==SQLITE_DONE ){
70064 if( nSrcPage==0 ){
70065 rc = sqlite3BtreeNewDb(p->pDest);
70066 nSrcPage = 1;
70068 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
70069 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
70071 if( rc==SQLITE_OK ){
70072 if( p->pDestDb ){
70073 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
70075 if( destMode==PAGER_JOURNALMODE_WAL ){
70076 rc = sqlite3BtreeSetVersion(p->pDest, 2);
70079 if( rc==SQLITE_OK ){
70080 int nDestTruncate;
70081 /* Set nDestTruncate to the final number of pages in the destination
70082 ** database. The complication here is that the destination page
70083 ** size may be different to the source page size.
70085 ** If the source page size is smaller than the destination page size,
70086 ** round up. In this case the call to sqlite3OsTruncate() below will
70087 ** fix the size of the file. However it is important to call
70088 ** sqlite3PagerTruncateImage() here so that any pages in the
70089 ** destination file that lie beyond the nDestTruncate page mark are
70090 ** journalled by PagerCommitPhaseOne() before they are destroyed
70091 ** by the file truncation.
70093 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
70094 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
70095 if( pgszSrc<pgszDest ){
70096 int ratio = pgszDest/pgszSrc;
70097 nDestTruncate = (nSrcPage+ratio-1)/ratio;
70098 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
70099 nDestTruncate--;
70101 }else{
70102 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
70104 assert( nDestTruncate>0 );
70106 if( pgszSrc<pgszDest ){
70107 /* If the source page-size is smaller than the destination page-size,
70108 ** two extra things may need to happen:
70110 ** * The destination may need to be truncated, and
70112 ** * Data stored on the pages immediately following the
70113 ** pending-byte page in the source database may need to be
70114 ** copied into the destination database.
70116 const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
70117 sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
70118 Pgno iPg;
70119 int nDstPage;
70120 i64 iOff;
70121 i64 iEnd;
70123 assert( pFile );
70124 assert( nDestTruncate==0
70125 || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
70126 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
70127 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
70130 /* This block ensures that all data required to recreate the original
70131 ** database has been stored in the journal for pDestPager and the
70132 ** journal synced to disk. So at this point we may safely modify
70133 ** the database file in any way, knowing that if a power failure
70134 ** occurs, the original database will be reconstructed from the
70135 ** journal file. */
70136 sqlite3PagerPagecount(pDestPager, &nDstPage);
70137 for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
70138 if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
70139 DbPage *pPg;
70140 rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
70141 if( rc==SQLITE_OK ){
70142 rc = sqlite3PagerWrite(pPg);
70143 sqlite3PagerUnref(pPg);
70147 if( rc==SQLITE_OK ){
70148 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
70151 /* Write the extra pages and truncate the database file as required */
70152 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
70153 for(
70154 iOff=PENDING_BYTE+pgszSrc;
70155 rc==SQLITE_OK && iOff<iEnd;
70156 iOff+=pgszSrc
70158 PgHdr *pSrcPg = 0;
70159 const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
70160 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
70161 if( rc==SQLITE_OK ){
70162 u8 *zData = sqlite3PagerGetData(pSrcPg);
70163 rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
70165 sqlite3PagerUnref(pSrcPg);
70167 if( rc==SQLITE_OK ){
70168 rc = backupTruncateFile(pFile, iSize);
70171 /* Sync the database file to disk. */
70172 if( rc==SQLITE_OK ){
70173 rc = sqlite3PagerSync(pDestPager, 0);
70175 }else{
70176 sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
70177 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
70180 /* Finish committing the transaction to the destination database. */
70181 if( SQLITE_OK==rc
70182 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
70184 rc = SQLITE_DONE;
70189 /* If bCloseTrans is true, then this function opened a read transaction
70190 ** on the source database. Close the read transaction here. There is
70191 ** no need to check the return values of the btree methods here, as
70192 ** "committing" a read-only transaction cannot fail.
70194 if( bCloseTrans ){
70195 TESTONLY( int rc2 );
70196 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
70197 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
70198 assert( rc2==SQLITE_OK );
70201 if( rc==SQLITE_IOERR_NOMEM ){
70202 rc = SQLITE_NOMEM_BKPT;
70204 p->rc = rc;
70206 if( p->pDestDb ){
70207 sqlite3_mutex_leave(p->pDestDb->mutex);
70209 sqlite3BtreeLeave(p->pSrc);
70210 sqlite3_mutex_leave(p->pSrcDb->mutex);
70211 return rc;
70215 ** Release all resources associated with an sqlite3_backup* handle.
70217 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
70218 sqlite3_backup **pp; /* Ptr to head of pagers backup list */
70219 sqlite3 *pSrcDb; /* Source database connection */
70220 int rc; /* Value to return */
70222 /* Enter the mutexes */
70223 if( p==0 ) return SQLITE_OK;
70224 pSrcDb = p->pSrcDb;
70225 sqlite3_mutex_enter(pSrcDb->mutex);
70226 sqlite3BtreeEnter(p->pSrc);
70227 if( p->pDestDb ){
70228 sqlite3_mutex_enter(p->pDestDb->mutex);
70231 /* Detach this backup from the source pager. */
70232 if( p->pDestDb ){
70233 p->pSrc->nBackup--;
70235 if( p->isAttached ){
70236 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
70237 while( *pp!=p ){
70238 pp = &(*pp)->pNext;
70240 *pp = p->pNext;
70243 /* If a transaction is still open on the Btree, roll it back. */
70244 sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
70246 /* Set the error code of the destination database handle. */
70247 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
70248 if( p->pDestDb ){
70249 sqlite3Error(p->pDestDb, rc);
70251 /* Exit the mutexes and free the backup context structure. */
70252 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
70254 sqlite3BtreeLeave(p->pSrc);
70255 if( p->pDestDb ){
70256 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
70257 ** call to sqlite3_backup_init() and is destroyed by a call to
70258 ** sqlite3_backup_finish(). */
70259 sqlite3_free(p);
70261 sqlite3LeaveMutexAndCloseZombie(pSrcDb);
70262 return rc;
70266 ** Return the number of pages still to be backed up as of the most recent
70267 ** call to sqlite3_backup_step().
70269 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
70270 #ifdef SQLITE_ENABLE_API_ARMOR
70271 if( p==0 ){
70272 (void)SQLITE_MISUSE_BKPT;
70273 return 0;
70275 #endif
70276 return p->nRemaining;
70280 ** Return the total number of pages in the source database as of the most
70281 ** recent call to sqlite3_backup_step().
70283 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
70284 #ifdef SQLITE_ENABLE_API_ARMOR
70285 if( p==0 ){
70286 (void)SQLITE_MISUSE_BKPT;
70287 return 0;
70289 #endif
70290 return p->nPagecount;
70294 ** This function is called after the contents of page iPage of the
70295 ** source database have been modified. If page iPage has already been
70296 ** copied into the destination database, then the data written to the
70297 ** destination is now invalidated. The destination copy of iPage needs
70298 ** to be updated with the new data before the backup operation is
70299 ** complete.
70301 ** It is assumed that the mutex associated with the BtShared object
70302 ** corresponding to the source database is held when this function is
70303 ** called.
70305 static SQLITE_NOINLINE void backupUpdate(
70306 sqlite3_backup *p,
70307 Pgno iPage,
70308 const u8 *aData
70310 assert( p!=0 );
70312 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
70313 if( !isFatalError(p->rc) && iPage<p->iNext ){
70314 /* The backup process p has already copied page iPage. But now it
70315 ** has been modified by a transaction on the source pager. Copy
70316 ** the new data into the backup.
70318 int rc;
70319 assert( p->pDestDb );
70320 sqlite3_mutex_enter(p->pDestDb->mutex);
70321 rc = backupOnePage(p, iPage, aData, 1);
70322 sqlite3_mutex_leave(p->pDestDb->mutex);
70323 assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
70324 if( rc!=SQLITE_OK ){
70325 p->rc = rc;
70328 }while( (p = p->pNext)!=0 );
70330 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
70331 if( pBackup ) backupUpdate(pBackup, iPage, aData);
70335 ** Restart the backup process. This is called when the pager layer
70336 ** detects that the database has been modified by an external database
70337 ** connection. In this case there is no way of knowing which of the
70338 ** pages that have been copied into the destination database are still
70339 ** valid and which are not, so the entire process needs to be restarted.
70341 ** It is assumed that the mutex associated with the BtShared object
70342 ** corresponding to the source database is held when this function is
70343 ** called.
70345 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
70346 sqlite3_backup *p; /* Iterator variable */
70347 for(p=pBackup; p; p=p->pNext){
70348 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
70349 p->iNext = 1;
70353 #ifndef SQLITE_OMIT_VACUUM
70355 ** Copy the complete content of pBtFrom into pBtTo. A transaction
70356 ** must be active for both files.
70358 ** The size of file pTo may be reduced by this operation. If anything
70359 ** goes wrong, the transaction on pTo is rolled back. If successful, the
70360 ** transaction is committed before returning.
70362 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
70363 int rc;
70364 sqlite3_file *pFd; /* File descriptor for database pTo */
70365 sqlite3_backup b;
70366 sqlite3BtreeEnter(pTo);
70367 sqlite3BtreeEnter(pFrom);
70369 assert( sqlite3BtreeIsInTrans(pTo) );
70370 pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
70371 if( pFd->pMethods ){
70372 i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
70373 rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
70374 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
70375 if( rc ) goto copy_finished;
70378 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
70379 ** to 0. This is used by the implementations of sqlite3_backup_step()
70380 ** and sqlite3_backup_finish() to detect that they are being called
70381 ** from this function, not directly by the user.
70383 memset(&b, 0, sizeof(b));
70384 b.pSrcDb = pFrom->db;
70385 b.pSrc = pFrom;
70386 b.pDest = pTo;
70387 b.iNext = 1;
70389 #ifdef SQLITE_HAS_CODEC
70390 sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
70391 #endif
70393 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
70394 ** file. By passing this as the number of pages to copy to
70395 ** sqlite3_backup_step(), we can guarantee that the copy finishes
70396 ** within a single call (unless an error occurs). The assert() statement
70397 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
70398 ** or an error code. */
70399 sqlite3_backup_step(&b, 0x7FFFFFFF);
70400 assert( b.rc!=SQLITE_OK );
70402 rc = sqlite3_backup_finish(&b);
70403 if( rc==SQLITE_OK ){
70404 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
70405 }else{
70406 sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
70409 assert( sqlite3BtreeIsInTrans(pTo)==0 );
70410 copy_finished:
70411 sqlite3BtreeLeave(pFrom);
70412 sqlite3BtreeLeave(pTo);
70413 return rc;
70415 #endif /* SQLITE_OMIT_VACUUM */
70417 /************** End of backup.c **********************************************/
70418 /************** Begin file vdbemem.c *****************************************/
70420 ** 2004 May 26
70422 ** The author disclaims copyright to this source code. In place of
70423 ** a legal notice, here is a blessing:
70425 ** May you do good and not evil.
70426 ** May you find forgiveness for yourself and forgive others.
70427 ** May you share freely, never taking more than you give.
70429 *************************************************************************
70431 ** This file contains code use to manipulate "Mem" structure. A "Mem"
70432 ** stores a single value in the VDBE. Mem is an opaque structure visible
70433 ** only within the VDBE. Interface routines refer to a Mem using the
70434 ** name sqlite_value
70436 /* #include "sqliteInt.h" */
70437 /* #include "vdbeInt.h" */
70439 #ifdef SQLITE_DEBUG
70441 ** Check invariants on a Mem object.
70443 ** This routine is intended for use inside of assert() statements, like
70444 ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
70446 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
70447 /* If MEM_Dyn is set then Mem.xDel!=0.
70448 ** Mem.xDel might not be initialized if MEM_Dyn is clear.
70450 assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
70452 /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
70453 ** ensure that if Mem.szMalloc>0 then it is safe to do
70454 ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
70455 ** That saves a few cycles in inner loops. */
70456 assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
70458 /* Cannot be both MEM_Int and MEM_Real at the same time */
70459 assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
70461 if( p->flags & MEM_Null ){
70462 /* Cannot be both MEM_Null and some other type */
70463 assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob
70464 |MEM_RowSet|MEM_Frame|MEM_Agg|MEM_Zero))==0 );
70466 /* If MEM_Null is set, then either the value is a pure NULL (the usual
70467 ** case) or it is a pointer set using sqlite3_bind_pointer() or
70468 ** sqlite3_result_pointer(). If a pointer, then MEM_Term must also be
70469 ** set.
70471 if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
70472 /* This is a pointer type. There may be a flag to indicate what to
70473 ** do with the pointer. */
70474 assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
70475 ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
70476 ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
70478 /* No other bits set */
70479 assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype
70480 |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
70481 }else{
70482 /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
70483 ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
70485 }else{
70486 /* The MEM_Cleared bit is only allowed on NULLs */
70487 assert( (p->flags & MEM_Cleared)==0 );
70490 /* The szMalloc field holds the correct memory allocation size */
70491 assert( p->szMalloc==0
70492 || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
70494 /* If p holds a string or blob, the Mem.z must point to exactly
70495 ** one of the following:
70497 ** (1) Memory in Mem.zMalloc and managed by the Mem object
70498 ** (2) Memory to be freed using Mem.xDel
70499 ** (3) An ephemeral string or blob
70500 ** (4) A static string or blob
70502 if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
70503 assert(
70504 ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
70505 ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
70506 ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
70507 ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
70510 return 1;
70512 #endif
70516 ** If pMem is an object with a valid string representation, this routine
70517 ** ensures the internal encoding for the string representation is
70518 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
70520 ** If pMem is not a string object, or the encoding of the string
70521 ** representation is already stored using the requested encoding, then this
70522 ** routine is a no-op.
70524 ** SQLITE_OK is returned if the conversion is successful (or not required).
70525 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
70526 ** between formats.
70528 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
70529 #ifndef SQLITE_OMIT_UTF16
70530 int rc;
70531 #endif
70532 assert( (pMem->flags&MEM_RowSet)==0 );
70533 assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
70534 || desiredEnc==SQLITE_UTF16BE );
70535 if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
70536 return SQLITE_OK;
70538 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70539 #ifdef SQLITE_OMIT_UTF16
70540 return SQLITE_ERROR;
70541 #else
70543 /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
70544 ** then the encoding of the value may not have changed.
70546 rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
70547 assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
70548 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
70549 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
70550 return rc;
70551 #endif
70555 ** Make sure pMem->z points to a writable allocation of at least
70556 ** min(n,32) bytes.
70558 ** If the bPreserve argument is true, then copy of the content of
70559 ** pMem->z into the new allocation. pMem must be either a string or
70560 ** blob if bPreserve is true. If bPreserve is false, any prior content
70561 ** in pMem->z is discarded.
70563 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
70564 assert( sqlite3VdbeCheckMemInvariants(pMem) );
70565 assert( (pMem->flags&MEM_RowSet)==0 );
70566 testcase( pMem->db==0 );
70568 /* If the bPreserve flag is set to true, then the memory cell must already
70569 ** contain a valid string or blob value. */
70570 assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
70571 testcase( bPreserve && pMem->z==0 );
70573 assert( pMem->szMalloc==0
70574 || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
70575 if( n<32 ) n = 32;
70576 if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
70577 pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
70578 bPreserve = 0;
70579 }else{
70580 if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
70581 pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
70583 if( pMem->zMalloc==0 ){
70584 sqlite3VdbeMemSetNull(pMem);
70585 pMem->z = 0;
70586 pMem->szMalloc = 0;
70587 return SQLITE_NOMEM_BKPT;
70588 }else{
70589 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
70592 if( bPreserve && pMem->z ){
70593 assert( pMem->z!=pMem->zMalloc );
70594 memcpy(pMem->zMalloc, pMem->z, pMem->n);
70596 if( (pMem->flags&MEM_Dyn)!=0 ){
70597 assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
70598 pMem->xDel((void *)(pMem->z));
70601 pMem->z = pMem->zMalloc;
70602 pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
70603 return SQLITE_OK;
70607 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
70608 ** If pMem->zMalloc already meets or exceeds the requested size, this
70609 ** routine is a no-op.
70611 ** Any prior string or blob content in the pMem object may be discarded.
70612 ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
70613 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
70614 ** values are preserved.
70616 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
70617 ** if unable to complete the resizing.
70619 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
70620 assert( szNew>0 );
70621 assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
70622 if( pMem->szMalloc<szNew ){
70623 return sqlite3VdbeMemGrow(pMem, szNew, 0);
70625 assert( (pMem->flags & MEM_Dyn)==0 );
70626 pMem->z = pMem->zMalloc;
70627 pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
70628 return SQLITE_OK;
70632 ** It is already known that pMem contains an unterminated string.
70633 ** Add the zero terminator.
70635 static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
70636 if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
70637 return SQLITE_NOMEM_BKPT;
70639 pMem->z[pMem->n] = 0;
70640 pMem->z[pMem->n+1] = 0;
70641 pMem->flags |= MEM_Term;
70642 return SQLITE_OK;
70646 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
70647 ** MEM.zMalloc, where it can be safely written.
70649 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
70651 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
70652 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70653 assert( (pMem->flags&MEM_RowSet)==0 );
70654 if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
70655 if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
70656 if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
70657 int rc = vdbeMemAddTerminator(pMem);
70658 if( rc ) return rc;
70661 pMem->flags &= ~MEM_Ephem;
70662 #ifdef SQLITE_DEBUG
70663 pMem->pScopyFrom = 0;
70664 #endif
70666 return SQLITE_OK;
70670 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
70671 ** blob stored in dynamically allocated space.
70673 #ifndef SQLITE_OMIT_INCRBLOB
70674 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
70675 int nByte;
70676 assert( pMem->flags & MEM_Zero );
70677 assert( pMem->flags&MEM_Blob );
70678 assert( (pMem->flags&MEM_RowSet)==0 );
70679 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70681 /* Set nByte to the number of bytes required to store the expanded blob. */
70682 nByte = pMem->n + pMem->u.nZero;
70683 if( nByte<=0 ){
70684 nByte = 1;
70686 if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
70687 return SQLITE_NOMEM_BKPT;
70690 memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
70691 pMem->n += pMem->u.nZero;
70692 pMem->flags &= ~(MEM_Zero|MEM_Term);
70693 return SQLITE_OK;
70695 #endif
70698 ** Make sure the given Mem is \u0000 terminated.
70700 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
70701 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70702 testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
70703 testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
70704 if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
70705 return SQLITE_OK; /* Nothing to do */
70706 }else{
70707 return vdbeMemAddTerminator(pMem);
70712 ** Add MEM_Str to the set of representations for the given Mem. Numbers
70713 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
70714 ** is a no-op.
70716 ** Existing representations MEM_Int and MEM_Real are invalidated if
70717 ** bForce is true but are retained if bForce is false.
70719 ** A MEM_Null value will never be passed to this function. This function is
70720 ** used for converting values to text for returning to the user (i.e. via
70721 ** sqlite3_value_text()), or for ensuring that values to be used as btree
70722 ** keys are strings. In the former case a NULL pointer is returned the
70723 ** user and the latter is an internal programming error.
70725 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
70726 int fg = pMem->flags;
70727 const int nByte = 32;
70729 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70730 assert( !(fg&MEM_Zero) );
70731 assert( !(fg&(MEM_Str|MEM_Blob)) );
70732 assert( fg&(MEM_Int|MEM_Real) );
70733 assert( (pMem->flags&MEM_RowSet)==0 );
70734 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70737 if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
70738 pMem->enc = 0;
70739 return SQLITE_NOMEM_BKPT;
70742 /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
70743 ** string representation of the value. Then, if the required encoding
70744 ** is UTF-16le or UTF-16be do a translation.
70746 ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
70748 if( fg & MEM_Int ){
70749 sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
70750 }else{
70751 assert( fg & MEM_Real );
70752 sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
70754 pMem->n = sqlite3Strlen30(pMem->z);
70755 pMem->enc = SQLITE_UTF8;
70756 pMem->flags |= MEM_Str|MEM_Term;
70757 if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
70758 sqlite3VdbeChangeEncoding(pMem, enc);
70759 return SQLITE_OK;
70763 ** Memory cell pMem contains the context of an aggregate function.
70764 ** This routine calls the finalize method for that function. The
70765 ** result of the aggregate is stored back into pMem.
70767 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
70768 ** otherwise.
70770 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
70771 int rc = SQLITE_OK;
70772 if( ALWAYS(pFunc && pFunc->xFinalize) ){
70773 sqlite3_context ctx;
70774 Mem t;
70775 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
70776 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70777 memset(&ctx, 0, sizeof(ctx));
70778 memset(&t, 0, sizeof(t));
70779 t.flags = MEM_Null;
70780 t.db = pMem->db;
70781 ctx.pOut = &t;
70782 ctx.pMem = pMem;
70783 ctx.pFunc = pFunc;
70784 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
70785 assert( (pMem->flags & MEM_Dyn)==0 );
70786 if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
70787 memcpy(pMem, &t, sizeof(t));
70788 rc = ctx.isError;
70790 return rc;
70794 ** If the memory cell contains a value that must be freed by
70795 ** invoking the external callback in Mem.xDel, then this routine
70796 ** will free that value. It also sets Mem.flags to MEM_Null.
70798 ** This is a helper routine for sqlite3VdbeMemSetNull() and
70799 ** for sqlite3VdbeMemRelease(). Use those other routines as the
70800 ** entry point for releasing Mem resources.
70802 static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
70803 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
70804 assert( VdbeMemDynamic(p) );
70805 if( p->flags&MEM_Agg ){
70806 sqlite3VdbeMemFinalize(p, p->u.pDef);
70807 assert( (p->flags & MEM_Agg)==0 );
70808 testcase( p->flags & MEM_Dyn );
70810 if( p->flags&MEM_Dyn ){
70811 assert( (p->flags&MEM_RowSet)==0 );
70812 assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
70813 p->xDel((void *)p->z);
70814 }else if( p->flags&MEM_RowSet ){
70815 sqlite3RowSetClear(p->u.pRowSet);
70816 }else if( p->flags&MEM_Frame ){
70817 VdbeFrame *pFrame = p->u.pFrame;
70818 pFrame->pParent = pFrame->v->pDelFrame;
70819 pFrame->v->pDelFrame = pFrame;
70821 p->flags = MEM_Null;
70825 ** Release memory held by the Mem p, both external memory cleared
70826 ** by p->xDel and memory in p->zMalloc.
70828 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
70829 ** the unusual case where there really is memory in p that needs
70830 ** to be freed.
70832 static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
70833 if( VdbeMemDynamic(p) ){
70834 vdbeMemClearExternAndSetNull(p);
70836 if( p->szMalloc ){
70837 sqlite3DbFreeNN(p->db, p->zMalloc);
70838 p->szMalloc = 0;
70840 p->z = 0;
70844 ** Release any memory resources held by the Mem. Both the memory that is
70845 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
70847 ** Use this routine prior to clean up prior to abandoning a Mem, or to
70848 ** reset a Mem back to its minimum memory utilization.
70850 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
70851 ** prior to inserting new content into the Mem.
70853 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
70854 assert( sqlite3VdbeCheckMemInvariants(p) );
70855 if( VdbeMemDynamic(p) || p->szMalloc ){
70856 vdbeMemClear(p);
70861 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
70862 ** If the double is out of range of a 64-bit signed integer then
70863 ** return the closest available 64-bit signed integer.
70865 static SQLITE_NOINLINE i64 doubleToInt64(double r){
70866 #ifdef SQLITE_OMIT_FLOATING_POINT
70867 /* When floating-point is omitted, double and int64 are the same thing */
70868 return r;
70869 #else
70871 ** Many compilers we encounter do not define constants for the
70872 ** minimum and maximum 64-bit integers, or they define them
70873 ** inconsistently. And many do not understand the "LL" notation.
70874 ** So we define our own static constants here using nothing
70875 ** larger than a 32-bit integer constant.
70877 static const i64 maxInt = LARGEST_INT64;
70878 static const i64 minInt = SMALLEST_INT64;
70880 if( r<=(double)minInt ){
70881 return minInt;
70882 }else if( r>=(double)maxInt ){
70883 return maxInt;
70884 }else{
70885 return (i64)r;
70887 #endif
70891 ** Return some kind of integer value which is the best we can do
70892 ** at representing the value that *pMem describes as an integer.
70893 ** If pMem is an integer, then the value is exact. If pMem is
70894 ** a floating-point then the value returned is the integer part.
70895 ** If pMem is a string or blob, then we make an attempt to convert
70896 ** it into an integer and return that. If pMem represents an
70897 ** an SQL-NULL value, return 0.
70899 ** If pMem represents a string value, its encoding might be changed.
70901 static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
70902 i64 value = 0;
70903 sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
70904 return value;
70906 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
70907 int flags;
70908 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70909 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70910 flags = pMem->flags;
70911 if( flags & MEM_Int ){
70912 return pMem->u.i;
70913 }else if( flags & MEM_Real ){
70914 return doubleToInt64(pMem->u.r);
70915 }else if( flags & (MEM_Str|MEM_Blob) ){
70916 assert( pMem->z || pMem->n==0 );
70917 return memIntValue(pMem);
70918 }else{
70919 return 0;
70924 ** Return the best representation of pMem that we can get into a
70925 ** double. If pMem is already a double or an integer, return its
70926 ** value. If it is a string or blob, try to convert it to a double.
70927 ** If it is a NULL, return 0.0.
70929 static SQLITE_NOINLINE double memRealValue(Mem *pMem){
70930 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
70931 double val = (double)0;
70932 sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
70933 return val;
70935 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
70936 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70937 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70938 if( pMem->flags & MEM_Real ){
70939 return pMem->u.r;
70940 }else if( pMem->flags & MEM_Int ){
70941 return (double)pMem->u.i;
70942 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
70943 return memRealValue(pMem);
70944 }else{
70945 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
70946 return (double)0;
70951 ** The MEM structure is already a MEM_Real. Try to also make it a
70952 ** MEM_Int if we can.
70954 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
70955 i64 ix;
70956 assert( pMem->flags & MEM_Real );
70957 assert( (pMem->flags & MEM_RowSet)==0 );
70958 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70959 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70961 ix = doubleToInt64(pMem->u.r);
70963 /* Only mark the value as an integer if
70965 ** (1) the round-trip conversion real->int->real is a no-op, and
70966 ** (2) The integer is neither the largest nor the smallest
70967 ** possible integer (ticket #3922)
70969 ** The second and third terms in the following conditional enforces
70970 ** the second condition under the assumption that addition overflow causes
70971 ** values to wrap around.
70973 if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
70974 pMem->u.i = ix;
70975 MemSetTypeFlag(pMem, MEM_Int);
70980 ** Convert pMem to type integer. Invalidate any prior representations.
70982 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
70983 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70984 assert( (pMem->flags & MEM_RowSet)==0 );
70985 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70987 pMem->u.i = sqlite3VdbeIntValue(pMem);
70988 MemSetTypeFlag(pMem, MEM_Int);
70989 return SQLITE_OK;
70993 ** Convert pMem so that it is of type MEM_Real.
70994 ** Invalidate any prior representations.
70996 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
70997 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70998 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
71000 pMem->u.r = sqlite3VdbeRealValue(pMem);
71001 MemSetTypeFlag(pMem, MEM_Real);
71002 return SQLITE_OK;
71006 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
71007 ** Invalidate any prior representations.
71009 ** Every effort is made to force the conversion, even if the input
71010 ** is a string that does not look completely like a number. Convert
71011 ** as much of the string as we can and ignore the rest.
71013 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
71014 if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
71015 int rc;
71016 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
71017 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
71018 rc = sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc);
71019 if( rc==0 ){
71020 MemSetTypeFlag(pMem, MEM_Int);
71021 }else{
71022 i64 i = pMem->u.i;
71023 sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
71024 if( rc==1 && pMem->u.r==(double)i ){
71025 pMem->u.i = i;
71026 MemSetTypeFlag(pMem, MEM_Int);
71027 }else{
71028 MemSetTypeFlag(pMem, MEM_Real);
71032 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
71033 pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
71034 return SQLITE_OK;
71038 ** Cast the datatype of the value in pMem according to the affinity
71039 ** "aff". Casting is different from applying affinity in that a cast
71040 ** is forced. In other words, the value is converted into the desired
71041 ** affinity even if that results in loss of data. This routine is
71042 ** used (for example) to implement the SQL "cast()" operator.
71044 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
71045 if( pMem->flags & MEM_Null ) return;
71046 switch( aff ){
71047 case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
71048 if( (pMem->flags & MEM_Blob)==0 ){
71049 sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
71050 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
71051 if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
71052 }else{
71053 pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
71055 break;
71057 case SQLITE_AFF_NUMERIC: {
71058 sqlite3VdbeMemNumerify(pMem);
71059 break;
71061 case SQLITE_AFF_INTEGER: {
71062 sqlite3VdbeMemIntegerify(pMem);
71063 break;
71065 case SQLITE_AFF_REAL: {
71066 sqlite3VdbeMemRealify(pMem);
71067 break;
71069 default: {
71070 assert( aff==SQLITE_AFF_TEXT );
71071 assert( MEM_Str==(MEM_Blob>>3) );
71072 pMem->flags |= (pMem->flags&MEM_Blob)>>3;
71073 sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
71074 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
71075 pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
71076 break;
71082 ** Initialize bulk memory to be a consistent Mem object.
71084 ** The minimum amount of initialization feasible is performed.
71086 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
71087 assert( (flags & ~MEM_TypeMask)==0 );
71088 pMem->flags = flags;
71089 pMem->db = db;
71090 pMem->szMalloc = 0;
71095 ** Delete any previous value and set the value stored in *pMem to NULL.
71097 ** This routine calls the Mem.xDel destructor to dispose of values that
71098 ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
71099 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
71100 ** routine to invoke the destructor and deallocates Mem.zMalloc.
71102 ** Use this routine to reset the Mem prior to insert a new value.
71104 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
71106 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
71107 if( VdbeMemDynamic(pMem) ){
71108 vdbeMemClearExternAndSetNull(pMem);
71109 }else{
71110 pMem->flags = MEM_Null;
71113 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
71114 sqlite3VdbeMemSetNull((Mem*)p);
71118 ** Delete any previous value and set the value to be a BLOB of length
71119 ** n containing all zeros.
71121 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
71122 sqlite3VdbeMemRelease(pMem);
71123 pMem->flags = MEM_Blob|MEM_Zero;
71124 pMem->n = 0;
71125 if( n<0 ) n = 0;
71126 pMem->u.nZero = n;
71127 pMem->enc = SQLITE_UTF8;
71128 pMem->z = 0;
71132 ** The pMem is known to contain content that needs to be destroyed prior
71133 ** to a value change. So invoke the destructor, then set the value to
71134 ** a 64-bit integer.
71136 static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
71137 sqlite3VdbeMemSetNull(pMem);
71138 pMem->u.i = val;
71139 pMem->flags = MEM_Int;
71143 ** Delete any previous value and set the value stored in *pMem to val,
71144 ** manifest type INTEGER.
71146 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
71147 if( VdbeMemDynamic(pMem) ){
71148 vdbeReleaseAndSetInt64(pMem, val);
71149 }else{
71150 pMem->u.i = val;
71151 pMem->flags = MEM_Int;
71155 /* A no-op destructor */
71156 static void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
71159 ** Set the value stored in *pMem should already be a NULL.
71160 ** Also store a pointer to go with it.
71162 SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
71163 Mem *pMem,
71164 void *pPtr,
71165 const char *zPType,
71166 void (*xDestructor)(void*)
71168 assert( pMem->flags==MEM_Null );
71169 pMem->u.zPType = zPType ? zPType : "";
71170 pMem->z = pPtr;
71171 pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
71172 pMem->eSubtype = 'p';
71173 pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
71176 #ifndef SQLITE_OMIT_FLOATING_POINT
71178 ** Delete any previous value and set the value stored in *pMem to val,
71179 ** manifest type REAL.
71181 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
71182 sqlite3VdbeMemSetNull(pMem);
71183 if( !sqlite3IsNaN(val) ){
71184 pMem->u.r = val;
71185 pMem->flags = MEM_Real;
71188 #endif
71191 ** Delete any previous value and set the value of pMem to be an
71192 ** empty boolean index.
71194 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
71195 sqlite3 *db = pMem->db;
71196 assert( db!=0 );
71197 assert( (pMem->flags & MEM_RowSet)==0 );
71198 sqlite3VdbeMemRelease(pMem);
71199 pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
71200 if( db->mallocFailed ){
71201 pMem->flags = MEM_Null;
71202 pMem->szMalloc = 0;
71203 }else{
71204 assert( pMem->zMalloc );
71205 pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
71206 pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
71207 assert( pMem->u.pRowSet!=0 );
71208 pMem->flags = MEM_RowSet;
71213 ** Return true if the Mem object contains a TEXT or BLOB that is
71214 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
71216 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
71217 assert( p->db!=0 );
71218 if( p->flags & (MEM_Str|MEM_Blob) ){
71219 int n = p->n;
71220 if( p->flags & MEM_Zero ){
71221 n += p->u.nZero;
71223 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
71225 return 0;
71228 #ifdef SQLITE_DEBUG
71230 ** This routine prepares a memory cell for modification by breaking
71231 ** its link to a shallow copy and by marking any current shallow
71232 ** copies of this cell as invalid.
71234 ** This is used for testing and debugging only - to make sure shallow
71235 ** copies are not misused.
71237 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
71238 int i;
71239 Mem *pX;
71240 for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
71241 if( pX->pScopyFrom==pMem ){
71242 pX->flags |= MEM_Undefined;
71243 pX->pScopyFrom = 0;
71246 pMem->pScopyFrom = 0;
71248 #endif /* SQLITE_DEBUG */
71252 ** Make an shallow copy of pFrom into pTo. Prior contents of
71253 ** pTo are freed. The pFrom->z field is not duplicated. If
71254 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
71255 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
71257 static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
71258 vdbeMemClearExternAndSetNull(pTo);
71259 assert( !VdbeMemDynamic(pTo) );
71260 sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
71262 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
71263 assert( (pFrom->flags & MEM_RowSet)==0 );
71264 assert( pTo->db==pFrom->db );
71265 if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
71266 memcpy(pTo, pFrom, MEMCELLSIZE);
71267 if( (pFrom->flags&MEM_Static)==0 ){
71268 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
71269 assert( srcType==MEM_Ephem || srcType==MEM_Static );
71270 pTo->flags |= srcType;
71275 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
71276 ** freed before the copy is made.
71278 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
71279 int rc = SQLITE_OK;
71281 assert( (pFrom->flags & MEM_RowSet)==0 );
71282 if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
71283 memcpy(pTo, pFrom, MEMCELLSIZE);
71284 pTo->flags &= ~MEM_Dyn;
71285 if( pTo->flags&(MEM_Str|MEM_Blob) ){
71286 if( 0==(pFrom->flags&MEM_Static) ){
71287 pTo->flags |= MEM_Ephem;
71288 rc = sqlite3VdbeMemMakeWriteable(pTo);
71292 return rc;
71296 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
71297 ** freed. If pFrom contains ephemeral data, a copy is made.
71299 ** pFrom contains an SQL NULL when this routine returns.
71301 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
71302 assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
71303 assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
71304 assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
71306 sqlite3VdbeMemRelease(pTo);
71307 memcpy(pTo, pFrom, sizeof(Mem));
71308 pFrom->flags = MEM_Null;
71309 pFrom->szMalloc = 0;
71313 ** Change the value of a Mem to be a string or a BLOB.
71315 ** The memory management strategy depends on the value of the xDel
71316 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
71317 ** string is copied into a (possibly existing) buffer managed by the
71318 ** Mem structure. Otherwise, any existing buffer is freed and the
71319 ** pointer copied.
71321 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
71322 ** size limit) then no memory allocation occurs. If the string can be
71323 ** stored without allocating memory, then it is. If a memory allocation
71324 ** is required to store the string, then value of pMem is unchanged. In
71325 ** either case, SQLITE_TOOBIG is returned.
71327 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
71328 Mem *pMem, /* Memory cell to set to string value */
71329 const char *z, /* String pointer */
71330 int n, /* Bytes in string, or negative */
71331 u8 enc, /* Encoding of z. 0 for BLOBs */
71332 void (*xDel)(void*) /* Destructor function */
71334 int nByte = n; /* New value for pMem->n */
71335 int iLimit; /* Maximum allowed string or blob size */
71336 u16 flags = 0; /* New value for pMem->flags */
71338 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
71339 assert( (pMem->flags & MEM_RowSet)==0 );
71341 /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
71342 if( !z ){
71343 sqlite3VdbeMemSetNull(pMem);
71344 return SQLITE_OK;
71347 if( pMem->db ){
71348 iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
71349 }else{
71350 iLimit = SQLITE_MAX_LENGTH;
71352 flags = (enc==0?MEM_Blob:MEM_Str);
71353 if( nByte<0 ){
71354 assert( enc!=0 );
71355 if( enc==SQLITE_UTF8 ){
71356 nByte = 0x7fffffff & (int)strlen(z);
71357 if( nByte>iLimit ) nByte = iLimit+1;
71358 }else{
71359 for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
71361 flags |= MEM_Term;
71364 /* The following block sets the new values of Mem.z and Mem.xDel. It
71365 ** also sets a flag in local variable "flags" to indicate the memory
71366 ** management (one of MEM_Dyn or MEM_Static).
71368 if( xDel==SQLITE_TRANSIENT ){
71369 int nAlloc = nByte;
71370 if( flags&MEM_Term ){
71371 nAlloc += (enc==SQLITE_UTF8?1:2);
71373 if( nByte>iLimit ){
71374 return SQLITE_TOOBIG;
71376 testcase( nAlloc==0 );
71377 testcase( nAlloc==31 );
71378 testcase( nAlloc==32 );
71379 if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
71380 return SQLITE_NOMEM_BKPT;
71382 memcpy(pMem->z, z, nAlloc);
71383 }else if( xDel==SQLITE_DYNAMIC ){
71384 sqlite3VdbeMemRelease(pMem);
71385 pMem->zMalloc = pMem->z = (char *)z;
71386 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
71387 }else{
71388 sqlite3VdbeMemRelease(pMem);
71389 pMem->z = (char *)z;
71390 pMem->xDel = xDel;
71391 flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
71394 pMem->n = nByte;
71395 pMem->flags = flags;
71396 pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
71398 #ifndef SQLITE_OMIT_UTF16
71399 if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
71400 return SQLITE_NOMEM_BKPT;
71402 #endif
71404 if( nByte>iLimit ){
71405 return SQLITE_TOOBIG;
71408 return SQLITE_OK;
71412 ** Move data out of a btree key or data field and into a Mem structure.
71413 ** The data is payload from the entry that pCur is currently pointing
71414 ** to. offset and amt determine what portion of the data or key to retrieve.
71415 ** The result is written into the pMem element.
71417 ** The pMem object must have been initialized. This routine will use
71418 ** pMem->zMalloc to hold the content from the btree, if possible. New
71419 ** pMem->zMalloc space will be allocated if necessary. The calling routine
71420 ** is responsible for making sure that the pMem object is eventually
71421 ** destroyed.
71423 ** If this routine fails for any reason (malloc returns NULL or unable
71424 ** to read from the disk) then the pMem is left in an inconsistent state.
71426 static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
71427 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
71428 u32 offset, /* Offset from the start of data to return bytes from. */
71429 u32 amt, /* Number of bytes to return. */
71430 Mem *pMem /* OUT: Return data in this Mem structure. */
71432 int rc;
71433 pMem->flags = MEM_Null;
71434 if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
71435 rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
71436 if( rc==SQLITE_OK ){
71437 pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
71438 pMem->flags = MEM_Blob;
71439 pMem->n = (int)amt;
71440 }else{
71441 sqlite3VdbeMemRelease(pMem);
71444 return rc;
71446 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
71447 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
71448 u32 offset, /* Offset from the start of data to return bytes from. */
71449 u32 amt, /* Number of bytes to return. */
71450 Mem *pMem /* OUT: Return data in this Mem structure. */
71452 char *zData; /* Data from the btree layer */
71453 u32 available = 0; /* Number of bytes available on the local btree page */
71454 int rc = SQLITE_OK; /* Return code */
71456 assert( sqlite3BtreeCursorIsValid(pCur) );
71457 assert( !VdbeMemDynamic(pMem) );
71459 /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
71460 ** that both the BtShared and database handle mutexes are held. */
71461 assert( (pMem->flags & MEM_RowSet)==0 );
71462 zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
71463 assert( zData!=0 );
71465 if( offset+amt<=available ){
71466 pMem->z = &zData[offset];
71467 pMem->flags = MEM_Blob|MEM_Ephem;
71468 pMem->n = (int)amt;
71469 }else{
71470 rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
71473 return rc;
71477 ** The pVal argument is known to be a value other than NULL.
71478 ** Convert it into a string with encoding enc and return a pointer
71479 ** to a zero-terminated version of that string.
71481 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
71482 assert( pVal!=0 );
71483 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
71484 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
71485 assert( (pVal->flags & MEM_RowSet)==0 );
71486 assert( (pVal->flags & (MEM_Null))==0 );
71487 if( pVal->flags & (MEM_Blob|MEM_Str) ){
71488 if( ExpandBlob(pVal) ) return 0;
71489 pVal->flags |= MEM_Str;
71490 if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
71491 sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
71493 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
71494 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
71495 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
71496 return 0;
71499 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
71500 }else{
71501 sqlite3VdbeMemStringify(pVal, enc, 0);
71502 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
71504 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
71505 || pVal->db->mallocFailed );
71506 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
71507 return pVal->z;
71508 }else{
71509 return 0;
71513 /* This function is only available internally, it is not part of the
71514 ** external API. It works in a similar way to sqlite3_value_text(),
71515 ** except the data returned is in the encoding specified by the second
71516 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
71517 ** SQLITE_UTF8.
71519 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
71520 ** If that is the case, then the result must be aligned on an even byte
71521 ** boundary.
71523 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
71524 if( !pVal ) return 0;
71525 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
71526 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
71527 assert( (pVal->flags & MEM_RowSet)==0 );
71528 if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
71529 return pVal->z;
71531 if( pVal->flags&MEM_Null ){
71532 return 0;
71534 return valueToText(pVal, enc);
71538 ** Create a new sqlite3_value object.
71540 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
71541 Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
71542 if( p ){
71543 p->flags = MEM_Null;
71544 p->db = db;
71546 return p;
71550 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
71551 ** valueNew(). See comments above valueNew() for details.
71553 struct ValueNewStat4Ctx {
71554 Parse *pParse;
71555 Index *pIdx;
71556 UnpackedRecord **ppRec;
71557 int iVal;
71561 ** Allocate and return a pointer to a new sqlite3_value object. If
71562 ** the second argument to this function is NULL, the object is allocated
71563 ** by calling sqlite3ValueNew().
71565 ** Otherwise, if the second argument is non-zero, then this function is
71566 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
71567 ** already been allocated, allocate the UnpackedRecord structure that
71568 ** that function will return to its caller here. Then return a pointer to
71569 ** an sqlite3_value within the UnpackedRecord.a[] array.
71571 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
71572 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71573 if( p ){
71574 UnpackedRecord *pRec = p->ppRec[0];
71576 if( pRec==0 ){
71577 Index *pIdx = p->pIdx; /* Index being probed */
71578 int nByte; /* Bytes of space to allocate */
71579 int i; /* Counter variable */
71580 int nCol = pIdx->nColumn; /* Number of index columns including rowid */
71582 nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
71583 pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
71584 if( pRec ){
71585 pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
71586 if( pRec->pKeyInfo ){
71587 assert( pRec->pKeyInfo->nAllField==nCol );
71588 assert( pRec->pKeyInfo->enc==ENC(db) );
71589 pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
71590 for(i=0; i<nCol; i++){
71591 pRec->aMem[i].flags = MEM_Null;
71592 pRec->aMem[i].db = db;
71594 }else{
71595 sqlite3DbFreeNN(db, pRec);
71596 pRec = 0;
71599 if( pRec==0 ) return 0;
71600 p->ppRec[0] = pRec;
71603 pRec->nField = p->iVal+1;
71604 return &pRec->aMem[p->iVal];
71606 #else
71607 UNUSED_PARAMETER(p);
71608 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
71609 return sqlite3ValueNew(db);
71613 ** The expression object indicated by the second argument is guaranteed
71614 ** to be a scalar SQL function. If
71616 ** * all function arguments are SQL literals,
71617 ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
71618 ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
71620 ** then this routine attempts to invoke the SQL function. Assuming no
71621 ** error occurs, output parameter (*ppVal) is set to point to a value
71622 ** object containing the result before returning SQLITE_OK.
71624 ** Affinity aff is applied to the result of the function before returning.
71625 ** If the result is a text value, the sqlite3_value object uses encoding
71626 ** enc.
71628 ** If the conditions above are not met, this function returns SQLITE_OK
71629 ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
71630 ** NULL and an SQLite error code returned.
71632 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71633 static int valueFromFunction(
71634 sqlite3 *db, /* The database connection */
71635 Expr *p, /* The expression to evaluate */
71636 u8 enc, /* Encoding to use */
71637 u8 aff, /* Affinity to use */
71638 sqlite3_value **ppVal, /* Write the new value here */
71639 struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
71641 sqlite3_context ctx; /* Context object for function invocation */
71642 sqlite3_value **apVal = 0; /* Function arguments */
71643 int nVal = 0; /* Size of apVal[] array */
71644 FuncDef *pFunc = 0; /* Function definition */
71645 sqlite3_value *pVal = 0; /* New value */
71646 int rc = SQLITE_OK; /* Return code */
71647 ExprList *pList = 0; /* Function arguments */
71648 int i; /* Iterator variable */
71650 assert( pCtx!=0 );
71651 assert( (p->flags & EP_TokenOnly)==0 );
71652 pList = p->x.pList;
71653 if( pList ) nVal = pList->nExpr;
71654 pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
71655 assert( pFunc );
71656 if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
71657 || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
71659 return SQLITE_OK;
71662 if( pList ){
71663 apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
71664 if( apVal==0 ){
71665 rc = SQLITE_NOMEM_BKPT;
71666 goto value_from_function_out;
71668 for(i=0; i<nVal; i++){
71669 rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
71670 if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
71674 pVal = valueNew(db, pCtx);
71675 if( pVal==0 ){
71676 rc = SQLITE_NOMEM_BKPT;
71677 goto value_from_function_out;
71680 assert( pCtx->pParse->rc==SQLITE_OK );
71681 memset(&ctx, 0, sizeof(ctx));
71682 ctx.pOut = pVal;
71683 ctx.pFunc = pFunc;
71684 pFunc->xSFunc(&ctx, nVal, apVal);
71685 if( ctx.isError ){
71686 rc = ctx.isError;
71687 sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
71688 }else{
71689 sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
71690 assert( rc==SQLITE_OK );
71691 rc = sqlite3VdbeChangeEncoding(pVal, enc);
71692 if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
71693 rc = SQLITE_TOOBIG;
71694 pCtx->pParse->nErr++;
71697 pCtx->pParse->rc = rc;
71699 value_from_function_out:
71700 if( rc!=SQLITE_OK ){
71701 pVal = 0;
71703 if( apVal ){
71704 for(i=0; i<nVal; i++){
71705 sqlite3ValueFree(apVal[i]);
71707 sqlite3DbFreeNN(db, apVal);
71710 *ppVal = pVal;
71711 return rc;
71713 #else
71714 # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
71715 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
71718 ** Extract a value from the supplied expression in the manner described
71719 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
71720 ** using valueNew().
71722 ** If pCtx is NULL and an error occurs after the sqlite3_value object
71723 ** has been allocated, it is freed before returning. Or, if pCtx is not
71724 ** NULL, it is assumed that the caller will free any allocated object
71725 ** in all cases.
71727 static int valueFromExpr(
71728 sqlite3 *db, /* The database connection */
71729 Expr *pExpr, /* The expression to evaluate */
71730 u8 enc, /* Encoding to use */
71731 u8 affinity, /* Affinity to use */
71732 sqlite3_value **ppVal, /* Write the new value here */
71733 struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
71735 int op;
71736 char *zVal = 0;
71737 sqlite3_value *pVal = 0;
71738 int negInt = 1;
71739 const char *zNeg = "";
71740 int rc = SQLITE_OK;
71742 assert( pExpr!=0 );
71743 while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
71744 if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
71746 /* Compressed expressions only appear when parsing the DEFAULT clause
71747 ** on a table column definition, and hence only when pCtx==0. This
71748 ** check ensures that an EP_TokenOnly expression is never passed down
71749 ** into valueFromFunction(). */
71750 assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
71752 if( op==TK_CAST ){
71753 u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
71754 rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
71755 testcase( rc!=SQLITE_OK );
71756 if( *ppVal ){
71757 sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
71758 sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
71760 return rc;
71763 /* Handle negative integers in a single step. This is needed in the
71764 ** case when the value is -9223372036854775808.
71766 if( op==TK_UMINUS
71767 && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
71768 pExpr = pExpr->pLeft;
71769 op = pExpr->op;
71770 negInt = -1;
71771 zNeg = "-";
71774 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
71775 pVal = valueNew(db, pCtx);
71776 if( pVal==0 ) goto no_mem;
71777 if( ExprHasProperty(pExpr, EP_IntValue) ){
71778 sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
71779 }else{
71780 zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
71781 if( zVal==0 ) goto no_mem;
71782 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
71784 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
71785 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
71786 }else{
71787 sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
71789 if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
71790 if( enc!=SQLITE_UTF8 ){
71791 rc = sqlite3VdbeChangeEncoding(pVal, enc);
71793 }else if( op==TK_UMINUS ) {
71794 /* This branch happens for multiple negative signs. Ex: -(-5) */
71795 if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
71796 && pVal!=0
71798 sqlite3VdbeMemNumerify(pVal);
71799 if( pVal->flags & MEM_Real ){
71800 pVal->u.r = -pVal->u.r;
71801 }else if( pVal->u.i==SMALLEST_INT64 ){
71802 pVal->u.r = -(double)SMALLEST_INT64;
71803 MemSetTypeFlag(pVal, MEM_Real);
71804 }else{
71805 pVal->u.i = -pVal->u.i;
71807 sqlite3ValueApplyAffinity(pVal, affinity, enc);
71809 }else if( op==TK_NULL ){
71810 pVal = valueNew(db, pCtx);
71811 if( pVal==0 ) goto no_mem;
71812 sqlite3VdbeMemNumerify(pVal);
71814 #ifndef SQLITE_OMIT_BLOB_LITERAL
71815 else if( op==TK_BLOB ){
71816 int nVal;
71817 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
71818 assert( pExpr->u.zToken[1]=='\'' );
71819 pVal = valueNew(db, pCtx);
71820 if( !pVal ) goto no_mem;
71821 zVal = &pExpr->u.zToken[2];
71822 nVal = sqlite3Strlen30(zVal)-1;
71823 assert( zVal[nVal]=='\'' );
71824 sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
71825 0, SQLITE_DYNAMIC);
71827 #endif
71829 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71830 else if( op==TK_FUNCTION && pCtx!=0 ){
71831 rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
71833 #endif
71835 *ppVal = pVal;
71836 return rc;
71838 no_mem:
71839 sqlite3OomFault(db);
71840 sqlite3DbFree(db, zVal);
71841 assert( *ppVal==0 );
71842 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71843 if( pCtx==0 ) sqlite3ValueFree(pVal);
71844 #else
71845 assert( pCtx==0 ); sqlite3ValueFree(pVal);
71846 #endif
71847 return SQLITE_NOMEM_BKPT;
71851 ** Create a new sqlite3_value object, containing the value of pExpr.
71853 ** This only works for very simple expressions that consist of one constant
71854 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
71855 ** be converted directly into a value, then the value is allocated and
71856 ** a pointer written to *ppVal. The caller is responsible for deallocating
71857 ** the value by passing it to sqlite3ValueFree() later on. If the expression
71858 ** cannot be converted to a value, then *ppVal is set to NULL.
71860 SQLITE_PRIVATE int sqlite3ValueFromExpr(
71861 sqlite3 *db, /* The database connection */
71862 Expr *pExpr, /* The expression to evaluate */
71863 u8 enc, /* Encoding to use */
71864 u8 affinity, /* Affinity to use */
71865 sqlite3_value **ppVal /* Write the new value here */
71867 return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
71870 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71872 ** The implementation of the sqlite_record() function. This function accepts
71873 ** a single argument of any type. The return value is a formatted database
71874 ** record (a blob) containing the argument value.
71876 ** This is used to convert the value stored in the 'sample' column of the
71877 ** sqlite_stat3 table to the record format SQLite uses internally.
71879 static void recordFunc(
71880 sqlite3_context *context,
71881 int argc,
71882 sqlite3_value **argv
71884 const int file_format = 1;
71885 u32 iSerial; /* Serial type */
71886 int nSerial; /* Bytes of space for iSerial as varint */
71887 u32 nVal; /* Bytes of space required for argv[0] */
71888 int nRet;
71889 sqlite3 *db;
71890 u8 *aRet;
71892 UNUSED_PARAMETER( argc );
71893 iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
71894 nSerial = sqlite3VarintLen(iSerial);
71895 db = sqlite3_context_db_handle(context);
71897 nRet = 1 + nSerial + nVal;
71898 aRet = sqlite3DbMallocRawNN(db, nRet);
71899 if( aRet==0 ){
71900 sqlite3_result_error_nomem(context);
71901 }else{
71902 aRet[0] = nSerial+1;
71903 putVarint32(&aRet[1], iSerial);
71904 sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
71905 sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
71906 sqlite3DbFreeNN(db, aRet);
71911 ** Register built-in functions used to help read ANALYZE data.
71913 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
71914 static FuncDef aAnalyzeTableFuncs[] = {
71915 FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
71917 sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
71921 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
71923 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
71924 ** pAlloc if one does not exist and the new value is added to the
71925 ** UnpackedRecord object.
71927 ** A value is extracted in the following cases:
71929 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
71931 ** * The expression is a bound variable, and this is a reprepare, or
71933 ** * The expression is a literal value.
71935 ** On success, *ppVal is made to point to the extracted value. The caller
71936 ** is responsible for ensuring that the value is eventually freed.
71938 static int stat4ValueFromExpr(
71939 Parse *pParse, /* Parse context */
71940 Expr *pExpr, /* The expression to extract a value from */
71941 u8 affinity, /* Affinity to use */
71942 struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
71943 sqlite3_value **ppVal /* OUT: New value object (or NULL) */
71945 int rc = SQLITE_OK;
71946 sqlite3_value *pVal = 0;
71947 sqlite3 *db = pParse->db;
71949 /* Skip over any TK_COLLATE nodes */
71950 pExpr = sqlite3ExprSkipCollate(pExpr);
71952 assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
71953 if( !pExpr ){
71954 pVal = valueNew(db, pAlloc);
71955 if( pVal ){
71956 sqlite3VdbeMemSetNull((Mem*)pVal);
71958 }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
71959 Vdbe *v;
71960 int iBindVar = pExpr->iColumn;
71961 sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
71962 if( (v = pParse->pReprepare)!=0 ){
71963 pVal = valueNew(db, pAlloc);
71964 if( pVal ){
71965 rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
71966 sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
71967 pVal->db = pParse->db;
71970 }else{
71971 rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
71974 assert( pVal==0 || pVal->db==db );
71975 *ppVal = pVal;
71976 return rc;
71980 ** This function is used to allocate and populate UnpackedRecord
71981 ** structures intended to be compared against sample index keys stored
71982 ** in the sqlite_stat4 table.
71984 ** A single call to this function populates zero or more fields of the
71985 ** record starting with field iVal (fields are numbered from left to
71986 ** right starting with 0). A single field is populated if:
71988 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
71990 ** * The expression is a bound variable, and this is a reprepare, or
71992 ** * The sqlite3ValueFromExpr() function is able to extract a value
71993 ** from the expression (i.e. the expression is a literal value).
71995 ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
71996 ** vector components that match either of the two latter criteria listed
71997 ** above.
71999 ** Before any value is appended to the record, the affinity of the
72000 ** corresponding column within index pIdx is applied to it. Before
72001 ** this function returns, output parameter *pnExtract is set to the
72002 ** number of values appended to the record.
72004 ** When this function is called, *ppRec must either point to an object
72005 ** allocated by an earlier call to this function, or must be NULL. If it
72006 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
72007 ** is allocated (and *ppRec set to point to it) before returning.
72009 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
72010 ** error if a value cannot be extracted from pExpr. If an error does
72011 ** occur, an SQLite error code is returned.
72013 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
72014 Parse *pParse, /* Parse context */
72015 Index *pIdx, /* Index being probed */
72016 UnpackedRecord **ppRec, /* IN/OUT: Probe record */
72017 Expr *pExpr, /* The expression to extract a value from */
72018 int nElem, /* Maximum number of values to append */
72019 int iVal, /* Array element to populate */
72020 int *pnExtract /* OUT: Values appended to the record */
72022 int rc = SQLITE_OK;
72023 int nExtract = 0;
72025 if( pExpr==0 || pExpr->op!=TK_SELECT ){
72026 int i;
72027 struct ValueNewStat4Ctx alloc;
72029 alloc.pParse = pParse;
72030 alloc.pIdx = pIdx;
72031 alloc.ppRec = ppRec;
72033 for(i=0; i<nElem; i++){
72034 sqlite3_value *pVal = 0;
72035 Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
72036 u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
72037 alloc.iVal = iVal+i;
72038 rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
72039 if( !pVal ) break;
72040 nExtract++;
72044 *pnExtract = nExtract;
72045 return rc;
72049 ** Attempt to extract a value from expression pExpr using the methods
72050 ** as described for sqlite3Stat4ProbeSetValue() above.
72052 ** If successful, set *ppVal to point to a new value object and return
72053 ** SQLITE_OK. If no value can be extracted, but no other error occurs
72054 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
72055 ** does occur, return an SQLite error code. The final value of *ppVal
72056 ** is undefined in this case.
72058 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
72059 Parse *pParse, /* Parse context */
72060 Expr *pExpr, /* The expression to extract a value from */
72061 u8 affinity, /* Affinity to use */
72062 sqlite3_value **ppVal /* OUT: New value object (or NULL) */
72064 return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
72068 ** Extract the iCol-th column from the nRec-byte record in pRec. Write
72069 ** the column value into *ppVal. If *ppVal is initially NULL then a new
72070 ** sqlite3_value object is allocated.
72072 ** If *ppVal is initially NULL then the caller is responsible for
72073 ** ensuring that the value written into *ppVal is eventually freed.
72075 SQLITE_PRIVATE int sqlite3Stat4Column(
72076 sqlite3 *db, /* Database handle */
72077 const void *pRec, /* Pointer to buffer containing record */
72078 int nRec, /* Size of buffer pRec in bytes */
72079 int iCol, /* Column to extract */
72080 sqlite3_value **ppVal /* OUT: Extracted value */
72082 u32 t; /* a column type code */
72083 int nHdr; /* Size of the header in the record */
72084 int iHdr; /* Next unread header byte */
72085 int iField; /* Next unread data byte */
72086 int szField; /* Size of the current data field */
72087 int i; /* Column index */
72088 u8 *a = (u8*)pRec; /* Typecast byte array */
72089 Mem *pMem = *ppVal; /* Write result into this Mem object */
72091 assert( iCol>0 );
72092 iHdr = getVarint32(a, nHdr);
72093 if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
72094 iField = nHdr;
72095 for(i=0; i<=iCol; i++){
72096 iHdr += getVarint32(&a[iHdr], t);
72097 testcase( iHdr==nHdr );
72098 testcase( iHdr==nHdr+1 );
72099 if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
72100 szField = sqlite3VdbeSerialTypeLen(t);
72101 iField += szField;
72103 testcase( iField==nRec );
72104 testcase( iField==nRec+1 );
72105 if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
72106 if( pMem==0 ){
72107 pMem = *ppVal = sqlite3ValueNew(db);
72108 if( pMem==0 ) return SQLITE_NOMEM_BKPT;
72110 sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
72111 pMem->enc = ENC(db);
72112 return SQLITE_OK;
72116 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
72117 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
72118 ** the object.
72120 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
72121 if( pRec ){
72122 int i;
72123 int nCol = pRec->pKeyInfo->nAllField;
72124 Mem *aMem = pRec->aMem;
72125 sqlite3 *db = aMem[0].db;
72126 for(i=0; i<nCol; i++){
72127 sqlite3VdbeMemRelease(&aMem[i]);
72129 sqlite3KeyInfoUnref(pRec->pKeyInfo);
72130 sqlite3DbFreeNN(db, pRec);
72133 #endif /* ifdef SQLITE_ENABLE_STAT4 */
72136 ** Change the string value of an sqlite3_value object
72138 SQLITE_PRIVATE void sqlite3ValueSetStr(
72139 sqlite3_value *v, /* Value to be set */
72140 int n, /* Length of string z */
72141 const void *z, /* Text of the new string */
72142 u8 enc, /* Encoding to use */
72143 void (*xDel)(void*) /* Destructor for the string */
72145 if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
72149 ** Free an sqlite3_value object
72151 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
72152 if( !v ) return;
72153 sqlite3VdbeMemRelease((Mem *)v);
72154 sqlite3DbFreeNN(((Mem*)v)->db, v);
72158 ** The sqlite3ValueBytes() routine returns the number of bytes in the
72159 ** sqlite3_value object assuming that it uses the encoding "enc".
72160 ** The valueBytes() routine is a helper function.
72162 static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
72163 return valueToText(pVal, enc)!=0 ? pVal->n : 0;
72165 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
72166 Mem *p = (Mem*)pVal;
72167 assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
72168 if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
72169 return p->n;
72171 if( (p->flags & MEM_Blob)!=0 ){
72172 if( p->flags & MEM_Zero ){
72173 return p->n + p->u.nZero;
72174 }else{
72175 return p->n;
72178 if( p->flags & MEM_Null ) return 0;
72179 return valueBytes(pVal, enc);
72182 /************** End of vdbemem.c *********************************************/
72183 /************** Begin file vdbeaux.c *****************************************/
72185 ** 2003 September 6
72187 ** The author disclaims copyright to this source code. In place of
72188 ** a legal notice, here is a blessing:
72190 ** May you do good and not evil.
72191 ** May you find forgiveness for yourself and forgive others.
72192 ** May you share freely, never taking more than you give.
72194 *************************************************************************
72195 ** This file contains code used for creating, destroying, and populating
72196 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
72198 /* #include "sqliteInt.h" */
72199 /* #include "vdbeInt.h" */
72202 ** Create a new virtual database engine.
72204 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
72205 sqlite3 *db = pParse->db;
72206 Vdbe *p;
72207 p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
72208 if( p==0 ) return 0;
72209 memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
72210 p->db = db;
72211 if( db->pVdbe ){
72212 db->pVdbe->pPrev = p;
72214 p->pNext = db->pVdbe;
72215 p->pPrev = 0;
72216 db->pVdbe = p;
72217 p->magic = VDBE_MAGIC_INIT;
72218 p->pParse = pParse;
72219 pParse->pVdbe = p;
72220 assert( pParse->aLabel==0 );
72221 assert( pParse->nLabel==0 );
72222 assert( pParse->nOpAlloc==0 );
72223 assert( pParse->szOpAlloc==0 );
72224 sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
72225 return p;
72229 ** Change the error string stored in Vdbe.zErrMsg
72231 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
72232 va_list ap;
72233 sqlite3DbFree(p->db, p->zErrMsg);
72234 va_start(ap, zFormat);
72235 p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
72236 va_end(ap);
72240 ** Remember the SQL string for a prepared statement.
72242 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
72243 if( p==0 ) return;
72244 p->prepFlags = prepFlags;
72245 if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
72246 p->expmask = 0;
72248 assert( p->zSql==0 );
72249 p->zSql = sqlite3DbStrNDup(p->db, z, n);
72253 ** Swap all content between two VDBE structures.
72255 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
72256 Vdbe tmp, *pTmp;
72257 char *zTmp;
72258 assert( pA->db==pB->db );
72259 tmp = *pA;
72260 *pA = *pB;
72261 *pB = tmp;
72262 pTmp = pA->pNext;
72263 pA->pNext = pB->pNext;
72264 pB->pNext = pTmp;
72265 pTmp = pA->pPrev;
72266 pA->pPrev = pB->pPrev;
72267 pB->pPrev = pTmp;
72268 zTmp = pA->zSql;
72269 pA->zSql = pB->zSql;
72270 pB->zSql = zTmp;
72271 pB->expmask = pA->expmask;
72272 pB->prepFlags = pA->prepFlags;
72273 memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
72274 pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
72278 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
72279 ** than its current size. nOp is guaranteed to be less than or equal
72280 ** to 1024/sizeof(Op).
72282 ** If an out-of-memory error occurs while resizing the array, return
72283 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
72284 ** unchanged (this is so that any opcodes already allocated can be
72285 ** correctly deallocated along with the rest of the Vdbe).
72287 static int growOpArray(Vdbe *v, int nOp){
72288 VdbeOp *pNew;
72289 Parse *p = v->pParse;
72291 /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
72292 ** more frequent reallocs and hence provide more opportunities for
72293 ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
72294 ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
72295 ** by the minimum* amount required until the size reaches 512. Normal
72296 ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
72297 ** size of the op array or add 1KB of space, whichever is smaller. */
72298 #ifdef SQLITE_TEST_REALLOC_STRESS
72299 int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
72300 #else
72301 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
72302 UNUSED_PARAMETER(nOp);
72303 #endif
72305 /* Ensure that the size of a VDBE does not grow too large */
72306 if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
72307 sqlite3OomFault(p->db);
72308 return SQLITE_NOMEM;
72311 assert( nOp<=(1024/sizeof(Op)) );
72312 assert( nNew>=(p->nOpAlloc+nOp) );
72313 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
72314 if( pNew ){
72315 p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
72316 p->nOpAlloc = p->szOpAlloc/sizeof(Op);
72317 v->aOp = pNew;
72319 return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
72322 #ifdef SQLITE_DEBUG
72323 /* This routine is just a convenient place to set a breakpoint that will
72324 ** fire after each opcode is inserted and displayed using
72325 ** "PRAGMA vdbe_addoptrace=on".
72327 static void test_addop_breakpoint(void){
72328 static int n = 0;
72329 n++;
72331 #endif
72334 ** Add a new instruction to the list of instructions current in the
72335 ** VDBE. Return the address of the new instruction.
72337 ** Parameters:
72339 ** p Pointer to the VDBE
72341 ** op The opcode for this instruction
72343 ** p1, p2, p3 Operands
72345 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
72346 ** the sqlite3VdbeChangeP4() function to change the value of the P4
72347 ** operand.
72349 static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
72350 assert( p->pParse->nOpAlloc<=p->nOp );
72351 if( growOpArray(p, 1) ) return 1;
72352 assert( p->pParse->nOpAlloc>p->nOp );
72353 return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
72355 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
72356 int i;
72357 VdbeOp *pOp;
72359 i = p->nOp;
72360 assert( p->magic==VDBE_MAGIC_INIT );
72361 assert( op>=0 && op<0xff );
72362 if( p->pParse->nOpAlloc<=i ){
72363 return growOp3(p, op, p1, p2, p3);
72365 p->nOp++;
72366 pOp = &p->aOp[i];
72367 pOp->opcode = (u8)op;
72368 pOp->p5 = 0;
72369 pOp->p1 = p1;
72370 pOp->p2 = p2;
72371 pOp->p3 = p3;
72372 pOp->p4.p = 0;
72373 pOp->p4type = P4_NOTUSED;
72374 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72375 pOp->zComment = 0;
72376 #endif
72377 #ifdef SQLITE_DEBUG
72378 if( p->db->flags & SQLITE_VdbeAddopTrace ){
72379 int jj, kk;
72380 Parse *pParse = p->pParse;
72381 for(jj=kk=0; jj<pParse->nColCache; jj++){
72382 struct yColCache *x = pParse->aColCache + jj;
72383 printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
72384 kk++;
72386 if( kk ) printf("\n");
72387 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
72388 test_addop_breakpoint();
72390 #endif
72391 #ifdef VDBE_PROFILE
72392 pOp->cycles = 0;
72393 pOp->cnt = 0;
72394 #endif
72395 #ifdef SQLITE_VDBE_COVERAGE
72396 pOp->iSrcLine = 0;
72397 #endif
72398 return i;
72400 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
72401 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
72403 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
72404 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
72406 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
72407 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
72410 /* Generate code for an unconditional jump to instruction iDest
72412 SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
72413 return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
72416 /* Generate code to cause the string zStr to be loaded into
72417 ** register iDest
72419 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
72420 return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
72424 ** Generate code that initializes multiple registers to string or integer
72425 ** constants. The registers begin with iDest and increase consecutively.
72426 ** One register is initialized for each characgter in zTypes[]. For each
72427 ** "s" character in zTypes[], the register is a string if the argument is
72428 ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
72429 ** in zTypes[], the register is initialized to an integer.
72431 ** If the input string does not end with "X" then an OP_ResultRow instruction
72432 ** is generated for the values inserted.
72434 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
72435 va_list ap;
72436 int i;
72437 char c;
72438 va_start(ap, zTypes);
72439 for(i=0; (c = zTypes[i])!=0; i++){
72440 if( c=='s' ){
72441 const char *z = va_arg(ap, const char*);
72442 sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
72443 }else if( c=='i' ){
72444 sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
72445 }else{
72446 goto skip_op_resultrow;
72449 sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
72450 skip_op_resultrow:
72451 va_end(ap);
72455 ** Add an opcode that includes the p4 value as a pointer.
72457 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
72458 Vdbe *p, /* Add the opcode to this VM */
72459 int op, /* The new opcode */
72460 int p1, /* The P1 operand */
72461 int p2, /* The P2 operand */
72462 int p3, /* The P3 operand */
72463 const char *zP4, /* The P4 operand */
72464 int p4type /* P4 operand type */
72466 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
72467 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
72468 return addr;
72472 ** Add an opcode that includes the p4 value with a P4_INT64 or
72473 ** P4_REAL type.
72475 SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
72476 Vdbe *p, /* Add the opcode to this VM */
72477 int op, /* The new opcode */
72478 int p1, /* The P1 operand */
72479 int p2, /* The P2 operand */
72480 int p3, /* The P3 operand */
72481 const u8 *zP4, /* The P4 operand */
72482 int p4type /* P4 operand type */
72484 char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
72485 if( p4copy ) memcpy(p4copy, zP4, 8);
72486 return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
72490 ** Add an OP_ParseSchema opcode. This routine is broken out from
72491 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
72492 ** as having been used.
72494 ** The zWhere string must have been obtained from sqlite3_malloc().
72495 ** This routine will take ownership of the allocated memory.
72497 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
72498 int j;
72499 sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
72500 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
72504 ** Add an opcode that includes the p4 value as an integer.
72506 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
72507 Vdbe *p, /* Add the opcode to this VM */
72508 int op, /* The new opcode */
72509 int p1, /* The P1 operand */
72510 int p2, /* The P2 operand */
72511 int p3, /* The P3 operand */
72512 int p4 /* The P4 operand as an integer */
72514 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
72515 if( p->db->mallocFailed==0 ){
72516 VdbeOp *pOp = &p->aOp[addr];
72517 pOp->p4type = P4_INT32;
72518 pOp->p4.i = p4;
72520 return addr;
72523 /* Insert the end of a co-routine
72525 SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
72526 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
72528 /* Clear the temporary register cache, thereby ensuring that each
72529 ** co-routine has its own independent set of registers, because co-routines
72530 ** might expect their registers to be preserved across an OP_Yield, and
72531 ** that could cause problems if two or more co-routines are using the same
72532 ** temporary register.
72534 v->pParse->nTempReg = 0;
72535 v->pParse->nRangeReg = 0;
72539 ** Create a new symbolic label for an instruction that has yet to be
72540 ** coded. The symbolic label is really just a negative number. The
72541 ** label can be used as the P2 value of an operation. Later, when
72542 ** the label is resolved to a specific address, the VDBE will scan
72543 ** through its operation list and change all values of P2 which match
72544 ** the label into the resolved address.
72546 ** The VDBE knows that a P2 value is a label because labels are
72547 ** always negative and P2 values are suppose to be non-negative.
72548 ** Hence, a negative P2 value is a label that has yet to be resolved.
72550 ** Zero is returned if a malloc() fails.
72552 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
72553 Parse *p = v->pParse;
72554 int i = p->nLabel++;
72555 assert( v->magic==VDBE_MAGIC_INIT );
72556 if( (i & (i-1))==0 ){
72557 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
72558 (i*2+1)*sizeof(p->aLabel[0]));
72560 if( p->aLabel ){
72561 p->aLabel[i] = -1;
72563 return ADDR(i);
72567 ** Resolve label "x" to be the address of the next instruction to
72568 ** be inserted. The parameter "x" must have been obtained from
72569 ** a prior call to sqlite3VdbeMakeLabel().
72571 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
72572 Parse *p = v->pParse;
72573 int j = ADDR(x);
72574 assert( v->magic==VDBE_MAGIC_INIT );
72575 assert( j<p->nLabel );
72576 assert( j>=0 );
72577 if( p->aLabel ){
72578 p->aLabel[j] = v->nOp;
72583 ** Mark the VDBE as one that can only be run one time.
72585 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
72586 p->runOnlyOnce = 1;
72590 ** Mark the VDBE as one that can only be run multiple times.
72592 SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
72593 p->runOnlyOnce = 0;
72596 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
72599 ** The following type and function are used to iterate through all opcodes
72600 ** in a Vdbe main program and each of the sub-programs (triggers) it may
72601 ** invoke directly or indirectly. It should be used as follows:
72603 ** Op *pOp;
72604 ** VdbeOpIter sIter;
72606 ** memset(&sIter, 0, sizeof(sIter));
72607 ** sIter.v = v; // v is of type Vdbe*
72608 ** while( (pOp = opIterNext(&sIter)) ){
72609 ** // Do something with pOp
72610 ** }
72611 ** sqlite3DbFree(v->db, sIter.apSub);
72614 typedef struct VdbeOpIter VdbeOpIter;
72615 struct VdbeOpIter {
72616 Vdbe *v; /* Vdbe to iterate through the opcodes of */
72617 SubProgram **apSub; /* Array of subprograms */
72618 int nSub; /* Number of entries in apSub */
72619 int iAddr; /* Address of next instruction to return */
72620 int iSub; /* 0 = main program, 1 = first sub-program etc. */
72622 static Op *opIterNext(VdbeOpIter *p){
72623 Vdbe *v = p->v;
72624 Op *pRet = 0;
72625 Op *aOp;
72626 int nOp;
72628 if( p->iSub<=p->nSub ){
72630 if( p->iSub==0 ){
72631 aOp = v->aOp;
72632 nOp = v->nOp;
72633 }else{
72634 aOp = p->apSub[p->iSub-1]->aOp;
72635 nOp = p->apSub[p->iSub-1]->nOp;
72637 assert( p->iAddr<nOp );
72639 pRet = &aOp[p->iAddr];
72640 p->iAddr++;
72641 if( p->iAddr==nOp ){
72642 p->iSub++;
72643 p->iAddr = 0;
72646 if( pRet->p4type==P4_SUBPROGRAM ){
72647 int nByte = (p->nSub+1)*sizeof(SubProgram*);
72648 int j;
72649 for(j=0; j<p->nSub; j++){
72650 if( p->apSub[j]==pRet->p4.pProgram ) break;
72652 if( j==p->nSub ){
72653 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
72654 if( !p->apSub ){
72655 pRet = 0;
72656 }else{
72657 p->apSub[p->nSub++] = pRet->p4.pProgram;
72663 return pRet;
72667 ** Check if the program stored in the VM associated with pParse may
72668 ** throw an ABORT exception (causing the statement, but not entire transaction
72669 ** to be rolled back). This condition is true if the main program or any
72670 ** sub-programs contains any of the following:
72672 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
72673 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
72674 ** * OP_Destroy
72675 ** * OP_VUpdate
72676 ** * OP_VRename
72677 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
72678 ** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
72679 ** (for CREATE TABLE AS SELECT ...)
72681 ** Then check that the value of Parse.mayAbort is true if an
72682 ** ABORT may be thrown, or false otherwise. Return true if it does
72683 ** match, or false otherwise. This function is intended to be used as
72684 ** part of an assert statement in the compiler. Similar to:
72686 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
72688 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
72689 int hasAbort = 0;
72690 int hasFkCounter = 0;
72691 int hasCreateTable = 0;
72692 int hasInitCoroutine = 0;
72693 Op *pOp;
72694 VdbeOpIter sIter;
72695 memset(&sIter, 0, sizeof(sIter));
72696 sIter.v = v;
72698 while( (pOp = opIterNext(&sIter))!=0 ){
72699 int opcode = pOp->opcode;
72700 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
72701 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
72702 && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
72704 hasAbort = 1;
72705 break;
72707 if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
72708 if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
72709 #ifndef SQLITE_OMIT_FOREIGN_KEY
72710 if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
72711 hasFkCounter = 1;
72713 #endif
72715 sqlite3DbFree(v->db, sIter.apSub);
72717 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
72718 ** If malloc failed, then the while() loop above may not have iterated
72719 ** through all opcodes and hasAbort may be set incorrectly. Return
72720 ** true for this case to prevent the assert() in the callers frame
72721 ** from failing. */
72722 return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
72723 || (hasCreateTable && hasInitCoroutine) );
72725 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
72728 ** This routine is called after all opcodes have been inserted. It loops
72729 ** through all the opcodes and fixes up some details.
72731 ** (1) For each jump instruction with a negative P2 value (a label)
72732 ** resolve the P2 value to an actual address.
72734 ** (2) Compute the maximum number of arguments used by any SQL function
72735 ** and store that value in *pMaxFuncArgs.
72737 ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
72738 ** indicate what the prepared statement actually does.
72740 ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
72742 ** (5) Reclaim the memory allocated for storing labels.
72744 ** This routine will only function correctly if the mkopcodeh.tcl generator
72745 ** script numbers the opcodes correctly. Changes to this routine must be
72746 ** coordinated with changes to mkopcodeh.tcl.
72748 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
72749 int nMaxArgs = *pMaxFuncArgs;
72750 Op *pOp;
72751 Parse *pParse = p->pParse;
72752 int *aLabel = pParse->aLabel;
72753 p->readOnly = 1;
72754 p->bIsReader = 0;
72755 pOp = &p->aOp[p->nOp-1];
72756 while(1){
72758 /* Only JUMP opcodes and the short list of special opcodes in the switch
72759 ** below need to be considered. The mkopcodeh.tcl generator script groups
72760 ** all these opcodes together near the front of the opcode list. Skip
72761 ** any opcode that does not need processing by virtual of the fact that
72762 ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
72764 if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
72765 /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
72766 ** cases from this switch! */
72767 switch( pOp->opcode ){
72768 case OP_Transaction: {
72769 if( pOp->p2!=0 ) p->readOnly = 0;
72770 /* fall thru */
72772 case OP_AutoCommit:
72773 case OP_Savepoint: {
72774 p->bIsReader = 1;
72775 break;
72777 #ifndef SQLITE_OMIT_WAL
72778 case OP_Checkpoint:
72779 #endif
72780 case OP_Vacuum:
72781 case OP_JournalMode: {
72782 p->readOnly = 0;
72783 p->bIsReader = 1;
72784 break;
72786 case OP_Next:
72787 case OP_NextIfOpen:
72788 case OP_SorterNext: {
72789 pOp->p4.xAdvance = sqlite3BtreeNext;
72790 pOp->p4type = P4_ADVANCE;
72791 /* The code generator never codes any of these opcodes as a jump
72792 ** to a label. They are always coded as a jump backwards to a
72793 ** known address */
72794 assert( pOp->p2>=0 );
72795 break;
72797 case OP_Prev:
72798 case OP_PrevIfOpen: {
72799 pOp->p4.xAdvance = sqlite3BtreePrevious;
72800 pOp->p4type = P4_ADVANCE;
72801 /* The code generator never codes any of these opcodes as a jump
72802 ** to a label. They are always coded as a jump backwards to a
72803 ** known address */
72804 assert( pOp->p2>=0 );
72805 break;
72807 #ifndef SQLITE_OMIT_VIRTUALTABLE
72808 case OP_VUpdate: {
72809 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
72810 break;
72812 case OP_VFilter: {
72813 int n;
72814 assert( (pOp - p->aOp) >= 3 );
72815 assert( pOp[-1].opcode==OP_Integer );
72816 n = pOp[-1].p1;
72817 if( n>nMaxArgs ) nMaxArgs = n;
72818 /* Fall through into the default case */
72820 #endif
72821 default: {
72822 if( pOp->p2<0 ){
72823 /* The mkopcodeh.tcl script has so arranged things that the only
72824 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
72825 ** have non-negative values for P2. */
72826 assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
72827 assert( ADDR(pOp->p2)<pParse->nLabel );
72828 pOp->p2 = aLabel[ADDR(pOp->p2)];
72830 break;
72833 /* The mkopcodeh.tcl script has so arranged things that the only
72834 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
72835 ** have non-negative values for P2. */
72836 assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
72838 if( pOp==p->aOp ) break;
72839 pOp--;
72841 sqlite3DbFree(p->db, pParse->aLabel);
72842 pParse->aLabel = 0;
72843 pParse->nLabel = 0;
72844 *pMaxFuncArgs = nMaxArgs;
72845 assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
72849 ** Return the address of the next instruction to be inserted.
72851 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
72852 assert( p->magic==VDBE_MAGIC_INIT );
72853 return p->nOp;
72857 ** Verify that at least N opcode slots are available in p without
72858 ** having to malloc for more space (except when compiled using
72859 ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
72860 ** to verify that certain calls to sqlite3VdbeAddOpList() can never
72861 ** fail due to a OOM fault and hence that the return value from
72862 ** sqlite3VdbeAddOpList() will always be non-NULL.
72864 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
72865 SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
72866 assert( p->nOp + N <= p->pParse->nOpAlloc );
72868 #endif
72871 ** Verify that the VM passed as the only argument does not contain
72872 ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
72873 ** by code in pragma.c to ensure that the implementation of certain
72874 ** pragmas comports with the flags specified in the mkpragmatab.tcl
72875 ** script.
72877 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
72878 SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
72879 int i;
72880 for(i=0; i<p->nOp; i++){
72881 assert( p->aOp[i].opcode!=OP_ResultRow );
72884 #endif
72887 ** This function returns a pointer to the array of opcodes associated with
72888 ** the Vdbe passed as the first argument. It is the callers responsibility
72889 ** to arrange for the returned array to be eventually freed using the
72890 ** vdbeFreeOpArray() function.
72892 ** Before returning, *pnOp is set to the number of entries in the returned
72893 ** array. Also, *pnMaxArg is set to the larger of its current value and
72894 ** the number of entries in the Vdbe.apArg[] array required to execute the
72895 ** returned program.
72897 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
72898 VdbeOp *aOp = p->aOp;
72899 assert( aOp && !p->db->mallocFailed );
72901 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
72902 assert( DbMaskAllZero(p->btreeMask) );
72904 resolveP2Values(p, pnMaxArg);
72905 *pnOp = p->nOp;
72906 p->aOp = 0;
72907 return aOp;
72911 ** Add a whole list of operations to the operation stack. Return a
72912 ** pointer to the first operation inserted.
72914 ** Non-zero P2 arguments to jump instructions are automatically adjusted
72915 ** so that the jump target is relative to the first operation inserted.
72917 SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
72918 Vdbe *p, /* Add opcodes to the prepared statement */
72919 int nOp, /* Number of opcodes to add */
72920 VdbeOpList const *aOp, /* The opcodes to be added */
72921 int iLineno /* Source-file line number of first opcode */
72923 int i;
72924 VdbeOp *pOut, *pFirst;
72925 assert( nOp>0 );
72926 assert( p->magic==VDBE_MAGIC_INIT );
72927 if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
72928 return 0;
72930 pFirst = pOut = &p->aOp[p->nOp];
72931 for(i=0; i<nOp; i++, aOp++, pOut++){
72932 pOut->opcode = aOp->opcode;
72933 pOut->p1 = aOp->p1;
72934 pOut->p2 = aOp->p2;
72935 assert( aOp->p2>=0 );
72936 if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
72937 pOut->p2 += p->nOp;
72939 pOut->p3 = aOp->p3;
72940 pOut->p4type = P4_NOTUSED;
72941 pOut->p4.p = 0;
72942 pOut->p5 = 0;
72943 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72944 pOut->zComment = 0;
72945 #endif
72946 #ifdef SQLITE_VDBE_COVERAGE
72947 pOut->iSrcLine = iLineno+i;
72948 #else
72949 (void)iLineno;
72950 #endif
72951 #ifdef SQLITE_DEBUG
72952 if( p->db->flags & SQLITE_VdbeAddopTrace ){
72953 sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
72955 #endif
72957 p->nOp += nOp;
72958 return pFirst;
72961 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
72963 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
72965 SQLITE_PRIVATE void sqlite3VdbeScanStatus(
72966 Vdbe *p, /* VM to add scanstatus() to */
72967 int addrExplain, /* Address of OP_Explain (or 0) */
72968 int addrLoop, /* Address of loop counter */
72969 int addrVisit, /* Address of rows visited counter */
72970 LogEst nEst, /* Estimated number of output rows */
72971 const char *zName /* Name of table or index being scanned */
72973 int nByte = (p->nScan+1) * sizeof(ScanStatus);
72974 ScanStatus *aNew;
72975 aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
72976 if( aNew ){
72977 ScanStatus *pNew = &aNew[p->nScan++];
72978 pNew->addrExplain = addrExplain;
72979 pNew->addrLoop = addrLoop;
72980 pNew->addrVisit = addrVisit;
72981 pNew->nEst = nEst;
72982 pNew->zName = sqlite3DbStrDup(p->db, zName);
72983 p->aScan = aNew;
72986 #endif
72990 ** Change the value of the opcode, or P1, P2, P3, or P5 operands
72991 ** for a specific instruction.
72993 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
72994 sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
72996 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
72997 sqlite3VdbeGetOp(p,addr)->p1 = val;
72999 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
73000 sqlite3VdbeGetOp(p,addr)->p2 = val;
73002 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
73003 sqlite3VdbeGetOp(p,addr)->p3 = val;
73005 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
73006 assert( p->nOp>0 || p->db->mallocFailed );
73007 if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
73011 ** Change the P2 operand of instruction addr so that it points to
73012 ** the address of the next instruction to be coded.
73014 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
73015 sqlite3VdbeChangeP2(p, addr, p->nOp);
73020 ** If the input FuncDef structure is ephemeral, then free it. If
73021 ** the FuncDef is not ephermal, then do nothing.
73023 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
73024 if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
73025 sqlite3DbFreeNN(db, pDef);
73029 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
73032 ** Delete a P4 value if necessary.
73034 static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
73035 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
73036 sqlite3DbFreeNN(db, p);
73038 static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
73039 freeEphemeralFunction(db, p->pFunc);
73040 sqlite3DbFreeNN(db, p);
73042 static void freeP4(sqlite3 *db, int p4type, void *p4){
73043 assert( db );
73044 switch( p4type ){
73045 case P4_FUNCCTX: {
73046 freeP4FuncCtx(db, (sqlite3_context*)p4);
73047 break;
73049 case P4_REAL:
73050 case P4_INT64:
73051 case P4_DYNAMIC:
73052 case P4_INTARRAY: {
73053 sqlite3DbFree(db, p4);
73054 break;
73056 case P4_KEYINFO: {
73057 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
73058 break;
73060 #ifdef SQLITE_ENABLE_CURSOR_HINTS
73061 case P4_EXPR: {
73062 sqlite3ExprDelete(db, (Expr*)p4);
73063 break;
73065 #endif
73066 case P4_FUNCDEF: {
73067 freeEphemeralFunction(db, (FuncDef*)p4);
73068 break;
73070 case P4_MEM: {
73071 if( db->pnBytesFreed==0 ){
73072 sqlite3ValueFree((sqlite3_value*)p4);
73073 }else{
73074 freeP4Mem(db, (Mem*)p4);
73076 break;
73078 case P4_VTAB : {
73079 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
73080 break;
73086 ** Free the space allocated for aOp and any p4 values allocated for the
73087 ** opcodes contained within. If aOp is not NULL it is assumed to contain
73088 ** nOp entries.
73090 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
73091 if( aOp ){
73092 Op *pOp;
73093 for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
73094 if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
73095 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
73096 sqlite3DbFree(db, pOp->zComment);
73097 #endif
73099 sqlite3DbFreeNN(db, aOp);
73104 ** Link the SubProgram object passed as the second argument into the linked
73105 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
73106 ** objects when the VM is no longer required.
73108 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
73109 p->pNext = pVdbe->pProgram;
73110 pVdbe->pProgram = p;
73114 ** Change the opcode at addr into OP_Noop
73116 SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
73117 VdbeOp *pOp;
73118 if( p->db->mallocFailed ) return 0;
73119 assert( addr>=0 && addr<p->nOp );
73120 pOp = &p->aOp[addr];
73121 freeP4(p->db, pOp->p4type, pOp->p4.p);
73122 pOp->p4type = P4_NOTUSED;
73123 pOp->p4.z = 0;
73124 pOp->opcode = OP_Noop;
73125 return 1;
73129 ** If the last opcode is "op" and it is not a jump destination,
73130 ** then remove it. Return true if and only if an opcode was removed.
73132 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
73133 if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
73134 return sqlite3VdbeChangeToNoop(p, p->nOp-1);
73135 }else{
73136 return 0;
73141 ** Change the value of the P4 operand for a specific instruction.
73142 ** This routine is useful when a large program is loaded from a
73143 ** static array using sqlite3VdbeAddOpList but we want to make a
73144 ** few minor changes to the program.
73146 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
73147 ** the string is made into memory obtained from sqlite3_malloc().
73148 ** A value of n==0 means copy bytes of zP4 up to and including the
73149 ** first null byte. If n>0 then copy n+1 bytes of zP4.
73151 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
73152 ** to a string or structure that is guaranteed to exist for the lifetime of
73153 ** the Vdbe. In these cases we can just copy the pointer.
73155 ** If addr<0 then change P4 on the most recently inserted instruction.
73157 static void SQLITE_NOINLINE vdbeChangeP4Full(
73158 Vdbe *p,
73159 Op *pOp,
73160 const char *zP4,
73161 int n
73163 if( pOp->p4type ){
73164 freeP4(p->db, pOp->p4type, pOp->p4.p);
73165 pOp->p4type = 0;
73166 pOp->p4.p = 0;
73168 if( n<0 ){
73169 sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
73170 }else{
73171 if( n==0 ) n = sqlite3Strlen30(zP4);
73172 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
73173 pOp->p4type = P4_DYNAMIC;
73176 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
73177 Op *pOp;
73178 sqlite3 *db;
73179 assert( p!=0 );
73180 db = p->db;
73181 assert( p->magic==VDBE_MAGIC_INIT );
73182 assert( p->aOp!=0 || db->mallocFailed );
73183 if( db->mallocFailed ){
73184 if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
73185 return;
73187 assert( p->nOp>0 );
73188 assert( addr<p->nOp );
73189 if( addr<0 ){
73190 addr = p->nOp - 1;
73192 pOp = &p->aOp[addr];
73193 if( n>=0 || pOp->p4type ){
73194 vdbeChangeP4Full(p, pOp, zP4, n);
73195 return;
73197 if( n==P4_INT32 ){
73198 /* Note: this cast is safe, because the origin data point was an int
73199 ** that was cast to a (const char *). */
73200 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
73201 pOp->p4type = P4_INT32;
73202 }else if( zP4!=0 ){
73203 assert( n<0 );
73204 pOp->p4.p = (void*)zP4;
73205 pOp->p4type = (signed char)n;
73206 if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
73211 ** Change the P4 operand of the most recently coded instruction
73212 ** to the value defined by the arguments. This is a high-speed
73213 ** version of sqlite3VdbeChangeP4().
73215 ** The P4 operand must not have been previously defined. And the new
73216 ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
73217 ** those cases.
73219 SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
73220 VdbeOp *pOp;
73221 assert( n!=P4_INT32 && n!=P4_VTAB );
73222 assert( n<=0 );
73223 if( p->db->mallocFailed ){
73224 freeP4(p->db, n, pP4);
73225 }else{
73226 assert( pP4!=0 );
73227 assert( p->nOp>0 );
73228 pOp = &p->aOp[p->nOp-1];
73229 assert( pOp->p4type==P4_NOTUSED );
73230 pOp->p4type = n;
73231 pOp->p4.p = pP4;
73236 ** Set the P4 on the most recently added opcode to the KeyInfo for the
73237 ** index given.
73239 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
73240 Vdbe *v = pParse->pVdbe;
73241 KeyInfo *pKeyInfo;
73242 assert( v!=0 );
73243 assert( pIdx!=0 );
73244 pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
73245 if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
73248 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
73250 ** Change the comment on the most recently coded instruction. Or
73251 ** insert a No-op and add the comment to that new instruction. This
73252 ** makes the code easier to read during debugging. None of this happens
73253 ** in a production build.
73255 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
73256 assert( p->nOp>0 || p->aOp==0 );
73257 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
73258 if( p->nOp ){
73259 assert( p->aOp );
73260 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
73261 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
73264 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
73265 va_list ap;
73266 if( p ){
73267 va_start(ap, zFormat);
73268 vdbeVComment(p, zFormat, ap);
73269 va_end(ap);
73272 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
73273 va_list ap;
73274 if( p ){
73275 sqlite3VdbeAddOp0(p, OP_Noop);
73276 va_start(ap, zFormat);
73277 vdbeVComment(p, zFormat, ap);
73278 va_end(ap);
73281 #endif /* NDEBUG */
73283 #ifdef SQLITE_VDBE_COVERAGE
73285 ** Set the value if the iSrcLine field for the previously coded instruction.
73287 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
73288 sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
73290 #endif /* SQLITE_VDBE_COVERAGE */
73293 ** Return the opcode for a given address. If the address is -1, then
73294 ** return the most recently inserted opcode.
73296 ** If a memory allocation error has occurred prior to the calling of this
73297 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
73298 ** is readable but not writable, though it is cast to a writable value.
73299 ** The return of a dummy opcode allows the call to continue functioning
73300 ** after an OOM fault without having to check to see if the return from
73301 ** this routine is a valid pointer. But because the dummy.opcode is 0,
73302 ** dummy will never be written to. This is verified by code inspection and
73303 ** by running with Valgrind.
73305 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
73306 /* C89 specifies that the constant "dummy" will be initialized to all
73307 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
73308 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
73309 assert( p->magic==VDBE_MAGIC_INIT );
73310 if( addr<0 ){
73311 addr = p->nOp - 1;
73313 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
73314 if( p->db->mallocFailed ){
73315 return (VdbeOp*)&dummy;
73316 }else{
73317 return &p->aOp[addr];
73321 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
73323 ** Return an integer value for one of the parameters to the opcode pOp
73324 ** determined by character c.
73326 static int translateP(char c, const Op *pOp){
73327 if( c=='1' ) return pOp->p1;
73328 if( c=='2' ) return pOp->p2;
73329 if( c=='3' ) return pOp->p3;
73330 if( c=='4' ) return pOp->p4.i;
73331 return pOp->p5;
73335 ** Compute a string for the "comment" field of a VDBE opcode listing.
73337 ** The Synopsis: field in comments in the vdbe.c source file gets converted
73338 ** to an extra string that is appended to the sqlite3OpcodeName(). In the
73339 ** absence of other comments, this synopsis becomes the comment on the opcode.
73340 ** Some translation occurs:
73342 ** "PX" -> "r[X]"
73343 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
73344 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
73345 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
73347 static int displayComment(
73348 const Op *pOp, /* The opcode to be commented */
73349 const char *zP4, /* Previously obtained value for P4 */
73350 char *zTemp, /* Write result here */
73351 int nTemp /* Space available in zTemp[] */
73353 const char *zOpName;
73354 const char *zSynopsis;
73355 int nOpName;
73356 int ii, jj;
73357 char zAlt[50];
73358 zOpName = sqlite3OpcodeName(pOp->opcode);
73359 nOpName = sqlite3Strlen30(zOpName);
73360 if( zOpName[nOpName+1] ){
73361 int seenCom = 0;
73362 char c;
73363 zSynopsis = zOpName += nOpName + 1;
73364 if( strncmp(zSynopsis,"IF ",3)==0 ){
73365 if( pOp->p5 & SQLITE_STOREP2 ){
73366 sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
73367 }else{
73368 sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
73370 zSynopsis = zAlt;
73372 for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
73373 if( c=='P' ){
73374 c = zSynopsis[++ii];
73375 if( c=='4' ){
73376 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
73377 }else if( c=='X' ){
73378 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
73379 seenCom = 1;
73380 }else{
73381 int v1 = translateP(c, pOp);
73382 int v2;
73383 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
73384 if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
73385 ii += 3;
73386 jj += sqlite3Strlen30(zTemp+jj);
73387 v2 = translateP(zSynopsis[ii], pOp);
73388 if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
73389 ii += 2;
73390 v2++;
73392 if( v2>1 ){
73393 sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
73395 }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
73396 ii += 4;
73399 jj += sqlite3Strlen30(zTemp+jj);
73400 }else{
73401 zTemp[jj++] = c;
73404 if( !seenCom && jj<nTemp-5 && pOp->zComment ){
73405 sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
73406 jj += sqlite3Strlen30(zTemp+jj);
73408 if( jj<nTemp ) zTemp[jj] = 0;
73409 }else if( pOp->zComment ){
73410 sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
73411 jj = sqlite3Strlen30(zTemp);
73412 }else{
73413 zTemp[0] = 0;
73414 jj = 0;
73416 return jj;
73418 #endif /* SQLITE_DEBUG */
73420 #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
73422 ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
73423 ** that can be displayed in the P4 column of EXPLAIN output.
73425 static void displayP4Expr(StrAccum *p, Expr *pExpr){
73426 const char *zOp = 0;
73427 switch( pExpr->op ){
73428 case TK_STRING:
73429 sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
73430 break;
73431 case TK_INTEGER:
73432 sqlite3XPrintf(p, "%d", pExpr->u.iValue);
73433 break;
73434 case TK_NULL:
73435 sqlite3XPrintf(p, "NULL");
73436 break;
73437 case TK_REGISTER: {
73438 sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
73439 break;
73441 case TK_COLUMN: {
73442 if( pExpr->iColumn<0 ){
73443 sqlite3XPrintf(p, "rowid");
73444 }else{
73445 sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
73447 break;
73449 case TK_LT: zOp = "LT"; break;
73450 case TK_LE: zOp = "LE"; break;
73451 case TK_GT: zOp = "GT"; break;
73452 case TK_GE: zOp = "GE"; break;
73453 case TK_NE: zOp = "NE"; break;
73454 case TK_EQ: zOp = "EQ"; break;
73455 case TK_IS: zOp = "IS"; break;
73456 case TK_ISNOT: zOp = "ISNOT"; break;
73457 case TK_AND: zOp = "AND"; break;
73458 case TK_OR: zOp = "OR"; break;
73459 case TK_PLUS: zOp = "ADD"; break;
73460 case TK_STAR: zOp = "MUL"; break;
73461 case TK_MINUS: zOp = "SUB"; break;
73462 case TK_REM: zOp = "REM"; break;
73463 case TK_BITAND: zOp = "BITAND"; break;
73464 case TK_BITOR: zOp = "BITOR"; break;
73465 case TK_SLASH: zOp = "DIV"; break;
73466 case TK_LSHIFT: zOp = "LSHIFT"; break;
73467 case TK_RSHIFT: zOp = "RSHIFT"; break;
73468 case TK_CONCAT: zOp = "CONCAT"; break;
73469 case TK_UMINUS: zOp = "MINUS"; break;
73470 case TK_UPLUS: zOp = "PLUS"; break;
73471 case TK_BITNOT: zOp = "BITNOT"; break;
73472 case TK_NOT: zOp = "NOT"; break;
73473 case TK_ISNULL: zOp = "ISNULL"; break;
73474 case TK_NOTNULL: zOp = "NOTNULL"; break;
73476 default:
73477 sqlite3XPrintf(p, "%s", "expr");
73478 break;
73481 if( zOp ){
73482 sqlite3XPrintf(p, "%s(", zOp);
73483 displayP4Expr(p, pExpr->pLeft);
73484 if( pExpr->pRight ){
73485 sqlite3StrAccumAppend(p, ",", 1);
73486 displayP4Expr(p, pExpr->pRight);
73488 sqlite3StrAccumAppend(p, ")", 1);
73491 #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
73494 #if VDBE_DISPLAY_P4
73496 ** Compute a string that describes the P4 parameter for an opcode.
73497 ** Use zTemp for any required temporary buffer space.
73499 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
73500 char *zP4 = zTemp;
73501 StrAccum x;
73502 assert( nTemp>=20 );
73503 sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
73504 switch( pOp->p4type ){
73505 case P4_KEYINFO: {
73506 int j;
73507 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
73508 assert( pKeyInfo->aSortOrder!=0 );
73509 sqlite3XPrintf(&x, "k(%d", pKeyInfo->nKeyField);
73510 for(j=0; j<pKeyInfo->nKeyField; j++){
73511 CollSeq *pColl = pKeyInfo->aColl[j];
73512 const char *zColl = pColl ? pColl->zName : "";
73513 if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
73514 sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
73516 sqlite3StrAccumAppend(&x, ")", 1);
73517 break;
73519 #ifdef SQLITE_ENABLE_CURSOR_HINTS
73520 case P4_EXPR: {
73521 displayP4Expr(&x, pOp->p4.pExpr);
73522 break;
73524 #endif
73525 case P4_COLLSEQ: {
73526 CollSeq *pColl = pOp->p4.pColl;
73527 sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
73528 break;
73530 case P4_FUNCDEF: {
73531 FuncDef *pDef = pOp->p4.pFunc;
73532 sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
73533 break;
73535 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
73536 case P4_FUNCCTX: {
73537 FuncDef *pDef = pOp->p4.pCtx->pFunc;
73538 sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
73539 break;
73541 #endif
73542 case P4_INT64: {
73543 sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
73544 break;
73546 case P4_INT32: {
73547 sqlite3XPrintf(&x, "%d", pOp->p4.i);
73548 break;
73550 case P4_REAL: {
73551 sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
73552 break;
73554 case P4_MEM: {
73555 Mem *pMem = pOp->p4.pMem;
73556 if( pMem->flags & MEM_Str ){
73557 zP4 = pMem->z;
73558 }else if( pMem->flags & MEM_Int ){
73559 sqlite3XPrintf(&x, "%lld", pMem->u.i);
73560 }else if( pMem->flags & MEM_Real ){
73561 sqlite3XPrintf(&x, "%.16g", pMem->u.r);
73562 }else if( pMem->flags & MEM_Null ){
73563 zP4 = "NULL";
73564 }else{
73565 assert( pMem->flags & MEM_Blob );
73566 zP4 = "(blob)";
73568 break;
73570 #ifndef SQLITE_OMIT_VIRTUALTABLE
73571 case P4_VTAB: {
73572 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
73573 sqlite3XPrintf(&x, "vtab:%p", pVtab);
73574 break;
73576 #endif
73577 case P4_INTARRAY: {
73578 int i;
73579 int *ai = pOp->p4.ai;
73580 int n = ai[0]; /* The first element of an INTARRAY is always the
73581 ** count of the number of elements to follow */
73582 for(i=1; i<=n; i++){
73583 sqlite3XPrintf(&x, ",%d", ai[i]);
73585 zTemp[0] = '[';
73586 sqlite3StrAccumAppend(&x, "]", 1);
73587 break;
73589 case P4_SUBPROGRAM: {
73590 sqlite3XPrintf(&x, "program");
73591 break;
73593 case P4_ADVANCE: {
73594 zTemp[0] = 0;
73595 break;
73597 case P4_TABLE: {
73598 sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
73599 break;
73601 default: {
73602 zP4 = pOp->p4.z;
73603 if( zP4==0 ){
73604 zP4 = zTemp;
73605 zTemp[0] = 0;
73609 sqlite3StrAccumFinish(&x);
73610 assert( zP4!=0 );
73611 return zP4;
73613 #endif /* VDBE_DISPLAY_P4 */
73616 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
73618 ** The prepared statements need to know in advance the complete set of
73619 ** attached databases that will be use. A mask of these databases
73620 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
73621 ** p->btreeMask of databases that will require a lock.
73623 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
73624 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
73625 assert( i<(int)sizeof(p->btreeMask)*8 );
73626 DbMaskSet(p->btreeMask, i);
73627 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
73628 DbMaskSet(p->lockMask, i);
73632 #if !defined(SQLITE_OMIT_SHARED_CACHE)
73634 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
73635 ** this routine obtains the mutex associated with each BtShared structure
73636 ** that may be accessed by the VM passed as an argument. In doing so it also
73637 ** sets the BtShared.db member of each of the BtShared structures, ensuring
73638 ** that the correct busy-handler callback is invoked if required.
73640 ** If SQLite is not threadsafe but does support shared-cache mode, then
73641 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
73642 ** of all of BtShared structures accessible via the database handle
73643 ** associated with the VM.
73645 ** If SQLite is not threadsafe and does not support shared-cache mode, this
73646 ** function is a no-op.
73648 ** The p->btreeMask field is a bitmask of all btrees that the prepared
73649 ** statement p will ever use. Let N be the number of bits in p->btreeMask
73650 ** corresponding to btrees that use shared cache. Then the runtime of
73651 ** this routine is N*N. But as N is rarely more than 1, this should not
73652 ** be a problem.
73654 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
73655 int i;
73656 sqlite3 *db;
73657 Db *aDb;
73658 int nDb;
73659 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
73660 db = p->db;
73661 aDb = db->aDb;
73662 nDb = db->nDb;
73663 for(i=0; i<nDb; i++){
73664 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
73665 sqlite3BtreeEnter(aDb[i].pBt);
73669 #endif
73671 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
73673 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
73675 static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
73676 int i;
73677 sqlite3 *db;
73678 Db *aDb;
73679 int nDb;
73680 db = p->db;
73681 aDb = db->aDb;
73682 nDb = db->nDb;
73683 for(i=0; i<nDb; i++){
73684 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
73685 sqlite3BtreeLeave(aDb[i].pBt);
73689 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
73690 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
73691 vdbeLeave(p);
73693 #endif
73695 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
73697 ** Print a single opcode. This routine is used for debugging only.
73699 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
73700 char *zP4;
73701 char zPtr[50];
73702 char zCom[100];
73703 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
73704 if( pOut==0 ) pOut = stdout;
73705 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
73706 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
73707 displayComment(pOp, zP4, zCom, sizeof(zCom));
73708 #else
73709 zCom[0] = 0;
73710 #endif
73711 /* NB: The sqlite3OpcodeName() function is implemented by code created
73712 ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
73713 ** information from the vdbe.c source text */
73714 fprintf(pOut, zFormat1, pc,
73715 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
73716 zCom
73718 fflush(pOut);
73720 #endif
73723 ** Initialize an array of N Mem element.
73725 static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
73726 while( (N--)>0 ){
73727 p->db = db;
73728 p->flags = flags;
73729 p->szMalloc = 0;
73730 #ifdef SQLITE_DEBUG
73731 p->pScopyFrom = 0;
73732 #endif
73733 p++;
73738 ** Release an array of N Mem elements
73740 static void releaseMemArray(Mem *p, int N){
73741 if( p && N ){
73742 Mem *pEnd = &p[N];
73743 sqlite3 *db = p->db;
73744 if( db->pnBytesFreed ){
73746 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
73747 }while( (++p)<pEnd );
73748 return;
73751 assert( (&p[1])==pEnd || p[0].db==p[1].db );
73752 assert( sqlite3VdbeCheckMemInvariants(p) );
73754 /* This block is really an inlined version of sqlite3VdbeMemRelease()
73755 ** that takes advantage of the fact that the memory cell value is
73756 ** being set to NULL after releasing any dynamic resources.
73758 ** The justification for duplicating code is that according to
73759 ** callgrind, this causes a certain test case to hit the CPU 4.7
73760 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
73761 ** sqlite3MemRelease() were called from here. With -O2, this jumps
73762 ** to 6.6 percent. The test case is inserting 1000 rows into a table
73763 ** with no indexes using a single prepared INSERT statement, bind()
73764 ** and reset(). Inserts are grouped into a transaction.
73766 testcase( p->flags & MEM_Agg );
73767 testcase( p->flags & MEM_Dyn );
73768 testcase( p->flags & MEM_Frame );
73769 testcase( p->flags & MEM_RowSet );
73770 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
73771 sqlite3VdbeMemRelease(p);
73772 }else if( p->szMalloc ){
73773 sqlite3DbFreeNN(db, p->zMalloc);
73774 p->szMalloc = 0;
73777 p->flags = MEM_Undefined;
73778 }while( (++p)<pEnd );
73783 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
73784 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
73786 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
73787 int i;
73788 Mem *aMem = VdbeFrameMem(p);
73789 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
73790 for(i=0; i<p->nChildCsr; i++){
73791 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
73793 releaseMemArray(aMem, p->nChildMem);
73794 sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
73795 sqlite3DbFree(p->v->db, p);
73798 #ifndef SQLITE_OMIT_EXPLAIN
73800 ** Give a listing of the program in the virtual machine.
73802 ** The interface is the same as sqlite3VdbeExec(). But instead of
73803 ** running the code, it invokes the callback once for each instruction.
73804 ** This feature is used to implement "EXPLAIN".
73806 ** When p->explain==1, each instruction is listed. When
73807 ** p->explain==2, only OP_Explain instructions are listed and these
73808 ** are shown in a different format. p->explain==2 is used to implement
73809 ** EXPLAIN QUERY PLAN.
73811 ** When p->explain==1, first the main program is listed, then each of
73812 ** the trigger subprograms are listed one by one.
73814 SQLITE_PRIVATE int sqlite3VdbeList(
73815 Vdbe *p /* The VDBE */
73817 int nRow; /* Stop when row count reaches this */
73818 int nSub = 0; /* Number of sub-vdbes seen so far */
73819 SubProgram **apSub = 0; /* Array of sub-vdbes */
73820 Mem *pSub = 0; /* Memory cell hold array of subprogs */
73821 sqlite3 *db = p->db; /* The database connection */
73822 int i; /* Loop counter */
73823 int rc = SQLITE_OK; /* Return code */
73824 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
73826 assert( p->explain );
73827 assert( p->magic==VDBE_MAGIC_RUN );
73828 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
73830 /* Even though this opcode does not use dynamic strings for
73831 ** the result, result columns may become dynamic if the user calls
73832 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
73834 releaseMemArray(pMem, 8);
73835 p->pResultSet = 0;
73837 if( p->rc==SQLITE_NOMEM_BKPT ){
73838 /* This happens if a malloc() inside a call to sqlite3_column_text() or
73839 ** sqlite3_column_text16() failed. */
73840 sqlite3OomFault(db);
73841 return SQLITE_ERROR;
73844 /* When the number of output rows reaches nRow, that means the
73845 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
73846 ** nRow is the sum of the number of rows in the main program, plus
73847 ** the sum of the number of rows in all trigger subprograms encountered
73848 ** so far. The nRow value will increase as new trigger subprograms are
73849 ** encountered, but p->pc will eventually catch up to nRow.
73851 nRow = p->nOp;
73852 if( p->explain==1 ){
73853 /* The first 8 memory cells are used for the result set. So we will
73854 ** commandeer the 9th cell to use as storage for an array of pointers
73855 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
73856 ** cells. */
73857 assert( p->nMem>9 );
73858 pSub = &p->aMem[9];
73859 if( pSub->flags&MEM_Blob ){
73860 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
73861 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
73862 nSub = pSub->n/sizeof(Vdbe*);
73863 apSub = (SubProgram **)pSub->z;
73865 for(i=0; i<nSub; i++){
73866 nRow += apSub[i]->nOp;
73871 i = p->pc++;
73872 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
73873 if( i>=nRow ){
73874 p->rc = SQLITE_OK;
73875 rc = SQLITE_DONE;
73876 }else if( db->u1.isInterrupted ){
73877 p->rc = SQLITE_INTERRUPT;
73878 rc = SQLITE_ERROR;
73879 sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
73880 }else{
73881 char *zP4;
73882 Op *pOp;
73883 if( i<p->nOp ){
73884 /* The output line number is small enough that we are still in the
73885 ** main program. */
73886 pOp = &p->aOp[i];
73887 }else{
73888 /* We are currently listing subprograms. Figure out which one and
73889 ** pick up the appropriate opcode. */
73890 int j;
73891 i -= p->nOp;
73892 for(j=0; i>=apSub[j]->nOp; j++){
73893 i -= apSub[j]->nOp;
73895 pOp = &apSub[j]->aOp[i];
73897 if( p->explain==1 ){
73898 pMem->flags = MEM_Int;
73899 pMem->u.i = i; /* Program counter */
73900 pMem++;
73902 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
73903 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
73904 assert( pMem->z!=0 );
73905 pMem->n = sqlite3Strlen30(pMem->z);
73906 pMem->enc = SQLITE_UTF8;
73907 pMem++;
73909 /* When an OP_Program opcode is encounter (the only opcode that has
73910 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
73911 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
73912 ** has not already been seen.
73914 if( pOp->p4type==P4_SUBPROGRAM ){
73915 int nByte = (nSub+1)*sizeof(SubProgram*);
73916 int j;
73917 for(j=0; j<nSub; j++){
73918 if( apSub[j]==pOp->p4.pProgram ) break;
73920 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
73921 apSub = (SubProgram **)pSub->z;
73922 apSub[nSub++] = pOp->p4.pProgram;
73923 pSub->flags |= MEM_Blob;
73924 pSub->n = nSub*sizeof(SubProgram*);
73929 pMem->flags = MEM_Int;
73930 pMem->u.i = pOp->p1; /* P1 */
73931 pMem++;
73933 pMem->flags = MEM_Int;
73934 pMem->u.i = pOp->p2; /* P2 */
73935 pMem++;
73937 pMem->flags = MEM_Int;
73938 pMem->u.i = pOp->p3; /* P3 */
73939 pMem++;
73941 if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
73942 assert( p->db->mallocFailed );
73943 return SQLITE_ERROR;
73945 pMem->flags = MEM_Str|MEM_Term;
73946 zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
73947 if( zP4!=pMem->z ){
73948 pMem->n = 0;
73949 sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
73950 }else{
73951 assert( pMem->z!=0 );
73952 pMem->n = sqlite3Strlen30(pMem->z);
73953 pMem->enc = SQLITE_UTF8;
73955 pMem++;
73957 if( p->explain==1 ){
73958 if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
73959 assert( p->db->mallocFailed );
73960 return SQLITE_ERROR;
73962 pMem->flags = MEM_Str|MEM_Term;
73963 pMem->n = 2;
73964 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
73965 pMem->enc = SQLITE_UTF8;
73966 pMem++;
73968 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
73969 if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
73970 assert( p->db->mallocFailed );
73971 return SQLITE_ERROR;
73973 pMem->flags = MEM_Str|MEM_Term;
73974 pMem->n = displayComment(pOp, zP4, pMem->z, 500);
73975 pMem->enc = SQLITE_UTF8;
73976 #else
73977 pMem->flags = MEM_Null; /* Comment */
73978 #endif
73981 p->nResColumn = 8 - 4*(p->explain-1);
73982 p->pResultSet = &p->aMem[1];
73983 p->rc = SQLITE_OK;
73984 rc = SQLITE_ROW;
73986 return rc;
73988 #endif /* SQLITE_OMIT_EXPLAIN */
73990 #ifdef SQLITE_DEBUG
73992 ** Print the SQL that was used to generate a VDBE program.
73994 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
73995 const char *z = 0;
73996 if( p->zSql ){
73997 z = p->zSql;
73998 }else if( p->nOp>=1 ){
73999 const VdbeOp *pOp = &p->aOp[0];
74000 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
74001 z = pOp->p4.z;
74002 while( sqlite3Isspace(*z) ) z++;
74005 if( z ) printf("SQL: [%s]\n", z);
74007 #endif
74009 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
74011 ** Print an IOTRACE message showing SQL content.
74013 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
74014 int nOp = p->nOp;
74015 VdbeOp *pOp;
74016 if( sqlite3IoTrace==0 ) return;
74017 if( nOp<1 ) return;
74018 pOp = &p->aOp[0];
74019 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
74020 int i, j;
74021 char z[1000];
74022 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
74023 for(i=0; sqlite3Isspace(z[i]); i++){}
74024 for(j=0; z[i]; i++){
74025 if( sqlite3Isspace(z[i]) ){
74026 if( z[i-1]!=' ' ){
74027 z[j++] = ' ';
74029 }else{
74030 z[j++] = z[i];
74033 z[j] = 0;
74034 sqlite3IoTrace("SQL %s\n", z);
74037 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
74039 /* An instance of this object describes bulk memory available for use
74040 ** by subcomponents of a prepared statement. Space is allocated out
74041 ** of a ReusableSpace object by the allocSpace() routine below.
74043 struct ReusableSpace {
74044 u8 *pSpace; /* Available memory */
74045 int nFree; /* Bytes of available memory */
74046 int nNeeded; /* Total bytes that could not be allocated */
74049 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
74050 ** from the ReusableSpace object. Return a pointer to the allocated
74051 ** memory on success. If insufficient memory is available in the
74052 ** ReusableSpace object, increase the ReusableSpace.nNeeded
74053 ** value by the amount needed and return NULL.
74055 ** If pBuf is not initially NULL, that means that the memory has already
74056 ** been allocated by a prior call to this routine, so just return a copy
74057 ** of pBuf and leave ReusableSpace unchanged.
74059 ** This allocator is employed to repurpose unused slots at the end of the
74060 ** opcode array of prepared state for other memory needs of the prepared
74061 ** statement.
74063 static void *allocSpace(
74064 struct ReusableSpace *p, /* Bulk memory available for allocation */
74065 void *pBuf, /* Pointer to a prior allocation */
74066 int nByte /* Bytes of memory needed */
74068 assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
74069 if( pBuf==0 ){
74070 nByte = ROUND8(nByte);
74071 if( nByte <= p->nFree ){
74072 p->nFree -= nByte;
74073 pBuf = &p->pSpace[p->nFree];
74074 }else{
74075 p->nNeeded += nByte;
74078 assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
74079 return pBuf;
74083 ** Rewind the VDBE back to the beginning in preparation for
74084 ** running it.
74086 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
74087 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
74088 int i;
74089 #endif
74090 assert( p!=0 );
74091 assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
74093 /* There should be at least one opcode.
74095 assert( p->nOp>0 );
74097 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
74098 p->magic = VDBE_MAGIC_RUN;
74100 #ifdef SQLITE_DEBUG
74101 for(i=0; i<p->nMem; i++){
74102 assert( p->aMem[i].db==p->db );
74104 #endif
74105 p->pc = -1;
74106 p->rc = SQLITE_OK;
74107 p->errorAction = OE_Abort;
74108 p->nChange = 0;
74109 p->cacheCtr = 1;
74110 p->minWriteFileFormat = 255;
74111 p->iStatement = 0;
74112 p->nFkConstraint = 0;
74113 #ifdef VDBE_PROFILE
74114 for(i=0; i<p->nOp; i++){
74115 p->aOp[i].cnt = 0;
74116 p->aOp[i].cycles = 0;
74118 #endif
74122 ** Prepare a virtual machine for execution for the first time after
74123 ** creating the virtual machine. This involves things such
74124 ** as allocating registers and initializing the program counter.
74125 ** After the VDBE has be prepped, it can be executed by one or more
74126 ** calls to sqlite3VdbeExec().
74128 ** This function may be called exactly once on each virtual machine.
74129 ** After this routine is called the VM has been "packaged" and is ready
74130 ** to run. After this routine is called, further calls to
74131 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
74132 ** the Vdbe from the Parse object that helped generate it so that the
74133 ** the Vdbe becomes an independent entity and the Parse object can be
74134 ** destroyed.
74136 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
74137 ** to its initial state after it has been run.
74139 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
74140 Vdbe *p, /* The VDBE */
74141 Parse *pParse /* Parsing context */
74143 sqlite3 *db; /* The database connection */
74144 int nVar; /* Number of parameters */
74145 int nMem; /* Number of VM memory registers */
74146 int nCursor; /* Number of cursors required */
74147 int nArg; /* Number of arguments in subprograms */
74148 int n; /* Loop counter */
74149 struct ReusableSpace x; /* Reusable bulk memory */
74151 assert( p!=0 );
74152 assert( p->nOp>0 );
74153 assert( pParse!=0 );
74154 assert( p->magic==VDBE_MAGIC_INIT );
74155 assert( pParse==p->pParse );
74156 db = p->db;
74157 assert( db->mallocFailed==0 );
74158 nVar = pParse->nVar;
74159 nMem = pParse->nMem;
74160 nCursor = pParse->nTab;
74161 nArg = pParse->nMaxArg;
74163 /* Each cursor uses a memory cell. The first cursor (cursor 0) can
74164 ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
74165 ** space at the end of aMem[] for cursors 1 and greater.
74166 ** See also: allocateCursor().
74168 nMem += nCursor;
74169 if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
74171 /* Figure out how much reusable memory is available at the end of the
74172 ** opcode array. This extra memory will be reallocated for other elements
74173 ** of the prepared statement.
74175 n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
74176 x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
74177 assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
74178 x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
74179 assert( x.nFree>=0 );
74180 assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
74182 resolveP2Values(p, &nArg);
74183 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
74184 if( pParse->explain && nMem<10 ){
74185 nMem = 10;
74187 p->expired = 0;
74189 /* Memory for registers, parameters, cursor, etc, is allocated in one or two
74190 ** passes. On the first pass, we try to reuse unused memory at the
74191 ** end of the opcode array. If we are unable to satisfy all memory
74192 ** requirements by reusing the opcode array tail, then the second
74193 ** pass will fill in the remainder using a fresh memory allocation.
74195 ** This two-pass approach that reuses as much memory as possible from
74196 ** the leftover memory at the end of the opcode array. This can significantly
74197 ** reduce the amount of memory held by a prepared statement.
74199 do {
74200 x.nNeeded = 0;
74201 p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
74202 p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
74203 p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
74204 p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
74205 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
74206 p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
74207 #endif
74208 if( x.nNeeded==0 ) break;
74209 x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
74210 x.nFree = x.nNeeded;
74211 }while( !db->mallocFailed );
74213 p->pVList = pParse->pVList;
74214 pParse->pVList = 0;
74215 p->explain = pParse->explain;
74216 if( db->mallocFailed ){
74217 p->nVar = 0;
74218 p->nCursor = 0;
74219 p->nMem = 0;
74220 }else{
74221 p->nCursor = nCursor;
74222 p->nVar = (ynVar)nVar;
74223 initMemArray(p->aVar, nVar, db, MEM_Null);
74224 p->nMem = nMem;
74225 initMemArray(p->aMem, nMem, db, MEM_Undefined);
74226 memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
74227 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
74228 memset(p->anExec, 0, p->nOp*sizeof(i64));
74229 #endif
74231 sqlite3VdbeRewind(p);
74235 ** Close a VDBE cursor and release all the resources that cursor
74236 ** happens to hold.
74238 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
74239 if( pCx==0 ){
74240 return;
74242 assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
74243 switch( pCx->eCurType ){
74244 case CURTYPE_SORTER: {
74245 sqlite3VdbeSorterClose(p->db, pCx);
74246 break;
74248 case CURTYPE_BTREE: {
74249 if( pCx->isEphemeral ){
74250 if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
74251 /* The pCx->pCursor will be close automatically, if it exists, by
74252 ** the call above. */
74253 }else{
74254 assert( pCx->uc.pCursor!=0 );
74255 sqlite3BtreeCloseCursor(pCx->uc.pCursor);
74257 break;
74259 #ifndef SQLITE_OMIT_VIRTUALTABLE
74260 case CURTYPE_VTAB: {
74261 sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
74262 const sqlite3_module *pModule = pVCur->pVtab->pModule;
74263 assert( pVCur->pVtab->nRef>0 );
74264 pVCur->pVtab->nRef--;
74265 pModule->xClose(pVCur);
74266 break;
74268 #endif
74273 ** Close all cursors in the current frame.
74275 static void closeCursorsInFrame(Vdbe *p){
74276 if( p->apCsr ){
74277 int i;
74278 for(i=0; i<p->nCursor; i++){
74279 VdbeCursor *pC = p->apCsr[i];
74280 if( pC ){
74281 sqlite3VdbeFreeCursor(p, pC);
74282 p->apCsr[i] = 0;
74289 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
74290 ** is used, for example, when a trigger sub-program is halted to restore
74291 ** control to the main program.
74293 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
74294 Vdbe *v = pFrame->v;
74295 closeCursorsInFrame(v);
74296 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
74297 v->anExec = pFrame->anExec;
74298 #endif
74299 v->aOp = pFrame->aOp;
74300 v->nOp = pFrame->nOp;
74301 v->aMem = pFrame->aMem;
74302 v->nMem = pFrame->nMem;
74303 v->apCsr = pFrame->apCsr;
74304 v->nCursor = pFrame->nCursor;
74305 v->db->lastRowid = pFrame->lastRowid;
74306 v->nChange = pFrame->nChange;
74307 v->db->nChange = pFrame->nDbChange;
74308 sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
74309 v->pAuxData = pFrame->pAuxData;
74310 pFrame->pAuxData = 0;
74311 return pFrame->pc;
74315 ** Close all cursors.
74317 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
74318 ** cell array. This is necessary as the memory cell array may contain
74319 ** pointers to VdbeFrame objects, which may in turn contain pointers to
74320 ** open cursors.
74322 static void closeAllCursors(Vdbe *p){
74323 if( p->pFrame ){
74324 VdbeFrame *pFrame;
74325 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
74326 sqlite3VdbeFrameRestore(pFrame);
74327 p->pFrame = 0;
74328 p->nFrame = 0;
74330 assert( p->nFrame==0 );
74331 closeCursorsInFrame(p);
74332 if( p->aMem ){
74333 releaseMemArray(p->aMem, p->nMem);
74335 while( p->pDelFrame ){
74336 VdbeFrame *pDel = p->pDelFrame;
74337 p->pDelFrame = pDel->pParent;
74338 sqlite3VdbeFrameDelete(pDel);
74341 /* Delete any auxdata allocations made by the VM */
74342 if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
74343 assert( p->pAuxData==0 );
74347 ** Set the number of result columns that will be returned by this SQL
74348 ** statement. This is now set at compile time, rather than during
74349 ** execution of the vdbe program so that sqlite3_column_count() can
74350 ** be called on an SQL statement before sqlite3_step().
74352 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
74353 int n;
74354 sqlite3 *db = p->db;
74356 if( p->nResColumn ){
74357 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
74358 sqlite3DbFree(db, p->aColName);
74360 n = nResColumn*COLNAME_N;
74361 p->nResColumn = (u16)nResColumn;
74362 p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
74363 if( p->aColName==0 ) return;
74364 initMemArray(p->aColName, n, db, MEM_Null);
74368 ** Set the name of the idx'th column to be returned by the SQL statement.
74369 ** zName must be a pointer to a nul terminated string.
74371 ** This call must be made after a call to sqlite3VdbeSetNumCols().
74373 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
74374 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
74375 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
74377 SQLITE_PRIVATE int sqlite3VdbeSetColName(
74378 Vdbe *p, /* Vdbe being configured */
74379 int idx, /* Index of column zName applies to */
74380 int var, /* One of the COLNAME_* constants */
74381 const char *zName, /* Pointer to buffer containing name */
74382 void (*xDel)(void*) /* Memory management strategy for zName */
74384 int rc;
74385 Mem *pColName;
74386 assert( idx<p->nResColumn );
74387 assert( var<COLNAME_N );
74388 if( p->db->mallocFailed ){
74389 assert( !zName || xDel!=SQLITE_DYNAMIC );
74390 return SQLITE_NOMEM_BKPT;
74392 assert( p->aColName!=0 );
74393 pColName = &(p->aColName[idx+var*p->nResColumn]);
74394 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
74395 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
74396 return rc;
74400 ** A read or write transaction may or may not be active on database handle
74401 ** db. If a transaction is active, commit it. If there is a
74402 ** write-transaction spanning more than one database file, this routine
74403 ** takes care of the master journal trickery.
74405 static int vdbeCommit(sqlite3 *db, Vdbe *p){
74406 int i;
74407 int nTrans = 0; /* Number of databases with an active write-transaction
74408 ** that are candidates for a two-phase commit using a
74409 ** master-journal */
74410 int rc = SQLITE_OK;
74411 int needXcommit = 0;
74413 #ifdef SQLITE_OMIT_VIRTUALTABLE
74414 /* With this option, sqlite3VtabSync() is defined to be simply
74415 ** SQLITE_OK so p is not used.
74417 UNUSED_PARAMETER(p);
74418 #endif
74420 /* Before doing anything else, call the xSync() callback for any
74421 ** virtual module tables written in this transaction. This has to
74422 ** be done before determining whether a master journal file is
74423 ** required, as an xSync() callback may add an attached database
74424 ** to the transaction.
74426 rc = sqlite3VtabSync(db, p);
74428 /* This loop determines (a) if the commit hook should be invoked and
74429 ** (b) how many database files have open write transactions, not
74430 ** including the temp database. (b) is important because if more than
74431 ** one database file has an open write transaction, a master journal
74432 ** file is required for an atomic commit.
74434 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
74435 Btree *pBt = db->aDb[i].pBt;
74436 if( sqlite3BtreeIsInTrans(pBt) ){
74437 /* Whether or not a database might need a master journal depends upon
74438 ** its journal mode (among other things). This matrix determines which
74439 ** journal modes use a master journal and which do not */
74440 static const u8 aMJNeeded[] = {
74441 /* DELETE */ 1,
74442 /* PERSIST */ 1,
74443 /* OFF */ 0,
74444 /* TRUNCATE */ 1,
74445 /* MEMORY */ 0,
74446 /* WAL */ 0
74448 Pager *pPager; /* Pager associated with pBt */
74449 needXcommit = 1;
74450 sqlite3BtreeEnter(pBt);
74451 pPager = sqlite3BtreePager(pBt);
74452 if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
74453 && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
74455 assert( i!=1 );
74456 nTrans++;
74458 rc = sqlite3PagerExclusiveLock(pPager);
74459 sqlite3BtreeLeave(pBt);
74462 if( rc!=SQLITE_OK ){
74463 return rc;
74466 /* If there are any write-transactions at all, invoke the commit hook */
74467 if( needXcommit && db->xCommitCallback ){
74468 rc = db->xCommitCallback(db->pCommitArg);
74469 if( rc ){
74470 return SQLITE_CONSTRAINT_COMMITHOOK;
74474 /* The simple case - no more than one database file (not counting the
74475 ** TEMP database) has a transaction active. There is no need for the
74476 ** master-journal.
74478 ** If the return value of sqlite3BtreeGetFilename() is a zero length
74479 ** string, it means the main database is :memory: or a temp file. In
74480 ** that case we do not support atomic multi-file commits, so use the
74481 ** simple case then too.
74483 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
74484 || nTrans<=1
74486 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
74487 Btree *pBt = db->aDb[i].pBt;
74488 if( pBt ){
74489 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
74493 /* Do the commit only if all databases successfully complete phase 1.
74494 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
74495 ** IO error while deleting or truncating a journal file. It is unlikely,
74496 ** but could happen. In this case abandon processing and return the error.
74498 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
74499 Btree *pBt = db->aDb[i].pBt;
74500 if( pBt ){
74501 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
74504 if( rc==SQLITE_OK ){
74505 sqlite3VtabCommit(db);
74509 /* The complex case - There is a multi-file write-transaction active.
74510 ** This requires a master journal file to ensure the transaction is
74511 ** committed atomically.
74513 #ifndef SQLITE_OMIT_DISKIO
74514 else{
74515 sqlite3_vfs *pVfs = db->pVfs;
74516 char *zMaster = 0; /* File-name for the master journal */
74517 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
74518 sqlite3_file *pMaster = 0;
74519 i64 offset = 0;
74520 int res;
74521 int retryCount = 0;
74522 int nMainFile;
74524 /* Select a master journal file name */
74525 nMainFile = sqlite3Strlen30(zMainFile);
74526 zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
74527 if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
74528 do {
74529 u32 iRandom;
74530 if( retryCount ){
74531 if( retryCount>100 ){
74532 sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
74533 sqlite3OsDelete(pVfs, zMaster, 0);
74534 break;
74535 }else if( retryCount==1 ){
74536 sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
74539 retryCount++;
74540 sqlite3_randomness(sizeof(iRandom), &iRandom);
74541 sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
74542 (iRandom>>8)&0xffffff, iRandom&0xff);
74543 /* The antipenultimate character of the master journal name must
74544 ** be "9" to avoid name collisions when using 8+3 filenames. */
74545 assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
74546 sqlite3FileSuffix3(zMainFile, zMaster);
74547 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
74548 }while( rc==SQLITE_OK && res );
74549 if( rc==SQLITE_OK ){
74550 /* Open the master journal. */
74551 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
74552 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
74553 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
74556 if( rc!=SQLITE_OK ){
74557 sqlite3DbFree(db, zMaster);
74558 return rc;
74561 /* Write the name of each database file in the transaction into the new
74562 ** master journal file. If an error occurs at this point close
74563 ** and delete the master journal file. All the individual journal files
74564 ** still have 'null' as the master journal pointer, so they will roll
74565 ** back independently if a failure occurs.
74567 for(i=0; i<db->nDb; i++){
74568 Btree *pBt = db->aDb[i].pBt;
74569 if( sqlite3BtreeIsInTrans(pBt) ){
74570 char const *zFile = sqlite3BtreeGetJournalname(pBt);
74571 if( zFile==0 ){
74572 continue; /* Ignore TEMP and :memory: databases */
74574 assert( zFile[0]!=0 );
74575 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
74576 offset += sqlite3Strlen30(zFile)+1;
74577 if( rc!=SQLITE_OK ){
74578 sqlite3OsCloseFree(pMaster);
74579 sqlite3OsDelete(pVfs, zMaster, 0);
74580 sqlite3DbFree(db, zMaster);
74581 return rc;
74586 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
74587 ** flag is set this is not required.
74589 if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
74590 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
74592 sqlite3OsCloseFree(pMaster);
74593 sqlite3OsDelete(pVfs, zMaster, 0);
74594 sqlite3DbFree(db, zMaster);
74595 return rc;
74598 /* Sync all the db files involved in the transaction. The same call
74599 ** sets the master journal pointer in each individual journal. If
74600 ** an error occurs here, do not delete the master journal file.
74602 ** If the error occurs during the first call to
74603 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
74604 ** master journal file will be orphaned. But we cannot delete it,
74605 ** in case the master journal file name was written into the journal
74606 ** file before the failure occurred.
74608 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
74609 Btree *pBt = db->aDb[i].pBt;
74610 if( pBt ){
74611 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
74614 sqlite3OsCloseFree(pMaster);
74615 assert( rc!=SQLITE_BUSY );
74616 if( rc!=SQLITE_OK ){
74617 sqlite3DbFree(db, zMaster);
74618 return rc;
74621 /* Delete the master journal file. This commits the transaction. After
74622 ** doing this the directory is synced again before any individual
74623 ** transaction files are deleted.
74625 rc = sqlite3OsDelete(pVfs, zMaster, 1);
74626 sqlite3DbFree(db, zMaster);
74627 zMaster = 0;
74628 if( rc ){
74629 return rc;
74632 /* All files and directories have already been synced, so the following
74633 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
74634 ** deleting or truncating journals. If something goes wrong while
74635 ** this is happening we don't really care. The integrity of the
74636 ** transaction is already guaranteed, but some stray 'cold' journals
74637 ** may be lying around. Returning an error code won't help matters.
74639 disable_simulated_io_errors();
74640 sqlite3BeginBenignMalloc();
74641 for(i=0; i<db->nDb; i++){
74642 Btree *pBt = db->aDb[i].pBt;
74643 if( pBt ){
74644 sqlite3BtreeCommitPhaseTwo(pBt, 1);
74647 sqlite3EndBenignMalloc();
74648 enable_simulated_io_errors();
74650 sqlite3VtabCommit(db);
74652 #endif
74654 return rc;
74658 ** This routine checks that the sqlite3.nVdbeActive count variable
74659 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
74660 ** currently active. An assertion fails if the two counts do not match.
74661 ** This is an internal self-check only - it is not an essential processing
74662 ** step.
74664 ** This is a no-op if NDEBUG is defined.
74666 #ifndef NDEBUG
74667 static void checkActiveVdbeCnt(sqlite3 *db){
74668 Vdbe *p;
74669 int cnt = 0;
74670 int nWrite = 0;
74671 int nRead = 0;
74672 p = db->pVdbe;
74673 while( p ){
74674 if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
74675 cnt++;
74676 if( p->readOnly==0 ) nWrite++;
74677 if( p->bIsReader ) nRead++;
74679 p = p->pNext;
74681 assert( cnt==db->nVdbeActive );
74682 assert( nWrite==db->nVdbeWrite );
74683 assert( nRead==db->nVdbeRead );
74685 #else
74686 #define checkActiveVdbeCnt(x)
74687 #endif
74690 ** If the Vdbe passed as the first argument opened a statement-transaction,
74691 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
74692 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
74693 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
74694 ** statement transaction is committed.
74696 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
74697 ** Otherwise SQLITE_OK.
74699 static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
74700 sqlite3 *const db = p->db;
74701 int rc = SQLITE_OK;
74702 int i;
74703 const int iSavepoint = p->iStatement-1;
74705 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
74706 assert( db->nStatement>0 );
74707 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
74709 for(i=0; i<db->nDb; i++){
74710 int rc2 = SQLITE_OK;
74711 Btree *pBt = db->aDb[i].pBt;
74712 if( pBt ){
74713 if( eOp==SAVEPOINT_ROLLBACK ){
74714 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
74716 if( rc2==SQLITE_OK ){
74717 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
74719 if( rc==SQLITE_OK ){
74720 rc = rc2;
74724 db->nStatement--;
74725 p->iStatement = 0;
74727 if( rc==SQLITE_OK ){
74728 if( eOp==SAVEPOINT_ROLLBACK ){
74729 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
74731 if( rc==SQLITE_OK ){
74732 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
74736 /* If the statement transaction is being rolled back, also restore the
74737 ** database handles deferred constraint counter to the value it had when
74738 ** the statement transaction was opened. */
74739 if( eOp==SAVEPOINT_ROLLBACK ){
74740 db->nDeferredCons = p->nStmtDefCons;
74741 db->nDeferredImmCons = p->nStmtDefImmCons;
74743 return rc;
74745 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
74746 if( p->db->nStatement && p->iStatement ){
74747 return vdbeCloseStatement(p, eOp);
74749 return SQLITE_OK;
74754 ** This function is called when a transaction opened by the database
74755 ** handle associated with the VM passed as an argument is about to be
74756 ** committed. If there are outstanding deferred foreign key constraint
74757 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
74759 ** If there are outstanding FK violations and this function returns
74760 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
74761 ** and write an error message to it. Then return SQLITE_ERROR.
74763 #ifndef SQLITE_OMIT_FOREIGN_KEY
74764 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
74765 sqlite3 *db = p->db;
74766 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
74767 || (!deferred && p->nFkConstraint>0)
74769 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
74770 p->errorAction = OE_Abort;
74771 sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
74772 return SQLITE_ERROR;
74774 return SQLITE_OK;
74776 #endif
74779 ** This routine is called the when a VDBE tries to halt. If the VDBE
74780 ** has made changes and is in autocommit mode, then commit those
74781 ** changes. If a rollback is needed, then do the rollback.
74783 ** This routine is the only way to move the state of a VM from
74784 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
74785 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
74787 ** Return an error code. If the commit could not complete because of
74788 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
74789 ** means the close did not happen and needs to be repeated.
74791 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
74792 int rc; /* Used to store transient return codes */
74793 sqlite3 *db = p->db;
74795 /* This function contains the logic that determines if a statement or
74796 ** transaction will be committed or rolled back as a result of the
74797 ** execution of this virtual machine.
74799 ** If any of the following errors occur:
74801 ** SQLITE_NOMEM
74802 ** SQLITE_IOERR
74803 ** SQLITE_FULL
74804 ** SQLITE_INTERRUPT
74806 ** Then the internal cache might have been left in an inconsistent
74807 ** state. We need to rollback the statement transaction, if there is
74808 ** one, or the complete transaction if there is no statement transaction.
74811 if( p->magic!=VDBE_MAGIC_RUN ){
74812 return SQLITE_OK;
74814 if( db->mallocFailed ){
74815 p->rc = SQLITE_NOMEM_BKPT;
74817 closeAllCursors(p);
74818 checkActiveVdbeCnt(db);
74820 /* No commit or rollback needed if the program never started or if the
74821 ** SQL statement does not read or write a database file. */
74822 if( p->pc>=0 && p->bIsReader ){
74823 int mrc; /* Primary error code from p->rc */
74824 int eStatementOp = 0;
74825 int isSpecialError; /* Set to true if a 'special' error */
74827 /* Lock all btrees used by the statement */
74828 sqlite3VdbeEnter(p);
74830 /* Check for one of the special errors */
74831 mrc = p->rc & 0xff;
74832 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
74833 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
74834 if( isSpecialError ){
74835 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
74836 ** no rollback is necessary. Otherwise, at least a savepoint
74837 ** transaction must be rolled back to restore the database to a
74838 ** consistent state.
74840 ** Even if the statement is read-only, it is important to perform
74841 ** a statement or transaction rollback operation. If the error
74842 ** occurred while writing to the journal, sub-journal or database
74843 ** file as part of an effort to free up cache space (see function
74844 ** pagerStress() in pager.c), the rollback is required to restore
74845 ** the pager to a consistent state.
74847 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
74848 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
74849 eStatementOp = SAVEPOINT_ROLLBACK;
74850 }else{
74851 /* We are forced to roll back the active transaction. Before doing
74852 ** so, abort any other statements this handle currently has active.
74854 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
74855 sqlite3CloseSavepoints(db);
74856 db->autoCommit = 1;
74857 p->nChange = 0;
74862 /* Check for immediate foreign key violations. */
74863 if( p->rc==SQLITE_OK ){
74864 sqlite3VdbeCheckFk(p, 0);
74867 /* If the auto-commit flag is set and this is the only active writer
74868 ** VM, then we do either a commit or rollback of the current transaction.
74870 ** Note: This block also runs if one of the special errors handled
74871 ** above has occurred.
74873 if( !sqlite3VtabInSync(db)
74874 && db->autoCommit
74875 && db->nVdbeWrite==(p->readOnly==0)
74877 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
74878 rc = sqlite3VdbeCheckFk(p, 1);
74879 if( rc!=SQLITE_OK ){
74880 if( NEVER(p->readOnly) ){
74881 sqlite3VdbeLeave(p);
74882 return SQLITE_ERROR;
74884 rc = SQLITE_CONSTRAINT_FOREIGNKEY;
74885 }else{
74886 /* The auto-commit flag is true, the vdbe program was successful
74887 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
74888 ** key constraints to hold up the transaction. This means a commit
74889 ** is required. */
74890 rc = vdbeCommit(db, p);
74892 if( rc==SQLITE_BUSY && p->readOnly ){
74893 sqlite3VdbeLeave(p);
74894 return SQLITE_BUSY;
74895 }else if( rc!=SQLITE_OK ){
74896 p->rc = rc;
74897 sqlite3RollbackAll(db, SQLITE_OK);
74898 p->nChange = 0;
74899 }else{
74900 db->nDeferredCons = 0;
74901 db->nDeferredImmCons = 0;
74902 db->flags &= ~SQLITE_DeferFKs;
74903 sqlite3CommitInternalChanges(db);
74905 }else{
74906 sqlite3RollbackAll(db, SQLITE_OK);
74907 p->nChange = 0;
74909 db->nStatement = 0;
74910 }else if( eStatementOp==0 ){
74911 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
74912 eStatementOp = SAVEPOINT_RELEASE;
74913 }else if( p->errorAction==OE_Abort ){
74914 eStatementOp = SAVEPOINT_ROLLBACK;
74915 }else{
74916 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
74917 sqlite3CloseSavepoints(db);
74918 db->autoCommit = 1;
74919 p->nChange = 0;
74923 /* If eStatementOp is non-zero, then a statement transaction needs to
74924 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
74925 ** do so. If this operation returns an error, and the current statement
74926 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
74927 ** current statement error code.
74929 if( eStatementOp ){
74930 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
74931 if( rc ){
74932 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
74933 p->rc = rc;
74934 sqlite3DbFree(db, p->zErrMsg);
74935 p->zErrMsg = 0;
74937 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
74938 sqlite3CloseSavepoints(db);
74939 db->autoCommit = 1;
74940 p->nChange = 0;
74944 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
74945 ** has been rolled back, update the database connection change-counter.
74947 if( p->changeCntOn ){
74948 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
74949 sqlite3VdbeSetChanges(db, p->nChange);
74950 }else{
74951 sqlite3VdbeSetChanges(db, 0);
74953 p->nChange = 0;
74956 /* Release the locks */
74957 sqlite3VdbeLeave(p);
74960 /* We have successfully halted and closed the VM. Record this fact. */
74961 if( p->pc>=0 ){
74962 db->nVdbeActive--;
74963 if( !p->readOnly ) db->nVdbeWrite--;
74964 if( p->bIsReader ) db->nVdbeRead--;
74965 assert( db->nVdbeActive>=db->nVdbeRead );
74966 assert( db->nVdbeRead>=db->nVdbeWrite );
74967 assert( db->nVdbeWrite>=0 );
74969 p->magic = VDBE_MAGIC_HALT;
74970 checkActiveVdbeCnt(db);
74971 if( db->mallocFailed ){
74972 p->rc = SQLITE_NOMEM_BKPT;
74975 /* If the auto-commit flag is set to true, then any locks that were held
74976 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
74977 ** to invoke any required unlock-notify callbacks.
74979 if( db->autoCommit ){
74980 sqlite3ConnectionUnlocked(db);
74983 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
74984 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
74989 ** Each VDBE holds the result of the most recent sqlite3_step() call
74990 ** in p->rc. This routine sets that result back to SQLITE_OK.
74992 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
74993 p->rc = SQLITE_OK;
74997 ** Copy the error code and error message belonging to the VDBE passed
74998 ** as the first argument to its database handle (so that they will be
74999 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
75001 ** This function does not clear the VDBE error code or message, just
75002 ** copies them to the database handle.
75004 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
75005 sqlite3 *db = p->db;
75006 int rc = p->rc;
75007 if( p->zErrMsg ){
75008 db->bBenignMalloc++;
75009 sqlite3BeginBenignMalloc();
75010 if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
75011 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
75012 sqlite3EndBenignMalloc();
75013 db->bBenignMalloc--;
75014 }else if( db->pErr ){
75015 sqlite3ValueSetNull(db->pErr);
75017 db->errCode = rc;
75018 return rc;
75021 #ifdef SQLITE_ENABLE_SQLLOG
75023 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
75024 ** invoke it.
75026 static void vdbeInvokeSqllog(Vdbe *v){
75027 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
75028 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
75029 assert( v->db->init.busy==0 );
75030 if( zExpanded ){
75031 sqlite3GlobalConfig.xSqllog(
75032 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
75034 sqlite3DbFree(v->db, zExpanded);
75038 #else
75039 # define vdbeInvokeSqllog(x)
75040 #endif
75043 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
75044 ** Write any error messages into *pzErrMsg. Return the result code.
75046 ** After this routine is run, the VDBE should be ready to be executed
75047 ** again.
75049 ** To look at it another way, this routine resets the state of the
75050 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
75051 ** VDBE_MAGIC_INIT.
75053 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
75054 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
75055 int i;
75056 #endif
75058 sqlite3 *db;
75059 db = p->db;
75061 /* If the VM did not run to completion or if it encountered an
75062 ** error, then it might not have been halted properly. So halt
75063 ** it now.
75065 sqlite3VdbeHalt(p);
75067 /* If the VDBE has be run even partially, then transfer the error code
75068 ** and error message from the VDBE into the main database structure. But
75069 ** if the VDBE has just been set to run but has not actually executed any
75070 ** instructions yet, leave the main database error information unchanged.
75072 if( p->pc>=0 ){
75073 vdbeInvokeSqllog(p);
75074 sqlite3VdbeTransferError(p);
75075 if( p->runOnlyOnce ) p->expired = 1;
75076 }else if( p->rc && p->expired ){
75077 /* The expired flag was set on the VDBE before the first call
75078 ** to sqlite3_step(). For consistency (since sqlite3_step() was
75079 ** called), set the database error in this case as well.
75081 sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
75084 /* Reset register contents and reclaim error message memory.
75086 #ifdef SQLITE_DEBUG
75087 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
75088 ** Vdbe.aMem[] arrays have already been cleaned up. */
75089 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
75090 if( p->aMem ){
75091 for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
75093 #endif
75094 sqlite3DbFree(db, p->zErrMsg);
75095 p->zErrMsg = 0;
75096 p->pResultSet = 0;
75098 /* Save profiling information from this VDBE run.
75100 #ifdef VDBE_PROFILE
75102 FILE *out = fopen("vdbe_profile.out", "a");
75103 if( out ){
75104 fprintf(out, "---- ");
75105 for(i=0; i<p->nOp; i++){
75106 fprintf(out, "%02x", p->aOp[i].opcode);
75108 fprintf(out, "\n");
75109 if( p->zSql ){
75110 char c, pc = 0;
75111 fprintf(out, "-- ");
75112 for(i=0; (c = p->zSql[i])!=0; i++){
75113 if( pc=='\n' ) fprintf(out, "-- ");
75114 putc(c, out);
75115 pc = c;
75117 if( pc!='\n' ) fprintf(out, "\n");
75119 for(i=0; i<p->nOp; i++){
75120 char zHdr[100];
75121 sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
75122 p->aOp[i].cnt,
75123 p->aOp[i].cycles,
75124 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
75126 fprintf(out, "%s", zHdr);
75127 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
75129 fclose(out);
75132 #endif
75133 p->magic = VDBE_MAGIC_RESET;
75134 return p->rc & db->errMask;
75138 ** Clean up and delete a VDBE after execution. Return an integer which is
75139 ** the result code. Write any error message text into *pzErrMsg.
75141 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
75142 int rc = SQLITE_OK;
75143 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
75144 rc = sqlite3VdbeReset(p);
75145 assert( (rc & p->db->errMask)==rc );
75147 sqlite3VdbeDelete(p);
75148 return rc;
75152 ** If parameter iOp is less than zero, then invoke the destructor for
75153 ** all auxiliary data pointers currently cached by the VM passed as
75154 ** the first argument.
75156 ** Or, if iOp is greater than or equal to zero, then the destructor is
75157 ** only invoked for those auxiliary data pointers created by the user
75158 ** function invoked by the OP_Function opcode at instruction iOp of
75159 ** VM pVdbe, and only then if:
75161 ** * the associated function parameter is the 32nd or later (counting
75162 ** from left to right), or
75164 ** * the corresponding bit in argument mask is clear (where the first
75165 ** function parameter corresponds to bit 0 etc.).
75167 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
75168 while( *pp ){
75169 AuxData *pAux = *pp;
75170 if( (iOp<0)
75171 || (pAux->iAuxOp==iOp
75172 && pAux->iAuxArg>=0
75173 && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
75175 testcase( pAux->iAuxArg==31 );
75176 if( pAux->xDeleteAux ){
75177 pAux->xDeleteAux(pAux->pAux);
75179 *pp = pAux->pNextAux;
75180 sqlite3DbFree(db, pAux);
75181 }else{
75182 pp= &pAux->pNextAux;
75188 ** Free all memory associated with the Vdbe passed as the second argument,
75189 ** except for object itself, which is preserved.
75191 ** The difference between this function and sqlite3VdbeDelete() is that
75192 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
75193 ** the database connection and frees the object itself.
75195 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
75196 SubProgram *pSub, *pNext;
75197 assert( p->db==0 || p->db==db );
75198 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
75199 for(pSub=p->pProgram; pSub; pSub=pNext){
75200 pNext = pSub->pNext;
75201 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
75202 sqlite3DbFree(db, pSub);
75204 if( p->magic!=VDBE_MAGIC_INIT ){
75205 releaseMemArray(p->aVar, p->nVar);
75206 sqlite3DbFree(db, p->pVList);
75207 sqlite3DbFree(db, p->pFree);
75209 vdbeFreeOpArray(db, p->aOp, p->nOp);
75210 sqlite3DbFree(db, p->aColName);
75211 sqlite3DbFree(db, p->zSql);
75212 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
75214 int i;
75215 for(i=0; i<p->nScan; i++){
75216 sqlite3DbFree(db, p->aScan[i].zName);
75218 sqlite3DbFree(db, p->aScan);
75220 #endif
75224 ** Delete an entire VDBE.
75226 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
75227 sqlite3 *db;
75229 if( NEVER(p==0) ) return;
75230 db = p->db;
75231 assert( sqlite3_mutex_held(db->mutex) );
75232 sqlite3VdbeClearObject(db, p);
75233 if( p->pPrev ){
75234 p->pPrev->pNext = p->pNext;
75235 }else{
75236 assert( db->pVdbe==p );
75237 db->pVdbe = p->pNext;
75239 if( p->pNext ){
75240 p->pNext->pPrev = p->pPrev;
75242 p->magic = VDBE_MAGIC_DEAD;
75243 p->db = 0;
75244 sqlite3DbFreeNN(db, p);
75248 ** The cursor "p" has a pending seek operation that has not yet been
75249 ** carried out. Seek the cursor now. If an error occurs, return
75250 ** the appropriate error code.
75252 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
75253 int res, rc;
75254 #ifdef SQLITE_TEST
75255 extern int sqlite3_search_count;
75256 #endif
75257 assert( p->deferredMoveto );
75258 assert( p->isTable );
75259 assert( p->eCurType==CURTYPE_BTREE );
75260 rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
75261 if( rc ) return rc;
75262 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
75263 #ifdef SQLITE_TEST
75264 sqlite3_search_count++;
75265 #endif
75266 p->deferredMoveto = 0;
75267 p->cacheStatus = CACHE_STALE;
75268 return SQLITE_OK;
75272 ** Something has moved cursor "p" out of place. Maybe the row it was
75273 ** pointed to was deleted out from under it. Or maybe the btree was
75274 ** rebalanced. Whatever the cause, try to restore "p" to the place it
75275 ** is supposed to be pointing. If the row was deleted out from under the
75276 ** cursor, set the cursor to point to a NULL row.
75278 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
75279 int isDifferentRow, rc;
75280 assert( p->eCurType==CURTYPE_BTREE );
75281 assert( p->uc.pCursor!=0 );
75282 assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
75283 rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
75284 p->cacheStatus = CACHE_STALE;
75285 if( isDifferentRow ) p->nullRow = 1;
75286 return rc;
75290 ** Check to ensure that the cursor is valid. Restore the cursor
75291 ** if need be. Return any I/O error from the restore operation.
75293 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
75294 assert( p->eCurType==CURTYPE_BTREE );
75295 if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
75296 return handleMovedCursor(p);
75298 return SQLITE_OK;
75302 ** Make sure the cursor p is ready to read or write the row to which it
75303 ** was last positioned. Return an error code if an OOM fault or I/O error
75304 ** prevents us from positioning the cursor to its correct position.
75306 ** If a MoveTo operation is pending on the given cursor, then do that
75307 ** MoveTo now. If no move is pending, check to see if the row has been
75308 ** deleted out from under the cursor and if it has, mark the row as
75309 ** a NULL row.
75311 ** If the cursor is already pointing to the correct row and that row has
75312 ** not been deleted out from under the cursor, then this routine is a no-op.
75314 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
75315 VdbeCursor *p = *pp;
75316 assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
75317 if( p->deferredMoveto ){
75318 int iMap;
75319 if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
75320 *pp = p->pAltCursor;
75321 *piCol = iMap - 1;
75322 return SQLITE_OK;
75324 return handleDeferredMoveto(p);
75326 if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
75327 return handleMovedCursor(p);
75329 return SQLITE_OK;
75333 ** The following functions:
75335 ** sqlite3VdbeSerialType()
75336 ** sqlite3VdbeSerialTypeLen()
75337 ** sqlite3VdbeSerialLen()
75338 ** sqlite3VdbeSerialPut()
75339 ** sqlite3VdbeSerialGet()
75341 ** encapsulate the code that serializes values for storage in SQLite
75342 ** data and index records. Each serialized value consists of a
75343 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
75344 ** integer, stored as a varint.
75346 ** In an SQLite index record, the serial type is stored directly before
75347 ** the blob of data that it corresponds to. In a table record, all serial
75348 ** types are stored at the start of the record, and the blobs of data at
75349 ** the end. Hence these functions allow the caller to handle the
75350 ** serial-type and data blob separately.
75352 ** The following table describes the various storage classes for data:
75354 ** serial type bytes of data type
75355 ** -------------- --------------- ---------------
75356 ** 0 0 NULL
75357 ** 1 1 signed integer
75358 ** 2 2 signed integer
75359 ** 3 3 signed integer
75360 ** 4 4 signed integer
75361 ** 5 6 signed integer
75362 ** 6 8 signed integer
75363 ** 7 8 IEEE float
75364 ** 8 0 Integer constant 0
75365 ** 9 0 Integer constant 1
75366 ** 10,11 reserved for expansion
75367 ** N>=12 and even (N-12)/2 BLOB
75368 ** N>=13 and odd (N-13)/2 text
75370 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
75371 ** of SQLite will not understand those serial types.
75375 ** Return the serial-type for the value stored in pMem.
75377 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
75378 int flags = pMem->flags;
75379 u32 n;
75381 assert( pLen!=0 );
75382 if( flags&MEM_Null ){
75383 *pLen = 0;
75384 return 0;
75386 if( flags&MEM_Int ){
75387 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
75388 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
75389 i64 i = pMem->u.i;
75390 u64 u;
75391 if( i<0 ){
75392 u = ~i;
75393 }else{
75394 u = i;
75396 if( u<=127 ){
75397 if( (i&1)==i && file_format>=4 ){
75398 *pLen = 0;
75399 return 8+(u32)u;
75400 }else{
75401 *pLen = 1;
75402 return 1;
75405 if( u<=32767 ){ *pLen = 2; return 2; }
75406 if( u<=8388607 ){ *pLen = 3; return 3; }
75407 if( u<=2147483647 ){ *pLen = 4; return 4; }
75408 if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
75409 *pLen = 8;
75410 return 6;
75412 if( flags&MEM_Real ){
75413 *pLen = 8;
75414 return 7;
75416 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
75417 assert( pMem->n>=0 );
75418 n = (u32)pMem->n;
75419 if( flags & MEM_Zero ){
75420 n += pMem->u.nZero;
75422 *pLen = n;
75423 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
75427 ** The sizes for serial types less than 128
75429 static const u8 sqlite3SmallTypeSizes[] = {
75430 /* 0 1 2 3 4 5 6 7 8 9 */
75431 /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
75432 /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
75433 /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
75434 /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
75435 /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
75436 /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
75437 /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
75438 /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
75439 /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
75440 /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
75441 /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
75442 /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
75443 /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
75447 ** Return the length of the data corresponding to the supplied serial-type.
75449 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
75450 if( serial_type>=128 ){
75451 return (serial_type-12)/2;
75452 }else{
75453 assert( serial_type<12
75454 || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
75455 return sqlite3SmallTypeSizes[serial_type];
75458 SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
75459 assert( serial_type<128 );
75460 return sqlite3SmallTypeSizes[serial_type];
75464 ** If we are on an architecture with mixed-endian floating
75465 ** points (ex: ARM7) then swap the lower 4 bytes with the
75466 ** upper 4 bytes. Return the result.
75468 ** For most architectures, this is a no-op.
75470 ** (later): It is reported to me that the mixed-endian problem
75471 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
75472 ** that early versions of GCC stored the two words of a 64-bit
75473 ** float in the wrong order. And that error has been propagated
75474 ** ever since. The blame is not necessarily with GCC, though.
75475 ** GCC might have just copying the problem from a prior compiler.
75476 ** I am also told that newer versions of GCC that follow a different
75477 ** ABI get the byte order right.
75479 ** Developers using SQLite on an ARM7 should compile and run their
75480 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
75481 ** enabled, some asserts below will ensure that the byte order of
75482 ** floating point values is correct.
75484 ** (2007-08-30) Frank van Vugt has studied this problem closely
75485 ** and has send his findings to the SQLite developers. Frank
75486 ** writes that some Linux kernels offer floating point hardware
75487 ** emulation that uses only 32-bit mantissas instead of a full
75488 ** 48-bits as required by the IEEE standard. (This is the
75489 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
75490 ** byte swapping becomes very complicated. To avoid problems,
75491 ** the necessary byte swapping is carried out using a 64-bit integer
75492 ** rather than a 64-bit float. Frank assures us that the code here
75493 ** works for him. We, the developers, have no way to independently
75494 ** verify this, but Frank seems to know what he is talking about
75495 ** so we trust him.
75497 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
75498 static u64 floatSwap(u64 in){
75499 union {
75500 u64 r;
75501 u32 i[2];
75502 } u;
75503 u32 t;
75505 u.r = in;
75506 t = u.i[0];
75507 u.i[0] = u.i[1];
75508 u.i[1] = t;
75509 return u.r;
75511 # define swapMixedEndianFloat(X) X = floatSwap(X)
75512 #else
75513 # define swapMixedEndianFloat(X)
75514 #endif
75517 ** Write the serialized data blob for the value stored in pMem into
75518 ** buf. It is assumed that the caller has allocated sufficient space.
75519 ** Return the number of bytes written.
75521 ** nBuf is the amount of space left in buf[]. The caller is responsible
75522 ** for allocating enough space to buf[] to hold the entire field, exclusive
75523 ** of the pMem->u.nZero bytes for a MEM_Zero value.
75525 ** Return the number of bytes actually written into buf[]. The number
75526 ** of bytes in the zero-filled tail is included in the return value only
75527 ** if those bytes were zeroed in buf[].
75529 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
75530 u32 len;
75532 /* Integer and Real */
75533 if( serial_type<=7 && serial_type>0 ){
75534 u64 v;
75535 u32 i;
75536 if( serial_type==7 ){
75537 assert( sizeof(v)==sizeof(pMem->u.r) );
75538 memcpy(&v, &pMem->u.r, sizeof(v));
75539 swapMixedEndianFloat(v);
75540 }else{
75541 v = pMem->u.i;
75543 len = i = sqlite3SmallTypeSizes[serial_type];
75544 assert( i>0 );
75546 buf[--i] = (u8)(v&0xFF);
75547 v >>= 8;
75548 }while( i );
75549 return len;
75552 /* String or blob */
75553 if( serial_type>=12 ){
75554 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
75555 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
75556 len = pMem->n;
75557 if( len>0 ) memcpy(buf, pMem->z, len);
75558 return len;
75561 /* NULL or constants 0 or 1 */
75562 return 0;
75565 /* Input "x" is a sequence of unsigned characters that represent a
75566 ** big-endian integer. Return the equivalent native integer
75568 #define ONE_BYTE_INT(x) ((i8)(x)[0])
75569 #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
75570 #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
75571 #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
75572 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
75575 ** Deserialize the data blob pointed to by buf as serial type serial_type
75576 ** and store the result in pMem. Return the number of bytes read.
75578 ** This function is implemented as two separate routines for performance.
75579 ** The few cases that require local variables are broken out into a separate
75580 ** routine so that in most cases the overhead of moving the stack pointer
75581 ** is avoided.
75583 static u32 SQLITE_NOINLINE serialGet(
75584 const unsigned char *buf, /* Buffer to deserialize from */
75585 u32 serial_type, /* Serial type to deserialize */
75586 Mem *pMem /* Memory cell to write value into */
75588 u64 x = FOUR_BYTE_UINT(buf);
75589 u32 y = FOUR_BYTE_UINT(buf+4);
75590 x = (x<<32) + y;
75591 if( serial_type==6 ){
75592 /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
75593 ** twos-complement integer. */
75594 pMem->u.i = *(i64*)&x;
75595 pMem->flags = MEM_Int;
75596 testcase( pMem->u.i<0 );
75597 }else{
75598 /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
75599 ** floating point number. */
75600 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
75601 /* Verify that integers and floating point values use the same
75602 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
75603 ** defined that 64-bit floating point values really are mixed
75604 ** endian.
75606 static const u64 t1 = ((u64)0x3ff00000)<<32;
75607 static const double r1 = 1.0;
75608 u64 t2 = t1;
75609 swapMixedEndianFloat(t2);
75610 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
75611 #endif
75612 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
75613 swapMixedEndianFloat(x);
75614 memcpy(&pMem->u.r, &x, sizeof(x));
75615 pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
75617 return 8;
75619 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
75620 const unsigned char *buf, /* Buffer to deserialize from */
75621 u32 serial_type, /* Serial type to deserialize */
75622 Mem *pMem /* Memory cell to write value into */
75624 switch( serial_type ){
75625 case 10: /* Reserved for future use */
75626 case 11: /* Reserved for future use */
75627 case 0: { /* Null */
75628 /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
75629 pMem->flags = MEM_Null;
75630 break;
75632 case 1: {
75633 /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
75634 ** integer. */
75635 pMem->u.i = ONE_BYTE_INT(buf);
75636 pMem->flags = MEM_Int;
75637 testcase( pMem->u.i<0 );
75638 return 1;
75640 case 2: { /* 2-byte signed integer */
75641 /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
75642 ** twos-complement integer. */
75643 pMem->u.i = TWO_BYTE_INT(buf);
75644 pMem->flags = MEM_Int;
75645 testcase( pMem->u.i<0 );
75646 return 2;
75648 case 3: { /* 3-byte signed integer */
75649 /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
75650 ** twos-complement integer. */
75651 pMem->u.i = THREE_BYTE_INT(buf);
75652 pMem->flags = MEM_Int;
75653 testcase( pMem->u.i<0 );
75654 return 3;
75656 case 4: { /* 4-byte signed integer */
75657 /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
75658 ** twos-complement integer. */
75659 pMem->u.i = FOUR_BYTE_INT(buf);
75660 #ifdef __HP_cc
75661 /* Work around a sign-extension bug in the HP compiler for HP/UX */
75662 if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
75663 #endif
75664 pMem->flags = MEM_Int;
75665 testcase( pMem->u.i<0 );
75666 return 4;
75668 case 5: { /* 6-byte signed integer */
75669 /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
75670 ** twos-complement integer. */
75671 pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
75672 pMem->flags = MEM_Int;
75673 testcase( pMem->u.i<0 );
75674 return 6;
75676 case 6: /* 8-byte signed integer */
75677 case 7: { /* IEEE floating point */
75678 /* These use local variables, so do them in a separate routine
75679 ** to avoid having to move the frame pointer in the common case */
75680 return serialGet(buf,serial_type,pMem);
75682 case 8: /* Integer 0 */
75683 case 9: { /* Integer 1 */
75684 /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
75685 /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
75686 pMem->u.i = serial_type-8;
75687 pMem->flags = MEM_Int;
75688 return 0;
75690 default: {
75691 /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
75692 ** length.
75693 ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
75694 ** (N-13)/2 bytes in length. */
75695 static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
75696 pMem->z = (char *)buf;
75697 pMem->n = (serial_type-12)/2;
75698 pMem->flags = aFlag[serial_type&1];
75699 return pMem->n;
75702 return 0;
75705 ** This routine is used to allocate sufficient space for an UnpackedRecord
75706 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
75707 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
75709 ** The space is either allocated using sqlite3DbMallocRaw() or from within
75710 ** the unaligned buffer passed via the second and third arguments (presumably
75711 ** stack space). If the former, then *ppFree is set to a pointer that should
75712 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
75713 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
75714 ** before returning.
75716 ** If an OOM error occurs, NULL is returned.
75718 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
75719 KeyInfo *pKeyInfo /* Description of the record */
75721 UnpackedRecord *p; /* Unpacked record to return */
75722 int nByte; /* Number of bytes required for *p */
75723 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
75724 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
75725 if( !p ) return 0;
75726 p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
75727 assert( pKeyInfo->aSortOrder!=0 );
75728 p->pKeyInfo = pKeyInfo;
75729 p->nField = pKeyInfo->nKeyField + 1;
75730 return p;
75734 ** Given the nKey-byte encoding of a record in pKey[], populate the
75735 ** UnpackedRecord structure indicated by the fourth argument with the
75736 ** contents of the decoded record.
75738 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
75739 KeyInfo *pKeyInfo, /* Information about the record format */
75740 int nKey, /* Size of the binary record */
75741 const void *pKey, /* The binary record */
75742 UnpackedRecord *p /* Populate this structure before returning. */
75744 const unsigned char *aKey = (const unsigned char *)pKey;
75745 int d;
75746 u32 idx; /* Offset in aKey[] to read from */
75747 u16 u; /* Unsigned loop counter */
75748 u32 szHdr;
75749 Mem *pMem = p->aMem;
75751 p->default_rc = 0;
75752 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
75753 idx = getVarint32(aKey, szHdr);
75754 d = szHdr;
75755 u = 0;
75756 while( idx<szHdr && d<=nKey ){
75757 u32 serial_type;
75759 idx += getVarint32(&aKey[idx], serial_type);
75760 pMem->enc = pKeyInfo->enc;
75761 pMem->db = pKeyInfo->db;
75762 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
75763 pMem->szMalloc = 0;
75764 pMem->z = 0;
75765 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
75766 pMem++;
75767 if( (++u)>=p->nField ) break;
75769 assert( u<=pKeyInfo->nKeyField + 1 );
75770 p->nField = u;
75773 #ifdef SQLITE_DEBUG
75775 ** This function compares two index or table record keys in the same way
75776 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
75777 ** this function deserializes and compares values using the
75778 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
75779 ** in assert() statements to ensure that the optimized code in
75780 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
75782 ** Return true if the result of comparison is equivalent to desiredResult.
75783 ** Return false if there is a disagreement.
75785 static int vdbeRecordCompareDebug(
75786 int nKey1, const void *pKey1, /* Left key */
75787 const UnpackedRecord *pPKey2, /* Right key */
75788 int desiredResult /* Correct answer */
75790 u32 d1; /* Offset into aKey[] of next data element */
75791 u32 idx1; /* Offset into aKey[] of next header element */
75792 u32 szHdr1; /* Number of bytes in header */
75793 int i = 0;
75794 int rc = 0;
75795 const unsigned char *aKey1 = (const unsigned char *)pKey1;
75796 KeyInfo *pKeyInfo;
75797 Mem mem1;
75799 pKeyInfo = pPKey2->pKeyInfo;
75800 if( pKeyInfo->db==0 ) return 1;
75801 mem1.enc = pKeyInfo->enc;
75802 mem1.db = pKeyInfo->db;
75803 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
75804 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
75806 /* Compilers may complain that mem1.u.i is potentially uninitialized.
75807 ** We could initialize it, as shown here, to silence those complaints.
75808 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
75809 ** the unnecessary initialization has a measurable negative performance
75810 ** impact, since this routine is a very high runner. And so, we choose
75811 ** to ignore the compiler warnings and leave this variable uninitialized.
75813 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
75815 idx1 = getVarint32(aKey1, szHdr1);
75816 if( szHdr1>98307 ) return SQLITE_CORRUPT;
75817 d1 = szHdr1;
75818 assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
75819 assert( pKeyInfo->aSortOrder!=0 );
75820 assert( pKeyInfo->nKeyField>0 );
75821 assert( idx1<=szHdr1 || CORRUPT_DB );
75823 u32 serial_type1;
75825 /* Read the serial types for the next element in each key. */
75826 idx1 += getVarint32( aKey1+idx1, serial_type1 );
75828 /* Verify that there is enough key space remaining to avoid
75829 ** a buffer overread. The "d1+serial_type1+2" subexpression will
75830 ** always be greater than or equal to the amount of required key space.
75831 ** Use that approximation to avoid the more expensive call to
75832 ** sqlite3VdbeSerialTypeLen() in the common case.
75834 if( d1+serial_type1+2>(u32)nKey1
75835 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
75837 break;
75840 /* Extract the values to be compared.
75842 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
75844 /* Do the comparison
75846 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
75847 if( rc!=0 ){
75848 assert( mem1.szMalloc==0 ); /* See comment below */
75849 if( pKeyInfo->aSortOrder[i] ){
75850 rc = -rc; /* Invert the result for DESC sort order. */
75852 goto debugCompareEnd;
75854 i++;
75855 }while( idx1<szHdr1 && i<pPKey2->nField );
75857 /* No memory allocation is ever used on mem1. Prove this using
75858 ** the following assert(). If the assert() fails, it indicates a
75859 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
75861 assert( mem1.szMalloc==0 );
75863 /* rc==0 here means that one of the keys ran out of fields and
75864 ** all the fields up to that point were equal. Return the default_rc
75865 ** value. */
75866 rc = pPKey2->default_rc;
75868 debugCompareEnd:
75869 if( desiredResult==0 && rc==0 ) return 1;
75870 if( desiredResult<0 && rc<0 ) return 1;
75871 if( desiredResult>0 && rc>0 ) return 1;
75872 if( CORRUPT_DB ) return 1;
75873 if( pKeyInfo->db->mallocFailed ) return 1;
75874 return 0;
75876 #endif
75878 #ifdef SQLITE_DEBUG
75880 ** Count the number of fields (a.k.a. columns) in the record given by
75881 ** pKey,nKey. The verify that this count is less than or equal to the
75882 ** limit given by pKeyInfo->nAllField.
75884 ** If this constraint is not satisfied, it means that the high-speed
75885 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
75886 ** not work correctly. If this assert() ever fires, it probably means
75887 ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
75888 ** incorrectly.
75890 static void vdbeAssertFieldCountWithinLimits(
75891 int nKey, const void *pKey, /* The record to verify */
75892 const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
75894 int nField = 0;
75895 u32 szHdr;
75896 u32 idx;
75897 u32 notUsed;
75898 const unsigned char *aKey = (const unsigned char*)pKey;
75900 if( CORRUPT_DB ) return;
75901 idx = getVarint32(aKey, szHdr);
75902 assert( nKey>=0 );
75903 assert( szHdr<=(u32)nKey );
75904 while( idx<szHdr ){
75905 idx += getVarint32(aKey+idx, notUsed);
75906 nField++;
75908 assert( nField <= pKeyInfo->nAllField );
75910 #else
75911 # define vdbeAssertFieldCountWithinLimits(A,B,C)
75912 #endif
75915 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
75916 ** using the collation sequence pColl. As usual, return a negative , zero
75917 ** or positive value if *pMem1 is less than, equal to or greater than
75918 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
75920 static int vdbeCompareMemString(
75921 const Mem *pMem1,
75922 const Mem *pMem2,
75923 const CollSeq *pColl,
75924 u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
75926 if( pMem1->enc==pColl->enc ){
75927 /* The strings are already in the correct encoding. Call the
75928 ** comparison function directly */
75929 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
75930 }else{
75931 int rc;
75932 const void *v1, *v2;
75933 Mem c1;
75934 Mem c2;
75935 sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
75936 sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
75937 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
75938 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
75939 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
75940 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
75941 if( (v1==0 || v2==0) ){
75942 if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
75943 rc = 0;
75944 }else{
75945 rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
75947 sqlite3VdbeMemRelease(&c1);
75948 sqlite3VdbeMemRelease(&c2);
75949 return rc;
75954 ** The input pBlob is guaranteed to be a Blob that is not marked
75955 ** with MEM_Zero. Return true if it could be a zero-blob.
75957 static int isAllZero(const char *z, int n){
75958 int i;
75959 for(i=0; i<n; i++){
75960 if( z[i] ) return 0;
75962 return 1;
75966 ** Compare two blobs. Return negative, zero, or positive if the first
75967 ** is less than, equal to, or greater than the second, respectively.
75968 ** If one blob is a prefix of the other, then the shorter is the lessor.
75970 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
75971 int c;
75972 int n1 = pB1->n;
75973 int n2 = pB2->n;
75975 /* It is possible to have a Blob value that has some non-zero content
75976 ** followed by zero content. But that only comes up for Blobs formed
75977 ** by the OP_MakeRecord opcode, and such Blobs never get passed into
75978 ** sqlite3MemCompare(). */
75979 assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
75980 assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
75982 if( (pB1->flags|pB2->flags) & MEM_Zero ){
75983 if( pB1->flags & pB2->flags & MEM_Zero ){
75984 return pB1->u.nZero - pB2->u.nZero;
75985 }else if( pB1->flags & MEM_Zero ){
75986 if( !isAllZero(pB2->z, pB2->n) ) return -1;
75987 return pB1->u.nZero - n2;
75988 }else{
75989 if( !isAllZero(pB1->z, pB1->n) ) return +1;
75990 return n1 - pB2->u.nZero;
75993 c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
75994 if( c ) return c;
75995 return n1 - n2;
75999 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
76000 ** number. Return negative, zero, or positive if the first (i64) is less than,
76001 ** equal to, or greater than the second (double).
76003 static int sqlite3IntFloatCompare(i64 i, double r){
76004 if( sizeof(LONGDOUBLE_TYPE)>8 ){
76005 LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
76006 if( x<r ) return -1;
76007 if( x>r ) return +1;
76008 return 0;
76009 }else{
76010 i64 y;
76011 double s;
76012 if( r<-9223372036854775808.0 ) return +1;
76013 if( r>9223372036854775807.0 ) return -1;
76014 y = (i64)r;
76015 if( i<y ) return -1;
76016 if( i>y ){
76017 if( y==SMALLEST_INT64 && r>0.0 ) return -1;
76018 return +1;
76020 s = (double)i;
76021 if( s<r ) return -1;
76022 if( s>r ) return +1;
76023 return 0;
76028 ** Compare the values contained by the two memory cells, returning
76029 ** negative, zero or positive if pMem1 is less than, equal to, or greater
76030 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
76031 ** and reals) sorted numerically, followed by text ordered by the collating
76032 ** sequence pColl and finally blob's ordered by memcmp().
76034 ** Two NULL values are considered equal by this function.
76036 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
76037 int f1, f2;
76038 int combined_flags;
76040 f1 = pMem1->flags;
76041 f2 = pMem2->flags;
76042 combined_flags = f1|f2;
76043 assert( (combined_flags & MEM_RowSet)==0 );
76045 /* If one value is NULL, it is less than the other. If both values
76046 ** are NULL, return 0.
76048 if( combined_flags&MEM_Null ){
76049 return (f2&MEM_Null) - (f1&MEM_Null);
76052 /* At least one of the two values is a number
76054 if( combined_flags&(MEM_Int|MEM_Real) ){
76055 if( (f1 & f2 & MEM_Int)!=0 ){
76056 if( pMem1->u.i < pMem2->u.i ) return -1;
76057 if( pMem1->u.i > pMem2->u.i ) return +1;
76058 return 0;
76060 if( (f1 & f2 & MEM_Real)!=0 ){
76061 if( pMem1->u.r < pMem2->u.r ) return -1;
76062 if( pMem1->u.r > pMem2->u.r ) return +1;
76063 return 0;
76065 if( (f1&MEM_Int)!=0 ){
76066 if( (f2&MEM_Real)!=0 ){
76067 return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
76068 }else{
76069 return -1;
76072 if( (f1&MEM_Real)!=0 ){
76073 if( (f2&MEM_Int)!=0 ){
76074 return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
76075 }else{
76076 return -1;
76079 return +1;
76082 /* If one value is a string and the other is a blob, the string is less.
76083 ** If both are strings, compare using the collating functions.
76085 if( combined_flags&MEM_Str ){
76086 if( (f1 & MEM_Str)==0 ){
76087 return 1;
76089 if( (f2 & MEM_Str)==0 ){
76090 return -1;
76093 assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
76094 assert( pMem1->enc==SQLITE_UTF8 ||
76095 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
76097 /* The collation sequence must be defined at this point, even if
76098 ** the user deletes the collation sequence after the vdbe program is
76099 ** compiled (this was not always the case).
76101 assert( !pColl || pColl->xCmp );
76103 if( pColl ){
76104 return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
76106 /* If a NULL pointer was passed as the collate function, fall through
76107 ** to the blob case and use memcmp(). */
76110 /* Both values must be blobs. Compare using memcmp(). */
76111 return sqlite3BlobCompare(pMem1, pMem2);
76116 ** The first argument passed to this function is a serial-type that
76117 ** corresponds to an integer - all values between 1 and 9 inclusive
76118 ** except 7. The second points to a buffer containing an integer value
76119 ** serialized according to serial_type. This function deserializes
76120 ** and returns the value.
76122 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
76123 u32 y;
76124 assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
76125 switch( serial_type ){
76126 case 0:
76127 case 1:
76128 testcase( aKey[0]&0x80 );
76129 return ONE_BYTE_INT(aKey);
76130 case 2:
76131 testcase( aKey[0]&0x80 );
76132 return TWO_BYTE_INT(aKey);
76133 case 3:
76134 testcase( aKey[0]&0x80 );
76135 return THREE_BYTE_INT(aKey);
76136 case 4: {
76137 testcase( aKey[0]&0x80 );
76138 y = FOUR_BYTE_UINT(aKey);
76139 return (i64)*(int*)&y;
76141 case 5: {
76142 testcase( aKey[0]&0x80 );
76143 return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
76145 case 6: {
76146 u64 x = FOUR_BYTE_UINT(aKey);
76147 testcase( aKey[0]&0x80 );
76148 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
76149 return (i64)*(i64*)&x;
76153 return (serial_type - 8);
76157 ** This function compares the two table rows or index records
76158 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
76159 ** or positive integer if key1 is less than, equal to or
76160 ** greater than key2. The {nKey1, pKey1} key must be a blob
76161 ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
76162 ** key must be a parsed key such as obtained from
76163 ** sqlite3VdbeParseRecord.
76165 ** If argument bSkip is non-zero, it is assumed that the caller has already
76166 ** determined that the first fields of the keys are equal.
76168 ** Key1 and Key2 do not have to contain the same number of fields. If all
76169 ** fields that appear in both keys are equal, then pPKey2->default_rc is
76170 ** returned.
76172 ** If database corruption is discovered, set pPKey2->errCode to
76173 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
76174 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
76175 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
76177 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
76178 int nKey1, const void *pKey1, /* Left key */
76179 UnpackedRecord *pPKey2, /* Right key */
76180 int bSkip /* If true, skip the first field */
76182 u32 d1; /* Offset into aKey[] of next data element */
76183 int i; /* Index of next field to compare */
76184 u32 szHdr1; /* Size of record header in bytes */
76185 u32 idx1; /* Offset of first type in header */
76186 int rc = 0; /* Return value */
76187 Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
76188 KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
76189 const unsigned char *aKey1 = (const unsigned char *)pKey1;
76190 Mem mem1;
76192 /* If bSkip is true, then the caller has already determined that the first
76193 ** two elements in the keys are equal. Fix the various stack variables so
76194 ** that this routine begins comparing at the second field. */
76195 if( bSkip ){
76196 u32 s1;
76197 idx1 = 1 + getVarint32(&aKey1[1], s1);
76198 szHdr1 = aKey1[0];
76199 d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
76200 i = 1;
76201 pRhs++;
76202 }else{
76203 idx1 = getVarint32(aKey1, szHdr1);
76204 d1 = szHdr1;
76205 if( d1>(unsigned)nKey1 ){
76206 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
76207 return 0; /* Corruption */
76209 i = 0;
76212 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
76213 assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
76214 || CORRUPT_DB );
76215 assert( pPKey2->pKeyInfo->aSortOrder!=0 );
76216 assert( pPKey2->pKeyInfo->nKeyField>0 );
76217 assert( idx1<=szHdr1 || CORRUPT_DB );
76219 u32 serial_type;
76221 /* RHS is an integer */
76222 if( pRhs->flags & MEM_Int ){
76223 serial_type = aKey1[idx1];
76224 testcase( serial_type==12 );
76225 if( serial_type>=10 ){
76226 rc = +1;
76227 }else if( serial_type==0 ){
76228 rc = -1;
76229 }else if( serial_type==7 ){
76230 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
76231 rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
76232 }else{
76233 i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
76234 i64 rhs = pRhs->u.i;
76235 if( lhs<rhs ){
76236 rc = -1;
76237 }else if( lhs>rhs ){
76238 rc = +1;
76243 /* RHS is real */
76244 else if( pRhs->flags & MEM_Real ){
76245 serial_type = aKey1[idx1];
76246 if( serial_type>=10 ){
76247 /* Serial types 12 or greater are strings and blobs (greater than
76248 ** numbers). Types 10 and 11 are currently "reserved for future
76249 ** use", so it doesn't really matter what the results of comparing
76250 ** them to numberic values are. */
76251 rc = +1;
76252 }else if( serial_type==0 ){
76253 rc = -1;
76254 }else{
76255 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
76256 if( serial_type==7 ){
76257 if( mem1.u.r<pRhs->u.r ){
76258 rc = -1;
76259 }else if( mem1.u.r>pRhs->u.r ){
76260 rc = +1;
76262 }else{
76263 rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
76268 /* RHS is a string */
76269 else if( pRhs->flags & MEM_Str ){
76270 getVarint32(&aKey1[idx1], serial_type);
76271 testcase( serial_type==12 );
76272 if( serial_type<12 ){
76273 rc = -1;
76274 }else if( !(serial_type & 0x01) ){
76275 rc = +1;
76276 }else{
76277 mem1.n = (serial_type - 12) / 2;
76278 testcase( (d1+mem1.n)==(unsigned)nKey1 );
76279 testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
76280 if( (d1+mem1.n) > (unsigned)nKey1 ){
76281 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
76282 return 0; /* Corruption */
76283 }else if( pKeyInfo->aColl[i] ){
76284 mem1.enc = pKeyInfo->enc;
76285 mem1.db = pKeyInfo->db;
76286 mem1.flags = MEM_Str;
76287 mem1.z = (char*)&aKey1[d1];
76288 rc = vdbeCompareMemString(
76289 &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
76291 }else{
76292 int nCmp = MIN(mem1.n, pRhs->n);
76293 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
76294 if( rc==0 ) rc = mem1.n - pRhs->n;
76299 /* RHS is a blob */
76300 else if( pRhs->flags & MEM_Blob ){
76301 assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
76302 getVarint32(&aKey1[idx1], serial_type);
76303 testcase( serial_type==12 );
76304 if( serial_type<12 || (serial_type & 0x01) ){
76305 rc = -1;
76306 }else{
76307 int nStr = (serial_type - 12) / 2;
76308 testcase( (d1+nStr)==(unsigned)nKey1 );
76309 testcase( (d1+nStr+1)==(unsigned)nKey1 );
76310 if( (d1+nStr) > (unsigned)nKey1 ){
76311 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
76312 return 0; /* Corruption */
76313 }else if( pRhs->flags & MEM_Zero ){
76314 if( !isAllZero((const char*)&aKey1[d1],nStr) ){
76315 rc = 1;
76316 }else{
76317 rc = nStr - pRhs->u.nZero;
76319 }else{
76320 int nCmp = MIN(nStr, pRhs->n);
76321 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
76322 if( rc==0 ) rc = nStr - pRhs->n;
76327 /* RHS is null */
76328 else{
76329 serial_type = aKey1[idx1];
76330 rc = (serial_type!=0);
76333 if( rc!=0 ){
76334 if( pKeyInfo->aSortOrder[i] ){
76335 rc = -rc;
76337 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
76338 assert( mem1.szMalloc==0 ); /* See comment below */
76339 return rc;
76342 i++;
76343 pRhs++;
76344 d1 += sqlite3VdbeSerialTypeLen(serial_type);
76345 idx1 += sqlite3VarintLen(serial_type);
76346 }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
76348 /* No memory allocation is ever used on mem1. Prove this using
76349 ** the following assert(). If the assert() fails, it indicates a
76350 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
76351 assert( mem1.szMalloc==0 );
76353 /* rc==0 here means that one or both of the keys ran out of fields and
76354 ** all the fields up to that point were equal. Return the default_rc
76355 ** value. */
76356 assert( CORRUPT_DB
76357 || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
76358 || pKeyInfo->db->mallocFailed
76360 pPKey2->eqSeen = 1;
76361 return pPKey2->default_rc;
76363 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
76364 int nKey1, const void *pKey1, /* Left key */
76365 UnpackedRecord *pPKey2 /* Right key */
76367 return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
76372 ** This function is an optimized version of sqlite3VdbeRecordCompare()
76373 ** that (a) the first field of pPKey2 is an integer, and (b) the
76374 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
76375 ** byte (i.e. is less than 128).
76377 ** To avoid concerns about buffer overreads, this routine is only used
76378 ** on schemas where the maximum valid header size is 63 bytes or less.
76380 static int vdbeRecordCompareInt(
76381 int nKey1, const void *pKey1, /* Left key */
76382 UnpackedRecord *pPKey2 /* Right key */
76384 const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
76385 int serial_type = ((const u8*)pKey1)[1];
76386 int res;
76387 u32 y;
76388 u64 x;
76389 i64 v;
76390 i64 lhs;
76392 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
76393 assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
76394 switch( serial_type ){
76395 case 1: { /* 1-byte signed integer */
76396 lhs = ONE_BYTE_INT(aKey);
76397 testcase( lhs<0 );
76398 break;
76400 case 2: { /* 2-byte signed integer */
76401 lhs = TWO_BYTE_INT(aKey);
76402 testcase( lhs<0 );
76403 break;
76405 case 3: { /* 3-byte signed integer */
76406 lhs = THREE_BYTE_INT(aKey);
76407 testcase( lhs<0 );
76408 break;
76410 case 4: { /* 4-byte signed integer */
76411 y = FOUR_BYTE_UINT(aKey);
76412 lhs = (i64)*(int*)&y;
76413 testcase( lhs<0 );
76414 break;
76416 case 5: { /* 6-byte signed integer */
76417 lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
76418 testcase( lhs<0 );
76419 break;
76421 case 6: { /* 8-byte signed integer */
76422 x = FOUR_BYTE_UINT(aKey);
76423 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
76424 lhs = *(i64*)&x;
76425 testcase( lhs<0 );
76426 break;
76428 case 8:
76429 lhs = 0;
76430 break;
76431 case 9:
76432 lhs = 1;
76433 break;
76435 /* This case could be removed without changing the results of running
76436 ** this code. Including it causes gcc to generate a faster switch
76437 ** statement (since the range of switch targets now starts at zero and
76438 ** is contiguous) but does not cause any duplicate code to be generated
76439 ** (as gcc is clever enough to combine the two like cases). Other
76440 ** compilers might be similar. */
76441 case 0: case 7:
76442 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
76444 default:
76445 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
76448 v = pPKey2->aMem[0].u.i;
76449 if( v>lhs ){
76450 res = pPKey2->r1;
76451 }else if( v<lhs ){
76452 res = pPKey2->r2;
76453 }else if( pPKey2->nField>1 ){
76454 /* The first fields of the two keys are equal. Compare the trailing
76455 ** fields. */
76456 res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
76457 }else{
76458 /* The first fields of the two keys are equal and there are no trailing
76459 ** fields. Return pPKey2->default_rc in this case. */
76460 res = pPKey2->default_rc;
76461 pPKey2->eqSeen = 1;
76464 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
76465 return res;
76469 ** This function is an optimized version of sqlite3VdbeRecordCompare()
76470 ** that (a) the first field of pPKey2 is a string, that (b) the first field
76471 ** uses the collation sequence BINARY and (c) that the size-of-header varint
76472 ** at the start of (pKey1/nKey1) fits in a single byte.
76474 static int vdbeRecordCompareString(
76475 int nKey1, const void *pKey1, /* Left key */
76476 UnpackedRecord *pPKey2 /* Right key */
76478 const u8 *aKey1 = (const u8*)pKey1;
76479 int serial_type;
76480 int res;
76482 assert( pPKey2->aMem[0].flags & MEM_Str );
76483 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
76484 getVarint32(&aKey1[1], serial_type);
76485 if( serial_type<12 ){
76486 res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
76487 }else if( !(serial_type & 0x01) ){
76488 res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
76489 }else{
76490 int nCmp;
76491 int nStr;
76492 int szHdr = aKey1[0];
76494 nStr = (serial_type-12) / 2;
76495 if( (szHdr + nStr) > nKey1 ){
76496 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
76497 return 0; /* Corruption */
76499 nCmp = MIN( pPKey2->aMem[0].n, nStr );
76500 res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
76502 if( res==0 ){
76503 res = nStr - pPKey2->aMem[0].n;
76504 if( res==0 ){
76505 if( pPKey2->nField>1 ){
76506 res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
76507 }else{
76508 res = pPKey2->default_rc;
76509 pPKey2->eqSeen = 1;
76511 }else if( res>0 ){
76512 res = pPKey2->r2;
76513 }else{
76514 res = pPKey2->r1;
76516 }else if( res>0 ){
76517 res = pPKey2->r2;
76518 }else{
76519 res = pPKey2->r1;
76523 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
76524 || CORRUPT_DB
76525 || pPKey2->pKeyInfo->db->mallocFailed
76527 return res;
76531 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
76532 ** suitable for comparing serialized records to the unpacked record passed
76533 ** as the only argument.
76535 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
76536 /* varintRecordCompareInt() and varintRecordCompareString() both assume
76537 ** that the size-of-header varint that occurs at the start of each record
76538 ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
76539 ** also assumes that it is safe to overread a buffer by at least the
76540 ** maximum possible legal header size plus 8 bytes. Because there is
76541 ** guaranteed to be at least 74 (but not 136) bytes of padding following each
76542 ** buffer passed to varintRecordCompareInt() this makes it convenient to
76543 ** limit the size of the header to 64 bytes in cases where the first field
76544 ** is an integer.
76546 ** The easiest way to enforce this limit is to consider only records with
76547 ** 13 fields or less. If the first field is an integer, the maximum legal
76548 ** header size is (12*5 + 1 + 1) bytes. */
76549 if( p->pKeyInfo->nAllField<=13 ){
76550 int flags = p->aMem[0].flags;
76551 if( p->pKeyInfo->aSortOrder[0] ){
76552 p->r1 = 1;
76553 p->r2 = -1;
76554 }else{
76555 p->r1 = -1;
76556 p->r2 = 1;
76558 if( (flags & MEM_Int) ){
76559 return vdbeRecordCompareInt;
76561 testcase( flags & MEM_Real );
76562 testcase( flags & MEM_Null );
76563 testcase( flags & MEM_Blob );
76564 if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
76565 assert( flags & MEM_Str );
76566 return vdbeRecordCompareString;
76570 return sqlite3VdbeRecordCompare;
76574 ** pCur points at an index entry created using the OP_MakeRecord opcode.
76575 ** Read the rowid (the last field in the record) and store it in *rowid.
76576 ** Return SQLITE_OK if everything works, or an error code otherwise.
76578 ** pCur might be pointing to text obtained from a corrupt database file.
76579 ** So the content cannot be trusted. Do appropriate checks on the content.
76581 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
76582 i64 nCellKey = 0;
76583 int rc;
76584 u32 szHdr; /* Size of the header */
76585 u32 typeRowid; /* Serial type of the rowid */
76586 u32 lenRowid; /* Size of the rowid */
76587 Mem m, v;
76589 /* Get the size of the index entry. Only indices entries of less
76590 ** than 2GiB are support - anything large must be database corruption.
76591 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
76592 ** this code can safely assume that nCellKey is 32-bits
76594 assert( sqlite3BtreeCursorIsValid(pCur) );
76595 nCellKey = sqlite3BtreePayloadSize(pCur);
76596 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
76598 /* Read in the complete content of the index entry */
76599 sqlite3VdbeMemInit(&m, db, 0);
76600 rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
76601 if( rc ){
76602 return rc;
76605 /* The index entry must begin with a header size */
76606 (void)getVarint32((u8*)m.z, szHdr);
76607 testcase( szHdr==3 );
76608 testcase( szHdr==m.n );
76609 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
76610 goto idx_rowid_corruption;
76613 /* The last field of the index should be an integer - the ROWID.
76614 ** Verify that the last entry really is an integer. */
76615 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
76616 testcase( typeRowid==1 );
76617 testcase( typeRowid==2 );
76618 testcase( typeRowid==3 );
76619 testcase( typeRowid==4 );
76620 testcase( typeRowid==5 );
76621 testcase( typeRowid==6 );
76622 testcase( typeRowid==8 );
76623 testcase( typeRowid==9 );
76624 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
76625 goto idx_rowid_corruption;
76627 lenRowid = sqlite3SmallTypeSizes[typeRowid];
76628 testcase( (u32)m.n==szHdr+lenRowid );
76629 if( unlikely((u32)m.n<szHdr+lenRowid) ){
76630 goto idx_rowid_corruption;
76633 /* Fetch the integer off the end of the index record */
76634 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
76635 *rowid = v.u.i;
76636 sqlite3VdbeMemRelease(&m);
76637 return SQLITE_OK;
76639 /* Jump here if database corruption is detected after m has been
76640 ** allocated. Free the m object and return SQLITE_CORRUPT. */
76641 idx_rowid_corruption:
76642 testcase( m.szMalloc!=0 );
76643 sqlite3VdbeMemRelease(&m);
76644 return SQLITE_CORRUPT_BKPT;
76648 ** Compare the key of the index entry that cursor pC is pointing to against
76649 ** the key string in pUnpacked. Write into *pRes a number
76650 ** that is negative, zero, or positive if pC is less than, equal to,
76651 ** or greater than pUnpacked. Return SQLITE_OK on success.
76653 ** pUnpacked is either created without a rowid or is truncated so that it
76654 ** omits the rowid at the end. The rowid at the end of the index entry
76655 ** is ignored as well. Hence, this routine only compares the prefixes
76656 ** of the keys prior to the final rowid, not the entire key.
76658 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
76659 sqlite3 *db, /* Database connection */
76660 VdbeCursor *pC, /* The cursor to compare against */
76661 UnpackedRecord *pUnpacked, /* Unpacked version of key */
76662 int *res /* Write the comparison result here */
76664 i64 nCellKey = 0;
76665 int rc;
76666 BtCursor *pCur;
76667 Mem m;
76669 assert( pC->eCurType==CURTYPE_BTREE );
76670 pCur = pC->uc.pCursor;
76671 assert( sqlite3BtreeCursorIsValid(pCur) );
76672 nCellKey = sqlite3BtreePayloadSize(pCur);
76673 /* nCellKey will always be between 0 and 0xffffffff because of the way
76674 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
76675 if( nCellKey<=0 || nCellKey>0x7fffffff ){
76676 *res = 0;
76677 return SQLITE_CORRUPT_BKPT;
76679 sqlite3VdbeMemInit(&m, db, 0);
76680 rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
76681 if( rc ){
76682 return rc;
76684 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
76685 sqlite3VdbeMemRelease(&m);
76686 return SQLITE_OK;
76690 ** This routine sets the value to be returned by subsequent calls to
76691 ** sqlite3_changes() on the database handle 'db'.
76693 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
76694 assert( sqlite3_mutex_held(db->mutex) );
76695 db->nChange = nChange;
76696 db->nTotalChange += nChange;
76700 ** Set a flag in the vdbe to update the change counter when it is finalised
76701 ** or reset.
76703 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
76704 v->changeCntOn = 1;
76708 ** Mark every prepared statement associated with a database connection
76709 ** as expired.
76711 ** An expired statement means that recompilation of the statement is
76712 ** recommend. Statements expire when things happen that make their
76713 ** programs obsolete. Removing user-defined functions or collating
76714 ** sequences, or changing an authorization function are the types of
76715 ** things that make prepared statements obsolete.
76717 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
76718 Vdbe *p;
76719 for(p = db->pVdbe; p; p=p->pNext){
76720 p->expired = 1;
76725 ** Return the database associated with the Vdbe.
76727 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
76728 return v->db;
76732 ** Return the SQLITE_PREPARE flags for a Vdbe.
76734 SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
76735 return v->prepFlags;
76739 ** Return a pointer to an sqlite3_value structure containing the value bound
76740 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
76741 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
76742 ** constants) to the value before returning it.
76744 ** The returned value must be freed by the caller using sqlite3ValueFree().
76746 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
76747 assert( iVar>0 );
76748 if( v ){
76749 Mem *pMem = &v->aVar[iVar-1];
76750 assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
76751 if( 0==(pMem->flags & MEM_Null) ){
76752 sqlite3_value *pRet = sqlite3ValueNew(v->db);
76753 if( pRet ){
76754 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
76755 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
76757 return pRet;
76760 return 0;
76764 ** Configure SQL variable iVar so that binding a new value to it signals
76765 ** to sqlite3_reoptimize() that re-preparing the statement may result
76766 ** in a better query plan.
76768 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
76769 assert( iVar>0 );
76770 assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
76771 if( iVar>=32 ){
76772 v->expmask |= 0x80000000;
76773 }else{
76774 v->expmask |= ((u32)1 << (iVar-1));
76779 ** Cause a function to throw an error if it was call from OP_PureFunc
76780 ** rather than OP_Function.
76782 ** OP_PureFunc means that the function must be deterministic, and should
76783 ** throw an error if it is given inputs that would make it non-deterministic.
76784 ** This routine is invoked by date/time functions that use non-deterministic
76785 ** features such as 'now'.
76787 SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
76788 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
76789 if( pCtx->pVdbe==0 ) return 1;
76790 #endif
76791 if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
76792 sqlite3_result_error(pCtx,
76793 "non-deterministic function in index expression or CHECK constraint",
76794 -1);
76795 return 0;
76797 return 1;
76800 #ifndef SQLITE_OMIT_VIRTUALTABLE
76802 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
76803 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
76804 ** in memory obtained from sqlite3DbMalloc).
76806 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
76807 if( pVtab->zErrMsg ){
76808 sqlite3 *db = p->db;
76809 sqlite3DbFree(db, p->zErrMsg);
76810 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
76811 sqlite3_free(pVtab->zErrMsg);
76812 pVtab->zErrMsg = 0;
76815 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76817 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76820 ** If the second argument is not NULL, release any allocations associated
76821 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
76822 ** structure itself, using sqlite3DbFree().
76824 ** This function is used to free UnpackedRecord structures allocated by
76825 ** the vdbeUnpackRecord() function found in vdbeapi.c.
76827 static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
76828 if( p ){
76829 int i;
76830 for(i=0; i<nField; i++){
76831 Mem *pMem = &p->aMem[i];
76832 if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
76834 sqlite3DbFreeNN(db, p);
76837 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76839 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76841 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
76842 ** then cursor passed as the second argument should point to the row about
76843 ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
76844 ** the required value will be read from the row the cursor points to.
76846 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
76847 Vdbe *v, /* Vdbe pre-update hook is invoked by */
76848 VdbeCursor *pCsr, /* Cursor to grab old.* values from */
76849 int op, /* SQLITE_INSERT, UPDATE or DELETE */
76850 const char *zDb, /* Database name */
76851 Table *pTab, /* Modified table */
76852 i64 iKey1, /* Initial key value */
76853 int iReg /* Register for new.* record */
76855 sqlite3 *db = v->db;
76856 i64 iKey2;
76857 PreUpdate preupdate;
76858 const char *zTbl = pTab->zName;
76859 static const u8 fakeSortOrder = 0;
76861 assert( db->pPreUpdate==0 );
76862 memset(&preupdate, 0, sizeof(PreUpdate));
76863 if( HasRowid(pTab)==0 ){
76864 iKey1 = iKey2 = 0;
76865 preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
76866 }else{
76867 if( op==SQLITE_UPDATE ){
76868 iKey2 = v->aMem[iReg].u.i;
76869 }else{
76870 iKey2 = iKey1;
76874 assert( pCsr->nField==pTab->nCol
76875 || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
76878 preupdate.v = v;
76879 preupdate.pCsr = pCsr;
76880 preupdate.op = op;
76881 preupdate.iNewReg = iReg;
76882 preupdate.keyinfo.db = db;
76883 preupdate.keyinfo.enc = ENC(db);
76884 preupdate.keyinfo.nKeyField = pTab->nCol;
76885 preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
76886 preupdate.iKey1 = iKey1;
76887 preupdate.iKey2 = iKey2;
76888 preupdate.pTab = pTab;
76890 db->pPreUpdate = &preupdate;
76891 db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
76892 db->pPreUpdate = 0;
76893 sqlite3DbFree(db, preupdate.aRecord);
76894 vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
76895 vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
76896 if( preupdate.aNew ){
76897 int i;
76898 for(i=0; i<pCsr->nField; i++){
76899 sqlite3VdbeMemRelease(&preupdate.aNew[i]);
76901 sqlite3DbFreeNN(db, preupdate.aNew);
76904 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76906 /************** End of vdbeaux.c *********************************************/
76907 /************** Begin file vdbeapi.c *****************************************/
76909 ** 2004 May 26
76911 ** The author disclaims copyright to this source code. In place of
76912 ** a legal notice, here is a blessing:
76914 ** May you do good and not evil.
76915 ** May you find forgiveness for yourself and forgive others.
76916 ** May you share freely, never taking more than you give.
76918 *************************************************************************
76920 ** This file contains code use to implement APIs that are part of the
76921 ** VDBE.
76923 /* #include "sqliteInt.h" */
76924 /* #include "vdbeInt.h" */
76926 #ifndef SQLITE_OMIT_DEPRECATED
76928 ** Return TRUE (non-zero) of the statement supplied as an argument needs
76929 ** to be recompiled. A statement needs to be recompiled whenever the
76930 ** execution environment changes in a way that would alter the program
76931 ** that sqlite3_prepare() generates. For example, if new functions or
76932 ** collating sequences are registered or if an authorizer function is
76933 ** added or changed.
76935 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
76936 Vdbe *p = (Vdbe*)pStmt;
76937 return p==0 || p->expired;
76939 #endif
76942 ** Check on a Vdbe to make sure it has not been finalized. Log
76943 ** an error and return true if it has been finalized (or is otherwise
76944 ** invalid). Return false if it is ok.
76946 static int vdbeSafety(Vdbe *p){
76947 if( p->db==0 ){
76948 sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
76949 return 1;
76950 }else{
76951 return 0;
76954 static int vdbeSafetyNotNull(Vdbe *p){
76955 if( p==0 ){
76956 sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
76957 return 1;
76958 }else{
76959 return vdbeSafety(p);
76963 #ifndef SQLITE_OMIT_TRACE
76965 ** Invoke the profile callback. This routine is only called if we already
76966 ** know that the profile callback is defined and needs to be invoked.
76968 static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
76969 sqlite3_int64 iNow;
76970 sqlite3_int64 iElapse;
76971 assert( p->startTime>0 );
76972 assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
76973 assert( db->init.busy==0 );
76974 assert( p->zSql!=0 );
76975 sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
76976 iElapse = (iNow - p->startTime)*1000000;
76977 if( db->xProfile ){
76978 db->xProfile(db->pProfileArg, p->zSql, iElapse);
76980 if( db->mTrace & SQLITE_TRACE_PROFILE ){
76981 db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
76983 p->startTime = 0;
76986 ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
76987 ** is needed, and it invokes the callback if it is needed.
76989 # define checkProfileCallback(DB,P) \
76990 if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
76991 #else
76992 # define checkProfileCallback(DB,P) /*no-op*/
76993 #endif
76996 ** The following routine destroys a virtual machine that is created by
76997 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
76998 ** success/failure code that describes the result of executing the virtual
76999 ** machine.
77001 ** This routine sets the error code and string returned by
77002 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
77004 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
77005 int rc;
77006 if( pStmt==0 ){
77007 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
77008 ** pointer is a harmless no-op. */
77009 rc = SQLITE_OK;
77010 }else{
77011 Vdbe *v = (Vdbe*)pStmt;
77012 sqlite3 *db = v->db;
77013 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
77014 sqlite3_mutex_enter(db->mutex);
77015 checkProfileCallback(db, v);
77016 rc = sqlite3VdbeFinalize(v);
77017 rc = sqlite3ApiExit(db, rc);
77018 sqlite3LeaveMutexAndCloseZombie(db);
77020 return rc;
77024 ** Terminate the current execution of an SQL statement and reset it
77025 ** back to its starting state so that it can be reused. A success code from
77026 ** the prior execution is returned.
77028 ** This routine sets the error code and string returned by
77029 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
77031 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
77032 int rc;
77033 if( pStmt==0 ){
77034 rc = SQLITE_OK;
77035 }else{
77036 Vdbe *v = (Vdbe*)pStmt;
77037 sqlite3 *db = v->db;
77038 sqlite3_mutex_enter(db->mutex);
77039 checkProfileCallback(db, v);
77040 rc = sqlite3VdbeReset(v);
77041 sqlite3VdbeRewind(v);
77042 assert( (rc & (db->errMask))==rc );
77043 rc = sqlite3ApiExit(db, rc);
77044 sqlite3_mutex_leave(db->mutex);
77046 return rc;
77050 ** Set all the parameters in the compiled SQL statement to NULL.
77052 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
77053 int i;
77054 int rc = SQLITE_OK;
77055 Vdbe *p = (Vdbe*)pStmt;
77056 #if SQLITE_THREADSAFE
77057 sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
77058 #endif
77059 sqlite3_mutex_enter(mutex);
77060 for(i=0; i<p->nVar; i++){
77061 sqlite3VdbeMemRelease(&p->aVar[i]);
77062 p->aVar[i].flags = MEM_Null;
77064 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
77065 if( p->expmask ){
77066 p->expired = 1;
77068 sqlite3_mutex_leave(mutex);
77069 return rc;
77073 /**************************** sqlite3_value_ *******************************
77074 ** The following routines extract information from a Mem or sqlite3_value
77075 ** structure.
77077 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
77078 Mem *p = (Mem*)pVal;
77079 if( p->flags & (MEM_Blob|MEM_Str) ){
77080 if( ExpandBlob(p)!=SQLITE_OK ){
77081 assert( p->flags==MEM_Null && p->z==0 );
77082 return 0;
77084 p->flags |= MEM_Blob;
77085 return p->n ? p->z : 0;
77086 }else{
77087 return sqlite3_value_text(pVal);
77090 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
77091 return sqlite3ValueBytes(pVal, SQLITE_UTF8);
77093 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
77094 return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
77096 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
77097 return sqlite3VdbeRealValue((Mem*)pVal);
77099 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
77100 return (int)sqlite3VdbeIntValue((Mem*)pVal);
77102 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
77103 return sqlite3VdbeIntValue((Mem*)pVal);
77105 SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
77106 Mem *pMem = (Mem*)pVal;
77107 return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
77109 SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
77110 Mem *p = (Mem*)pVal;
77111 if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
77112 (MEM_Null|MEM_Term|MEM_Subtype)
77113 && zPType!=0
77114 && p->eSubtype=='p'
77115 && strcmp(p->u.zPType, zPType)==0
77117 return (void*)p->z;
77118 }else{
77119 return 0;
77122 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
77123 return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
77125 #ifndef SQLITE_OMIT_UTF16
77126 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
77127 return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
77129 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
77130 return sqlite3ValueText(pVal, SQLITE_UTF16BE);
77132 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
77133 return sqlite3ValueText(pVal, SQLITE_UTF16LE);
77135 #endif /* SQLITE_OMIT_UTF16 */
77136 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
77137 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
77138 ** point number string BLOB NULL
77140 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
77141 static const u8 aType[] = {
77142 SQLITE_BLOB, /* 0x00 */
77143 SQLITE_NULL, /* 0x01 */
77144 SQLITE_TEXT, /* 0x02 */
77145 SQLITE_NULL, /* 0x03 */
77146 SQLITE_INTEGER, /* 0x04 */
77147 SQLITE_NULL, /* 0x05 */
77148 SQLITE_INTEGER, /* 0x06 */
77149 SQLITE_NULL, /* 0x07 */
77150 SQLITE_FLOAT, /* 0x08 */
77151 SQLITE_NULL, /* 0x09 */
77152 SQLITE_FLOAT, /* 0x0a */
77153 SQLITE_NULL, /* 0x0b */
77154 SQLITE_INTEGER, /* 0x0c */
77155 SQLITE_NULL, /* 0x0d */
77156 SQLITE_INTEGER, /* 0x0e */
77157 SQLITE_NULL, /* 0x0f */
77158 SQLITE_BLOB, /* 0x10 */
77159 SQLITE_NULL, /* 0x11 */
77160 SQLITE_TEXT, /* 0x12 */
77161 SQLITE_NULL, /* 0x13 */
77162 SQLITE_INTEGER, /* 0x14 */
77163 SQLITE_NULL, /* 0x15 */
77164 SQLITE_INTEGER, /* 0x16 */
77165 SQLITE_NULL, /* 0x17 */
77166 SQLITE_FLOAT, /* 0x18 */
77167 SQLITE_NULL, /* 0x19 */
77168 SQLITE_FLOAT, /* 0x1a */
77169 SQLITE_NULL, /* 0x1b */
77170 SQLITE_INTEGER, /* 0x1c */
77171 SQLITE_NULL, /* 0x1d */
77172 SQLITE_INTEGER, /* 0x1e */
77173 SQLITE_NULL, /* 0x1f */
77175 return aType[pVal->flags&MEM_AffMask];
77178 /* Make a copy of an sqlite3_value object
77180 SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
77181 sqlite3_value *pNew;
77182 if( pOrig==0 ) return 0;
77183 pNew = sqlite3_malloc( sizeof(*pNew) );
77184 if( pNew==0 ) return 0;
77185 memset(pNew, 0, sizeof(*pNew));
77186 memcpy(pNew, pOrig, MEMCELLSIZE);
77187 pNew->flags &= ~MEM_Dyn;
77188 pNew->db = 0;
77189 if( pNew->flags&(MEM_Str|MEM_Blob) ){
77190 pNew->flags &= ~(MEM_Static|MEM_Dyn);
77191 pNew->flags |= MEM_Ephem;
77192 if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
77193 sqlite3ValueFree(pNew);
77194 pNew = 0;
77197 return pNew;
77200 /* Destroy an sqlite3_value object previously obtained from
77201 ** sqlite3_value_dup().
77203 SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
77204 sqlite3ValueFree(pOld);
77208 /**************************** sqlite3_result_ *******************************
77209 ** The following routines are used by user-defined functions to specify
77210 ** the function result.
77212 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
77213 ** result as a string or blob but if the string or blob is too large, it
77214 ** then sets the error code to SQLITE_TOOBIG
77216 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
77217 ** on value P is not going to be used and need to be destroyed.
77219 static void setResultStrOrError(
77220 sqlite3_context *pCtx, /* Function context */
77221 const char *z, /* String pointer */
77222 int n, /* Bytes in string, or negative */
77223 u8 enc, /* Encoding of z. 0 for BLOBs */
77224 void (*xDel)(void*) /* Destructor function */
77226 if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
77227 sqlite3_result_error_toobig(pCtx);
77230 static int invokeValueDestructor(
77231 const void *p, /* Value to destroy */
77232 void (*xDel)(void*), /* The destructor */
77233 sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
77235 assert( xDel!=SQLITE_DYNAMIC );
77236 if( xDel==0 ){
77237 /* noop */
77238 }else if( xDel==SQLITE_TRANSIENT ){
77239 /* noop */
77240 }else{
77241 xDel((void*)p);
77243 if( pCtx ) sqlite3_result_error_toobig(pCtx);
77244 return SQLITE_TOOBIG;
77246 SQLITE_API void sqlite3_result_blob(
77247 sqlite3_context *pCtx,
77248 const void *z,
77249 int n,
77250 void (*xDel)(void *)
77252 assert( n>=0 );
77253 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77254 setResultStrOrError(pCtx, z, n, 0, xDel);
77256 SQLITE_API void sqlite3_result_blob64(
77257 sqlite3_context *pCtx,
77258 const void *z,
77259 sqlite3_uint64 n,
77260 void (*xDel)(void *)
77262 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77263 assert( xDel!=SQLITE_DYNAMIC );
77264 if( n>0x7fffffff ){
77265 (void)invokeValueDestructor(z, xDel, pCtx);
77266 }else{
77267 setResultStrOrError(pCtx, z, (int)n, 0, xDel);
77270 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
77271 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77272 sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
77274 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
77275 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77276 pCtx->isError = SQLITE_ERROR;
77277 pCtx->fErrorOrAux = 1;
77278 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
77280 #ifndef SQLITE_OMIT_UTF16
77281 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
77282 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77283 pCtx->isError = SQLITE_ERROR;
77284 pCtx->fErrorOrAux = 1;
77285 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
77287 #endif
77288 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
77289 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77290 sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
77292 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
77293 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77294 sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
77296 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
77297 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77298 sqlite3VdbeMemSetNull(pCtx->pOut);
77300 SQLITE_API void sqlite3_result_pointer(
77301 sqlite3_context *pCtx,
77302 void *pPtr,
77303 const char *zPType,
77304 void (*xDestructor)(void*)
77306 Mem *pOut = pCtx->pOut;
77307 assert( sqlite3_mutex_held(pOut->db->mutex) );
77308 sqlite3VdbeMemRelease(pOut);
77309 pOut->flags = MEM_Null;
77310 sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
77312 SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
77313 Mem *pOut = pCtx->pOut;
77314 assert( sqlite3_mutex_held(pOut->db->mutex) );
77315 pOut->eSubtype = eSubtype & 0xff;
77316 pOut->flags |= MEM_Subtype;
77318 SQLITE_API void sqlite3_result_text(
77319 sqlite3_context *pCtx,
77320 const char *z,
77321 int n,
77322 void (*xDel)(void *)
77324 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77325 setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
77327 SQLITE_API void sqlite3_result_text64(
77328 sqlite3_context *pCtx,
77329 const char *z,
77330 sqlite3_uint64 n,
77331 void (*xDel)(void *),
77332 unsigned char enc
77334 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77335 assert( xDel!=SQLITE_DYNAMIC );
77336 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
77337 if( n>0x7fffffff ){
77338 (void)invokeValueDestructor(z, xDel, pCtx);
77339 }else{
77340 setResultStrOrError(pCtx, z, (int)n, enc, xDel);
77343 #ifndef SQLITE_OMIT_UTF16
77344 SQLITE_API void sqlite3_result_text16(
77345 sqlite3_context *pCtx,
77346 const void *z,
77347 int n,
77348 void (*xDel)(void *)
77350 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77351 setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
77353 SQLITE_API void sqlite3_result_text16be(
77354 sqlite3_context *pCtx,
77355 const void *z,
77356 int n,
77357 void (*xDel)(void *)
77359 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77360 setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
77362 SQLITE_API void sqlite3_result_text16le(
77363 sqlite3_context *pCtx,
77364 const void *z,
77365 int n,
77366 void (*xDel)(void *)
77368 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77369 setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
77371 #endif /* SQLITE_OMIT_UTF16 */
77372 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
77373 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77374 sqlite3VdbeMemCopy(pCtx->pOut, pValue);
77376 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
77377 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77378 sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
77380 SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
77381 Mem *pOut = pCtx->pOut;
77382 assert( sqlite3_mutex_held(pOut->db->mutex) );
77383 if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
77384 return SQLITE_TOOBIG;
77386 sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
77387 return SQLITE_OK;
77389 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
77390 pCtx->isError = errCode;
77391 pCtx->fErrorOrAux = 1;
77392 #ifdef SQLITE_DEBUG
77393 if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
77394 #endif
77395 if( pCtx->pOut->flags & MEM_Null ){
77396 sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
77397 SQLITE_UTF8, SQLITE_STATIC);
77401 /* Force an SQLITE_TOOBIG error. */
77402 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
77403 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77404 pCtx->isError = SQLITE_TOOBIG;
77405 pCtx->fErrorOrAux = 1;
77406 sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
77407 SQLITE_UTF8, SQLITE_STATIC);
77410 /* An SQLITE_NOMEM error. */
77411 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
77412 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77413 sqlite3VdbeMemSetNull(pCtx->pOut);
77414 pCtx->isError = SQLITE_NOMEM_BKPT;
77415 pCtx->fErrorOrAux = 1;
77416 sqlite3OomFault(pCtx->pOut->db);
77420 ** This function is called after a transaction has been committed. It
77421 ** invokes callbacks registered with sqlite3_wal_hook() as required.
77423 static int doWalCallbacks(sqlite3 *db){
77424 int rc = SQLITE_OK;
77425 #ifndef SQLITE_OMIT_WAL
77426 int i;
77427 for(i=0; i<db->nDb; i++){
77428 Btree *pBt = db->aDb[i].pBt;
77429 if( pBt ){
77430 int nEntry;
77431 sqlite3BtreeEnter(pBt);
77432 nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
77433 sqlite3BtreeLeave(pBt);
77434 if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
77435 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
77439 #endif
77440 return rc;
77445 ** Execute the statement pStmt, either until a row of data is ready, the
77446 ** statement is completely executed or an error occurs.
77448 ** This routine implements the bulk of the logic behind the sqlite_step()
77449 ** API. The only thing omitted is the automatic recompile if a
77450 ** schema change has occurred. That detail is handled by the
77451 ** outer sqlite3_step() wrapper procedure.
77453 static int sqlite3Step(Vdbe *p){
77454 sqlite3 *db;
77455 int rc;
77457 assert(p);
77458 if( p->magic!=VDBE_MAGIC_RUN ){
77459 /* We used to require that sqlite3_reset() be called before retrying
77460 ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
77461 ** with version 3.7.0, we changed this so that sqlite3_reset() would
77462 ** be called automatically instead of throwing the SQLITE_MISUSE error.
77463 ** This "automatic-reset" change is not technically an incompatibility,
77464 ** since any application that receives an SQLITE_MISUSE is broken by
77465 ** definition.
77467 ** Nevertheless, some published applications that were originally written
77468 ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
77469 ** returns, and those were broken by the automatic-reset change. As a
77470 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
77471 ** legacy behavior of returning SQLITE_MISUSE for cases where the
77472 ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
77473 ** or SQLITE_BUSY error.
77475 #ifdef SQLITE_OMIT_AUTORESET
77476 if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
77477 sqlite3_reset((sqlite3_stmt*)p);
77478 }else{
77479 return SQLITE_MISUSE_BKPT;
77481 #else
77482 sqlite3_reset((sqlite3_stmt*)p);
77483 #endif
77486 /* Check that malloc() has not failed. If it has, return early. */
77487 db = p->db;
77488 if( db->mallocFailed ){
77489 p->rc = SQLITE_NOMEM;
77490 return SQLITE_NOMEM_BKPT;
77493 if( p->pc<=0 && p->expired ){
77494 p->rc = SQLITE_SCHEMA;
77495 rc = SQLITE_ERROR;
77496 goto end_of_step;
77498 if( p->pc<0 ){
77499 /* If there are no other statements currently running, then
77500 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
77501 ** from interrupting a statement that has not yet started.
77503 if( db->nVdbeActive==0 ){
77504 db->u1.isInterrupted = 0;
77507 assert( db->nVdbeWrite>0 || db->autoCommit==0
77508 || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
77511 #ifndef SQLITE_OMIT_TRACE
77512 if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
77513 && !db->init.busy && p->zSql ){
77514 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
77515 }else{
77516 assert( p->startTime==0 );
77518 #endif
77520 db->nVdbeActive++;
77521 if( p->readOnly==0 ) db->nVdbeWrite++;
77522 if( p->bIsReader ) db->nVdbeRead++;
77523 p->pc = 0;
77525 #ifdef SQLITE_DEBUG
77526 p->rcApp = SQLITE_OK;
77527 #endif
77528 #ifndef SQLITE_OMIT_EXPLAIN
77529 if( p->explain ){
77530 rc = sqlite3VdbeList(p);
77531 }else
77532 #endif /* SQLITE_OMIT_EXPLAIN */
77534 db->nVdbeExec++;
77535 rc = sqlite3VdbeExec(p);
77536 db->nVdbeExec--;
77539 #ifndef SQLITE_OMIT_TRACE
77540 /* If the statement completed successfully, invoke the profile callback */
77541 if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
77542 #endif
77544 if( rc==SQLITE_DONE && db->autoCommit ){
77545 assert( p->rc==SQLITE_OK );
77546 p->rc = doWalCallbacks(db);
77547 if( p->rc!=SQLITE_OK ){
77548 rc = SQLITE_ERROR;
77552 db->errCode = rc;
77553 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
77554 p->rc = SQLITE_NOMEM_BKPT;
77556 end_of_step:
77557 /* At this point local variable rc holds the value that should be
77558 ** returned if this statement was compiled using the legacy
77559 ** sqlite3_prepare() interface. According to the docs, this can only
77560 ** be one of the values in the first assert() below. Variable p->rc
77561 ** contains the value that would be returned if sqlite3_finalize()
77562 ** were called on statement p.
77564 assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
77565 || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
77567 assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
77568 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
77569 && rc!=SQLITE_ROW
77570 && rc!=SQLITE_DONE
77572 /* If this statement was prepared using saved SQL and an
77573 ** error has occurred, then return the error code in p->rc to the
77574 ** caller. Set the error code in the database handle to the same value.
77576 rc = sqlite3VdbeTransferError(p);
77578 return (rc&db->errMask);
77582 ** This is the top-level implementation of sqlite3_step(). Call
77583 ** sqlite3Step() to do most of the work. If a schema error occurs,
77584 ** call sqlite3Reprepare() and try again.
77586 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
77587 int rc = SQLITE_OK; /* Result from sqlite3Step() */
77588 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
77589 int cnt = 0; /* Counter to prevent infinite loop of reprepares */
77590 sqlite3 *db; /* The database connection */
77592 if( vdbeSafetyNotNull(v) ){
77593 return SQLITE_MISUSE_BKPT;
77595 db = v->db;
77596 sqlite3_mutex_enter(db->mutex);
77597 v->doingRerun = 0;
77598 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
77599 && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
77600 int savedPc = v->pc;
77601 rc = sqlite3Reprepare(v);
77602 if( rc!=SQLITE_OK ){
77603 /* This case occurs after failing to recompile an sql statement.
77604 ** The error message from the SQL compiler has already been loaded
77605 ** into the database handle. This block copies the error message
77606 ** from the database handle into the statement and sets the statement
77607 ** program counter to 0 to ensure that when the statement is
77608 ** finalized or reset the parser error message is available via
77609 ** sqlite3_errmsg() and sqlite3_errcode().
77611 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
77612 sqlite3DbFree(db, v->zErrMsg);
77613 if( !db->mallocFailed ){
77614 v->zErrMsg = sqlite3DbStrDup(db, zErr);
77615 v->rc = rc = sqlite3ApiExit(db, rc);
77616 } else {
77617 v->zErrMsg = 0;
77618 v->rc = rc = SQLITE_NOMEM_BKPT;
77620 break;
77622 sqlite3_reset(pStmt);
77623 if( savedPc>=0 ) v->doingRerun = 1;
77624 assert( v->expired==0 );
77626 sqlite3_mutex_leave(db->mutex);
77627 return rc;
77632 ** Extract the user data from a sqlite3_context structure and return a
77633 ** pointer to it.
77635 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
77636 assert( p && p->pFunc );
77637 return p->pFunc->pUserData;
77641 ** Extract the user data from a sqlite3_context structure and return a
77642 ** pointer to it.
77644 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
77645 ** returns a copy of the pointer to the database connection (the 1st
77646 ** parameter) of the sqlite3_create_function() and
77647 ** sqlite3_create_function16() routines that originally registered the
77648 ** application defined function.
77650 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
77651 assert( p && p->pOut );
77652 return p->pOut->db;
77656 ** Return the current time for a statement. If the current time
77657 ** is requested more than once within the same run of a single prepared
77658 ** statement, the exact same time is returned for each invocation regardless
77659 ** of the amount of time that elapses between invocations. In other words,
77660 ** the time returned is always the time of the first call.
77662 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
77663 int rc;
77664 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
77665 sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
77666 assert( p->pVdbe!=0 );
77667 #else
77668 sqlite3_int64 iTime = 0;
77669 sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
77670 #endif
77671 if( *piTime==0 ){
77672 rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
77673 if( rc ) *piTime = 0;
77675 return *piTime;
77679 ** The following is the implementation of an SQL function that always
77680 ** fails with an error message stating that the function is used in the
77681 ** wrong context. The sqlite3_overload_function() API might construct
77682 ** SQL function that use this routine so that the functions will exist
77683 ** for name resolution but are actually overloaded by the xFindFunction
77684 ** method of virtual tables.
77686 SQLITE_PRIVATE void sqlite3InvalidFunction(
77687 sqlite3_context *context, /* The function calling context */
77688 int NotUsed, /* Number of arguments to the function */
77689 sqlite3_value **NotUsed2 /* Value of each argument */
77691 const char *zName = context->pFunc->zName;
77692 char *zErr;
77693 UNUSED_PARAMETER2(NotUsed, NotUsed2);
77694 zErr = sqlite3_mprintf(
77695 "unable to use function %s in the requested context", zName);
77696 sqlite3_result_error(context, zErr, -1);
77697 sqlite3_free(zErr);
77701 ** Create a new aggregate context for p and return a pointer to
77702 ** its pMem->z element.
77704 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
77705 Mem *pMem = p->pMem;
77706 assert( (pMem->flags & MEM_Agg)==0 );
77707 if( nByte<=0 ){
77708 sqlite3VdbeMemSetNull(pMem);
77709 pMem->z = 0;
77710 }else{
77711 sqlite3VdbeMemClearAndResize(pMem, nByte);
77712 pMem->flags = MEM_Agg;
77713 pMem->u.pDef = p->pFunc;
77714 if( pMem->z ){
77715 memset(pMem->z, 0, nByte);
77718 return (void*)pMem->z;
77722 ** Allocate or return the aggregate context for a user function. A new
77723 ** context is allocated on the first call. Subsequent calls return the
77724 ** same context that was returned on prior calls.
77726 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
77727 assert( p && p->pFunc && p->pFunc->xFinalize );
77728 assert( sqlite3_mutex_held(p->pOut->db->mutex) );
77729 testcase( nByte<0 );
77730 if( (p->pMem->flags & MEM_Agg)==0 ){
77731 return createAggContext(p, nByte);
77732 }else{
77733 return (void*)p->pMem->z;
77738 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
77739 ** the user-function defined by pCtx.
77741 ** The left-most argument is 0.
77743 ** Undocumented behavior: If iArg is negative then access a cache of
77744 ** auxiliary data pointers that is available to all functions within a
77745 ** single prepared statement. The iArg values must match.
77747 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
77748 AuxData *pAuxData;
77750 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77751 #if SQLITE_ENABLE_STAT3_OR_STAT4
77752 if( pCtx->pVdbe==0 ) return 0;
77753 #else
77754 assert( pCtx->pVdbe!=0 );
77755 #endif
77756 for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
77757 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
77758 return pAuxData->pAux;
77761 return 0;
77765 ** Set the auxiliary data pointer and delete function, for the iArg'th
77766 ** argument to the user-function defined by pCtx. Any previous value is
77767 ** deleted by calling the delete function specified when it was set.
77769 ** The left-most argument is 0.
77771 ** Undocumented behavior: If iArg is negative then make the data available
77772 ** to all functions within the current prepared statement using iArg as an
77773 ** access code.
77775 SQLITE_API void sqlite3_set_auxdata(
77776 sqlite3_context *pCtx,
77777 int iArg,
77778 void *pAux,
77779 void (*xDelete)(void*)
77781 AuxData *pAuxData;
77782 Vdbe *pVdbe = pCtx->pVdbe;
77784 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77785 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
77786 if( pVdbe==0 ) goto failed;
77787 #else
77788 assert( pVdbe!=0 );
77789 #endif
77791 for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
77792 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
77793 break;
77796 if( pAuxData==0 ){
77797 pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
77798 if( !pAuxData ) goto failed;
77799 pAuxData->iAuxOp = pCtx->iOp;
77800 pAuxData->iAuxArg = iArg;
77801 pAuxData->pNextAux = pVdbe->pAuxData;
77802 pVdbe->pAuxData = pAuxData;
77803 if( pCtx->fErrorOrAux==0 ){
77804 pCtx->isError = 0;
77805 pCtx->fErrorOrAux = 1;
77807 }else if( pAuxData->xDeleteAux ){
77808 pAuxData->xDeleteAux(pAuxData->pAux);
77811 pAuxData->pAux = pAux;
77812 pAuxData->xDeleteAux = xDelete;
77813 return;
77815 failed:
77816 if( xDelete ){
77817 xDelete(pAux);
77821 #ifndef SQLITE_OMIT_DEPRECATED
77823 ** Return the number of times the Step function of an aggregate has been
77824 ** called.
77826 ** This function is deprecated. Do not use it for new code. It is
77827 ** provide only to avoid breaking legacy code. New aggregate function
77828 ** implementations should keep their own counts within their aggregate
77829 ** context.
77831 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
77832 assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
77833 return p->pMem->n;
77835 #endif
77838 ** Return the number of columns in the result set for the statement pStmt.
77840 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
77841 Vdbe *pVm = (Vdbe *)pStmt;
77842 return pVm ? pVm->nResColumn : 0;
77846 ** Return the number of values available from the current row of the
77847 ** currently executing statement pStmt.
77849 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
77850 Vdbe *pVm = (Vdbe *)pStmt;
77851 if( pVm==0 || pVm->pResultSet==0 ) return 0;
77852 return pVm->nResColumn;
77856 ** Return a pointer to static memory containing an SQL NULL value.
77858 static const Mem *columnNullValue(void){
77859 /* Even though the Mem structure contains an element
77860 ** of type i64, on certain architectures (x86) with certain compiler
77861 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
77862 ** instead of an 8-byte one. This all works fine, except that when
77863 ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
77864 ** that a Mem structure is located on an 8-byte boundary. To prevent
77865 ** these assert()s from failing, when building with SQLITE_DEBUG defined
77866 ** using gcc, we force nullMem to be 8-byte aligned using the magical
77867 ** __attribute__((aligned(8))) macro. */
77868 static const Mem nullMem
77869 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
77870 __attribute__((aligned(8)))
77871 #endif
77873 /* .u = */ {0},
77874 /* .flags = */ (u16)MEM_Null,
77875 /* .enc = */ (u8)0,
77876 /* .eSubtype = */ (u8)0,
77877 /* .n = */ (int)0,
77878 /* .z = */ (char*)0,
77879 /* .zMalloc = */ (char*)0,
77880 /* .szMalloc = */ (int)0,
77881 /* .uTemp = */ (u32)0,
77882 /* .db = */ (sqlite3*)0,
77883 /* .xDel = */ (void(*)(void*))0,
77884 #ifdef SQLITE_DEBUG
77885 /* .pScopyFrom = */ (Mem*)0,
77886 /* .pFiller = */ (void*)0,
77887 #endif
77889 return &nullMem;
77893 ** Check to see if column iCol of the given statement is valid. If
77894 ** it is, return a pointer to the Mem for the value of that column.
77895 ** If iCol is not valid, return a pointer to a Mem which has a value
77896 ** of NULL.
77898 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
77899 Vdbe *pVm;
77900 Mem *pOut;
77902 pVm = (Vdbe *)pStmt;
77903 if( pVm==0 ) return (Mem*)columnNullValue();
77904 assert( pVm->db );
77905 sqlite3_mutex_enter(pVm->db->mutex);
77906 if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
77907 pOut = &pVm->pResultSet[i];
77908 }else{
77909 sqlite3Error(pVm->db, SQLITE_RANGE);
77910 pOut = (Mem*)columnNullValue();
77912 return pOut;
77916 ** This function is called after invoking an sqlite3_value_XXX function on a
77917 ** column value (i.e. a value returned by evaluating an SQL expression in the
77918 ** select list of a SELECT statement) that may cause a malloc() failure. If
77919 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
77920 ** code of statement pStmt set to SQLITE_NOMEM.
77922 ** Specifically, this is called from within:
77924 ** sqlite3_column_int()
77925 ** sqlite3_column_int64()
77926 ** sqlite3_column_text()
77927 ** sqlite3_column_text16()
77928 ** sqlite3_column_real()
77929 ** sqlite3_column_bytes()
77930 ** sqlite3_column_bytes16()
77931 ** sqiite3_column_blob()
77933 static void columnMallocFailure(sqlite3_stmt *pStmt)
77935 /* If malloc() failed during an encoding conversion within an
77936 ** sqlite3_column_XXX API, then set the return code of the statement to
77937 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
77938 ** and _finalize() will return NOMEM.
77940 Vdbe *p = (Vdbe *)pStmt;
77941 if( p ){
77942 assert( p->db!=0 );
77943 assert( sqlite3_mutex_held(p->db->mutex) );
77944 p->rc = sqlite3ApiExit(p->db, p->rc);
77945 sqlite3_mutex_leave(p->db->mutex);
77949 /**************************** sqlite3_column_ *******************************
77950 ** The following routines are used to access elements of the current row
77951 ** in the result set.
77953 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
77954 const void *val;
77955 val = sqlite3_value_blob( columnMem(pStmt,i) );
77956 /* Even though there is no encoding conversion, value_blob() might
77957 ** need to call malloc() to expand the result of a zeroblob()
77958 ** expression.
77960 columnMallocFailure(pStmt);
77961 return val;
77963 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
77964 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
77965 columnMallocFailure(pStmt);
77966 return val;
77968 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
77969 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
77970 columnMallocFailure(pStmt);
77971 return val;
77973 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
77974 double val = sqlite3_value_double( columnMem(pStmt,i) );
77975 columnMallocFailure(pStmt);
77976 return val;
77978 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
77979 int val = sqlite3_value_int( columnMem(pStmt,i) );
77980 columnMallocFailure(pStmt);
77981 return val;
77983 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
77984 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
77985 columnMallocFailure(pStmt);
77986 return val;
77988 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
77989 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
77990 columnMallocFailure(pStmt);
77991 return val;
77993 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
77994 Mem *pOut = columnMem(pStmt, i);
77995 if( pOut->flags&MEM_Static ){
77996 pOut->flags &= ~MEM_Static;
77997 pOut->flags |= MEM_Ephem;
77999 columnMallocFailure(pStmt);
78000 return (sqlite3_value *)pOut;
78002 #ifndef SQLITE_OMIT_UTF16
78003 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
78004 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
78005 columnMallocFailure(pStmt);
78006 return val;
78008 #endif /* SQLITE_OMIT_UTF16 */
78009 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
78010 int iType = sqlite3_value_type( columnMem(pStmt,i) );
78011 columnMallocFailure(pStmt);
78012 return iType;
78016 ** Convert the N-th element of pStmt->pColName[] into a string using
78017 ** xFunc() then return that string. If N is out of range, return 0.
78019 ** There are up to 5 names for each column. useType determines which
78020 ** name is returned. Here are the names:
78022 ** 0 The column name as it should be displayed for output
78023 ** 1 The datatype name for the column
78024 ** 2 The name of the database that the column derives from
78025 ** 3 The name of the table that the column derives from
78026 ** 4 The name of the table column that the result column derives from
78028 ** If the result is not a simple column reference (if it is an expression
78029 ** or a constant) then useTypes 2, 3, and 4 return NULL.
78031 static const void *columnName(
78032 sqlite3_stmt *pStmt,
78033 int N,
78034 const void *(*xFunc)(Mem*),
78035 int useType
78037 const void *ret;
78038 Vdbe *p;
78039 int n;
78040 sqlite3 *db;
78041 #ifdef SQLITE_ENABLE_API_ARMOR
78042 if( pStmt==0 ){
78043 (void)SQLITE_MISUSE_BKPT;
78044 return 0;
78046 #endif
78047 ret = 0;
78048 p = (Vdbe *)pStmt;
78049 db = p->db;
78050 assert( db!=0 );
78051 n = sqlite3_column_count(pStmt);
78052 if( N<n && N>=0 ){
78053 N += useType*n;
78054 sqlite3_mutex_enter(db->mutex);
78055 assert( db->mallocFailed==0 );
78056 ret = xFunc(&p->aColName[N]);
78057 /* A malloc may have failed inside of the xFunc() call. If this
78058 ** is the case, clear the mallocFailed flag and return NULL.
78060 if( db->mallocFailed ){
78061 sqlite3OomClear(db);
78062 ret = 0;
78064 sqlite3_mutex_leave(db->mutex);
78066 return ret;
78070 ** Return the name of the Nth column of the result set returned by SQL
78071 ** statement pStmt.
78073 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
78074 return columnName(
78075 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
78077 #ifndef SQLITE_OMIT_UTF16
78078 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
78079 return columnName(
78080 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
78082 #endif
78085 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
78086 ** not define OMIT_DECLTYPE.
78088 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
78089 # error "Must not define both SQLITE_OMIT_DECLTYPE \
78090 and SQLITE_ENABLE_COLUMN_METADATA"
78091 #endif
78093 #ifndef SQLITE_OMIT_DECLTYPE
78095 ** Return the column declaration type (if applicable) of the 'i'th column
78096 ** of the result set of SQL statement pStmt.
78098 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
78099 return columnName(
78100 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
78102 #ifndef SQLITE_OMIT_UTF16
78103 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
78104 return columnName(
78105 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
78107 #endif /* SQLITE_OMIT_UTF16 */
78108 #endif /* SQLITE_OMIT_DECLTYPE */
78110 #ifdef SQLITE_ENABLE_COLUMN_METADATA
78112 ** Return the name of the database from which a result column derives.
78113 ** NULL is returned if the result column is an expression or constant or
78114 ** anything else which is not an unambiguous reference to a database column.
78116 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
78117 return columnName(
78118 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
78120 #ifndef SQLITE_OMIT_UTF16
78121 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
78122 return columnName(
78123 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
78125 #endif /* SQLITE_OMIT_UTF16 */
78128 ** Return the name of the table from which a result column derives.
78129 ** NULL is returned if the result column is an expression or constant or
78130 ** anything else which is not an unambiguous reference to a database column.
78132 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
78133 return columnName(
78134 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
78136 #ifndef SQLITE_OMIT_UTF16
78137 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
78138 return columnName(
78139 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
78141 #endif /* SQLITE_OMIT_UTF16 */
78144 ** Return the name of the table column from which a result column derives.
78145 ** NULL is returned if the result column is an expression or constant or
78146 ** anything else which is not an unambiguous reference to a database column.
78148 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
78149 return columnName(
78150 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
78152 #ifndef SQLITE_OMIT_UTF16
78153 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
78154 return columnName(
78155 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
78157 #endif /* SQLITE_OMIT_UTF16 */
78158 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
78161 /******************************* sqlite3_bind_ ***************************
78163 ** Routines used to attach values to wildcards in a compiled SQL statement.
78166 ** Unbind the value bound to variable i in virtual machine p. This is the
78167 ** the same as binding a NULL value to the column. If the "i" parameter is
78168 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
78170 ** A successful evaluation of this routine acquires the mutex on p.
78171 ** the mutex is released if any kind of error occurs.
78173 ** The error code stored in database p->db is overwritten with the return
78174 ** value in any case.
78176 static int vdbeUnbind(Vdbe *p, int i){
78177 Mem *pVar;
78178 if( vdbeSafetyNotNull(p) ){
78179 return SQLITE_MISUSE_BKPT;
78181 sqlite3_mutex_enter(p->db->mutex);
78182 if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
78183 sqlite3Error(p->db, SQLITE_MISUSE);
78184 sqlite3_mutex_leave(p->db->mutex);
78185 sqlite3_log(SQLITE_MISUSE,
78186 "bind on a busy prepared statement: [%s]", p->zSql);
78187 return SQLITE_MISUSE_BKPT;
78189 if( i<1 || i>p->nVar ){
78190 sqlite3Error(p->db, SQLITE_RANGE);
78191 sqlite3_mutex_leave(p->db->mutex);
78192 return SQLITE_RANGE;
78194 i--;
78195 pVar = &p->aVar[i];
78196 sqlite3VdbeMemRelease(pVar);
78197 pVar->flags = MEM_Null;
78198 sqlite3Error(p->db, SQLITE_OK);
78200 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
78201 ** binding a new value to this variable invalidates the current query plan.
78203 ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
78204 ** parameter in the WHERE clause might influence the choice of query plan
78205 ** for a statement, then the statement will be automatically recompiled,
78206 ** as if there had been a schema change, on the first sqlite3_step() call
78207 ** following any change to the bindings of that parameter.
78209 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
78210 if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
78211 p->expired = 1;
78213 return SQLITE_OK;
78217 ** Bind a text or BLOB value.
78219 static int bindText(
78220 sqlite3_stmt *pStmt, /* The statement to bind against */
78221 int i, /* Index of the parameter to bind */
78222 const void *zData, /* Pointer to the data to be bound */
78223 int nData, /* Number of bytes of data to be bound */
78224 void (*xDel)(void*), /* Destructor for the data */
78225 u8 encoding /* Encoding for the data */
78227 Vdbe *p = (Vdbe *)pStmt;
78228 Mem *pVar;
78229 int rc;
78231 rc = vdbeUnbind(p, i);
78232 if( rc==SQLITE_OK ){
78233 if( zData!=0 ){
78234 pVar = &p->aVar[i-1];
78235 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
78236 if( rc==SQLITE_OK && encoding!=0 ){
78237 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
78239 if( rc ){
78240 sqlite3Error(p->db, rc);
78241 rc = sqlite3ApiExit(p->db, rc);
78244 sqlite3_mutex_leave(p->db->mutex);
78245 }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
78246 xDel((void*)zData);
78248 return rc;
78253 ** Bind a blob value to an SQL statement variable.
78255 SQLITE_API int sqlite3_bind_blob(
78256 sqlite3_stmt *pStmt,
78257 int i,
78258 const void *zData,
78259 int nData,
78260 void (*xDel)(void*)
78262 #ifdef SQLITE_ENABLE_API_ARMOR
78263 if( nData<0 ) return SQLITE_MISUSE_BKPT;
78264 #endif
78265 return bindText(pStmt, i, zData, nData, xDel, 0);
78267 SQLITE_API int sqlite3_bind_blob64(
78268 sqlite3_stmt *pStmt,
78269 int i,
78270 const void *zData,
78271 sqlite3_uint64 nData,
78272 void (*xDel)(void*)
78274 assert( xDel!=SQLITE_DYNAMIC );
78275 if( nData>0x7fffffff ){
78276 return invokeValueDestructor(zData, xDel, 0);
78277 }else{
78278 return bindText(pStmt, i, zData, (int)nData, xDel, 0);
78281 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
78282 int rc;
78283 Vdbe *p = (Vdbe *)pStmt;
78284 rc = vdbeUnbind(p, i);
78285 if( rc==SQLITE_OK ){
78286 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
78287 sqlite3_mutex_leave(p->db->mutex);
78289 return rc;
78291 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
78292 return sqlite3_bind_int64(p, i, (i64)iValue);
78294 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
78295 int rc;
78296 Vdbe *p = (Vdbe *)pStmt;
78297 rc = vdbeUnbind(p, i);
78298 if( rc==SQLITE_OK ){
78299 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
78300 sqlite3_mutex_leave(p->db->mutex);
78302 return rc;
78304 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
78305 int rc;
78306 Vdbe *p = (Vdbe*)pStmt;
78307 rc = vdbeUnbind(p, i);
78308 if( rc==SQLITE_OK ){
78309 sqlite3_mutex_leave(p->db->mutex);
78311 return rc;
78313 SQLITE_API int sqlite3_bind_pointer(
78314 sqlite3_stmt *pStmt,
78315 int i,
78316 void *pPtr,
78317 const char *zPTtype,
78318 void (*xDestructor)(void*)
78320 int rc;
78321 Vdbe *p = (Vdbe*)pStmt;
78322 rc = vdbeUnbind(p, i);
78323 if( rc==SQLITE_OK ){
78324 sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
78325 sqlite3_mutex_leave(p->db->mutex);
78326 }else if( xDestructor ){
78327 xDestructor(pPtr);
78329 return rc;
78331 SQLITE_API int sqlite3_bind_text(
78332 sqlite3_stmt *pStmt,
78333 int i,
78334 const char *zData,
78335 int nData,
78336 void (*xDel)(void*)
78338 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
78340 SQLITE_API int sqlite3_bind_text64(
78341 sqlite3_stmt *pStmt,
78342 int i,
78343 const char *zData,
78344 sqlite3_uint64 nData,
78345 void (*xDel)(void*),
78346 unsigned char enc
78348 assert( xDel!=SQLITE_DYNAMIC );
78349 if( nData>0x7fffffff ){
78350 return invokeValueDestructor(zData, xDel, 0);
78351 }else{
78352 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
78353 return bindText(pStmt, i, zData, (int)nData, xDel, enc);
78356 #ifndef SQLITE_OMIT_UTF16
78357 SQLITE_API int sqlite3_bind_text16(
78358 sqlite3_stmt *pStmt,
78359 int i,
78360 const void *zData,
78361 int nData,
78362 void (*xDel)(void*)
78364 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
78366 #endif /* SQLITE_OMIT_UTF16 */
78367 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
78368 int rc;
78369 switch( sqlite3_value_type((sqlite3_value*)pValue) ){
78370 case SQLITE_INTEGER: {
78371 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
78372 break;
78374 case SQLITE_FLOAT: {
78375 rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
78376 break;
78378 case SQLITE_BLOB: {
78379 if( pValue->flags & MEM_Zero ){
78380 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
78381 }else{
78382 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
78384 break;
78386 case SQLITE_TEXT: {
78387 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
78388 pValue->enc);
78389 break;
78391 default: {
78392 rc = sqlite3_bind_null(pStmt, i);
78393 break;
78396 return rc;
78398 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
78399 int rc;
78400 Vdbe *p = (Vdbe *)pStmt;
78401 rc = vdbeUnbind(p, i);
78402 if( rc==SQLITE_OK ){
78403 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
78404 sqlite3_mutex_leave(p->db->mutex);
78406 return rc;
78408 SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
78409 int rc;
78410 Vdbe *p = (Vdbe *)pStmt;
78411 sqlite3_mutex_enter(p->db->mutex);
78412 if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
78413 rc = SQLITE_TOOBIG;
78414 }else{
78415 assert( (n & 0x7FFFFFFF)==n );
78416 rc = sqlite3_bind_zeroblob(pStmt, i, n);
78418 rc = sqlite3ApiExit(p->db, rc);
78419 sqlite3_mutex_leave(p->db->mutex);
78420 return rc;
78424 ** Return the number of wildcards that can be potentially bound to.
78425 ** This routine is added to support DBD::SQLite.
78427 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
78428 Vdbe *p = (Vdbe*)pStmt;
78429 return p ? p->nVar : 0;
78433 ** Return the name of a wildcard parameter. Return NULL if the index
78434 ** is out of range or if the wildcard is unnamed.
78436 ** The result is always UTF-8.
78438 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
78439 Vdbe *p = (Vdbe*)pStmt;
78440 if( p==0 ) return 0;
78441 return sqlite3VListNumToName(p->pVList, i);
78445 ** Given a wildcard parameter name, return the index of the variable
78446 ** with that name. If there is no variable with the given name,
78447 ** return 0.
78449 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
78450 if( p==0 || zName==0 ) return 0;
78451 return sqlite3VListNameToNum(p->pVList, zName, nName);
78453 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
78454 return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
78458 ** Transfer all bindings from the first statement over to the second.
78460 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
78461 Vdbe *pFrom = (Vdbe*)pFromStmt;
78462 Vdbe *pTo = (Vdbe*)pToStmt;
78463 int i;
78464 assert( pTo->db==pFrom->db );
78465 assert( pTo->nVar==pFrom->nVar );
78466 sqlite3_mutex_enter(pTo->db->mutex);
78467 for(i=0; i<pFrom->nVar; i++){
78468 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
78470 sqlite3_mutex_leave(pTo->db->mutex);
78471 return SQLITE_OK;
78474 #ifndef SQLITE_OMIT_DEPRECATED
78476 ** Deprecated external interface. Internal/core SQLite code
78477 ** should call sqlite3TransferBindings.
78479 ** It is misuse to call this routine with statements from different
78480 ** database connections. But as this is a deprecated interface, we
78481 ** will not bother to check for that condition.
78483 ** If the two statements contain a different number of bindings, then
78484 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
78485 ** SQLITE_OK is returned.
78487 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
78488 Vdbe *pFrom = (Vdbe*)pFromStmt;
78489 Vdbe *pTo = (Vdbe*)pToStmt;
78490 if( pFrom->nVar!=pTo->nVar ){
78491 return SQLITE_ERROR;
78493 assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
78494 if( pTo->expmask ){
78495 pTo->expired = 1;
78497 assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
78498 if( pFrom->expmask ){
78499 pFrom->expired = 1;
78501 return sqlite3TransferBindings(pFromStmt, pToStmt);
78503 #endif
78506 ** Return the sqlite3* database handle to which the prepared statement given
78507 ** in the argument belongs. This is the same database handle that was
78508 ** the first argument to the sqlite3_prepare() that was used to create
78509 ** the statement in the first place.
78511 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
78512 return pStmt ? ((Vdbe*)pStmt)->db : 0;
78516 ** Return true if the prepared statement is guaranteed to not modify the
78517 ** database.
78519 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
78520 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
78524 ** Return true if the prepared statement is in need of being reset.
78526 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
78527 Vdbe *v = (Vdbe*)pStmt;
78528 return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
78532 ** Return a pointer to the next prepared statement after pStmt associated
78533 ** with database connection pDb. If pStmt is NULL, return the first
78534 ** prepared statement for the database connection. Return NULL if there
78535 ** are no more.
78537 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
78538 sqlite3_stmt *pNext;
78539 #ifdef SQLITE_ENABLE_API_ARMOR
78540 if( !sqlite3SafetyCheckOk(pDb) ){
78541 (void)SQLITE_MISUSE_BKPT;
78542 return 0;
78544 #endif
78545 sqlite3_mutex_enter(pDb->mutex);
78546 if( pStmt==0 ){
78547 pNext = (sqlite3_stmt*)pDb->pVdbe;
78548 }else{
78549 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
78551 sqlite3_mutex_leave(pDb->mutex);
78552 return pNext;
78556 ** Return the value of a status counter for a prepared statement
78558 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
78559 Vdbe *pVdbe = (Vdbe*)pStmt;
78560 u32 v;
78561 #ifdef SQLITE_ENABLE_API_ARMOR
78562 if( !pStmt ){
78563 (void)SQLITE_MISUSE_BKPT;
78564 return 0;
78566 #endif
78567 if( op==SQLITE_STMTSTATUS_MEMUSED ){
78568 sqlite3 *db = pVdbe->db;
78569 sqlite3_mutex_enter(db->mutex);
78570 v = 0;
78571 db->pnBytesFreed = (int*)&v;
78572 sqlite3VdbeClearObject(db, pVdbe);
78573 sqlite3DbFree(db, pVdbe);
78574 db->pnBytesFreed = 0;
78575 sqlite3_mutex_leave(db->mutex);
78576 }else{
78577 v = pVdbe->aCounter[op];
78578 if( resetFlag ) pVdbe->aCounter[op] = 0;
78580 return (int)v;
78584 ** Return the SQL associated with a prepared statement
78586 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
78587 Vdbe *p = (Vdbe *)pStmt;
78588 return p ? p->zSql : 0;
78592 ** Return the SQL associated with a prepared statement with
78593 ** bound parameters expanded. Space to hold the returned string is
78594 ** obtained from sqlite3_malloc(). The caller is responsible for
78595 ** freeing the returned string by passing it to sqlite3_free().
78597 ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
78598 ** expanded bound parameters.
78600 SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
78601 #ifdef SQLITE_OMIT_TRACE
78602 return 0;
78603 #else
78604 char *z = 0;
78605 const char *zSql = sqlite3_sql(pStmt);
78606 if( zSql ){
78607 Vdbe *p = (Vdbe *)pStmt;
78608 sqlite3_mutex_enter(p->db->mutex);
78609 z = sqlite3VdbeExpandSql(p, zSql);
78610 sqlite3_mutex_leave(p->db->mutex);
78612 return z;
78613 #endif
78616 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
78618 ** Allocate and populate an UnpackedRecord structure based on the serialized
78619 ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
78620 ** if successful, or a NULL pointer if an OOM error is encountered.
78622 static UnpackedRecord *vdbeUnpackRecord(
78623 KeyInfo *pKeyInfo,
78624 int nKey,
78625 const void *pKey
78627 UnpackedRecord *pRet; /* Return value */
78629 pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
78630 if( pRet ){
78631 memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
78632 sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
78634 return pRet;
78638 ** This function is called from within a pre-update callback to retrieve
78639 ** a field of the row currently being updated or deleted.
78641 SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
78642 PreUpdate *p = db->pPreUpdate;
78643 Mem *pMem;
78644 int rc = SQLITE_OK;
78646 /* Test that this call is being made from within an SQLITE_DELETE or
78647 ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
78648 if( !p || p->op==SQLITE_INSERT ){
78649 rc = SQLITE_MISUSE_BKPT;
78650 goto preupdate_old_out;
78652 if( p->pPk ){
78653 iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
78655 if( iIdx>=p->pCsr->nField || iIdx<0 ){
78656 rc = SQLITE_RANGE;
78657 goto preupdate_old_out;
78660 /* If the old.* record has not yet been loaded into memory, do so now. */
78661 if( p->pUnpacked==0 ){
78662 u32 nRec;
78663 u8 *aRec;
78665 nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
78666 aRec = sqlite3DbMallocRaw(db, nRec);
78667 if( !aRec ) goto preupdate_old_out;
78668 rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
78669 if( rc==SQLITE_OK ){
78670 p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
78671 if( !p->pUnpacked ) rc = SQLITE_NOMEM;
78673 if( rc!=SQLITE_OK ){
78674 sqlite3DbFree(db, aRec);
78675 goto preupdate_old_out;
78677 p->aRecord = aRec;
78680 pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
78681 if( iIdx==p->pTab->iPKey ){
78682 sqlite3VdbeMemSetInt64(pMem, p->iKey1);
78683 }else if( iIdx>=p->pUnpacked->nField ){
78684 *ppValue = (sqlite3_value *)columnNullValue();
78685 }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
78686 if( pMem->flags & MEM_Int ){
78687 sqlite3VdbeMemRealify(pMem);
78691 preupdate_old_out:
78692 sqlite3Error(db, rc);
78693 return sqlite3ApiExit(db, rc);
78695 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
78697 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
78699 ** This function is called from within a pre-update callback to retrieve
78700 ** the number of columns in the row being updated, deleted or inserted.
78702 SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
78703 PreUpdate *p = db->pPreUpdate;
78704 return (p ? p->keyinfo.nKeyField : 0);
78706 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
78708 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
78710 ** This function is designed to be called from within a pre-update callback
78711 ** only. It returns zero if the change that caused the callback was made
78712 ** immediately by a user SQL statement. Or, if the change was made by a
78713 ** trigger program, it returns the number of trigger programs currently
78714 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
78715 ** top-level trigger etc.).
78717 ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
78718 ** or SET DEFAULT action is considered a trigger.
78720 SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
78721 PreUpdate *p = db->pPreUpdate;
78722 return (p ? p->v->nFrame : 0);
78724 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
78726 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
78728 ** This function is called from within a pre-update callback to retrieve
78729 ** a field of the row currently being updated or inserted.
78731 SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
78732 PreUpdate *p = db->pPreUpdate;
78733 int rc = SQLITE_OK;
78734 Mem *pMem;
78736 if( !p || p->op==SQLITE_DELETE ){
78737 rc = SQLITE_MISUSE_BKPT;
78738 goto preupdate_new_out;
78740 if( p->pPk && p->op!=SQLITE_UPDATE ){
78741 iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
78743 if( iIdx>=p->pCsr->nField || iIdx<0 ){
78744 rc = SQLITE_RANGE;
78745 goto preupdate_new_out;
78748 if( p->op==SQLITE_INSERT ){
78749 /* For an INSERT, memory cell p->iNewReg contains the serialized record
78750 ** that is being inserted. Deserialize it. */
78751 UnpackedRecord *pUnpack = p->pNewUnpacked;
78752 if( !pUnpack ){
78753 Mem *pData = &p->v->aMem[p->iNewReg];
78754 rc = ExpandBlob(pData);
78755 if( rc!=SQLITE_OK ) goto preupdate_new_out;
78756 pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
78757 if( !pUnpack ){
78758 rc = SQLITE_NOMEM;
78759 goto preupdate_new_out;
78761 p->pNewUnpacked = pUnpack;
78763 pMem = &pUnpack->aMem[iIdx];
78764 if( iIdx==p->pTab->iPKey ){
78765 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
78766 }else if( iIdx>=pUnpack->nField ){
78767 pMem = (sqlite3_value *)columnNullValue();
78769 }else{
78770 /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
78771 ** value. Make a copy of the cell contents and return a pointer to it.
78772 ** It is not safe to return a pointer to the memory cell itself as the
78773 ** caller may modify the value text encoding.
78775 assert( p->op==SQLITE_UPDATE );
78776 if( !p->aNew ){
78777 p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
78778 if( !p->aNew ){
78779 rc = SQLITE_NOMEM;
78780 goto preupdate_new_out;
78783 assert( iIdx>=0 && iIdx<p->pCsr->nField );
78784 pMem = &p->aNew[iIdx];
78785 if( pMem->flags==0 ){
78786 if( iIdx==p->pTab->iPKey ){
78787 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
78788 }else{
78789 rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
78790 if( rc!=SQLITE_OK ) goto preupdate_new_out;
78794 *ppValue = pMem;
78796 preupdate_new_out:
78797 sqlite3Error(db, rc);
78798 return sqlite3ApiExit(db, rc);
78800 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
78802 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
78804 ** Return status data for a single loop within query pStmt.
78806 SQLITE_API int sqlite3_stmt_scanstatus(
78807 sqlite3_stmt *pStmt, /* Prepared statement being queried */
78808 int idx, /* Index of loop to report on */
78809 int iScanStatusOp, /* Which metric to return */
78810 void *pOut /* OUT: Write the answer here */
78812 Vdbe *p = (Vdbe*)pStmt;
78813 ScanStatus *pScan;
78814 if( idx<0 || idx>=p->nScan ) return 1;
78815 pScan = &p->aScan[idx];
78816 switch( iScanStatusOp ){
78817 case SQLITE_SCANSTAT_NLOOP: {
78818 *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
78819 break;
78821 case SQLITE_SCANSTAT_NVISIT: {
78822 *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
78823 break;
78825 case SQLITE_SCANSTAT_EST: {
78826 double r = 1.0;
78827 LogEst x = pScan->nEst;
78828 while( x<100 ){
78829 x += 10;
78830 r *= 0.5;
78832 *(double*)pOut = r*sqlite3LogEstToInt(x);
78833 break;
78835 case SQLITE_SCANSTAT_NAME: {
78836 *(const char**)pOut = pScan->zName;
78837 break;
78839 case SQLITE_SCANSTAT_EXPLAIN: {
78840 if( pScan->addrExplain ){
78841 *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
78842 }else{
78843 *(const char**)pOut = 0;
78845 break;
78847 case SQLITE_SCANSTAT_SELECTID: {
78848 if( pScan->addrExplain ){
78849 *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
78850 }else{
78851 *(int*)pOut = -1;
78853 break;
78855 default: {
78856 return 1;
78859 return 0;
78863 ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
78865 SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
78866 Vdbe *p = (Vdbe*)pStmt;
78867 memset(p->anExec, 0, p->nOp * sizeof(i64));
78869 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
78871 /************** End of vdbeapi.c *********************************************/
78872 /************** Begin file vdbetrace.c ***************************************/
78874 ** 2009 November 25
78876 ** The author disclaims copyright to this source code. In place of
78877 ** a legal notice, here is a blessing:
78879 ** May you do good and not evil.
78880 ** May you find forgiveness for yourself and forgive others.
78881 ** May you share freely, never taking more than you give.
78883 *************************************************************************
78885 ** This file contains code used to insert the values of host parameters
78886 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
78888 ** The Vdbe parse-tree explainer is also found here.
78890 /* #include "sqliteInt.h" */
78891 /* #include "vdbeInt.h" */
78893 #ifndef SQLITE_OMIT_TRACE
78896 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
78897 ** bytes in this text up to but excluding the first character in
78898 ** a host parameter. If the text contains no host parameters, return
78899 ** the total number of bytes in the text.
78901 static int findNextHostParameter(const char *zSql, int *pnToken){
78902 int tokenType;
78903 int nTotal = 0;
78904 int n;
78906 *pnToken = 0;
78907 while( zSql[0] ){
78908 n = sqlite3GetToken((u8*)zSql, &tokenType);
78909 assert( n>0 && tokenType!=TK_ILLEGAL );
78910 if( tokenType==TK_VARIABLE ){
78911 *pnToken = n;
78912 break;
78914 nTotal += n;
78915 zSql += n;
78917 return nTotal;
78921 ** This function returns a pointer to a nul-terminated string in memory
78922 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
78923 ** string contains a copy of zRawSql but with host parameters expanded to
78924 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
78925 ** then the returned string holds a copy of zRawSql with "-- " prepended
78926 ** to each line of text.
78928 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
78929 ** then long strings and blobs are truncated to that many bytes. This
78930 ** can be used to prevent unreasonably large trace strings when dealing
78931 ** with large (multi-megabyte) strings and blobs.
78933 ** The calling function is responsible for making sure the memory returned
78934 ** is eventually freed.
78936 ** ALGORITHM: Scan the input string looking for host parameters in any of
78937 ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
78938 ** string literals, quoted identifier names, and comments. For text forms,
78939 ** the host parameter index is found by scanning the prepared
78940 ** statement for the corresponding OP_Variable opcode. Once the host
78941 ** parameter index is known, locate the value in p->aVar[]. Then render
78942 ** the value as a literal in place of the host parameter name.
78944 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
78945 Vdbe *p, /* The prepared statement being evaluated */
78946 const char *zRawSql /* Raw text of the SQL statement */
78948 sqlite3 *db; /* The database connection */
78949 int idx = 0; /* Index of a host parameter */
78950 int nextIndex = 1; /* Index of next ? host parameter */
78951 int n; /* Length of a token prefix */
78952 int nToken; /* Length of the parameter token */
78953 int i; /* Loop counter */
78954 Mem *pVar; /* Value of a host parameter */
78955 StrAccum out; /* Accumulate the output here */
78956 #ifndef SQLITE_OMIT_UTF16
78957 Mem utf8; /* Used to convert UTF16 into UTF8 for display */
78958 #endif
78959 char zBase[100]; /* Initial working space */
78961 db = p->db;
78962 sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
78963 db->aLimit[SQLITE_LIMIT_LENGTH]);
78964 if( db->nVdbeExec>1 ){
78965 while( *zRawSql ){
78966 const char *zStart = zRawSql;
78967 while( *(zRawSql++)!='\n' && *zRawSql );
78968 sqlite3StrAccumAppend(&out, "-- ", 3);
78969 assert( (zRawSql - zStart) > 0 );
78970 sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
78972 }else if( p->nVar==0 ){
78973 sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
78974 }else{
78975 while( zRawSql[0] ){
78976 n = findNextHostParameter(zRawSql, &nToken);
78977 assert( n>0 );
78978 sqlite3StrAccumAppend(&out, zRawSql, n);
78979 zRawSql += n;
78980 assert( zRawSql[0] || nToken==0 );
78981 if( nToken==0 ) break;
78982 if( zRawSql[0]=='?' ){
78983 if( nToken>1 ){
78984 assert( sqlite3Isdigit(zRawSql[1]) );
78985 sqlite3GetInt32(&zRawSql[1], &idx);
78986 }else{
78987 idx = nextIndex;
78989 }else{
78990 assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
78991 zRawSql[0]=='@' || zRawSql[0]=='#' );
78992 testcase( zRawSql[0]==':' );
78993 testcase( zRawSql[0]=='$' );
78994 testcase( zRawSql[0]=='@' );
78995 testcase( zRawSql[0]=='#' );
78996 idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
78997 assert( idx>0 );
78999 zRawSql += nToken;
79000 nextIndex = idx + 1;
79001 assert( idx>0 && idx<=p->nVar );
79002 pVar = &p->aVar[idx-1];
79003 if( pVar->flags & MEM_Null ){
79004 sqlite3StrAccumAppend(&out, "NULL", 4);
79005 }else if( pVar->flags & MEM_Int ){
79006 sqlite3XPrintf(&out, "%lld", pVar->u.i);
79007 }else if( pVar->flags & MEM_Real ){
79008 sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
79009 }else if( pVar->flags & MEM_Str ){
79010 int nOut; /* Number of bytes of the string text to include in output */
79011 #ifndef SQLITE_OMIT_UTF16
79012 u8 enc = ENC(db);
79013 if( enc!=SQLITE_UTF8 ){
79014 memset(&utf8, 0, sizeof(utf8));
79015 utf8.db = db;
79016 sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
79017 if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
79018 out.accError = STRACCUM_NOMEM;
79019 out.nAlloc = 0;
79021 pVar = &utf8;
79023 #endif
79024 nOut = pVar->n;
79025 #ifdef SQLITE_TRACE_SIZE_LIMIT
79026 if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
79027 nOut = SQLITE_TRACE_SIZE_LIMIT;
79028 while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
79030 #endif
79031 sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
79032 #ifdef SQLITE_TRACE_SIZE_LIMIT
79033 if( nOut<pVar->n ){
79034 sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
79036 #endif
79037 #ifndef SQLITE_OMIT_UTF16
79038 if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
79039 #endif
79040 }else if( pVar->flags & MEM_Zero ){
79041 sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
79042 }else{
79043 int nOut; /* Number of bytes of the blob to include in output */
79044 assert( pVar->flags & MEM_Blob );
79045 sqlite3StrAccumAppend(&out, "x'", 2);
79046 nOut = pVar->n;
79047 #ifdef SQLITE_TRACE_SIZE_LIMIT
79048 if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
79049 #endif
79050 for(i=0; i<nOut; i++){
79051 sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
79053 sqlite3StrAccumAppend(&out, "'", 1);
79054 #ifdef SQLITE_TRACE_SIZE_LIMIT
79055 if( nOut<pVar->n ){
79056 sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
79058 #endif
79062 if( out.accError ) sqlite3StrAccumReset(&out);
79063 return sqlite3StrAccumFinish(&out);
79066 #endif /* #ifndef SQLITE_OMIT_TRACE */
79068 /************** End of vdbetrace.c *******************************************/
79069 /************** Begin file vdbe.c ********************************************/
79071 ** 2001 September 15
79073 ** The author disclaims copyright to this source code. In place of
79074 ** a legal notice, here is a blessing:
79076 ** May you do good and not evil.
79077 ** May you find forgiveness for yourself and forgive others.
79078 ** May you share freely, never taking more than you give.
79080 *************************************************************************
79081 ** The code in this file implements the function that runs the
79082 ** bytecode of a prepared statement.
79084 ** Various scripts scan this source file in order to generate HTML
79085 ** documentation, headers files, or other derived files. The formatting
79086 ** of the code in this file is, therefore, important. See other comments
79087 ** in this file for details. If in doubt, do not deviate from existing
79088 ** commenting and indentation practices when changing or adding code.
79090 /* #include "sqliteInt.h" */
79091 /* #include "vdbeInt.h" */
79094 ** Invoke this macro on memory cells just prior to changing the
79095 ** value of the cell. This macro verifies that shallow copies are
79096 ** not misused. A shallow copy of a string or blob just copies a
79097 ** pointer to the string or blob, not the content. If the original
79098 ** is changed while the copy is still in use, the string or blob might
79099 ** be changed out from under the copy. This macro verifies that nothing
79100 ** like that ever happens.
79102 #ifdef SQLITE_DEBUG
79103 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
79104 #else
79105 # define memAboutToChange(P,M)
79106 #endif
79109 ** The following global variable is incremented every time a cursor
79110 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
79111 ** procedures use this information to make sure that indices are
79112 ** working correctly. This variable has no function other than to
79113 ** help verify the correct operation of the library.
79115 #ifdef SQLITE_TEST
79116 SQLITE_API int sqlite3_search_count = 0;
79117 #endif
79120 ** When this global variable is positive, it gets decremented once before
79121 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
79122 ** field of the sqlite3 structure is set in order to simulate an interrupt.
79124 ** This facility is used for testing purposes only. It does not function
79125 ** in an ordinary build.
79127 #ifdef SQLITE_TEST
79128 SQLITE_API int sqlite3_interrupt_count = 0;
79129 #endif
79132 ** The next global variable is incremented each type the OP_Sort opcode
79133 ** is executed. The test procedures use this information to make sure that
79134 ** sorting is occurring or not occurring at appropriate times. This variable
79135 ** has no function other than to help verify the correct operation of the
79136 ** library.
79138 #ifdef SQLITE_TEST
79139 SQLITE_API int sqlite3_sort_count = 0;
79140 #endif
79143 ** The next global variable records the size of the largest MEM_Blob
79144 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
79145 ** use this information to make sure that the zero-blob functionality
79146 ** is working correctly. This variable has no function other than to
79147 ** help verify the correct operation of the library.
79149 #ifdef SQLITE_TEST
79150 SQLITE_API int sqlite3_max_blobsize = 0;
79151 static void updateMaxBlobsize(Mem *p){
79152 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
79153 sqlite3_max_blobsize = p->n;
79156 #endif
79159 ** This macro evaluates to true if either the update hook or the preupdate
79160 ** hook are enabled for database connect DB.
79162 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
79163 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
79164 #else
79165 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
79166 #endif
79169 ** The next global variable is incremented each time the OP_Found opcode
79170 ** is executed. This is used to test whether or not the foreign key
79171 ** operation implemented using OP_FkIsZero is working. This variable
79172 ** has no function other than to help verify the correct operation of the
79173 ** library.
79175 #ifdef SQLITE_TEST
79176 SQLITE_API int sqlite3_found_count = 0;
79177 #endif
79180 ** Test a register to see if it exceeds the current maximum blob size.
79181 ** If it does, record the new maximum blob size.
79183 #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
79184 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
79185 #else
79186 # define UPDATE_MAX_BLOBSIZE(P)
79187 #endif
79190 ** Invoke the VDBE coverage callback, if that callback is defined. This
79191 ** feature is used for test suite validation only and does not appear an
79192 ** production builds.
79194 ** M is an integer, 2 or 3, that indices how many different ways the
79195 ** branch can go. It is usually 2. "I" is the direction the branch
79196 ** goes. 0 means falls through. 1 means branch is taken. 2 means the
79197 ** second alternative branch is taken.
79199 ** iSrcLine is the source code line (from the __LINE__ macro) that
79200 ** generated the VDBE instruction. This instrumentation assumes that all
79201 ** source code is in a single file (the amalgamation). Special values 1
79202 ** and 2 for the iSrcLine parameter mean that this particular branch is
79203 ** always taken or never taken, respectively.
79205 #if !defined(SQLITE_VDBE_COVERAGE)
79206 # define VdbeBranchTaken(I,M)
79207 #else
79208 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
79209 static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
79210 if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
79211 M = iSrcLine;
79212 /* Assert the truth of VdbeCoverageAlwaysTaken() and
79213 ** VdbeCoverageNeverTaken() */
79214 assert( (M & I)==I );
79215 }else{
79216 if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
79217 sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
79218 iSrcLine,I,M);
79221 #endif
79224 ** Convert the given register into a string if it isn't one
79225 ** already. Return non-zero if a malloc() fails.
79227 #define Stringify(P, enc) \
79228 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
79229 { goto no_mem; }
79232 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
79233 ** a pointer to a dynamically allocated string where some other entity
79234 ** is responsible for deallocating that string. Because the register
79235 ** does not control the string, it might be deleted without the register
79236 ** knowing it.
79238 ** This routine converts an ephemeral string into a dynamically allocated
79239 ** string that the register itself controls. In other words, it
79240 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
79242 #define Deephemeralize(P) \
79243 if( ((P)->flags&MEM_Ephem)!=0 \
79244 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
79246 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
79247 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
79250 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
79251 ** if we run out of memory.
79253 static VdbeCursor *allocateCursor(
79254 Vdbe *p, /* The virtual machine */
79255 int iCur, /* Index of the new VdbeCursor */
79256 int nField, /* Number of fields in the table or index */
79257 int iDb, /* Database the cursor belongs to, or -1 */
79258 u8 eCurType /* Type of the new cursor */
79260 /* Find the memory cell that will be used to store the blob of memory
79261 ** required for this VdbeCursor structure. It is convenient to use a
79262 ** vdbe memory cell to manage the memory allocation required for a
79263 ** VdbeCursor structure for the following reasons:
79265 ** * Sometimes cursor numbers are used for a couple of different
79266 ** purposes in a vdbe program. The different uses might require
79267 ** different sized allocations. Memory cells provide growable
79268 ** allocations.
79270 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
79271 ** be freed lazily via the sqlite3_release_memory() API. This
79272 ** minimizes the number of malloc calls made by the system.
79274 ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
79275 ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
79276 ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
79278 Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
79280 int nByte;
79281 VdbeCursor *pCx = 0;
79282 nByte =
79283 ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
79284 (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
79286 assert( iCur>=0 && iCur<p->nCursor );
79287 if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
79288 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
79289 p->apCsr[iCur] = 0;
79291 if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
79292 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
79293 memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
79294 pCx->eCurType = eCurType;
79295 pCx->iDb = iDb;
79296 pCx->nField = nField;
79297 pCx->aOffset = &pCx->aType[nField];
79298 if( eCurType==CURTYPE_BTREE ){
79299 pCx->uc.pCursor = (BtCursor*)
79300 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
79301 sqlite3BtreeCursorZero(pCx->uc.pCursor);
79304 return pCx;
79308 ** Try to convert a value into a numeric representation if we can
79309 ** do so without loss of information. In other words, if the string
79310 ** looks like a number, convert it into a number. If it does not
79311 ** look like a number, leave it alone.
79313 ** If the bTryForInt flag is true, then extra effort is made to give
79314 ** an integer representation. Strings that look like floating point
79315 ** values but which have no fractional component (example: '48.00')
79316 ** will have a MEM_Int representation when bTryForInt is true.
79318 ** If bTryForInt is false, then if the input string contains a decimal
79319 ** point or exponential notation, the result is only MEM_Real, even
79320 ** if there is an exact integer representation of the quantity.
79322 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
79323 double rValue;
79324 i64 iValue;
79325 u8 enc = pRec->enc;
79326 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
79327 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
79328 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
79329 pRec->u.i = iValue;
79330 pRec->flags |= MEM_Int;
79331 }else{
79332 pRec->u.r = rValue;
79333 pRec->flags |= MEM_Real;
79334 if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
79339 ** Processing is determine by the affinity parameter:
79341 ** SQLITE_AFF_INTEGER:
79342 ** SQLITE_AFF_REAL:
79343 ** SQLITE_AFF_NUMERIC:
79344 ** Try to convert pRec to an integer representation or a
79345 ** floating-point representation if an integer representation
79346 ** is not possible. Note that the integer representation is
79347 ** always preferred, even if the affinity is REAL, because
79348 ** an integer representation is more space efficient on disk.
79350 ** SQLITE_AFF_TEXT:
79351 ** Convert pRec to a text representation.
79353 ** SQLITE_AFF_BLOB:
79354 ** No-op. pRec is unchanged.
79356 static void applyAffinity(
79357 Mem *pRec, /* The value to apply affinity to */
79358 char affinity, /* The affinity to be applied */
79359 u8 enc /* Use this text encoding */
79361 if( affinity>=SQLITE_AFF_NUMERIC ){
79362 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
79363 || affinity==SQLITE_AFF_NUMERIC );
79364 if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
79365 if( (pRec->flags & MEM_Real)==0 ){
79366 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
79367 }else{
79368 sqlite3VdbeIntegerAffinity(pRec);
79371 }else if( affinity==SQLITE_AFF_TEXT ){
79372 /* Only attempt the conversion to TEXT if there is an integer or real
79373 ** representation (blob and NULL do not get converted) but no string
79374 ** representation. It would be harmless to repeat the conversion if
79375 ** there is already a string rep, but it is pointless to waste those
79376 ** CPU cycles. */
79377 if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
79378 if( (pRec->flags&(MEM_Real|MEM_Int)) ){
79379 sqlite3VdbeMemStringify(pRec, enc, 1);
79382 pRec->flags &= ~(MEM_Real|MEM_Int);
79387 ** Try to convert the type of a function argument or a result column
79388 ** into a numeric representation. Use either INTEGER or REAL whichever
79389 ** is appropriate. But only do the conversion if it is possible without
79390 ** loss of information and return the revised type of the argument.
79392 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
79393 int eType = sqlite3_value_type(pVal);
79394 if( eType==SQLITE_TEXT ){
79395 Mem *pMem = (Mem*)pVal;
79396 applyNumericAffinity(pMem, 0);
79397 eType = sqlite3_value_type(pVal);
79399 return eType;
79403 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
79404 ** not the internal Mem* type.
79406 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
79407 sqlite3_value *pVal,
79408 u8 affinity,
79409 u8 enc
79411 applyAffinity((Mem *)pVal, affinity, enc);
79415 ** pMem currently only holds a string type (or maybe a BLOB that we can
79416 ** interpret as a string if we want to). Compute its corresponding
79417 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
79418 ** accordingly.
79420 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
79421 assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
79422 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
79423 if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
79424 return 0;
79426 if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
79427 return MEM_Int;
79429 return MEM_Real;
79433 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
79434 ** none.
79436 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
79437 ** But it does set pMem->u.r and pMem->u.i appropriately.
79439 static u16 numericType(Mem *pMem){
79440 if( pMem->flags & (MEM_Int|MEM_Real) ){
79441 return pMem->flags & (MEM_Int|MEM_Real);
79443 if( pMem->flags & (MEM_Str|MEM_Blob) ){
79444 return computeNumericType(pMem);
79446 return 0;
79449 #ifdef SQLITE_DEBUG
79451 ** Write a nice string representation of the contents of cell pMem
79452 ** into buffer zBuf, length nBuf.
79454 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
79455 char *zCsr = zBuf;
79456 int f = pMem->flags;
79458 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
79460 if( f&MEM_Blob ){
79461 int i;
79462 char c;
79463 if( f & MEM_Dyn ){
79464 c = 'z';
79465 assert( (f & (MEM_Static|MEM_Ephem))==0 );
79466 }else if( f & MEM_Static ){
79467 c = 't';
79468 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
79469 }else if( f & MEM_Ephem ){
79470 c = 'e';
79471 assert( (f & (MEM_Static|MEM_Dyn))==0 );
79472 }else{
79473 c = 's';
79475 *(zCsr++) = c;
79476 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
79477 zCsr += sqlite3Strlen30(zCsr);
79478 for(i=0; i<16 && i<pMem->n; i++){
79479 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
79480 zCsr += sqlite3Strlen30(zCsr);
79482 for(i=0; i<16 && i<pMem->n; i++){
79483 char z = pMem->z[i];
79484 if( z<32 || z>126 ) *zCsr++ = '.';
79485 else *zCsr++ = z;
79487 *(zCsr++) = ']';
79488 if( f & MEM_Zero ){
79489 sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
79490 zCsr += sqlite3Strlen30(zCsr);
79492 *zCsr = '\0';
79493 }else if( f & MEM_Str ){
79494 int j, k;
79495 zBuf[0] = ' ';
79496 if( f & MEM_Dyn ){
79497 zBuf[1] = 'z';
79498 assert( (f & (MEM_Static|MEM_Ephem))==0 );
79499 }else if( f & MEM_Static ){
79500 zBuf[1] = 't';
79501 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
79502 }else if( f & MEM_Ephem ){
79503 zBuf[1] = 'e';
79504 assert( (f & (MEM_Static|MEM_Dyn))==0 );
79505 }else{
79506 zBuf[1] = 's';
79508 k = 2;
79509 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
79510 k += sqlite3Strlen30(&zBuf[k]);
79511 zBuf[k++] = '[';
79512 for(j=0; j<15 && j<pMem->n; j++){
79513 u8 c = pMem->z[j];
79514 if( c>=0x20 && c<0x7f ){
79515 zBuf[k++] = c;
79516 }else{
79517 zBuf[k++] = '.';
79520 zBuf[k++] = ']';
79521 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
79522 k += sqlite3Strlen30(&zBuf[k]);
79523 zBuf[k++] = 0;
79526 #endif
79528 #ifdef SQLITE_DEBUG
79530 ** Print the value of a register for tracing purposes:
79532 static void memTracePrint(Mem *p){
79533 if( p->flags & MEM_Undefined ){
79534 printf(" undefined");
79535 }else if( p->flags & MEM_Null ){
79536 printf(" NULL");
79537 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
79538 printf(" si:%lld", p->u.i);
79539 }else if( p->flags & MEM_Int ){
79540 printf(" i:%lld", p->u.i);
79541 #ifndef SQLITE_OMIT_FLOATING_POINT
79542 }else if( p->flags & MEM_Real ){
79543 printf(" r:%g", p->u.r);
79544 #endif
79545 }else if( p->flags & MEM_RowSet ){
79546 printf(" (rowset)");
79547 }else{
79548 char zBuf[200];
79549 sqlite3VdbeMemPrettyPrint(p, zBuf);
79550 printf(" %s", zBuf);
79552 if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
79554 static void registerTrace(int iReg, Mem *p){
79555 printf("REG[%d] = ", iReg);
79556 memTracePrint(p);
79557 printf("\n");
79558 sqlite3VdbeCheckMemInvariants(p);
79560 #endif
79562 #ifdef SQLITE_DEBUG
79563 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
79564 #else
79565 # define REGISTER_TRACE(R,M)
79566 #endif
79569 #ifdef VDBE_PROFILE
79572 ** hwtime.h contains inline assembler code for implementing
79573 ** high-performance timing routines.
79575 /************** Include hwtime.h in the middle of vdbe.c *********************/
79576 /************** Begin file hwtime.h ******************************************/
79578 ** 2008 May 27
79580 ** The author disclaims copyright to this source code. In place of
79581 ** a legal notice, here is a blessing:
79583 ** May you do good and not evil.
79584 ** May you find forgiveness for yourself and forgive others.
79585 ** May you share freely, never taking more than you give.
79587 ******************************************************************************
79589 ** This file contains inline asm code for retrieving "high-performance"
79590 ** counters for x86 class CPUs.
79592 #ifndef SQLITE_HWTIME_H
79593 #define SQLITE_HWTIME_H
79596 ** The following routine only works on pentium-class (or newer) processors.
79597 ** It uses the RDTSC opcode to read the cycle count value out of the
79598 ** processor and returns that value. This can be used for high-res
79599 ** profiling.
79601 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
79602 (defined(i386) || defined(__i386__) || defined(_M_IX86))
79604 #if defined(__GNUC__)
79606 __inline__ sqlite_uint64 sqlite3Hwtime(void){
79607 unsigned int lo, hi;
79608 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
79609 return (sqlite_uint64)hi << 32 | lo;
79612 #elif defined(_MSC_VER)
79614 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
79615 __asm {
79616 rdtsc
79617 ret ; return value at EDX:EAX
79621 #endif
79623 #elif (defined(__GNUC__) && defined(__x86_64__))
79625 __inline__ sqlite_uint64 sqlite3Hwtime(void){
79626 unsigned long val;
79627 __asm__ __volatile__ ("rdtsc" : "=A" (val));
79628 return val;
79631 #elif (defined(__GNUC__) && defined(__ppc__))
79633 __inline__ sqlite_uint64 sqlite3Hwtime(void){
79634 unsigned long long retval;
79635 unsigned long junk;
79636 __asm__ __volatile__ ("\n\
79637 1: mftbu %1\n\
79638 mftb %L0\n\
79639 mftbu %0\n\
79640 cmpw %0,%1\n\
79641 bne 1b"
79642 : "=r" (retval), "=r" (junk));
79643 return retval;
79646 #else
79648 #error Need implementation of sqlite3Hwtime() for your platform.
79651 ** To compile without implementing sqlite3Hwtime() for your platform,
79652 ** you can remove the above #error and use the following
79653 ** stub function. You will lose timing support for many
79654 ** of the debugging and testing utilities, but it should at
79655 ** least compile and run.
79657 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
79659 #endif
79661 #endif /* !defined(SQLITE_HWTIME_H) */
79663 /************** End of hwtime.h **********************************************/
79664 /************** Continuing where we left off in vdbe.c ***********************/
79666 #endif
79668 #ifndef NDEBUG
79670 ** This function is only called from within an assert() expression. It
79671 ** checks that the sqlite3.nTransaction variable is correctly set to
79672 ** the number of non-transaction savepoints currently in the
79673 ** linked list starting at sqlite3.pSavepoint.
79675 ** Usage:
79677 ** assert( checkSavepointCount(db) );
79679 static int checkSavepointCount(sqlite3 *db){
79680 int n = 0;
79681 Savepoint *p;
79682 for(p=db->pSavepoint; p; p=p->pNext) n++;
79683 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
79684 return 1;
79686 #endif
79689 ** Return the register of pOp->p2 after first preparing it to be
79690 ** overwritten with an integer value.
79692 static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
79693 sqlite3VdbeMemSetNull(pOut);
79694 pOut->flags = MEM_Int;
79695 return pOut;
79697 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
79698 Mem *pOut;
79699 assert( pOp->p2>0 );
79700 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
79701 pOut = &p->aMem[pOp->p2];
79702 memAboutToChange(p, pOut);
79703 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
79704 return out2PrereleaseWithClear(pOut);
79705 }else{
79706 pOut->flags = MEM_Int;
79707 return pOut;
79713 ** Execute as much of a VDBE program as we can.
79714 ** This is the core of sqlite3_step().
79716 SQLITE_PRIVATE int sqlite3VdbeExec(
79717 Vdbe *p /* The VDBE */
79719 Op *aOp = p->aOp; /* Copy of p->aOp */
79720 Op *pOp = aOp; /* Current operation */
79721 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
79722 Op *pOrigOp; /* Value of pOp at the top of the loop */
79723 #endif
79724 #ifdef SQLITE_DEBUG
79725 int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
79726 #endif
79727 int rc = SQLITE_OK; /* Value to return */
79728 sqlite3 *db = p->db; /* The database */
79729 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
79730 u8 encoding = ENC(db); /* The database encoding */
79731 int iCompare = 0; /* Result of last comparison */
79732 unsigned nVmStep = 0; /* Number of virtual machine steps */
79733 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
79734 unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
79735 #endif
79736 Mem *aMem = p->aMem; /* Copy of p->aMem */
79737 Mem *pIn1 = 0; /* 1st input operand */
79738 Mem *pIn2 = 0; /* 2nd input operand */
79739 Mem *pIn3 = 0; /* 3rd input operand */
79740 Mem *pOut = 0; /* Output operand */
79741 #ifdef VDBE_PROFILE
79742 u64 start; /* CPU clock count at start of opcode */
79743 #endif
79744 /*** INSERT STACK UNION HERE ***/
79746 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
79747 sqlite3VdbeEnter(p);
79748 if( p->rc==SQLITE_NOMEM ){
79749 /* This happens if a malloc() inside a call to sqlite3_column_text() or
79750 ** sqlite3_column_text16() failed. */
79751 goto no_mem;
79753 assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
79754 assert( p->bIsReader || p->readOnly!=0 );
79755 p->iCurrentTime = 0;
79756 assert( p->explain==0 );
79757 p->pResultSet = 0;
79758 db->busyHandler.nBusy = 0;
79759 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
79760 sqlite3VdbeIOTraceSql(p);
79761 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
79762 if( db->xProgress ){
79763 u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
79764 assert( 0 < db->nProgressOps );
79765 nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
79766 }else{
79767 nProgressLimit = 0xffffffff;
79769 #endif
79770 #ifdef SQLITE_DEBUG
79771 sqlite3BeginBenignMalloc();
79772 if( p->pc==0
79773 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
79775 int i;
79776 int once = 1;
79777 sqlite3VdbePrintSql(p);
79778 if( p->db->flags & SQLITE_VdbeListing ){
79779 printf("VDBE Program Listing:\n");
79780 for(i=0; i<p->nOp; i++){
79781 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
79784 if( p->db->flags & SQLITE_VdbeEQP ){
79785 for(i=0; i<p->nOp; i++){
79786 if( aOp[i].opcode==OP_Explain ){
79787 if( once ) printf("VDBE Query Plan:\n");
79788 printf("%s\n", aOp[i].p4.z);
79789 once = 0;
79793 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
79795 sqlite3EndBenignMalloc();
79796 #endif
79797 for(pOp=&aOp[p->pc]; 1; pOp++){
79798 /* Errors are detected by individual opcodes, with an immediate
79799 ** jumps to abort_due_to_error. */
79800 assert( rc==SQLITE_OK );
79802 assert( pOp>=aOp && pOp<&aOp[p->nOp]);
79803 #ifdef VDBE_PROFILE
79804 start = sqlite3Hwtime();
79805 #endif
79806 nVmStep++;
79807 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
79808 if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
79809 #endif
79811 /* Only allow tracing if SQLITE_DEBUG is defined.
79813 #ifdef SQLITE_DEBUG
79814 if( db->flags & SQLITE_VdbeTrace ){
79815 sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
79817 #endif
79820 /* Check to see if we need to simulate an interrupt. This only happens
79821 ** if we have a special test build.
79823 #ifdef SQLITE_TEST
79824 if( sqlite3_interrupt_count>0 ){
79825 sqlite3_interrupt_count--;
79826 if( sqlite3_interrupt_count==0 ){
79827 sqlite3_interrupt(db);
79830 #endif
79832 /* Sanity checking on other operands */
79833 #ifdef SQLITE_DEBUG
79835 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
79836 if( (opProperty & OPFLG_IN1)!=0 ){
79837 assert( pOp->p1>0 );
79838 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
79839 assert( memIsValid(&aMem[pOp->p1]) );
79840 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
79841 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
79843 if( (opProperty & OPFLG_IN2)!=0 ){
79844 assert( pOp->p2>0 );
79845 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
79846 assert( memIsValid(&aMem[pOp->p2]) );
79847 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
79848 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
79850 if( (opProperty & OPFLG_IN3)!=0 ){
79851 assert( pOp->p3>0 );
79852 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
79853 assert( memIsValid(&aMem[pOp->p3]) );
79854 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
79855 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
79857 if( (opProperty & OPFLG_OUT2)!=0 ){
79858 assert( pOp->p2>0 );
79859 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
79860 memAboutToChange(p, &aMem[pOp->p2]);
79862 if( (opProperty & OPFLG_OUT3)!=0 ){
79863 assert( pOp->p3>0 );
79864 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
79865 memAboutToChange(p, &aMem[pOp->p3]);
79868 #endif
79869 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
79870 pOrigOp = pOp;
79871 #endif
79873 switch( pOp->opcode ){
79875 /*****************************************************************************
79876 ** What follows is a massive switch statement where each case implements a
79877 ** separate instruction in the virtual machine. If we follow the usual
79878 ** indentation conventions, each case should be indented by 6 spaces. But
79879 ** that is a lot of wasted space on the left margin. So the code within
79880 ** the switch statement will break with convention and be flush-left. Another
79881 ** big comment (similar to this one) will mark the point in the code where
79882 ** we transition back to normal indentation.
79884 ** The formatting of each case is important. The makefile for SQLite
79885 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
79886 ** file looking for lines that begin with "case OP_". The opcodes.h files
79887 ** will be filled with #defines that give unique integer values to each
79888 ** opcode and the opcodes.c file is filled with an array of strings where
79889 ** each string is the symbolic name for the corresponding opcode. If the
79890 ** case statement is followed by a comment of the form "/# same as ... #/"
79891 ** that comment is used to determine the particular value of the opcode.
79893 ** Other keywords in the comment that follows each case are used to
79894 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
79895 ** Keywords include: in1, in2, in3, out2, out3. See
79896 ** the mkopcodeh.awk script for additional information.
79898 ** Documentation about VDBE opcodes is generated by scanning this file
79899 ** for lines of that contain "Opcode:". That line and all subsequent
79900 ** comment lines are used in the generation of the opcode.html documentation
79901 ** file.
79903 ** SUMMARY:
79905 ** Formatting is important to scripts that scan this file.
79906 ** Do not deviate from the formatting style currently in use.
79908 *****************************************************************************/
79910 /* Opcode: Goto * P2 * * *
79912 ** An unconditional jump to address P2.
79913 ** The next instruction executed will be
79914 ** the one at index P2 from the beginning of
79915 ** the program.
79917 ** The P1 parameter is not actually used by this opcode. However, it
79918 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
79919 ** that this Goto is the bottom of a loop and that the lines from P2 down
79920 ** to the current line should be indented for EXPLAIN output.
79922 case OP_Goto: { /* jump */
79923 jump_to_p2_and_check_for_interrupt:
79924 pOp = &aOp[pOp->p2 - 1];
79926 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
79927 ** OP_VNext, or OP_SorterNext) all jump here upon
79928 ** completion. Check to see if sqlite3_interrupt() has been called
79929 ** or if the progress callback needs to be invoked.
79931 ** This code uses unstructured "goto" statements and does not look clean.
79932 ** But that is not due to sloppy coding habits. The code is written this
79933 ** way for performance, to avoid having to run the interrupt and progress
79934 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
79935 ** faster according to "valgrind --tool=cachegrind" */
79936 check_for_interrupt:
79937 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
79938 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
79939 /* Call the progress callback if it is configured and the required number
79940 ** of VDBE ops have been executed (either since this invocation of
79941 ** sqlite3VdbeExec() or since last time the progress callback was called).
79942 ** If the progress callback returns non-zero, exit the virtual machine with
79943 ** a return code SQLITE_ABORT.
79945 if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
79946 assert( db->nProgressOps!=0 );
79947 nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
79948 if( db->xProgress(db->pProgressArg) ){
79949 rc = SQLITE_INTERRUPT;
79950 goto abort_due_to_error;
79953 #endif
79955 break;
79958 /* Opcode: Gosub P1 P2 * * *
79960 ** Write the current address onto register P1
79961 ** and then jump to address P2.
79963 case OP_Gosub: { /* jump */
79964 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
79965 pIn1 = &aMem[pOp->p1];
79966 assert( VdbeMemDynamic(pIn1)==0 );
79967 memAboutToChange(p, pIn1);
79968 pIn1->flags = MEM_Int;
79969 pIn1->u.i = (int)(pOp-aOp);
79970 REGISTER_TRACE(pOp->p1, pIn1);
79972 /* Most jump operations do a goto to this spot in order to update
79973 ** the pOp pointer. */
79974 jump_to_p2:
79975 pOp = &aOp[pOp->p2 - 1];
79976 break;
79979 /* Opcode: Return P1 * * * *
79981 ** Jump to the next instruction after the address in register P1. After
79982 ** the jump, register P1 becomes undefined.
79984 case OP_Return: { /* in1 */
79985 pIn1 = &aMem[pOp->p1];
79986 assert( pIn1->flags==MEM_Int );
79987 pOp = &aOp[pIn1->u.i];
79988 pIn1->flags = MEM_Undefined;
79989 break;
79992 /* Opcode: InitCoroutine P1 P2 P3 * *
79994 ** Set up register P1 so that it will Yield to the coroutine
79995 ** located at address P3.
79997 ** If P2!=0 then the coroutine implementation immediately follows
79998 ** this opcode. So jump over the coroutine implementation to
79999 ** address P2.
80001 ** See also: EndCoroutine
80003 case OP_InitCoroutine: { /* jump */
80004 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
80005 assert( pOp->p2>=0 && pOp->p2<p->nOp );
80006 assert( pOp->p3>=0 && pOp->p3<p->nOp );
80007 pOut = &aMem[pOp->p1];
80008 assert( !VdbeMemDynamic(pOut) );
80009 pOut->u.i = pOp->p3 - 1;
80010 pOut->flags = MEM_Int;
80011 if( pOp->p2 ) goto jump_to_p2;
80012 break;
80015 /* Opcode: EndCoroutine P1 * * * *
80017 ** The instruction at the address in register P1 is a Yield.
80018 ** Jump to the P2 parameter of that Yield.
80019 ** After the jump, register P1 becomes undefined.
80021 ** See also: InitCoroutine
80023 case OP_EndCoroutine: { /* in1 */
80024 VdbeOp *pCaller;
80025 pIn1 = &aMem[pOp->p1];
80026 assert( pIn1->flags==MEM_Int );
80027 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
80028 pCaller = &aOp[pIn1->u.i];
80029 assert( pCaller->opcode==OP_Yield );
80030 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
80031 pOp = &aOp[pCaller->p2 - 1];
80032 pIn1->flags = MEM_Undefined;
80033 break;
80036 /* Opcode: Yield P1 P2 * * *
80038 ** Swap the program counter with the value in register P1. This
80039 ** has the effect of yielding to a coroutine.
80041 ** If the coroutine that is launched by this instruction ends with
80042 ** Yield or Return then continue to the next instruction. But if
80043 ** the coroutine launched by this instruction ends with
80044 ** EndCoroutine, then jump to P2 rather than continuing with the
80045 ** next instruction.
80047 ** See also: InitCoroutine
80049 case OP_Yield: { /* in1, jump */
80050 int pcDest;
80051 pIn1 = &aMem[pOp->p1];
80052 assert( VdbeMemDynamic(pIn1)==0 );
80053 pIn1->flags = MEM_Int;
80054 pcDest = (int)pIn1->u.i;
80055 pIn1->u.i = (int)(pOp - aOp);
80056 REGISTER_TRACE(pOp->p1, pIn1);
80057 pOp = &aOp[pcDest];
80058 break;
80061 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
80062 ** Synopsis: if r[P3]=null halt
80064 ** Check the value in register P3. If it is NULL then Halt using
80065 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
80066 ** value in register P3 is not NULL, then this routine is a no-op.
80067 ** The P5 parameter should be 1.
80069 case OP_HaltIfNull: { /* in3 */
80070 pIn3 = &aMem[pOp->p3];
80071 if( (pIn3->flags & MEM_Null)==0 ) break;
80072 /* Fall through into OP_Halt */
80075 /* Opcode: Halt P1 P2 * P4 P5
80077 ** Exit immediately. All open cursors, etc are closed
80078 ** automatically.
80080 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
80081 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
80082 ** For errors, it can be some other value. If P1!=0 then P2 will determine
80083 ** whether or not to rollback the current transaction. Do not rollback
80084 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
80085 ** then back out all changes that have occurred during this execution of the
80086 ** VDBE, but do not rollback the transaction.
80088 ** If P4 is not null then it is an error message string.
80090 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
80092 ** 0: (no change)
80093 ** 1: NOT NULL contraint failed: P4
80094 ** 2: UNIQUE constraint failed: P4
80095 ** 3: CHECK constraint failed: P4
80096 ** 4: FOREIGN KEY constraint failed: P4
80098 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
80099 ** omitted.
80101 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
80102 ** every program. So a jump past the last instruction of the program
80103 ** is the same as executing Halt.
80105 case OP_Halt: {
80106 VdbeFrame *pFrame;
80107 int pcx;
80109 pcx = (int)(pOp - aOp);
80110 if( pOp->p1==SQLITE_OK && p->pFrame ){
80111 /* Halt the sub-program. Return control to the parent frame. */
80112 pFrame = p->pFrame;
80113 p->pFrame = pFrame->pParent;
80114 p->nFrame--;
80115 sqlite3VdbeSetChanges(db, p->nChange);
80116 pcx = sqlite3VdbeFrameRestore(pFrame);
80117 if( pOp->p2==OE_Ignore ){
80118 /* Instruction pcx is the OP_Program that invoked the sub-program
80119 ** currently being halted. If the p2 instruction of this OP_Halt
80120 ** instruction is set to OE_Ignore, then the sub-program is throwing
80121 ** an IGNORE exception. In this case jump to the address specified
80122 ** as the p2 of the calling OP_Program. */
80123 pcx = p->aOp[pcx].p2-1;
80125 aOp = p->aOp;
80126 aMem = p->aMem;
80127 pOp = &aOp[pcx];
80128 break;
80130 p->rc = pOp->p1;
80131 p->errorAction = (u8)pOp->p2;
80132 p->pc = pcx;
80133 assert( pOp->p5<=4 );
80134 if( p->rc ){
80135 if( pOp->p5 ){
80136 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
80137 "FOREIGN KEY" };
80138 testcase( pOp->p5==1 );
80139 testcase( pOp->p5==2 );
80140 testcase( pOp->p5==3 );
80141 testcase( pOp->p5==4 );
80142 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
80143 if( pOp->p4.z ){
80144 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
80146 }else{
80147 sqlite3VdbeError(p, "%s", pOp->p4.z);
80149 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
80151 rc = sqlite3VdbeHalt(p);
80152 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
80153 if( rc==SQLITE_BUSY ){
80154 p->rc = SQLITE_BUSY;
80155 }else{
80156 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
80157 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
80158 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
80160 goto vdbe_return;
80163 /* Opcode: Integer P1 P2 * * *
80164 ** Synopsis: r[P2]=P1
80166 ** The 32-bit integer value P1 is written into register P2.
80168 case OP_Integer: { /* out2 */
80169 pOut = out2Prerelease(p, pOp);
80170 pOut->u.i = pOp->p1;
80171 break;
80174 /* Opcode: Int64 * P2 * P4 *
80175 ** Synopsis: r[P2]=P4
80177 ** P4 is a pointer to a 64-bit integer value.
80178 ** Write that value into register P2.
80180 case OP_Int64: { /* out2 */
80181 pOut = out2Prerelease(p, pOp);
80182 assert( pOp->p4.pI64!=0 );
80183 pOut->u.i = *pOp->p4.pI64;
80184 break;
80187 #ifndef SQLITE_OMIT_FLOATING_POINT
80188 /* Opcode: Real * P2 * P4 *
80189 ** Synopsis: r[P2]=P4
80191 ** P4 is a pointer to a 64-bit floating point value.
80192 ** Write that value into register P2.
80194 case OP_Real: { /* same as TK_FLOAT, out2 */
80195 pOut = out2Prerelease(p, pOp);
80196 pOut->flags = MEM_Real;
80197 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
80198 pOut->u.r = *pOp->p4.pReal;
80199 break;
80201 #endif
80203 /* Opcode: String8 * P2 * P4 *
80204 ** Synopsis: r[P2]='P4'
80206 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
80207 ** into a String opcode before it is executed for the first time. During
80208 ** this transformation, the length of string P4 is computed and stored
80209 ** as the P1 parameter.
80211 case OP_String8: { /* same as TK_STRING, out2 */
80212 assert( pOp->p4.z!=0 );
80213 pOut = out2Prerelease(p, pOp);
80214 pOp->opcode = OP_String;
80215 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
80217 #ifndef SQLITE_OMIT_UTF16
80218 if( encoding!=SQLITE_UTF8 ){
80219 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
80220 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
80221 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
80222 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
80223 assert( VdbeMemDynamic(pOut)==0 );
80224 pOut->szMalloc = 0;
80225 pOut->flags |= MEM_Static;
80226 if( pOp->p4type==P4_DYNAMIC ){
80227 sqlite3DbFree(db, pOp->p4.z);
80229 pOp->p4type = P4_DYNAMIC;
80230 pOp->p4.z = pOut->z;
80231 pOp->p1 = pOut->n;
80233 testcase( rc==SQLITE_TOOBIG );
80234 #endif
80235 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80236 goto too_big;
80238 assert( rc==SQLITE_OK );
80239 /* Fall through to the next case, OP_String */
80242 /* Opcode: String P1 P2 P3 P4 P5
80243 ** Synopsis: r[P2]='P4' (len=P1)
80245 ** The string value P4 of length P1 (bytes) is stored in register P2.
80247 ** If P3 is not zero and the content of register P3 is equal to P5, then
80248 ** the datatype of the register P2 is converted to BLOB. The content is
80249 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
80250 ** of a string, as if it had been CAST. In other words:
80252 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
80254 case OP_String: { /* out2 */
80255 assert( pOp->p4.z!=0 );
80256 pOut = out2Prerelease(p, pOp);
80257 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
80258 pOut->z = pOp->p4.z;
80259 pOut->n = pOp->p1;
80260 pOut->enc = encoding;
80261 UPDATE_MAX_BLOBSIZE(pOut);
80262 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
80263 if( pOp->p3>0 ){
80264 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
80265 pIn3 = &aMem[pOp->p3];
80266 assert( pIn3->flags & MEM_Int );
80267 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
80269 #endif
80270 break;
80273 /* Opcode: Null P1 P2 P3 * *
80274 ** Synopsis: r[P2..P3]=NULL
80276 ** Write a NULL into registers P2. If P3 greater than P2, then also write
80277 ** NULL into register P3 and every register in between P2 and P3. If P3
80278 ** is less than P2 (typically P3 is zero) then only register P2 is
80279 ** set to NULL.
80281 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
80282 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
80283 ** OP_Ne or OP_Eq.
80285 case OP_Null: { /* out2 */
80286 int cnt;
80287 u16 nullFlag;
80288 pOut = out2Prerelease(p, pOp);
80289 cnt = pOp->p3-pOp->p2;
80290 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
80291 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
80292 pOut->n = 0;
80293 while( cnt>0 ){
80294 pOut++;
80295 memAboutToChange(p, pOut);
80296 sqlite3VdbeMemSetNull(pOut);
80297 pOut->flags = nullFlag;
80298 pOut->n = 0;
80299 cnt--;
80301 break;
80304 /* Opcode: SoftNull P1 * * * *
80305 ** Synopsis: r[P1]=NULL
80307 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
80308 ** instruction, but do not free any string or blob memory associated with
80309 ** the register, so that if the value was a string or blob that was
80310 ** previously copied using OP_SCopy, the copies will continue to be valid.
80312 case OP_SoftNull: {
80313 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
80314 pOut = &aMem[pOp->p1];
80315 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
80316 break;
80319 /* Opcode: Blob P1 P2 * P4 *
80320 ** Synopsis: r[P2]=P4 (len=P1)
80322 ** P4 points to a blob of data P1 bytes long. Store this
80323 ** blob in register P2.
80325 case OP_Blob: { /* out2 */
80326 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
80327 pOut = out2Prerelease(p, pOp);
80328 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
80329 pOut->enc = encoding;
80330 UPDATE_MAX_BLOBSIZE(pOut);
80331 break;
80334 /* Opcode: Variable P1 P2 * P4 *
80335 ** Synopsis: r[P2]=parameter(P1,P4)
80337 ** Transfer the values of bound parameter P1 into register P2
80339 ** If the parameter is named, then its name appears in P4.
80340 ** The P4 value is used by sqlite3_bind_parameter_name().
80342 case OP_Variable: { /* out2 */
80343 Mem *pVar; /* Value being transferred */
80345 assert( pOp->p1>0 && pOp->p1<=p->nVar );
80346 assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
80347 pVar = &p->aVar[pOp->p1 - 1];
80348 if( sqlite3VdbeMemTooBig(pVar) ){
80349 goto too_big;
80351 pOut = &aMem[pOp->p2];
80352 sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
80353 UPDATE_MAX_BLOBSIZE(pOut);
80354 break;
80357 /* Opcode: Move P1 P2 P3 * *
80358 ** Synopsis: r[P2@P3]=r[P1@P3]
80360 ** Move the P3 values in register P1..P1+P3-1 over into
80361 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
80362 ** left holding a NULL. It is an error for register ranges
80363 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
80364 ** for P3 to be less than 1.
80366 case OP_Move: {
80367 int n; /* Number of registers left to copy */
80368 int p1; /* Register to copy from */
80369 int p2; /* Register to copy to */
80371 n = pOp->p3;
80372 p1 = pOp->p1;
80373 p2 = pOp->p2;
80374 assert( n>0 && p1>0 && p2>0 );
80375 assert( p1+n<=p2 || p2+n<=p1 );
80377 pIn1 = &aMem[p1];
80378 pOut = &aMem[p2];
80380 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
80381 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
80382 assert( memIsValid(pIn1) );
80383 memAboutToChange(p, pOut);
80384 sqlite3VdbeMemMove(pOut, pIn1);
80385 #ifdef SQLITE_DEBUG
80386 if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
80387 pOut->pScopyFrom += pOp->p2 - p1;
80389 #endif
80390 Deephemeralize(pOut);
80391 REGISTER_TRACE(p2++, pOut);
80392 pIn1++;
80393 pOut++;
80394 }while( --n );
80395 break;
80398 /* Opcode: Copy P1 P2 P3 * *
80399 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
80401 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
80403 ** This instruction makes a deep copy of the value. A duplicate
80404 ** is made of any string or blob constant. See also OP_SCopy.
80406 case OP_Copy: {
80407 int n;
80409 n = pOp->p3;
80410 pIn1 = &aMem[pOp->p1];
80411 pOut = &aMem[pOp->p2];
80412 assert( pOut!=pIn1 );
80413 while( 1 ){
80414 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
80415 Deephemeralize(pOut);
80416 #ifdef SQLITE_DEBUG
80417 pOut->pScopyFrom = 0;
80418 #endif
80419 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
80420 if( (n--)==0 ) break;
80421 pOut++;
80422 pIn1++;
80424 break;
80427 /* Opcode: SCopy P1 P2 * * *
80428 ** Synopsis: r[P2]=r[P1]
80430 ** Make a shallow copy of register P1 into register P2.
80432 ** This instruction makes a shallow copy of the value. If the value
80433 ** is a string or blob, then the copy is only a pointer to the
80434 ** original and hence if the original changes so will the copy.
80435 ** Worse, if the original is deallocated, the copy becomes invalid.
80436 ** Thus the program must guarantee that the original will not change
80437 ** during the lifetime of the copy. Use OP_Copy to make a complete
80438 ** copy.
80440 case OP_SCopy: { /* out2 */
80441 pIn1 = &aMem[pOp->p1];
80442 pOut = &aMem[pOp->p2];
80443 assert( pOut!=pIn1 );
80444 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
80445 #ifdef SQLITE_DEBUG
80446 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
80447 #endif
80448 break;
80451 /* Opcode: IntCopy P1 P2 * * *
80452 ** Synopsis: r[P2]=r[P1]
80454 ** Transfer the integer value held in register P1 into register P2.
80456 ** This is an optimized version of SCopy that works only for integer
80457 ** values.
80459 case OP_IntCopy: { /* out2 */
80460 pIn1 = &aMem[pOp->p1];
80461 assert( (pIn1->flags & MEM_Int)!=0 );
80462 pOut = &aMem[pOp->p2];
80463 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
80464 break;
80467 /* Opcode: ResultRow P1 P2 * * *
80468 ** Synopsis: output=r[P1@P2]
80470 ** The registers P1 through P1+P2-1 contain a single row of
80471 ** results. This opcode causes the sqlite3_step() call to terminate
80472 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
80473 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
80474 ** the result row.
80476 case OP_ResultRow: {
80477 Mem *pMem;
80478 int i;
80479 assert( p->nResColumn==pOp->p2 );
80480 assert( pOp->p1>0 );
80481 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
80483 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
80484 /* Run the progress counter just before returning.
80486 if( db->xProgress!=0
80487 && nVmStep>=nProgressLimit
80488 && db->xProgress(db->pProgressArg)!=0
80490 rc = SQLITE_INTERRUPT;
80491 goto abort_due_to_error;
80493 #endif
80495 /* If this statement has violated immediate foreign key constraints, do
80496 ** not return the number of rows modified. And do not RELEASE the statement
80497 ** transaction. It needs to be rolled back. */
80498 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
80499 assert( db->flags&SQLITE_CountRows );
80500 assert( p->usesStmtJournal );
80501 goto abort_due_to_error;
80504 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
80505 ** DML statements invoke this opcode to return the number of rows
80506 ** modified to the user. This is the only way that a VM that
80507 ** opens a statement transaction may invoke this opcode.
80509 ** In case this is such a statement, close any statement transaction
80510 ** opened by this VM before returning control to the user. This is to
80511 ** ensure that statement-transactions are always nested, not overlapping.
80512 ** If the open statement-transaction is not closed here, then the user
80513 ** may step another VM that opens its own statement transaction. This
80514 ** may lead to overlapping statement transactions.
80516 ** The statement transaction is never a top-level transaction. Hence
80517 ** the RELEASE call below can never fail.
80519 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
80520 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
80521 assert( rc==SQLITE_OK );
80523 /* Invalidate all ephemeral cursor row caches */
80524 p->cacheCtr = (p->cacheCtr + 2)|1;
80526 /* Make sure the results of the current row are \000 terminated
80527 ** and have an assigned type. The results are de-ephemeralized as
80528 ** a side effect.
80530 pMem = p->pResultSet = &aMem[pOp->p1];
80531 for(i=0; i<pOp->p2; i++){
80532 assert( memIsValid(&pMem[i]) );
80533 Deephemeralize(&pMem[i]);
80534 assert( (pMem[i].flags & MEM_Ephem)==0
80535 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
80536 sqlite3VdbeMemNulTerminate(&pMem[i]);
80537 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
80539 if( db->mallocFailed ) goto no_mem;
80541 if( db->mTrace & SQLITE_TRACE_ROW ){
80542 db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
80545 /* Return SQLITE_ROW
80547 p->pc = (int)(pOp - aOp) + 1;
80548 rc = SQLITE_ROW;
80549 goto vdbe_return;
80552 /* Opcode: Concat P1 P2 P3 * *
80553 ** Synopsis: r[P3]=r[P2]+r[P1]
80555 ** Add the text in register P1 onto the end of the text in
80556 ** register P2 and store the result in register P3.
80557 ** If either the P1 or P2 text are NULL then store NULL in P3.
80559 ** P3 = P2 || P1
80561 ** It is illegal for P1 and P3 to be the same register. Sometimes,
80562 ** if P3 is the same register as P2, the implementation is able
80563 ** to avoid a memcpy().
80565 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
80566 i64 nByte;
80568 pIn1 = &aMem[pOp->p1];
80569 pIn2 = &aMem[pOp->p2];
80570 pOut = &aMem[pOp->p3];
80571 assert( pIn1!=pOut );
80572 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
80573 sqlite3VdbeMemSetNull(pOut);
80574 break;
80576 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
80577 Stringify(pIn1, encoding);
80578 Stringify(pIn2, encoding);
80579 nByte = pIn1->n + pIn2->n;
80580 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80581 goto too_big;
80583 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
80584 goto no_mem;
80586 MemSetTypeFlag(pOut, MEM_Str);
80587 if( pOut!=pIn2 ){
80588 memcpy(pOut->z, pIn2->z, pIn2->n);
80590 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
80591 pOut->z[nByte]=0;
80592 pOut->z[nByte+1] = 0;
80593 pOut->flags |= MEM_Term;
80594 pOut->n = (int)nByte;
80595 pOut->enc = encoding;
80596 UPDATE_MAX_BLOBSIZE(pOut);
80597 break;
80600 /* Opcode: Add P1 P2 P3 * *
80601 ** Synopsis: r[P3]=r[P1]+r[P2]
80603 ** Add the value in register P1 to the value in register P2
80604 ** and store the result in register P3.
80605 ** If either input is NULL, the result is NULL.
80607 /* Opcode: Multiply P1 P2 P3 * *
80608 ** Synopsis: r[P3]=r[P1]*r[P2]
80611 ** Multiply the value in register P1 by the value in register P2
80612 ** and store the result in register P3.
80613 ** If either input is NULL, the result is NULL.
80615 /* Opcode: Subtract P1 P2 P3 * *
80616 ** Synopsis: r[P3]=r[P2]-r[P1]
80618 ** Subtract the value in register P1 from the value in register P2
80619 ** and store the result in register P3.
80620 ** If either input is NULL, the result is NULL.
80622 /* Opcode: Divide P1 P2 P3 * *
80623 ** Synopsis: r[P3]=r[P2]/r[P1]
80625 ** Divide the value in register P1 by the value in register P2
80626 ** and store the result in register P3 (P3=P2/P1). If the value in
80627 ** register P1 is zero, then the result is NULL. If either input is
80628 ** NULL, the result is NULL.
80630 /* Opcode: Remainder P1 P2 P3 * *
80631 ** Synopsis: r[P3]=r[P2]%r[P1]
80633 ** Compute the remainder after integer register P2 is divided by
80634 ** register P1 and store the result in register P3.
80635 ** If the value in register P1 is zero the result is NULL.
80636 ** If either operand is NULL, the result is NULL.
80638 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
80639 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
80640 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
80641 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
80642 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
80643 char bIntint; /* Started out as two integer operands */
80644 u16 flags; /* Combined MEM_* flags from both inputs */
80645 u16 type1; /* Numeric type of left operand */
80646 u16 type2; /* Numeric type of right operand */
80647 i64 iA; /* Integer value of left operand */
80648 i64 iB; /* Integer value of right operand */
80649 double rA; /* Real value of left operand */
80650 double rB; /* Real value of right operand */
80652 pIn1 = &aMem[pOp->p1];
80653 type1 = numericType(pIn1);
80654 pIn2 = &aMem[pOp->p2];
80655 type2 = numericType(pIn2);
80656 pOut = &aMem[pOp->p3];
80657 flags = pIn1->flags | pIn2->flags;
80658 if( (type1 & type2 & MEM_Int)!=0 ){
80659 iA = pIn1->u.i;
80660 iB = pIn2->u.i;
80661 bIntint = 1;
80662 switch( pOp->opcode ){
80663 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
80664 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
80665 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
80666 case OP_Divide: {
80667 if( iA==0 ) goto arithmetic_result_is_null;
80668 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
80669 iB /= iA;
80670 break;
80672 default: {
80673 if( iA==0 ) goto arithmetic_result_is_null;
80674 if( iA==-1 ) iA = 1;
80675 iB %= iA;
80676 break;
80679 pOut->u.i = iB;
80680 MemSetTypeFlag(pOut, MEM_Int);
80681 }else if( (flags & MEM_Null)!=0 ){
80682 goto arithmetic_result_is_null;
80683 }else{
80684 bIntint = 0;
80685 fp_math:
80686 rA = sqlite3VdbeRealValue(pIn1);
80687 rB = sqlite3VdbeRealValue(pIn2);
80688 switch( pOp->opcode ){
80689 case OP_Add: rB += rA; break;
80690 case OP_Subtract: rB -= rA; break;
80691 case OP_Multiply: rB *= rA; break;
80692 case OP_Divide: {
80693 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
80694 if( rA==(double)0 ) goto arithmetic_result_is_null;
80695 rB /= rA;
80696 break;
80698 default: {
80699 iA = (i64)rA;
80700 iB = (i64)rB;
80701 if( iA==0 ) goto arithmetic_result_is_null;
80702 if( iA==-1 ) iA = 1;
80703 rB = (double)(iB % iA);
80704 break;
80707 #ifdef SQLITE_OMIT_FLOATING_POINT
80708 pOut->u.i = rB;
80709 MemSetTypeFlag(pOut, MEM_Int);
80710 #else
80711 if( sqlite3IsNaN(rB) ){
80712 goto arithmetic_result_is_null;
80714 pOut->u.r = rB;
80715 MemSetTypeFlag(pOut, MEM_Real);
80716 if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
80717 sqlite3VdbeIntegerAffinity(pOut);
80719 #endif
80721 break;
80723 arithmetic_result_is_null:
80724 sqlite3VdbeMemSetNull(pOut);
80725 break;
80728 /* Opcode: CollSeq P1 * * P4
80730 ** P4 is a pointer to a CollSeq object. If the next call to a user function
80731 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
80732 ** be returned. This is used by the built-in min(), max() and nullif()
80733 ** functions.
80735 ** If P1 is not zero, then it is a register that a subsequent min() or
80736 ** max() aggregate will set to 1 if the current row is not the minimum or
80737 ** maximum. The P1 register is initialized to 0 by this instruction.
80739 ** The interface used by the implementation of the aforementioned functions
80740 ** to retrieve the collation sequence set by this opcode is not available
80741 ** publicly. Only built-in functions have access to this feature.
80743 case OP_CollSeq: {
80744 assert( pOp->p4type==P4_COLLSEQ );
80745 if( pOp->p1 ){
80746 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
80748 break;
80751 /* Opcode: BitAnd P1 P2 P3 * *
80752 ** Synopsis: r[P3]=r[P1]&r[P2]
80754 ** Take the bit-wise AND of the values in register P1 and P2 and
80755 ** store the result in register P3.
80756 ** If either input is NULL, the result is NULL.
80758 /* Opcode: BitOr P1 P2 P3 * *
80759 ** Synopsis: r[P3]=r[P1]|r[P2]
80761 ** Take the bit-wise OR of the values in register P1 and P2 and
80762 ** store the result in register P3.
80763 ** If either input is NULL, the result is NULL.
80765 /* Opcode: ShiftLeft P1 P2 P3 * *
80766 ** Synopsis: r[P3]=r[P2]<<r[P1]
80768 ** Shift the integer value in register P2 to the left by the
80769 ** number of bits specified by the integer in register P1.
80770 ** Store the result in register P3.
80771 ** If either input is NULL, the result is NULL.
80773 /* Opcode: ShiftRight P1 P2 P3 * *
80774 ** Synopsis: r[P3]=r[P2]>>r[P1]
80776 ** Shift the integer value in register P2 to the right by the
80777 ** number of bits specified by the integer in register P1.
80778 ** Store the result in register P3.
80779 ** If either input is NULL, the result is NULL.
80781 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
80782 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
80783 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
80784 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
80785 i64 iA;
80786 u64 uA;
80787 i64 iB;
80788 u8 op;
80790 pIn1 = &aMem[pOp->p1];
80791 pIn2 = &aMem[pOp->p2];
80792 pOut = &aMem[pOp->p3];
80793 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
80794 sqlite3VdbeMemSetNull(pOut);
80795 break;
80797 iA = sqlite3VdbeIntValue(pIn2);
80798 iB = sqlite3VdbeIntValue(pIn1);
80799 op = pOp->opcode;
80800 if( op==OP_BitAnd ){
80801 iA &= iB;
80802 }else if( op==OP_BitOr ){
80803 iA |= iB;
80804 }else if( iB!=0 ){
80805 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
80807 /* If shifting by a negative amount, shift in the other direction */
80808 if( iB<0 ){
80809 assert( OP_ShiftRight==OP_ShiftLeft+1 );
80810 op = 2*OP_ShiftLeft + 1 - op;
80811 iB = iB>(-64) ? -iB : 64;
80814 if( iB>=64 ){
80815 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
80816 }else{
80817 memcpy(&uA, &iA, sizeof(uA));
80818 if( op==OP_ShiftLeft ){
80819 uA <<= iB;
80820 }else{
80821 uA >>= iB;
80822 /* Sign-extend on a right shift of a negative number */
80823 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
80825 memcpy(&iA, &uA, sizeof(iA));
80828 pOut->u.i = iA;
80829 MemSetTypeFlag(pOut, MEM_Int);
80830 break;
80833 /* Opcode: AddImm P1 P2 * * *
80834 ** Synopsis: r[P1]=r[P1]+P2
80836 ** Add the constant P2 to the value in register P1.
80837 ** The result is always an integer.
80839 ** To force any register to be an integer, just add 0.
80841 case OP_AddImm: { /* in1 */
80842 pIn1 = &aMem[pOp->p1];
80843 memAboutToChange(p, pIn1);
80844 sqlite3VdbeMemIntegerify(pIn1);
80845 pIn1->u.i += pOp->p2;
80846 break;
80849 /* Opcode: MustBeInt P1 P2 * * *
80851 ** Force the value in register P1 to be an integer. If the value
80852 ** in P1 is not an integer and cannot be converted into an integer
80853 ** without data loss, then jump immediately to P2, or if P2==0
80854 ** raise an SQLITE_MISMATCH exception.
80856 case OP_MustBeInt: { /* jump, in1 */
80857 pIn1 = &aMem[pOp->p1];
80858 if( (pIn1->flags & MEM_Int)==0 ){
80859 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
80860 VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
80861 if( (pIn1->flags & MEM_Int)==0 ){
80862 if( pOp->p2==0 ){
80863 rc = SQLITE_MISMATCH;
80864 goto abort_due_to_error;
80865 }else{
80866 goto jump_to_p2;
80870 MemSetTypeFlag(pIn1, MEM_Int);
80871 break;
80874 #ifndef SQLITE_OMIT_FLOATING_POINT
80875 /* Opcode: RealAffinity P1 * * * *
80877 ** If register P1 holds an integer convert it to a real value.
80879 ** This opcode is used when extracting information from a column that
80880 ** has REAL affinity. Such column values may still be stored as
80881 ** integers, for space efficiency, but after extraction we want them
80882 ** to have only a real value.
80884 case OP_RealAffinity: { /* in1 */
80885 pIn1 = &aMem[pOp->p1];
80886 if( pIn1->flags & MEM_Int ){
80887 sqlite3VdbeMemRealify(pIn1);
80889 break;
80891 #endif
80893 #ifndef SQLITE_OMIT_CAST
80894 /* Opcode: Cast P1 P2 * * *
80895 ** Synopsis: affinity(r[P1])
80897 ** Force the value in register P1 to be the type defined by P2.
80899 ** <ul>
80900 ** <li> P2=='A' &rarr; BLOB
80901 ** <li> P2=='B' &rarr; TEXT
80902 ** <li> P2=='C' &rarr; NUMERIC
80903 ** <li> P2=='D' &rarr; INTEGER
80904 ** <li> P2=='E' &rarr; REAL
80905 ** </ul>
80907 ** A NULL value is not changed by this routine. It remains NULL.
80909 case OP_Cast: { /* in1 */
80910 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
80911 testcase( pOp->p2==SQLITE_AFF_TEXT );
80912 testcase( pOp->p2==SQLITE_AFF_BLOB );
80913 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
80914 testcase( pOp->p2==SQLITE_AFF_INTEGER );
80915 testcase( pOp->p2==SQLITE_AFF_REAL );
80916 pIn1 = &aMem[pOp->p1];
80917 memAboutToChange(p, pIn1);
80918 rc = ExpandBlob(pIn1);
80919 sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
80920 UPDATE_MAX_BLOBSIZE(pIn1);
80921 if( rc ) goto abort_due_to_error;
80922 break;
80924 #endif /* SQLITE_OMIT_CAST */
80926 /* Opcode: Eq P1 P2 P3 P4 P5
80927 ** Synopsis: IF r[P3]==r[P1]
80929 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
80930 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
80931 ** store the result of comparison in register P2.
80933 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
80934 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
80935 ** to coerce both inputs according to this affinity before the
80936 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
80937 ** affinity is used. Note that the affinity conversions are stored
80938 ** back into the input registers P1 and P3. So this opcode can cause
80939 ** persistent changes to registers P1 and P3.
80941 ** Once any conversions have taken place, and neither value is NULL,
80942 ** the values are compared. If both values are blobs then memcmp() is
80943 ** used to determine the results of the comparison. If both values
80944 ** are text, then the appropriate collating function specified in
80945 ** P4 is used to do the comparison. If P4 is not specified then
80946 ** memcmp() is used to compare text string. If both values are
80947 ** numeric, then a numeric comparison is used. If the two values
80948 ** are of different types, then numbers are considered less than
80949 ** strings and strings are considered less than blobs.
80951 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
80952 ** true or false and is never NULL. If both operands are NULL then the result
80953 ** of comparison is true. If either operand is NULL then the result is false.
80954 ** If neither operand is NULL the result is the same as it would be if
80955 ** the SQLITE_NULLEQ flag were omitted from P5.
80957 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
80958 ** content of r[P2] is only changed if the new value is NULL or 0 (false).
80959 ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
80961 /* Opcode: Ne P1 P2 P3 P4 P5
80962 ** Synopsis: IF r[P3]!=r[P1]
80964 ** This works just like the Eq opcode except that the jump is taken if
80965 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
80966 ** additional information.
80968 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
80969 ** content of r[P2] is only changed if the new value is NULL or 1 (true).
80970 ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
80972 /* Opcode: Lt P1 P2 P3 P4 P5
80973 ** Synopsis: IF r[P3]<r[P1]
80975 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
80976 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
80977 ** the result of comparison (0 or 1 or NULL) into register P2.
80979 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
80980 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
80981 ** bit is clear then fall through if either operand is NULL.
80983 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
80984 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
80985 ** to coerce both inputs according to this affinity before the
80986 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
80987 ** affinity is used. Note that the affinity conversions are stored
80988 ** back into the input registers P1 and P3. So this opcode can cause
80989 ** persistent changes to registers P1 and P3.
80991 ** Once any conversions have taken place, and neither value is NULL,
80992 ** the values are compared. If both values are blobs then memcmp() is
80993 ** used to determine the results of the comparison. If both values
80994 ** are text, then the appropriate collating function specified in
80995 ** P4 is used to do the comparison. If P4 is not specified then
80996 ** memcmp() is used to compare text string. If both values are
80997 ** numeric, then a numeric comparison is used. If the two values
80998 ** are of different types, then numbers are considered less than
80999 ** strings and strings are considered less than blobs.
81001 /* Opcode: Le P1 P2 P3 P4 P5
81002 ** Synopsis: IF r[P3]<=r[P1]
81004 ** This works just like the Lt opcode except that the jump is taken if
81005 ** the content of register P3 is less than or equal to the content of
81006 ** register P1. See the Lt opcode for additional information.
81008 /* Opcode: Gt P1 P2 P3 P4 P5
81009 ** Synopsis: IF r[P3]>r[P1]
81011 ** This works just like the Lt opcode except that the jump is taken if
81012 ** the content of register P3 is greater than the content of
81013 ** register P1. See the Lt opcode for additional information.
81015 /* Opcode: Ge P1 P2 P3 P4 P5
81016 ** Synopsis: IF r[P3]>=r[P1]
81018 ** This works just like the Lt opcode except that the jump is taken if
81019 ** the content of register P3 is greater than or equal to the content of
81020 ** register P1. See the Lt opcode for additional information.
81022 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
81023 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
81024 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
81025 case OP_Le: /* same as TK_LE, jump, in1, in3 */
81026 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
81027 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
81028 int res, res2; /* Result of the comparison of pIn1 against pIn3 */
81029 char affinity; /* Affinity to use for comparison */
81030 u16 flags1; /* Copy of initial value of pIn1->flags */
81031 u16 flags3; /* Copy of initial value of pIn3->flags */
81033 pIn1 = &aMem[pOp->p1];
81034 pIn3 = &aMem[pOp->p3];
81035 flags1 = pIn1->flags;
81036 flags3 = pIn3->flags;
81037 if( (flags1 | flags3)&MEM_Null ){
81038 /* One or both operands are NULL */
81039 if( pOp->p5 & SQLITE_NULLEQ ){
81040 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
81041 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
81042 ** or not both operands are null.
81044 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
81045 assert( (flags1 & MEM_Cleared)==0 );
81046 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
81047 if( (flags1&flags3&MEM_Null)!=0
81048 && (flags3&MEM_Cleared)==0
81050 res = 0; /* Operands are equal */
81051 }else{
81052 res = 1; /* Operands are not equal */
81054 }else{
81055 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
81056 ** then the result is always NULL.
81057 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
81059 if( pOp->p5 & SQLITE_STOREP2 ){
81060 pOut = &aMem[pOp->p2];
81061 iCompare = 1; /* Operands are not equal */
81062 memAboutToChange(p, pOut);
81063 MemSetTypeFlag(pOut, MEM_Null);
81064 REGISTER_TRACE(pOp->p2, pOut);
81065 }else{
81066 VdbeBranchTaken(2,3);
81067 if( pOp->p5 & SQLITE_JUMPIFNULL ){
81068 goto jump_to_p2;
81071 break;
81073 }else{
81074 /* Neither operand is NULL. Do a comparison. */
81075 affinity = pOp->p5 & SQLITE_AFF_MASK;
81076 if( affinity>=SQLITE_AFF_NUMERIC ){
81077 if( (flags1 | flags3)&MEM_Str ){
81078 if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
81079 applyNumericAffinity(pIn1,0);
81080 testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
81081 flags3 = pIn3->flags;
81083 if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
81084 applyNumericAffinity(pIn3,0);
81087 /* Handle the common case of integer comparison here, as an
81088 ** optimization, to avoid a call to sqlite3MemCompare() */
81089 if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
81090 if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
81091 if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
81092 res = 0;
81093 goto compare_op;
81095 }else if( affinity==SQLITE_AFF_TEXT ){
81096 if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
81097 testcase( pIn1->flags & MEM_Int );
81098 testcase( pIn1->flags & MEM_Real );
81099 sqlite3VdbeMemStringify(pIn1, encoding, 1);
81100 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
81101 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
81102 assert( pIn1!=pIn3 );
81104 if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
81105 testcase( pIn3->flags & MEM_Int );
81106 testcase( pIn3->flags & MEM_Real );
81107 sqlite3VdbeMemStringify(pIn3, encoding, 1);
81108 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
81109 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
81112 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
81113 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
81115 compare_op:
81116 /* At this point, res is negative, zero, or positive if reg[P1] is
81117 ** less than, equal to, or greater than reg[P3], respectively. Compute
81118 ** the answer to this operator in res2, depending on what the comparison
81119 ** operator actually is. The next block of code depends on the fact
81120 ** that the 6 comparison operators are consecutive integers in this
81121 ** order: NE, EQ, GT, LE, LT, GE */
81122 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
81123 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
81124 if( res<0 ){ /* ne, eq, gt, le, lt, ge */
81125 static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
81126 res2 = aLTb[pOp->opcode - OP_Ne];
81127 }else if( res==0 ){
81128 static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
81129 res2 = aEQb[pOp->opcode - OP_Ne];
81130 }else{
81131 static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
81132 res2 = aGTb[pOp->opcode - OP_Ne];
81135 /* Undo any changes made by applyAffinity() to the input registers. */
81136 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
81137 pIn1->flags = flags1;
81138 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
81139 pIn3->flags = flags3;
81141 if( pOp->p5 & SQLITE_STOREP2 ){
81142 pOut = &aMem[pOp->p2];
81143 iCompare = res;
81144 if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
81145 /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
81146 ** and prevents OP_Ne from overwriting NULL with 0. This flag
81147 ** is only used in contexts where either:
81148 ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
81149 ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
81150 ** Therefore it is not necessary to check the content of r[P2] for
81151 ** NULL. */
81152 assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
81153 assert( res2==0 || res2==1 );
81154 testcase( res2==0 && pOp->opcode==OP_Eq );
81155 testcase( res2==1 && pOp->opcode==OP_Eq );
81156 testcase( res2==0 && pOp->opcode==OP_Ne );
81157 testcase( res2==1 && pOp->opcode==OP_Ne );
81158 if( (pOp->opcode==OP_Eq)==res2 ) break;
81160 memAboutToChange(p, pOut);
81161 MemSetTypeFlag(pOut, MEM_Int);
81162 pOut->u.i = res2;
81163 REGISTER_TRACE(pOp->p2, pOut);
81164 }else{
81165 VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
81166 if( res2 ){
81167 goto jump_to_p2;
81170 break;
81173 /* Opcode: ElseNotEq * P2 * * *
81175 ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
81176 ** If result of an OP_Eq comparison on the same two operands
81177 ** would have be NULL or false (0), then then jump to P2.
81178 ** If the result of an OP_Eq comparison on the two previous operands
81179 ** would have been true (1), then fall through.
81181 case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
81182 assert( pOp>aOp );
81183 assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
81184 assert( pOp[-1].p5 & SQLITE_STOREP2 );
81185 VdbeBranchTaken(iCompare!=0, 2);
81186 if( iCompare!=0 ) goto jump_to_p2;
81187 break;
81191 /* Opcode: Permutation * * * P4 *
81193 ** Set the permutation used by the OP_Compare operator in the next
81194 ** instruction. The permutation is stored in the P4 operand.
81196 ** The permutation is only valid until the next OP_Compare that has
81197 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
81198 ** occur immediately prior to the OP_Compare.
81200 ** The first integer in the P4 integer array is the length of the array
81201 ** and does not become part of the permutation.
81203 case OP_Permutation: {
81204 assert( pOp->p4type==P4_INTARRAY );
81205 assert( pOp->p4.ai );
81206 assert( pOp[1].opcode==OP_Compare );
81207 assert( pOp[1].p5 & OPFLAG_PERMUTE );
81208 break;
81211 /* Opcode: Compare P1 P2 P3 P4 P5
81212 ** Synopsis: r[P1@P3] <-> r[P2@P3]
81214 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
81215 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
81216 ** the comparison for use by the next OP_Jump instruct.
81218 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
81219 ** determined by the most recent OP_Permutation operator. If the
81220 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
81221 ** order.
81223 ** P4 is a KeyInfo structure that defines collating sequences and sort
81224 ** orders for the comparison. The permutation applies to registers
81225 ** only. The KeyInfo elements are used sequentially.
81227 ** The comparison is a sort comparison, so NULLs compare equal,
81228 ** NULLs are less than numbers, numbers are less than strings,
81229 ** and strings are less than blobs.
81231 case OP_Compare: {
81232 int n;
81233 int i;
81234 int p1;
81235 int p2;
81236 const KeyInfo *pKeyInfo;
81237 int idx;
81238 CollSeq *pColl; /* Collating sequence to use on this term */
81239 int bRev; /* True for DESCENDING sort order */
81240 int *aPermute; /* The permutation */
81242 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
81243 aPermute = 0;
81244 }else{
81245 assert( pOp>aOp );
81246 assert( pOp[-1].opcode==OP_Permutation );
81247 assert( pOp[-1].p4type==P4_INTARRAY );
81248 aPermute = pOp[-1].p4.ai + 1;
81249 assert( aPermute!=0 );
81251 n = pOp->p3;
81252 pKeyInfo = pOp->p4.pKeyInfo;
81253 assert( n>0 );
81254 assert( pKeyInfo!=0 );
81255 p1 = pOp->p1;
81256 p2 = pOp->p2;
81257 #ifdef SQLITE_DEBUG
81258 if( aPermute ){
81259 int k, mx = 0;
81260 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
81261 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
81262 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
81263 }else{
81264 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
81265 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
81267 #endif /* SQLITE_DEBUG */
81268 for(i=0; i<n; i++){
81269 idx = aPermute ? aPermute[i] : i;
81270 assert( memIsValid(&aMem[p1+idx]) );
81271 assert( memIsValid(&aMem[p2+idx]) );
81272 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
81273 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
81274 assert( i<pKeyInfo->nKeyField );
81275 pColl = pKeyInfo->aColl[i];
81276 bRev = pKeyInfo->aSortOrder[i];
81277 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
81278 if( iCompare ){
81279 if( bRev ) iCompare = -iCompare;
81280 break;
81283 break;
81286 /* Opcode: Jump P1 P2 P3 * *
81288 ** Jump to the instruction at address P1, P2, or P3 depending on whether
81289 ** in the most recent OP_Compare instruction the P1 vector was less than
81290 ** equal to, or greater than the P2 vector, respectively.
81292 case OP_Jump: { /* jump */
81293 if( iCompare<0 ){
81294 VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
81295 }else if( iCompare==0 ){
81296 VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
81297 }else{
81298 VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
81300 break;
81303 /* Opcode: And P1 P2 P3 * *
81304 ** Synopsis: r[P3]=(r[P1] && r[P2])
81306 ** Take the logical AND of the values in registers P1 and P2 and
81307 ** write the result into register P3.
81309 ** If either P1 or P2 is 0 (false) then the result is 0 even if
81310 ** the other input is NULL. A NULL and true or two NULLs give
81311 ** a NULL output.
81313 /* Opcode: Or P1 P2 P3 * *
81314 ** Synopsis: r[P3]=(r[P1] || r[P2])
81316 ** Take the logical OR of the values in register P1 and P2 and
81317 ** store the answer in register P3.
81319 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
81320 ** even if the other input is NULL. A NULL and false or two NULLs
81321 ** give a NULL output.
81323 case OP_And: /* same as TK_AND, in1, in2, out3 */
81324 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
81325 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
81326 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
81328 pIn1 = &aMem[pOp->p1];
81329 if( pIn1->flags & MEM_Null ){
81330 v1 = 2;
81331 }else{
81332 v1 = sqlite3VdbeIntValue(pIn1)!=0;
81334 pIn2 = &aMem[pOp->p2];
81335 if( pIn2->flags & MEM_Null ){
81336 v2 = 2;
81337 }else{
81338 v2 = sqlite3VdbeIntValue(pIn2)!=0;
81340 if( pOp->opcode==OP_And ){
81341 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
81342 v1 = and_logic[v1*3+v2];
81343 }else{
81344 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
81345 v1 = or_logic[v1*3+v2];
81347 pOut = &aMem[pOp->p3];
81348 if( v1==2 ){
81349 MemSetTypeFlag(pOut, MEM_Null);
81350 }else{
81351 pOut->u.i = v1;
81352 MemSetTypeFlag(pOut, MEM_Int);
81354 break;
81357 /* Opcode: Not P1 P2 * * *
81358 ** Synopsis: r[P2]= !r[P1]
81360 ** Interpret the value in register P1 as a boolean value. Store the
81361 ** boolean complement in register P2. If the value in register P1 is
81362 ** NULL, then a NULL is stored in P2.
81364 case OP_Not: { /* same as TK_NOT, in1, out2 */
81365 pIn1 = &aMem[pOp->p1];
81366 pOut = &aMem[pOp->p2];
81367 sqlite3VdbeMemSetNull(pOut);
81368 if( (pIn1->flags & MEM_Null)==0 ){
81369 pOut->flags = MEM_Int;
81370 pOut->u.i = !sqlite3VdbeIntValue(pIn1);
81372 break;
81375 /* Opcode: BitNot P1 P2 * * *
81376 ** Synopsis: r[P1]= ~r[P1]
81378 ** Interpret the content of register P1 as an integer. Store the
81379 ** ones-complement of the P1 value into register P2. If P1 holds
81380 ** a NULL then store a NULL in P2.
81382 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
81383 pIn1 = &aMem[pOp->p1];
81384 pOut = &aMem[pOp->p2];
81385 sqlite3VdbeMemSetNull(pOut);
81386 if( (pIn1->flags & MEM_Null)==0 ){
81387 pOut->flags = MEM_Int;
81388 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
81390 break;
81393 /* Opcode: Once P1 P2 * * *
81395 ** Fall through to the next instruction the first time this opcode is
81396 ** encountered on each invocation of the byte-code program. Jump to P2
81397 ** on the second and all subsequent encounters during the same invocation.
81399 ** Top-level programs determine first invocation by comparing the P1
81400 ** operand against the P1 operand on the OP_Init opcode at the beginning
81401 ** of the program. If the P1 values differ, then fall through and make
81402 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
81403 ** the same then take the jump.
81405 ** For subprograms, there is a bitmask in the VdbeFrame that determines
81406 ** whether or not the jump should be taken. The bitmask is necessary
81407 ** because the self-altering code trick does not work for recursive
81408 ** triggers.
81410 case OP_Once: { /* jump */
81411 u32 iAddr; /* Address of this instruction */
81412 assert( p->aOp[0].opcode==OP_Init );
81413 if( p->pFrame ){
81414 iAddr = (int)(pOp - p->aOp);
81415 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
81416 VdbeBranchTaken(1, 2);
81417 goto jump_to_p2;
81419 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
81420 }else{
81421 if( p->aOp[0].p1==pOp->p1 ){
81422 VdbeBranchTaken(1, 2);
81423 goto jump_to_p2;
81426 VdbeBranchTaken(0, 2);
81427 pOp->p1 = p->aOp[0].p1;
81428 break;
81431 /* Opcode: If P1 P2 P3 * *
81433 ** Jump to P2 if the value in register P1 is true. The value
81434 ** is considered true if it is numeric and non-zero. If the value
81435 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
81437 /* Opcode: IfNot P1 P2 P3 * *
81439 ** Jump to P2 if the value in register P1 is False. The value
81440 ** is considered false if it has a numeric value of zero. If the value
81441 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
81443 case OP_If: /* jump, in1 */
81444 case OP_IfNot: { /* jump, in1 */
81445 int c;
81446 pIn1 = &aMem[pOp->p1];
81447 if( pIn1->flags & MEM_Null ){
81448 c = pOp->p3;
81449 }else{
81450 #ifdef SQLITE_OMIT_FLOATING_POINT
81451 c = sqlite3VdbeIntValue(pIn1)!=0;
81452 #else
81453 c = sqlite3VdbeRealValue(pIn1)!=0.0;
81454 #endif
81455 if( pOp->opcode==OP_IfNot ) c = !c;
81457 VdbeBranchTaken(c!=0, 2);
81458 if( c ){
81459 goto jump_to_p2;
81461 break;
81464 /* Opcode: IsNull P1 P2 * * *
81465 ** Synopsis: if r[P1]==NULL goto P2
81467 ** Jump to P2 if the value in register P1 is NULL.
81469 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
81470 pIn1 = &aMem[pOp->p1];
81471 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
81472 if( (pIn1->flags & MEM_Null)!=0 ){
81473 goto jump_to_p2;
81475 break;
81478 /* Opcode: NotNull P1 P2 * * *
81479 ** Synopsis: if r[P1]!=NULL goto P2
81481 ** Jump to P2 if the value in register P1 is not NULL.
81483 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
81484 pIn1 = &aMem[pOp->p1];
81485 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
81486 if( (pIn1->flags & MEM_Null)==0 ){
81487 goto jump_to_p2;
81489 break;
81492 /* Opcode: IfNullRow P1 P2 P3 * *
81493 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
81495 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
81496 ** If it is, then set register P3 to NULL and jump immediately to P2.
81497 ** If P1 is not on a NULL row, then fall through without making any
81498 ** changes.
81500 case OP_IfNullRow: { /* jump */
81501 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81502 assert( p->apCsr[pOp->p1]!=0 );
81503 if( p->apCsr[pOp->p1]->nullRow ){
81504 sqlite3VdbeMemSetNull(aMem + pOp->p3);
81505 goto jump_to_p2;
81507 break;
81510 /* Opcode: Column P1 P2 P3 P4 P5
81511 ** Synopsis: r[P3]=PX
81513 ** Interpret the data that cursor P1 points to as a structure built using
81514 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
81515 ** information about the format of the data.) Extract the P2-th column
81516 ** from this record. If there are less that (P2+1)
81517 ** values in the record, extract a NULL.
81519 ** The value extracted is stored in register P3.
81521 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
81522 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
81523 ** the result.
81525 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
81526 ** then the cache of the cursor is reset prior to extracting the column.
81527 ** The first OP_Column against a pseudo-table after the value of the content
81528 ** register has changed should have this bit set.
81530 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
81531 ** the result is guaranteed to only be used as the argument of a length()
81532 ** or typeof() function, respectively. The loading of large blobs can be
81533 ** skipped for length() and all content loading can be skipped for typeof().
81535 case OP_Column: {
81536 int p2; /* column number to retrieve */
81537 VdbeCursor *pC; /* The VDBE cursor */
81538 BtCursor *pCrsr; /* The BTree cursor */
81539 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
81540 int len; /* The length of the serialized data for the column */
81541 int i; /* Loop counter */
81542 Mem *pDest; /* Where to write the extracted value */
81543 Mem sMem; /* For storing the record being decoded */
81544 const u8 *zData; /* Part of the record being decoded */
81545 const u8 *zHdr; /* Next unparsed byte of the header */
81546 const u8 *zEndHdr; /* Pointer to first byte after the header */
81547 u64 offset64; /* 64-bit offset */
81548 u32 t; /* A type code from the record header */
81549 Mem *pReg; /* PseudoTable input register */
81551 pC = p->apCsr[pOp->p1];
81552 p2 = pOp->p2;
81554 /* If the cursor cache is stale (meaning it is not currently point at
81555 ** the correct row) then bring it up-to-date by doing the necessary
81556 ** B-Tree seek. */
81557 rc = sqlite3VdbeCursorMoveto(&pC, &p2);
81558 if( rc ) goto abort_due_to_error;
81560 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
81561 pDest = &aMem[pOp->p3];
81562 memAboutToChange(p, pDest);
81563 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81564 assert( pC!=0 );
81565 assert( p2<pC->nField );
81566 aOffset = pC->aOffset;
81567 assert( pC->eCurType!=CURTYPE_VTAB );
81568 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
81569 assert( pC->eCurType!=CURTYPE_SORTER );
81571 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
81572 if( pC->nullRow ){
81573 if( pC->eCurType==CURTYPE_PSEUDO ){
81574 /* For the special case of as pseudo-cursor, the seekResult field
81575 ** identifies the register that holds the record */
81576 assert( pC->seekResult>0 );
81577 pReg = &aMem[pC->seekResult];
81578 assert( pReg->flags & MEM_Blob );
81579 assert( memIsValid(pReg) );
81580 pC->payloadSize = pC->szRow = pReg->n;
81581 pC->aRow = (u8*)pReg->z;
81582 }else{
81583 sqlite3VdbeMemSetNull(pDest);
81584 goto op_column_out;
81586 }else{
81587 pCrsr = pC->uc.pCursor;
81588 assert( pC->eCurType==CURTYPE_BTREE );
81589 assert( pCrsr );
81590 assert( sqlite3BtreeCursorIsValid(pCrsr) );
81591 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
81592 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
81593 assert( pC->szRow<=pC->payloadSize );
81594 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
81595 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
81596 goto too_big;
81599 pC->cacheStatus = p->cacheCtr;
81600 pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
81601 pC->nHdrParsed = 0;
81604 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
81605 /* pC->aRow does not have to hold the entire row, but it does at least
81606 ** need to cover the header of the record. If pC->aRow does not contain
81607 ** the complete header, then set it to zero, forcing the header to be
81608 ** dynamically allocated. */
81609 pC->aRow = 0;
81610 pC->szRow = 0;
81612 /* Make sure a corrupt database has not given us an oversize header.
81613 ** Do this now to avoid an oversize memory allocation.
81615 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
81616 ** types use so much data space that there can only be 4096 and 32 of
81617 ** them, respectively. So the maximum header length results from a
81618 ** 3-byte type for each of the maximum of 32768 columns plus three
81619 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
81621 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
81622 goto op_column_corrupt;
81624 }else{
81625 /* This is an optimization. By skipping over the first few tests
81626 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
81627 ** measurable performance gain.
81629 ** This branch is taken even if aOffset[0]==0. Such a record is never
81630 ** generated by SQLite, and could be considered corruption, but we
81631 ** accept it for historical reasons. When aOffset[0]==0, the code this
81632 ** branch jumps to reads past the end of the record, but never more
81633 ** than a few bytes. Even if the record occurs at the end of the page
81634 ** content area, the "page header" comes after the page content and so
81635 ** this overread is harmless. Similar overreads can occur for a corrupt
81636 ** database file.
81638 zData = pC->aRow;
81639 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
81640 testcase( aOffset[0]==0 );
81641 goto op_column_read_header;
81645 /* Make sure at least the first p2+1 entries of the header have been
81646 ** parsed and valid information is in aOffset[] and pC->aType[].
81648 if( pC->nHdrParsed<=p2 ){
81649 /* If there is more header available for parsing in the record, try
81650 ** to extract additional fields up through the p2+1-th field
81652 if( pC->iHdrOffset<aOffset[0] ){
81653 /* Make sure zData points to enough of the record to cover the header. */
81654 if( pC->aRow==0 ){
81655 memset(&sMem, 0, sizeof(sMem));
81656 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
81657 if( rc!=SQLITE_OK ) goto abort_due_to_error;
81658 zData = (u8*)sMem.z;
81659 }else{
81660 zData = pC->aRow;
81663 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
81664 op_column_read_header:
81665 i = pC->nHdrParsed;
81666 offset64 = aOffset[i];
81667 zHdr = zData + pC->iHdrOffset;
81668 zEndHdr = zData + aOffset[0];
81669 testcase( zHdr>=zEndHdr );
81671 if( (t = zHdr[0])<0x80 ){
81672 zHdr++;
81673 offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
81674 }else{
81675 zHdr += sqlite3GetVarint32(zHdr, &t);
81676 offset64 += sqlite3VdbeSerialTypeLen(t);
81678 pC->aType[i++] = t;
81679 aOffset[i] = (u32)(offset64 & 0xffffffff);
81680 }while( i<=p2 && zHdr<zEndHdr );
81682 /* The record is corrupt if any of the following are true:
81683 ** (1) the bytes of the header extend past the declared header size
81684 ** (2) the entire header was used but not all data was used
81685 ** (3) the end of the data extends beyond the end of the record.
81687 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
81688 || (offset64 > pC->payloadSize)
81690 if( aOffset[0]==0 ){
81691 i = 0;
81692 zHdr = zEndHdr;
81693 }else{
81694 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
81695 goto op_column_corrupt;
81699 pC->nHdrParsed = i;
81700 pC->iHdrOffset = (u32)(zHdr - zData);
81701 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
81702 }else{
81703 t = 0;
81706 /* If after trying to extract new entries from the header, nHdrParsed is
81707 ** still not up to p2, that means that the record has fewer than p2
81708 ** columns. So the result will be either the default value or a NULL.
81710 if( pC->nHdrParsed<=p2 ){
81711 if( pOp->p4type==P4_MEM ){
81712 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
81713 }else{
81714 sqlite3VdbeMemSetNull(pDest);
81716 goto op_column_out;
81718 }else{
81719 t = pC->aType[p2];
81722 /* Extract the content for the p2+1-th column. Control can only
81723 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
81724 ** all valid.
81726 assert( p2<pC->nHdrParsed );
81727 assert( rc==SQLITE_OK );
81728 assert( sqlite3VdbeCheckMemInvariants(pDest) );
81729 if( VdbeMemDynamic(pDest) ){
81730 sqlite3VdbeMemSetNull(pDest);
81732 assert( t==pC->aType[p2] );
81733 if( pC->szRow>=aOffset[p2+1] ){
81734 /* This is the common case where the desired content fits on the original
81735 ** page - where the content is not on an overflow page */
81736 zData = pC->aRow + aOffset[p2];
81737 if( t<12 ){
81738 sqlite3VdbeSerialGet(zData, t, pDest);
81739 }else{
81740 /* If the column value is a string, we need a persistent value, not
81741 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
81742 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
81744 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
81745 pDest->n = len = (t-12)/2;
81746 pDest->enc = encoding;
81747 if( pDest->szMalloc < len+2 ){
81748 pDest->flags = MEM_Null;
81749 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
81750 }else{
81751 pDest->z = pDest->zMalloc;
81753 memcpy(pDest->z, zData, len);
81754 pDest->z[len] = 0;
81755 pDest->z[len+1] = 0;
81756 pDest->flags = aFlag[t&1];
81758 }else{
81759 pDest->enc = encoding;
81760 /* This branch happens only when content is on overflow pages */
81761 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
81762 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
81763 || (len = sqlite3VdbeSerialTypeLen(t))==0
81765 /* Content is irrelevant for
81766 ** 1. the typeof() function,
81767 ** 2. the length(X) function if X is a blob, and
81768 ** 3. if the content length is zero.
81769 ** So we might as well use bogus content rather than reading
81770 ** content from disk.
81772 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
81773 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
81774 ** read up to 16. So 16 bytes of bogus content is supplied.
81776 static u8 aZero[16]; /* This is the bogus content */
81777 sqlite3VdbeSerialGet(aZero, t, pDest);
81778 }else{
81779 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
81780 if( rc!=SQLITE_OK ) goto abort_due_to_error;
81781 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
81782 pDest->flags &= ~MEM_Ephem;
81786 op_column_out:
81787 UPDATE_MAX_BLOBSIZE(pDest);
81788 REGISTER_TRACE(pOp->p3, pDest);
81789 break;
81791 op_column_corrupt:
81792 if( aOp[0].p3>0 ){
81793 pOp = &aOp[aOp[0].p3-1];
81794 break;
81795 }else{
81796 rc = SQLITE_CORRUPT_BKPT;
81797 goto abort_due_to_error;
81801 /* Opcode: Affinity P1 P2 * P4 *
81802 ** Synopsis: affinity(r[P1@P2])
81804 ** Apply affinities to a range of P2 registers starting with P1.
81806 ** P4 is a string that is P2 characters long. The N-th character of the
81807 ** string indicates the column affinity that should be used for the N-th
81808 ** memory cell in the range.
81810 case OP_Affinity: {
81811 const char *zAffinity; /* The affinity to be applied */
81813 zAffinity = pOp->p4.z;
81814 assert( zAffinity!=0 );
81815 assert( pOp->p2>0 );
81816 assert( zAffinity[pOp->p2]==0 );
81817 pIn1 = &aMem[pOp->p1];
81819 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
81820 assert( memIsValid(pIn1) );
81821 applyAffinity(pIn1, *(zAffinity++), encoding);
81822 pIn1++;
81823 }while( zAffinity[0] );
81824 break;
81827 /* Opcode: MakeRecord P1 P2 P3 P4 *
81828 ** Synopsis: r[P3]=mkrec(r[P1@P2])
81830 ** Convert P2 registers beginning with P1 into the [record format]
81831 ** use as a data record in a database table or as a key
81832 ** in an index. The OP_Column opcode can decode the record later.
81834 ** P4 may be a string that is P2 characters long. The N-th character of the
81835 ** string indicates the column affinity that should be used for the N-th
81836 ** field of the index key.
81838 ** The mapping from character to affinity is given by the SQLITE_AFF_
81839 ** macros defined in sqliteInt.h.
81841 ** If P4 is NULL then all index fields have the affinity BLOB.
81843 case OP_MakeRecord: {
81844 u8 *zNewRecord; /* A buffer to hold the data for the new record */
81845 Mem *pRec; /* The new record */
81846 u64 nData; /* Number of bytes of data space */
81847 int nHdr; /* Number of bytes of header space */
81848 i64 nByte; /* Data space required for this record */
81849 i64 nZero; /* Number of zero bytes at the end of the record */
81850 int nVarint; /* Number of bytes in a varint */
81851 u32 serial_type; /* Type field */
81852 Mem *pData0; /* First field to be combined into the record */
81853 Mem *pLast; /* Last field of the record */
81854 int nField; /* Number of fields in the record */
81855 char *zAffinity; /* The affinity string for the record */
81856 int file_format; /* File format to use for encoding */
81857 int i; /* Space used in zNewRecord[] header */
81858 int j; /* Space used in zNewRecord[] content */
81859 u32 len; /* Length of a field */
81861 /* Assuming the record contains N fields, the record format looks
81862 ** like this:
81864 ** ------------------------------------------------------------------------
81865 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
81866 ** ------------------------------------------------------------------------
81868 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
81869 ** and so forth.
81871 ** Each type field is a varint representing the serial type of the
81872 ** corresponding data element (see sqlite3VdbeSerialType()). The
81873 ** hdr-size field is also a varint which is the offset from the beginning
81874 ** of the record to data0.
81876 nData = 0; /* Number of bytes of data space */
81877 nHdr = 0; /* Number of bytes of header space */
81878 nZero = 0; /* Number of zero bytes at the end of the record */
81879 nField = pOp->p1;
81880 zAffinity = pOp->p4.z;
81881 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
81882 pData0 = &aMem[nField];
81883 nField = pOp->p2;
81884 pLast = &pData0[nField-1];
81885 file_format = p->minWriteFileFormat;
81887 /* Identify the output register */
81888 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
81889 pOut = &aMem[pOp->p3];
81890 memAboutToChange(p, pOut);
81892 /* Apply the requested affinity to all inputs
81894 assert( pData0<=pLast );
81895 if( zAffinity ){
81896 pRec = pData0;
81898 applyAffinity(pRec++, *(zAffinity++), encoding);
81899 assert( zAffinity[0]==0 || pRec<=pLast );
81900 }while( zAffinity[0] );
81903 #ifdef SQLITE_ENABLE_NULL_TRIM
81904 /* NULLs can be safely trimmed from the end of the record, as long as
81905 ** as the schema format is 2 or more and none of the omitted columns
81906 ** have a non-NULL default value. Also, the record must be left with
81907 ** at least one field. If P5>0 then it will be one more than the
81908 ** index of the right-most column with a non-NULL default value */
81909 if( pOp->p5 ){
81910 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
81911 pLast--;
81912 nField--;
81915 #endif
81917 /* Loop through the elements that will make up the record to figure
81918 ** out how much space is required for the new record.
81920 pRec = pLast;
81922 assert( memIsValid(pRec) );
81923 pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
81924 if( pRec->flags & MEM_Zero ){
81925 if( nData ){
81926 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
81927 }else{
81928 nZero += pRec->u.nZero;
81929 len -= pRec->u.nZero;
81932 nData += len;
81933 testcase( serial_type==127 );
81934 testcase( serial_type==128 );
81935 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
81936 if( pRec==pData0 ) break;
81937 pRec--;
81938 }while(1);
81940 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
81941 ** which determines the total number of bytes in the header. The varint
81942 ** value is the size of the header in bytes including the size varint
81943 ** itself. */
81944 testcase( nHdr==126 );
81945 testcase( nHdr==127 );
81946 if( nHdr<=126 ){
81947 /* The common case */
81948 nHdr += 1;
81949 }else{
81950 /* Rare case of a really large header */
81951 nVarint = sqlite3VarintLen(nHdr);
81952 nHdr += nVarint;
81953 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
81955 nByte = nHdr+nData;
81956 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
81957 goto too_big;
81960 /* Make sure the output register has a buffer large enough to store
81961 ** the new record. The output register (pOp->p3) is not allowed to
81962 ** be one of the input registers (because the following call to
81963 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
81965 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
81966 goto no_mem;
81968 zNewRecord = (u8 *)pOut->z;
81970 /* Write the record */
81971 i = putVarint32(zNewRecord, nHdr);
81972 j = nHdr;
81973 assert( pData0<=pLast );
81974 pRec = pData0;
81976 serial_type = pRec->uTemp;
81977 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
81978 ** additional varints, one per column. */
81979 i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
81980 /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
81981 ** immediately follow the header. */
81982 j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
81983 }while( (++pRec)<=pLast );
81984 assert( i==nHdr );
81985 assert( j==nByte );
81987 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
81988 pOut->n = (int)nByte;
81989 pOut->flags = MEM_Blob;
81990 if( nZero ){
81991 pOut->u.nZero = nZero;
81992 pOut->flags |= MEM_Zero;
81994 REGISTER_TRACE(pOp->p3, pOut);
81995 UPDATE_MAX_BLOBSIZE(pOut);
81996 break;
81999 /* Opcode: Count P1 P2 * * *
82000 ** Synopsis: r[P2]=count()
82002 ** Store the number of entries (an integer value) in the table or index
82003 ** opened by cursor P1 in register P2
82005 #ifndef SQLITE_OMIT_BTREECOUNT
82006 case OP_Count: { /* out2 */
82007 i64 nEntry;
82008 BtCursor *pCrsr;
82010 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
82011 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
82012 assert( pCrsr );
82013 nEntry = 0; /* Not needed. Only used to silence a warning. */
82014 rc = sqlite3BtreeCount(pCrsr, &nEntry);
82015 if( rc ) goto abort_due_to_error;
82016 pOut = out2Prerelease(p, pOp);
82017 pOut->u.i = nEntry;
82018 break;
82020 #endif
82022 /* Opcode: Savepoint P1 * * P4 *
82024 ** Open, release or rollback the savepoint named by parameter P4, depending
82025 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
82026 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
82028 case OP_Savepoint: {
82029 int p1; /* Value of P1 operand */
82030 char *zName; /* Name of savepoint */
82031 int nName;
82032 Savepoint *pNew;
82033 Savepoint *pSavepoint;
82034 Savepoint *pTmp;
82035 int iSavepoint;
82036 int ii;
82038 p1 = pOp->p1;
82039 zName = pOp->p4.z;
82041 /* Assert that the p1 parameter is valid. Also that if there is no open
82042 ** transaction, then there cannot be any savepoints.
82044 assert( db->pSavepoint==0 || db->autoCommit==0 );
82045 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
82046 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
82047 assert( checkSavepointCount(db) );
82048 assert( p->bIsReader );
82050 if( p1==SAVEPOINT_BEGIN ){
82051 if( db->nVdbeWrite>0 ){
82052 /* A new savepoint cannot be created if there are active write
82053 ** statements (i.e. open read/write incremental blob handles).
82055 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
82056 rc = SQLITE_BUSY;
82057 }else{
82058 nName = sqlite3Strlen30(zName);
82060 #ifndef SQLITE_OMIT_VIRTUALTABLE
82061 /* This call is Ok even if this savepoint is actually a transaction
82062 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
82063 ** If this is a transaction savepoint being opened, it is guaranteed
82064 ** that the db->aVTrans[] array is empty. */
82065 assert( db->autoCommit==0 || db->nVTrans==0 );
82066 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
82067 db->nStatement+db->nSavepoint);
82068 if( rc!=SQLITE_OK ) goto abort_due_to_error;
82069 #endif
82071 /* Create a new savepoint structure. */
82072 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
82073 if( pNew ){
82074 pNew->zName = (char *)&pNew[1];
82075 memcpy(pNew->zName, zName, nName+1);
82077 /* If there is no open transaction, then mark this as a special
82078 ** "transaction savepoint". */
82079 if( db->autoCommit ){
82080 db->autoCommit = 0;
82081 db->isTransactionSavepoint = 1;
82082 }else{
82083 db->nSavepoint++;
82086 /* Link the new savepoint into the database handle's list. */
82087 pNew->pNext = db->pSavepoint;
82088 db->pSavepoint = pNew;
82089 pNew->nDeferredCons = db->nDeferredCons;
82090 pNew->nDeferredImmCons = db->nDeferredImmCons;
82093 }else{
82094 iSavepoint = 0;
82096 /* Find the named savepoint. If there is no such savepoint, then an
82097 ** an error is returned to the user. */
82098 for(
82099 pSavepoint = db->pSavepoint;
82100 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
82101 pSavepoint = pSavepoint->pNext
82103 iSavepoint++;
82105 if( !pSavepoint ){
82106 sqlite3VdbeError(p, "no such savepoint: %s", zName);
82107 rc = SQLITE_ERROR;
82108 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
82109 /* It is not possible to release (commit) a savepoint if there are
82110 ** active write statements.
82112 sqlite3VdbeError(p, "cannot release savepoint - "
82113 "SQL statements in progress");
82114 rc = SQLITE_BUSY;
82115 }else{
82117 /* Determine whether or not this is a transaction savepoint. If so,
82118 ** and this is a RELEASE command, then the current transaction
82119 ** is committed.
82121 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
82122 if( isTransaction && p1==SAVEPOINT_RELEASE ){
82123 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
82124 goto vdbe_return;
82126 db->autoCommit = 1;
82127 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
82128 p->pc = (int)(pOp - aOp);
82129 db->autoCommit = 0;
82130 p->rc = rc = SQLITE_BUSY;
82131 goto vdbe_return;
82133 db->isTransactionSavepoint = 0;
82134 rc = p->rc;
82135 }else{
82136 int isSchemaChange;
82137 iSavepoint = db->nSavepoint - iSavepoint - 1;
82138 if( p1==SAVEPOINT_ROLLBACK ){
82139 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
82140 for(ii=0; ii<db->nDb; ii++){
82141 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
82142 SQLITE_ABORT_ROLLBACK,
82143 isSchemaChange==0);
82144 if( rc!=SQLITE_OK ) goto abort_due_to_error;
82146 }else{
82147 isSchemaChange = 0;
82149 for(ii=0; ii<db->nDb; ii++){
82150 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
82151 if( rc!=SQLITE_OK ){
82152 goto abort_due_to_error;
82155 if( isSchemaChange ){
82156 sqlite3ExpirePreparedStatements(db);
82157 sqlite3ResetAllSchemasOfConnection(db);
82158 db->mDbFlags |= DBFLAG_SchemaChange;
82162 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
82163 ** savepoints nested inside of the savepoint being operated on. */
82164 while( db->pSavepoint!=pSavepoint ){
82165 pTmp = db->pSavepoint;
82166 db->pSavepoint = pTmp->pNext;
82167 sqlite3DbFree(db, pTmp);
82168 db->nSavepoint--;
82171 /* If it is a RELEASE, then destroy the savepoint being operated on
82172 ** too. If it is a ROLLBACK TO, then set the number of deferred
82173 ** constraint violations present in the database to the value stored
82174 ** when the savepoint was created. */
82175 if( p1==SAVEPOINT_RELEASE ){
82176 assert( pSavepoint==db->pSavepoint );
82177 db->pSavepoint = pSavepoint->pNext;
82178 sqlite3DbFree(db, pSavepoint);
82179 if( !isTransaction ){
82180 db->nSavepoint--;
82182 }else{
82183 db->nDeferredCons = pSavepoint->nDeferredCons;
82184 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
82187 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
82188 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
82189 if( rc!=SQLITE_OK ) goto abort_due_to_error;
82193 if( rc ) goto abort_due_to_error;
82195 break;
82198 /* Opcode: AutoCommit P1 P2 * * *
82200 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
82201 ** back any currently active btree transactions. If there are any active
82202 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
82203 ** there are active writing VMs or active VMs that use shared cache.
82205 ** This instruction causes the VM to halt.
82207 case OP_AutoCommit: {
82208 int desiredAutoCommit;
82209 int iRollback;
82211 desiredAutoCommit = pOp->p1;
82212 iRollback = pOp->p2;
82213 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
82214 assert( desiredAutoCommit==1 || iRollback==0 );
82215 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
82216 assert( p->bIsReader );
82218 if( desiredAutoCommit!=db->autoCommit ){
82219 if( iRollback ){
82220 assert( desiredAutoCommit==1 );
82221 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
82222 db->autoCommit = 1;
82223 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
82224 /* If this instruction implements a COMMIT and other VMs are writing
82225 ** return an error indicating that the other VMs must complete first.
82227 sqlite3VdbeError(p, "cannot commit transaction - "
82228 "SQL statements in progress");
82229 rc = SQLITE_BUSY;
82230 goto abort_due_to_error;
82231 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
82232 goto vdbe_return;
82233 }else{
82234 db->autoCommit = (u8)desiredAutoCommit;
82236 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
82237 p->pc = (int)(pOp - aOp);
82238 db->autoCommit = (u8)(1-desiredAutoCommit);
82239 p->rc = rc = SQLITE_BUSY;
82240 goto vdbe_return;
82242 assert( db->nStatement==0 );
82243 sqlite3CloseSavepoints(db);
82244 if( p->rc==SQLITE_OK ){
82245 rc = SQLITE_DONE;
82246 }else{
82247 rc = SQLITE_ERROR;
82249 goto vdbe_return;
82250 }else{
82251 sqlite3VdbeError(p,
82252 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
82253 (iRollback)?"cannot rollback - no transaction is active":
82254 "cannot commit - no transaction is active"));
82256 rc = SQLITE_ERROR;
82257 goto abort_due_to_error;
82259 break;
82262 /* Opcode: Transaction P1 P2 P3 P4 P5
82264 ** Begin a transaction on database P1 if a transaction is not already
82265 ** active.
82266 ** If P2 is non-zero, then a write-transaction is started, or if a
82267 ** read-transaction is already active, it is upgraded to a write-transaction.
82268 ** If P2 is zero, then a read-transaction is started.
82270 ** P1 is the index of the database file on which the transaction is
82271 ** started. Index 0 is the main database file and index 1 is the
82272 ** file used for temporary tables. Indices of 2 or more are used for
82273 ** attached databases.
82275 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
82276 ** true (this flag is set if the Vdbe may modify more than one row and may
82277 ** throw an ABORT exception), a statement transaction may also be opened.
82278 ** More specifically, a statement transaction is opened iff the database
82279 ** connection is currently not in autocommit mode, or if there are other
82280 ** active statements. A statement transaction allows the changes made by this
82281 ** VDBE to be rolled back after an error without having to roll back the
82282 ** entire transaction. If no error is encountered, the statement transaction
82283 ** will automatically commit when the VDBE halts.
82285 ** If P5!=0 then this opcode also checks the schema cookie against P3
82286 ** and the schema generation counter against P4.
82287 ** The cookie changes its value whenever the database schema changes.
82288 ** This operation is used to detect when that the cookie has changed
82289 ** and that the current process needs to reread the schema. If the schema
82290 ** cookie in P3 differs from the schema cookie in the database header or
82291 ** if the schema generation counter in P4 differs from the current
82292 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
82293 ** halts. The sqlite3_step() wrapper function might then reprepare the
82294 ** statement and rerun it from the beginning.
82296 case OP_Transaction: {
82297 Btree *pBt;
82298 int iMeta;
82299 int iGen;
82301 assert( p->bIsReader );
82302 assert( p->readOnly==0 || pOp->p2==0 );
82303 assert( pOp->p1>=0 && pOp->p1<db->nDb );
82304 assert( DbMaskTest(p->btreeMask, pOp->p1) );
82305 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
82306 rc = SQLITE_READONLY;
82307 goto abort_due_to_error;
82309 pBt = db->aDb[pOp->p1].pBt;
82311 if( pBt ){
82312 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
82313 testcase( rc==SQLITE_BUSY_SNAPSHOT );
82314 testcase( rc==SQLITE_BUSY_RECOVERY );
82315 if( rc!=SQLITE_OK ){
82316 if( (rc&0xff)==SQLITE_BUSY ){
82317 p->pc = (int)(pOp - aOp);
82318 p->rc = rc;
82319 goto vdbe_return;
82321 goto abort_due_to_error;
82324 if( pOp->p2 && p->usesStmtJournal
82325 && (db->autoCommit==0 || db->nVdbeRead>1)
82327 assert( sqlite3BtreeIsInTrans(pBt) );
82328 if( p->iStatement==0 ){
82329 assert( db->nStatement>=0 && db->nSavepoint>=0 );
82330 db->nStatement++;
82331 p->iStatement = db->nSavepoint + db->nStatement;
82334 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
82335 if( rc==SQLITE_OK ){
82336 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
82339 /* Store the current value of the database handles deferred constraint
82340 ** counter. If the statement transaction needs to be rolled back,
82341 ** the value of this counter needs to be restored too. */
82342 p->nStmtDefCons = db->nDeferredCons;
82343 p->nStmtDefImmCons = db->nDeferredImmCons;
82346 /* Gather the schema version number for checking:
82347 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
82348 ** version is checked to ensure that the schema has not changed since the
82349 ** SQL statement was prepared.
82351 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
82352 iGen = db->aDb[pOp->p1].pSchema->iGeneration;
82353 }else{
82354 iGen = iMeta = 0;
82356 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
82357 if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
82358 sqlite3DbFree(db, p->zErrMsg);
82359 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
82360 /* If the schema-cookie from the database file matches the cookie
82361 ** stored with the in-memory representation of the schema, do
82362 ** not reload the schema from the database file.
82364 ** If virtual-tables are in use, this is not just an optimization.
82365 ** Often, v-tables store their data in other SQLite tables, which
82366 ** are queried from within xNext() and other v-table methods using
82367 ** prepared queries. If such a query is out-of-date, we do not want to
82368 ** discard the database schema, as the user code implementing the
82369 ** v-table would have to be ready for the sqlite3_vtab structure itself
82370 ** to be invalidated whenever sqlite3_step() is called from within
82371 ** a v-table method.
82373 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
82374 sqlite3ResetOneSchema(db, pOp->p1);
82376 p->expired = 1;
82377 rc = SQLITE_SCHEMA;
82379 if( rc ) goto abort_due_to_error;
82380 break;
82383 /* Opcode: ReadCookie P1 P2 P3 * *
82385 ** Read cookie number P3 from database P1 and write it into register P2.
82386 ** P3==1 is the schema version. P3==2 is the database format.
82387 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
82388 ** the main database file and P1==1 is the database file used to store
82389 ** temporary tables.
82391 ** There must be a read-lock on the database (either a transaction
82392 ** must be started or there must be an open cursor) before
82393 ** executing this instruction.
82395 case OP_ReadCookie: { /* out2 */
82396 int iMeta;
82397 int iDb;
82398 int iCookie;
82400 assert( p->bIsReader );
82401 iDb = pOp->p1;
82402 iCookie = pOp->p3;
82403 assert( pOp->p3<SQLITE_N_BTREE_META );
82404 assert( iDb>=0 && iDb<db->nDb );
82405 assert( db->aDb[iDb].pBt!=0 );
82406 assert( DbMaskTest(p->btreeMask, iDb) );
82408 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
82409 pOut = out2Prerelease(p, pOp);
82410 pOut->u.i = iMeta;
82411 break;
82414 /* Opcode: SetCookie P1 P2 P3 * *
82416 ** Write the integer value P3 into cookie number P2 of database P1.
82417 ** P2==1 is the schema version. P2==2 is the database format.
82418 ** P2==3 is the recommended pager cache
82419 ** size, and so forth. P1==0 is the main database file and P1==1 is the
82420 ** database file used to store temporary tables.
82422 ** A transaction must be started before executing this opcode.
82424 case OP_SetCookie: {
82425 Db *pDb;
82426 assert( pOp->p2<SQLITE_N_BTREE_META );
82427 assert( pOp->p1>=0 && pOp->p1<db->nDb );
82428 assert( DbMaskTest(p->btreeMask, pOp->p1) );
82429 assert( p->readOnly==0 );
82430 pDb = &db->aDb[pOp->p1];
82431 assert( pDb->pBt!=0 );
82432 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
82433 /* See note about index shifting on OP_ReadCookie */
82434 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
82435 if( pOp->p2==BTREE_SCHEMA_VERSION ){
82436 /* When the schema cookie changes, record the new cookie internally */
82437 pDb->pSchema->schema_cookie = pOp->p3;
82438 db->mDbFlags |= DBFLAG_SchemaChange;
82439 }else if( pOp->p2==BTREE_FILE_FORMAT ){
82440 /* Record changes in the file format */
82441 pDb->pSchema->file_format = pOp->p3;
82443 if( pOp->p1==1 ){
82444 /* Invalidate all prepared statements whenever the TEMP database
82445 ** schema is changed. Ticket #1644 */
82446 sqlite3ExpirePreparedStatements(db);
82447 p->expired = 0;
82449 if( rc ) goto abort_due_to_error;
82450 break;
82453 /* Opcode: OpenRead P1 P2 P3 P4 P5
82454 ** Synopsis: root=P2 iDb=P3
82456 ** Open a read-only cursor for the database table whose root page is
82457 ** P2 in a database file. The database file is determined by P3.
82458 ** P3==0 means the main database, P3==1 means the database used for
82459 ** temporary tables, and P3>1 means used the corresponding attached
82460 ** database. Give the new cursor an identifier of P1. The P1
82461 ** values need not be contiguous but all P1 values should be small integers.
82462 ** It is an error for P1 to be negative.
82464 ** If P5!=0 then use the content of register P2 as the root page, not
82465 ** the value of P2 itself.
82467 ** There will be a read lock on the database whenever there is an
82468 ** open cursor. If the database was unlocked prior to this instruction
82469 ** then a read lock is acquired as part of this instruction. A read
82470 ** lock allows other processes to read the database but prohibits
82471 ** any other process from modifying the database. The read lock is
82472 ** released when all cursors are closed. If this instruction attempts
82473 ** to get a read lock but fails, the script terminates with an
82474 ** SQLITE_BUSY error code.
82476 ** The P4 value may be either an integer (P4_INT32) or a pointer to
82477 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
82478 ** structure, then said structure defines the content and collating
82479 ** sequence of the index being opened. Otherwise, if P4 is an integer
82480 ** value, it is set to the number of columns in the table.
82482 ** See also: OpenWrite, ReopenIdx
82484 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
82485 ** Synopsis: root=P2 iDb=P3
82487 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
82488 ** checks to see if the cursor on P1 is already open with a root page
82489 ** number of P2 and if it is this opcode becomes a no-op. In other words,
82490 ** if the cursor is already open, do not reopen it.
82492 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
82493 ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
82494 ** every other ReopenIdx or OpenRead for the same cursor number.
82496 ** See the OpenRead opcode documentation for additional information.
82498 /* Opcode: OpenWrite P1 P2 P3 P4 P5
82499 ** Synopsis: root=P2 iDb=P3
82501 ** Open a read/write cursor named P1 on the table or index whose root
82502 ** page is P2. Or if P5!=0 use the content of register P2 to find the
82503 ** root page.
82505 ** The P4 value may be either an integer (P4_INT32) or a pointer to
82506 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
82507 ** structure, then said structure defines the content and collating
82508 ** sequence of the index being opened. Otherwise, if P4 is an integer
82509 ** value, it is set to the number of columns in the table, or to the
82510 ** largest index of any column of the table that is actually used.
82512 ** This instruction works just like OpenRead except that it opens the cursor
82513 ** in read/write mode. For a given table, there can be one or more read-only
82514 ** cursors or a single read/write cursor but not both.
82516 ** See also OpenRead.
82518 case OP_ReopenIdx: {
82519 int nField;
82520 KeyInfo *pKeyInfo;
82521 int p2;
82522 int iDb;
82523 int wrFlag;
82524 Btree *pX;
82525 VdbeCursor *pCur;
82526 Db *pDb;
82528 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
82529 assert( pOp->p4type==P4_KEYINFO );
82530 pCur = p->apCsr[pOp->p1];
82531 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
82532 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
82533 goto open_cursor_set_hints;
82535 /* If the cursor is not currently open or is open on a different
82536 ** index, then fall through into OP_OpenRead to force a reopen */
82537 case OP_OpenRead:
82538 case OP_OpenWrite:
82540 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
82541 assert( p->bIsReader );
82542 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
82543 || p->readOnly==0 );
82545 if( p->expired ){
82546 rc = SQLITE_ABORT_ROLLBACK;
82547 goto abort_due_to_error;
82550 nField = 0;
82551 pKeyInfo = 0;
82552 p2 = pOp->p2;
82553 iDb = pOp->p3;
82554 assert( iDb>=0 && iDb<db->nDb );
82555 assert( DbMaskTest(p->btreeMask, iDb) );
82556 pDb = &db->aDb[iDb];
82557 pX = pDb->pBt;
82558 assert( pX!=0 );
82559 if( pOp->opcode==OP_OpenWrite ){
82560 assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
82561 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
82562 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82563 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
82564 p->minWriteFileFormat = pDb->pSchema->file_format;
82566 }else{
82567 wrFlag = 0;
82569 if( pOp->p5 & OPFLAG_P2ISREG ){
82570 assert( p2>0 );
82571 assert( p2<=(p->nMem+1 - p->nCursor) );
82572 pIn2 = &aMem[p2];
82573 assert( memIsValid(pIn2) );
82574 assert( (pIn2->flags & MEM_Int)!=0 );
82575 sqlite3VdbeMemIntegerify(pIn2);
82576 p2 = (int)pIn2->u.i;
82577 /* The p2 value always comes from a prior OP_CreateBtree opcode and
82578 ** that opcode will always set the p2 value to 2 or more or else fail.
82579 ** If there were a failure, the prepared statement would have halted
82580 ** before reaching this instruction. */
82581 assert( p2>=2 );
82583 if( pOp->p4type==P4_KEYINFO ){
82584 pKeyInfo = pOp->p4.pKeyInfo;
82585 assert( pKeyInfo->enc==ENC(db) );
82586 assert( pKeyInfo->db==db );
82587 nField = pKeyInfo->nAllField;
82588 }else if( pOp->p4type==P4_INT32 ){
82589 nField = pOp->p4.i;
82591 assert( pOp->p1>=0 );
82592 assert( nField>=0 );
82593 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
82594 pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
82595 if( pCur==0 ) goto no_mem;
82596 pCur->nullRow = 1;
82597 pCur->isOrdered = 1;
82598 pCur->pgnoRoot = p2;
82599 #ifdef SQLITE_DEBUG
82600 pCur->wrFlag = wrFlag;
82601 #endif
82602 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
82603 pCur->pKeyInfo = pKeyInfo;
82604 /* Set the VdbeCursor.isTable variable. Previous versions of
82605 ** SQLite used to check if the root-page flags were sane at this point
82606 ** and report database corruption if they were not, but this check has
82607 ** since moved into the btree layer. */
82608 pCur->isTable = pOp->p4type!=P4_KEYINFO;
82610 open_cursor_set_hints:
82611 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
82612 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
82613 testcase( pOp->p5 & OPFLAG_BULKCSR );
82614 #ifdef SQLITE_ENABLE_CURSOR_HINTS
82615 testcase( pOp->p2 & OPFLAG_SEEKEQ );
82616 #endif
82617 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
82618 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
82619 if( rc ) goto abort_due_to_error;
82620 break;
82623 /* Opcode: OpenDup P1 P2 * * *
82625 ** Open a new cursor P1 that points to the same ephemeral table as
82626 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
82627 ** opcode. Only ephemeral cursors may be duplicated.
82629 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
82631 case OP_OpenDup: {
82632 VdbeCursor *pOrig; /* The original cursor to be duplicated */
82633 VdbeCursor *pCx; /* The new cursor */
82635 pOrig = p->apCsr[pOp->p2];
82636 assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
82638 pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
82639 if( pCx==0 ) goto no_mem;
82640 pCx->nullRow = 1;
82641 pCx->isEphemeral = 1;
82642 pCx->pKeyInfo = pOrig->pKeyInfo;
82643 pCx->isTable = pOrig->isTable;
82644 rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
82645 pCx->pKeyInfo, pCx->uc.pCursor);
82646 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
82647 ** opened for a database. Since there is already an open cursor when this
82648 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
82649 assert( rc==SQLITE_OK );
82650 break;
82654 /* Opcode: OpenEphemeral P1 P2 * P4 P5
82655 ** Synopsis: nColumn=P2
82657 ** Open a new cursor P1 to a transient table.
82658 ** The cursor is always opened read/write even if
82659 ** the main database is read-only. The ephemeral
82660 ** table is deleted automatically when the cursor is closed.
82662 ** P2 is the number of columns in the ephemeral table.
82663 ** The cursor points to a BTree table if P4==0 and to a BTree index
82664 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
82665 ** that defines the format of keys in the index.
82667 ** The P5 parameter can be a mask of the BTREE_* flags defined
82668 ** in btree.h. These flags control aspects of the operation of
82669 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
82670 ** added automatically.
82672 /* Opcode: OpenAutoindex P1 P2 * P4 *
82673 ** Synopsis: nColumn=P2
82675 ** This opcode works the same as OP_OpenEphemeral. It has a
82676 ** different name to distinguish its use. Tables created using
82677 ** by this opcode will be used for automatically created transient
82678 ** indices in joins.
82680 case OP_OpenAutoindex:
82681 case OP_OpenEphemeral: {
82682 VdbeCursor *pCx;
82683 KeyInfo *pKeyInfo;
82685 static const int vfsFlags =
82686 SQLITE_OPEN_READWRITE |
82687 SQLITE_OPEN_CREATE |
82688 SQLITE_OPEN_EXCLUSIVE |
82689 SQLITE_OPEN_DELETEONCLOSE |
82690 SQLITE_OPEN_TRANSIENT_DB;
82691 assert( pOp->p1>=0 );
82692 assert( pOp->p2>=0 );
82693 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
82694 if( pCx==0 ) goto no_mem;
82695 pCx->nullRow = 1;
82696 pCx->isEphemeral = 1;
82697 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
82698 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
82699 if( rc==SQLITE_OK ){
82700 rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
82702 if( rc==SQLITE_OK ){
82703 /* If a transient index is required, create it by calling
82704 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
82705 ** opening it. If a transient table is required, just use the
82706 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
82708 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
82709 int pgno;
82710 assert( pOp->p4type==P4_KEYINFO );
82711 rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
82712 if( rc==SQLITE_OK ){
82713 assert( pgno==MASTER_ROOT+1 );
82714 assert( pKeyInfo->db==db );
82715 assert( pKeyInfo->enc==ENC(db) );
82716 rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
82717 pKeyInfo, pCx->uc.pCursor);
82719 pCx->isTable = 0;
82720 }else{
82721 rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
82722 0, pCx->uc.pCursor);
82723 pCx->isTable = 1;
82726 if( rc ) goto abort_due_to_error;
82727 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
82728 break;
82731 /* Opcode: SorterOpen P1 P2 P3 P4 *
82733 ** This opcode works like OP_OpenEphemeral except that it opens
82734 ** a transient index that is specifically designed to sort large
82735 ** tables using an external merge-sort algorithm.
82737 ** If argument P3 is non-zero, then it indicates that the sorter may
82738 ** assume that a stable sort considering the first P3 fields of each
82739 ** key is sufficient to produce the required results.
82741 case OP_SorterOpen: {
82742 VdbeCursor *pCx;
82744 assert( pOp->p1>=0 );
82745 assert( pOp->p2>=0 );
82746 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
82747 if( pCx==0 ) goto no_mem;
82748 pCx->pKeyInfo = pOp->p4.pKeyInfo;
82749 assert( pCx->pKeyInfo->db==db );
82750 assert( pCx->pKeyInfo->enc==ENC(db) );
82751 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
82752 if( rc ) goto abort_due_to_error;
82753 break;
82756 /* Opcode: SequenceTest P1 P2 * * *
82757 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
82759 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
82760 ** to P2. Regardless of whether or not the jump is taken, increment the
82761 ** the sequence value.
82763 case OP_SequenceTest: {
82764 VdbeCursor *pC;
82765 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82766 pC = p->apCsr[pOp->p1];
82767 assert( isSorter(pC) );
82768 if( (pC->seqCount++)==0 ){
82769 goto jump_to_p2;
82771 break;
82774 /* Opcode: OpenPseudo P1 P2 P3 * *
82775 ** Synopsis: P3 columns in r[P2]
82777 ** Open a new cursor that points to a fake table that contains a single
82778 ** row of data. The content of that one row is the content of memory
82779 ** register P2. In other words, cursor P1 becomes an alias for the
82780 ** MEM_Blob content contained in register P2.
82782 ** A pseudo-table created by this opcode is used to hold a single
82783 ** row output from the sorter so that the row can be decomposed into
82784 ** individual columns using the OP_Column opcode. The OP_Column opcode
82785 ** is the only cursor opcode that works with a pseudo-table.
82787 ** P3 is the number of fields in the records that will be stored by
82788 ** the pseudo-table.
82790 case OP_OpenPseudo: {
82791 VdbeCursor *pCx;
82793 assert( pOp->p1>=0 );
82794 assert( pOp->p3>=0 );
82795 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
82796 if( pCx==0 ) goto no_mem;
82797 pCx->nullRow = 1;
82798 pCx->seekResult = pOp->p2;
82799 pCx->isTable = 1;
82800 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
82801 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
82802 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
82803 ** which is a performance optimization */
82804 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
82805 assert( pOp->p5==0 );
82806 break;
82809 /* Opcode: Close P1 * * * *
82811 ** Close a cursor previously opened as P1. If P1 is not
82812 ** currently open, this instruction is a no-op.
82814 case OP_Close: {
82815 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82816 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
82817 p->apCsr[pOp->p1] = 0;
82818 break;
82821 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
82822 /* Opcode: ColumnsUsed P1 * * P4 *
82824 ** This opcode (which only exists if SQLite was compiled with
82825 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
82826 ** table or index for cursor P1 are used. P4 is a 64-bit integer
82827 ** (P4_INT64) in which the first 63 bits are one for each of the
82828 ** first 63 columns of the table or index that are actually used
82829 ** by the cursor. The high-order bit is set if any column after
82830 ** the 64th is used.
82832 case OP_ColumnsUsed: {
82833 VdbeCursor *pC;
82834 pC = p->apCsr[pOp->p1];
82835 assert( pC->eCurType==CURTYPE_BTREE );
82836 pC->maskUsed = *(u64*)pOp->p4.pI64;
82837 break;
82839 #endif
82841 /* Opcode: SeekGE P1 P2 P3 P4 *
82842 ** Synopsis: key=r[P3@P4]
82844 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
82845 ** use the value in register P3 as the key. If cursor P1 refers
82846 ** to an SQL index, then P3 is the first in an array of P4 registers
82847 ** that are used as an unpacked index key.
82849 ** Reposition cursor P1 so that it points to the smallest entry that
82850 ** is greater than or equal to the key value. If there are no records
82851 ** greater than or equal to the key and P2 is not zero, then jump to P2.
82853 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
82854 ** opcode will always land on a record that equally equals the key, or
82855 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
82856 ** opcode must be followed by an IdxLE opcode with the same arguments.
82857 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
82858 ** IdxLE opcode will be used on subsequent loop iterations.
82860 ** This opcode leaves the cursor configured to move in forward order,
82861 ** from the beginning toward the end. In other words, the cursor is
82862 ** configured to use Next, not Prev.
82864 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
82866 /* Opcode: SeekGT P1 P2 P3 P4 *
82867 ** Synopsis: key=r[P3@P4]
82869 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
82870 ** use the value in register P3 as a key. If cursor P1 refers
82871 ** to an SQL index, then P3 is the first in an array of P4 registers
82872 ** that are used as an unpacked index key.
82874 ** Reposition cursor P1 so that it points to the smallest entry that
82875 ** is greater than the key value. If there are no records greater than
82876 ** the key and P2 is not zero, then jump to P2.
82878 ** This opcode leaves the cursor configured to move in forward order,
82879 ** from the beginning toward the end. In other words, the cursor is
82880 ** configured to use Next, not Prev.
82882 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
82884 /* Opcode: SeekLT P1 P2 P3 P4 *
82885 ** Synopsis: key=r[P3@P4]
82887 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
82888 ** use the value in register P3 as a key. If cursor P1 refers
82889 ** to an SQL index, then P3 is the first in an array of P4 registers
82890 ** that are used as an unpacked index key.
82892 ** Reposition cursor P1 so that it points to the largest entry that
82893 ** is less than the key value. If there are no records less than
82894 ** the key and P2 is not zero, then jump to P2.
82896 ** This opcode leaves the cursor configured to move in reverse order,
82897 ** from the end toward the beginning. In other words, the cursor is
82898 ** configured to use Prev, not Next.
82900 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
82902 /* Opcode: SeekLE P1 P2 P3 P4 *
82903 ** Synopsis: key=r[P3@P4]
82905 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
82906 ** use the value in register P3 as a key. If cursor P1 refers
82907 ** to an SQL index, then P3 is the first in an array of P4 registers
82908 ** that are used as an unpacked index key.
82910 ** Reposition cursor P1 so that it points to the largest entry that
82911 ** is less than or equal to the key value. If there are no records
82912 ** less than or equal to the key and P2 is not zero, then jump to P2.
82914 ** This opcode leaves the cursor configured to move in reverse order,
82915 ** from the end toward the beginning. In other words, the cursor is
82916 ** configured to use Prev, not Next.
82918 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
82919 ** opcode will always land on a record that equally equals the key, or
82920 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
82921 ** opcode must be followed by an IdxGE opcode with the same arguments.
82922 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
82923 ** IdxGE opcode will be used on subsequent loop iterations.
82925 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
82927 case OP_SeekLT: /* jump, in3 */
82928 case OP_SeekLE: /* jump, in3 */
82929 case OP_SeekGE: /* jump, in3 */
82930 case OP_SeekGT: { /* jump, in3 */
82931 int res; /* Comparison result */
82932 int oc; /* Opcode */
82933 VdbeCursor *pC; /* The cursor to seek */
82934 UnpackedRecord r; /* The key to seek for */
82935 int nField; /* Number of columns or fields in the key */
82936 i64 iKey; /* The rowid we are to seek to */
82937 int eqOnly; /* Only interested in == results */
82939 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82940 assert( pOp->p2!=0 );
82941 pC = p->apCsr[pOp->p1];
82942 assert( pC!=0 );
82943 assert( pC->eCurType==CURTYPE_BTREE );
82944 assert( OP_SeekLE == OP_SeekLT+1 );
82945 assert( OP_SeekGE == OP_SeekLT+2 );
82946 assert( OP_SeekGT == OP_SeekLT+3 );
82947 assert( pC->isOrdered );
82948 assert( pC->uc.pCursor!=0 );
82949 oc = pOp->opcode;
82950 eqOnly = 0;
82951 pC->nullRow = 0;
82952 #ifdef SQLITE_DEBUG
82953 pC->seekOp = pOp->opcode;
82954 #endif
82956 if( pC->isTable ){
82957 /* The BTREE_SEEK_EQ flag is only set on index cursors */
82958 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
82959 || CORRUPT_DB );
82961 /* The input value in P3 might be of any type: integer, real, string,
82962 ** blob, or NULL. But it needs to be an integer before we can do
82963 ** the seek, so convert it. */
82964 pIn3 = &aMem[pOp->p3];
82965 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
82966 applyNumericAffinity(pIn3, 0);
82968 iKey = sqlite3VdbeIntValue(pIn3);
82970 /* If the P3 value could not be converted into an integer without
82971 ** loss of information, then special processing is required... */
82972 if( (pIn3->flags & MEM_Int)==0 ){
82973 if( (pIn3->flags & MEM_Real)==0 ){
82974 /* If the P3 value cannot be converted into any kind of a number,
82975 ** then the seek is not possible, so jump to P2 */
82976 VdbeBranchTaken(1,2); goto jump_to_p2;
82977 break;
82980 /* If the approximation iKey is larger than the actual real search
82981 ** term, substitute >= for > and < for <=. e.g. if the search term
82982 ** is 4.9 and the integer approximation 5:
82984 ** (x > 4.9) -> (x >= 5)
82985 ** (x <= 4.9) -> (x < 5)
82987 if( pIn3->u.r<(double)iKey ){
82988 assert( OP_SeekGE==(OP_SeekGT-1) );
82989 assert( OP_SeekLT==(OP_SeekLE-1) );
82990 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
82991 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
82994 /* If the approximation iKey is smaller than the actual real search
82995 ** term, substitute <= for < and > for >=. */
82996 else if( pIn3->u.r>(double)iKey ){
82997 assert( OP_SeekLE==(OP_SeekLT+1) );
82998 assert( OP_SeekGT==(OP_SeekGE+1) );
82999 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
83000 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
83003 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
83004 pC->movetoTarget = iKey; /* Used by OP_Delete */
83005 if( rc!=SQLITE_OK ){
83006 goto abort_due_to_error;
83008 }else{
83009 /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
83010 ** OP_SeekLE opcodes are allowed, and these must be immediately followed
83011 ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
83013 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
83014 eqOnly = 1;
83015 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
83016 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
83017 assert( pOp[1].p1==pOp[0].p1 );
83018 assert( pOp[1].p2==pOp[0].p2 );
83019 assert( pOp[1].p3==pOp[0].p3 );
83020 assert( pOp[1].p4.i==pOp[0].p4.i );
83023 nField = pOp->p4.i;
83024 assert( pOp->p4type==P4_INT32 );
83025 assert( nField>0 );
83026 r.pKeyInfo = pC->pKeyInfo;
83027 r.nField = (u16)nField;
83029 /* The next line of code computes as follows, only faster:
83030 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
83031 ** r.default_rc = -1;
83032 ** }else{
83033 ** r.default_rc = +1;
83034 ** }
83036 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
83037 assert( oc!=OP_SeekGT || r.default_rc==-1 );
83038 assert( oc!=OP_SeekLE || r.default_rc==-1 );
83039 assert( oc!=OP_SeekGE || r.default_rc==+1 );
83040 assert( oc!=OP_SeekLT || r.default_rc==+1 );
83042 r.aMem = &aMem[pOp->p3];
83043 #ifdef SQLITE_DEBUG
83044 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
83045 #endif
83046 r.eqSeen = 0;
83047 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
83048 if( rc!=SQLITE_OK ){
83049 goto abort_due_to_error;
83051 if( eqOnly && r.eqSeen==0 ){
83052 assert( res!=0 );
83053 goto seek_not_found;
83056 pC->deferredMoveto = 0;
83057 pC->cacheStatus = CACHE_STALE;
83058 #ifdef SQLITE_TEST
83059 sqlite3_search_count++;
83060 #endif
83061 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
83062 if( res<0 || (res==0 && oc==OP_SeekGT) ){
83063 res = 0;
83064 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
83065 if( rc!=SQLITE_OK ){
83066 if( rc==SQLITE_DONE ){
83067 rc = SQLITE_OK;
83068 res = 1;
83069 }else{
83070 goto abort_due_to_error;
83073 }else{
83074 res = 0;
83076 }else{
83077 assert( oc==OP_SeekLT || oc==OP_SeekLE );
83078 if( res>0 || (res==0 && oc==OP_SeekLT) ){
83079 res = 0;
83080 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
83081 if( rc!=SQLITE_OK ){
83082 if( rc==SQLITE_DONE ){
83083 rc = SQLITE_OK;
83084 res = 1;
83085 }else{
83086 goto abort_due_to_error;
83089 }else{
83090 /* res might be negative because the table is empty. Check to
83091 ** see if this is the case.
83093 res = sqlite3BtreeEof(pC->uc.pCursor);
83096 seek_not_found:
83097 assert( pOp->p2>0 );
83098 VdbeBranchTaken(res!=0,2);
83099 if( res ){
83100 goto jump_to_p2;
83101 }else if( eqOnly ){
83102 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
83103 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
83105 break;
83108 /* Opcode: Found P1 P2 P3 P4 *
83109 ** Synopsis: key=r[P3@P4]
83111 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
83112 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
83113 ** record.
83115 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
83116 ** is a prefix of any entry in P1 then a jump is made to P2 and
83117 ** P1 is left pointing at the matching entry.
83119 ** This operation leaves the cursor in a state where it can be
83120 ** advanced in the forward direction. The Next instruction will work,
83121 ** but not the Prev instruction.
83123 ** See also: NotFound, NoConflict, NotExists. SeekGe
83125 /* Opcode: NotFound P1 P2 P3 P4 *
83126 ** Synopsis: key=r[P3@P4]
83128 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
83129 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
83130 ** record.
83132 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
83133 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
83134 ** does contain an entry whose prefix matches the P3/P4 record then control
83135 ** falls through to the next instruction and P1 is left pointing at the
83136 ** matching entry.
83138 ** This operation leaves the cursor in a state where it cannot be
83139 ** advanced in either direction. In other words, the Next and Prev
83140 ** opcodes do not work after this operation.
83142 ** See also: Found, NotExists, NoConflict
83144 /* Opcode: NoConflict P1 P2 P3 P4 *
83145 ** Synopsis: key=r[P3@P4]
83147 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
83148 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
83149 ** record.
83151 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
83152 ** contains any NULL value, jump immediately to P2. If all terms of the
83153 ** record are not-NULL then a check is done to determine if any row in the
83154 ** P1 index btree has a matching key prefix. If there are no matches, jump
83155 ** immediately to P2. If there is a match, fall through and leave the P1
83156 ** cursor pointing to the matching row.
83158 ** This opcode is similar to OP_NotFound with the exceptions that the
83159 ** branch is always taken if any part of the search key input is NULL.
83161 ** This operation leaves the cursor in a state where it cannot be
83162 ** advanced in either direction. In other words, the Next and Prev
83163 ** opcodes do not work after this operation.
83165 ** See also: NotFound, Found, NotExists
83167 case OP_NoConflict: /* jump, in3 */
83168 case OP_NotFound: /* jump, in3 */
83169 case OP_Found: { /* jump, in3 */
83170 int alreadyExists;
83171 int takeJump;
83172 int ii;
83173 VdbeCursor *pC;
83174 int res;
83175 UnpackedRecord *pFree;
83176 UnpackedRecord *pIdxKey;
83177 UnpackedRecord r;
83179 #ifdef SQLITE_TEST
83180 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
83181 #endif
83183 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83184 assert( pOp->p4type==P4_INT32 );
83185 pC = p->apCsr[pOp->p1];
83186 assert( pC!=0 );
83187 #ifdef SQLITE_DEBUG
83188 pC->seekOp = pOp->opcode;
83189 #endif
83190 pIn3 = &aMem[pOp->p3];
83191 assert( pC->eCurType==CURTYPE_BTREE );
83192 assert( pC->uc.pCursor!=0 );
83193 assert( pC->isTable==0 );
83194 if( pOp->p4.i>0 ){
83195 r.pKeyInfo = pC->pKeyInfo;
83196 r.nField = (u16)pOp->p4.i;
83197 r.aMem = pIn3;
83198 #ifdef SQLITE_DEBUG
83199 for(ii=0; ii<r.nField; ii++){
83200 assert( memIsValid(&r.aMem[ii]) );
83201 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
83202 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
83204 #endif
83205 pIdxKey = &r;
83206 pFree = 0;
83207 }else{
83208 assert( pIn3->flags & MEM_Blob );
83209 rc = ExpandBlob(pIn3);
83210 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
83211 if( rc ) goto no_mem;
83212 pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
83213 if( pIdxKey==0 ) goto no_mem;
83214 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
83216 pIdxKey->default_rc = 0;
83217 takeJump = 0;
83218 if( pOp->opcode==OP_NoConflict ){
83219 /* For the OP_NoConflict opcode, take the jump if any of the
83220 ** input fields are NULL, since any key with a NULL will not
83221 ** conflict */
83222 for(ii=0; ii<pIdxKey->nField; ii++){
83223 if( pIdxKey->aMem[ii].flags & MEM_Null ){
83224 takeJump = 1;
83225 break;
83229 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
83230 if( pFree ) sqlite3DbFreeNN(db, pFree);
83231 if( rc!=SQLITE_OK ){
83232 goto abort_due_to_error;
83234 pC->seekResult = res;
83235 alreadyExists = (res==0);
83236 pC->nullRow = 1-alreadyExists;
83237 pC->deferredMoveto = 0;
83238 pC->cacheStatus = CACHE_STALE;
83239 if( pOp->opcode==OP_Found ){
83240 VdbeBranchTaken(alreadyExists!=0,2);
83241 if( alreadyExists ) goto jump_to_p2;
83242 }else{
83243 VdbeBranchTaken(takeJump||alreadyExists==0,2);
83244 if( takeJump || !alreadyExists ) goto jump_to_p2;
83246 break;
83249 /* Opcode: SeekRowid P1 P2 P3 * *
83250 ** Synopsis: intkey=r[P3]
83252 ** P1 is the index of a cursor open on an SQL table btree (with integer
83253 ** keys). If register P3 does not contain an integer or if P1 does not
83254 ** contain a record with rowid P3 then jump immediately to P2.
83255 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
83256 ** a record with rowid P3 then
83257 ** leave the cursor pointing at that record and fall through to the next
83258 ** instruction.
83260 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
83261 ** the P3 register must be guaranteed to contain an integer value. With this
83262 ** opcode, register P3 might not contain an integer.
83264 ** The OP_NotFound opcode performs the same operation on index btrees
83265 ** (with arbitrary multi-value keys).
83267 ** This opcode leaves the cursor in a state where it cannot be advanced
83268 ** in either direction. In other words, the Next and Prev opcodes will
83269 ** not work following this opcode.
83271 ** See also: Found, NotFound, NoConflict, SeekRowid
83273 /* Opcode: NotExists P1 P2 P3 * *
83274 ** Synopsis: intkey=r[P3]
83276 ** P1 is the index of a cursor open on an SQL table btree (with integer
83277 ** keys). P3 is an integer rowid. If P1 does not contain a record with
83278 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
83279 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
83280 ** leave the cursor pointing at that record and fall through to the next
83281 ** instruction.
83283 ** The OP_SeekRowid opcode performs the same operation but also allows the
83284 ** P3 register to contain a non-integer value, in which case the jump is
83285 ** always taken. This opcode requires that P3 always contain an integer.
83287 ** The OP_NotFound opcode performs the same operation on index btrees
83288 ** (with arbitrary multi-value keys).
83290 ** This opcode leaves the cursor in a state where it cannot be advanced
83291 ** in either direction. In other words, the Next and Prev opcodes will
83292 ** not work following this opcode.
83294 ** See also: Found, NotFound, NoConflict, SeekRowid
83296 case OP_SeekRowid: { /* jump, in3 */
83297 VdbeCursor *pC;
83298 BtCursor *pCrsr;
83299 int res;
83300 u64 iKey;
83302 pIn3 = &aMem[pOp->p3];
83303 if( (pIn3->flags & MEM_Int)==0 ){
83304 applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
83305 if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
83307 /* Fall through into OP_NotExists */
83308 case OP_NotExists: /* jump, in3 */
83309 pIn3 = &aMem[pOp->p3];
83310 assert( pIn3->flags & MEM_Int );
83311 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83312 pC = p->apCsr[pOp->p1];
83313 assert( pC!=0 );
83314 #ifdef SQLITE_DEBUG
83315 pC->seekOp = 0;
83316 #endif
83317 assert( pC->isTable );
83318 assert( pC->eCurType==CURTYPE_BTREE );
83319 pCrsr = pC->uc.pCursor;
83320 assert( pCrsr!=0 );
83321 res = 0;
83322 iKey = pIn3->u.i;
83323 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
83324 assert( rc==SQLITE_OK || res==0 );
83325 pC->movetoTarget = iKey; /* Used by OP_Delete */
83326 pC->nullRow = 0;
83327 pC->cacheStatus = CACHE_STALE;
83328 pC->deferredMoveto = 0;
83329 VdbeBranchTaken(res!=0,2);
83330 pC->seekResult = res;
83331 if( res!=0 ){
83332 assert( rc==SQLITE_OK );
83333 if( pOp->p2==0 ){
83334 rc = SQLITE_CORRUPT_BKPT;
83335 }else{
83336 goto jump_to_p2;
83339 if( rc ) goto abort_due_to_error;
83340 break;
83343 /* Opcode: Sequence P1 P2 * * *
83344 ** Synopsis: r[P2]=cursor[P1].ctr++
83346 ** Find the next available sequence number for cursor P1.
83347 ** Write the sequence number into register P2.
83348 ** The sequence number on the cursor is incremented after this
83349 ** instruction.
83351 case OP_Sequence: { /* out2 */
83352 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83353 assert( p->apCsr[pOp->p1]!=0 );
83354 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
83355 pOut = out2Prerelease(p, pOp);
83356 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
83357 break;
83361 /* Opcode: NewRowid P1 P2 P3 * *
83362 ** Synopsis: r[P2]=rowid
83364 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
83365 ** The record number is not previously used as a key in the database
83366 ** table that cursor P1 points to. The new record number is written
83367 ** written to register P2.
83369 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
83370 ** the largest previously generated record number. No new record numbers are
83371 ** allowed to be less than this value. When this value reaches its maximum,
83372 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
83373 ** generated record number. This P3 mechanism is used to help implement the
83374 ** AUTOINCREMENT feature.
83376 case OP_NewRowid: { /* out2 */
83377 i64 v; /* The new rowid */
83378 VdbeCursor *pC; /* Cursor of table to get the new rowid */
83379 int res; /* Result of an sqlite3BtreeLast() */
83380 int cnt; /* Counter to limit the number of searches */
83381 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
83382 VdbeFrame *pFrame; /* Root frame of VDBE */
83384 v = 0;
83385 res = 0;
83386 pOut = out2Prerelease(p, pOp);
83387 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83388 pC = p->apCsr[pOp->p1];
83389 assert( pC!=0 );
83390 assert( pC->eCurType==CURTYPE_BTREE );
83391 assert( pC->uc.pCursor!=0 );
83393 /* The next rowid or record number (different terms for the same
83394 ** thing) is obtained in a two-step algorithm.
83396 ** First we attempt to find the largest existing rowid and add one
83397 ** to that. But if the largest existing rowid is already the maximum
83398 ** positive integer, we have to fall through to the second
83399 ** probabilistic algorithm
83401 ** The second algorithm is to select a rowid at random and see if
83402 ** it already exists in the table. If it does not exist, we have
83403 ** succeeded. If the random rowid does exist, we select a new one
83404 ** and try again, up to 100 times.
83406 assert( pC->isTable );
83408 #ifdef SQLITE_32BIT_ROWID
83409 # define MAX_ROWID 0x7fffffff
83410 #else
83411 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
83412 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
83413 ** to provide the constant while making all compilers happy.
83415 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
83416 #endif
83418 if( !pC->useRandomRowid ){
83419 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
83420 if( rc!=SQLITE_OK ){
83421 goto abort_due_to_error;
83423 if( res ){
83424 v = 1; /* IMP: R-61914-48074 */
83425 }else{
83426 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
83427 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
83428 if( v>=MAX_ROWID ){
83429 pC->useRandomRowid = 1;
83430 }else{
83431 v++; /* IMP: R-29538-34987 */
83436 #ifndef SQLITE_OMIT_AUTOINCREMENT
83437 if( pOp->p3 ){
83438 /* Assert that P3 is a valid memory cell. */
83439 assert( pOp->p3>0 );
83440 if( p->pFrame ){
83441 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
83442 /* Assert that P3 is a valid memory cell. */
83443 assert( pOp->p3<=pFrame->nMem );
83444 pMem = &pFrame->aMem[pOp->p3];
83445 }else{
83446 /* Assert that P3 is a valid memory cell. */
83447 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
83448 pMem = &aMem[pOp->p3];
83449 memAboutToChange(p, pMem);
83451 assert( memIsValid(pMem) );
83453 REGISTER_TRACE(pOp->p3, pMem);
83454 sqlite3VdbeMemIntegerify(pMem);
83455 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
83456 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
83457 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
83458 goto abort_due_to_error;
83460 if( v<pMem->u.i+1 ){
83461 v = pMem->u.i + 1;
83463 pMem->u.i = v;
83465 #endif
83466 if( pC->useRandomRowid ){
83467 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
83468 ** largest possible integer (9223372036854775807) then the database
83469 ** engine starts picking positive candidate ROWIDs at random until
83470 ** it finds one that is not previously used. */
83471 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
83472 ** an AUTOINCREMENT table. */
83473 cnt = 0;
83475 sqlite3_randomness(sizeof(v), &v);
83476 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
83477 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
83478 0, &res))==SQLITE_OK)
83479 && (res==0)
83480 && (++cnt<100));
83481 if( rc ) goto abort_due_to_error;
83482 if( res==0 ){
83483 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
83484 goto abort_due_to_error;
83486 assert( v>0 ); /* EV: R-40812-03570 */
83488 pC->deferredMoveto = 0;
83489 pC->cacheStatus = CACHE_STALE;
83491 pOut->u.i = v;
83492 break;
83495 /* Opcode: Insert P1 P2 P3 P4 P5
83496 ** Synopsis: intkey=r[P3] data=r[P2]
83498 ** Write an entry into the table of cursor P1. A new entry is
83499 ** created if it doesn't already exist or the data for an existing
83500 ** entry is overwritten. The data is the value MEM_Blob stored in register
83501 ** number P2. The key is stored in register P3. The key must
83502 ** be a MEM_Int.
83504 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
83505 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
83506 ** then rowid is stored for subsequent return by the
83507 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
83509 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
83510 ** run faster by avoiding an unnecessary seek on cursor P1. However,
83511 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
83512 ** seeks on the cursor or if the most recent seek used a key equal to P3.
83514 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
83515 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
83516 ** is part of an INSERT operation. The difference is only important to
83517 ** the update hook.
83519 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
83520 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
83521 ** following a successful insert.
83523 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
83524 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
83525 ** and register P2 becomes ephemeral. If the cursor is changed, the
83526 ** value of register P2 will then change. Make sure this does not
83527 ** cause any problems.)
83529 ** This instruction only works on tables. The equivalent instruction
83530 ** for indices is OP_IdxInsert.
83532 /* Opcode: InsertInt P1 P2 P3 P4 P5
83533 ** Synopsis: intkey=P3 data=r[P2]
83535 ** This works exactly like OP_Insert except that the key is the
83536 ** integer value P3, not the value of the integer stored in register P3.
83538 case OP_Insert:
83539 case OP_InsertInt: {
83540 Mem *pData; /* MEM cell holding data for the record to be inserted */
83541 Mem *pKey; /* MEM cell holding key for the record */
83542 VdbeCursor *pC; /* Cursor to table into which insert is written */
83543 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
83544 const char *zDb; /* database name - used by the update hook */
83545 Table *pTab; /* Table structure - used by update and pre-update hooks */
83546 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
83547 BtreePayload x; /* Payload to be inserted */
83549 op = 0;
83550 pData = &aMem[pOp->p2];
83551 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83552 assert( memIsValid(pData) );
83553 pC = p->apCsr[pOp->p1];
83554 assert( pC!=0 );
83555 assert( pC->eCurType==CURTYPE_BTREE );
83556 assert( pC->uc.pCursor!=0 );
83557 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
83558 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
83559 REGISTER_TRACE(pOp->p2, pData);
83561 if( pOp->opcode==OP_Insert ){
83562 pKey = &aMem[pOp->p3];
83563 assert( pKey->flags & MEM_Int );
83564 assert( memIsValid(pKey) );
83565 REGISTER_TRACE(pOp->p3, pKey);
83566 x.nKey = pKey->u.i;
83567 }else{
83568 assert( pOp->opcode==OP_InsertInt );
83569 x.nKey = pOp->p3;
83572 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
83573 assert( pC->iDb>=0 );
83574 zDb = db->aDb[pC->iDb].zDbSName;
83575 pTab = pOp->p4.pTab;
83576 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
83577 op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
83578 }else{
83579 pTab = 0; /* Not needed. Silence a compiler warning. */
83580 zDb = 0; /* Not needed. Silence a compiler warning. */
83583 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
83584 /* Invoke the pre-update hook, if any */
83585 if( db->xPreUpdateCallback
83586 && pOp->p4type==P4_TABLE
83587 && !(pOp->p5 & OPFLAG_ISUPDATE)
83589 sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
83591 if( pOp->p5 & OPFLAG_ISNOOP ) break;
83592 #endif
83594 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
83595 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
83596 assert( pData->flags & (MEM_Blob|MEM_Str) );
83597 x.pData = pData->z;
83598 x.nData = pData->n;
83599 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
83600 if( pData->flags & MEM_Zero ){
83601 x.nZero = pData->u.nZero;
83602 }else{
83603 x.nZero = 0;
83605 x.pKey = 0;
83606 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
83607 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
83609 pC->deferredMoveto = 0;
83610 pC->cacheStatus = CACHE_STALE;
83612 /* Invoke the update-hook if required. */
83613 if( rc ) goto abort_due_to_error;
83614 if( db->xUpdateCallback && op ){
83615 db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
83617 break;
83620 /* Opcode: Delete P1 P2 P3 P4 P5
83622 ** Delete the record at which the P1 cursor is currently pointing.
83624 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
83625 ** the cursor will be left pointing at either the next or the previous
83626 ** record in the table. If it is left pointing at the next record, then
83627 ** the next Next instruction will be a no-op. As a result, in this case
83628 ** it is ok to delete a record from within a Next loop. If
83629 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
83630 ** left in an undefined state.
83632 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
83633 ** delete one of several associated with deleting a table row and all its
83634 ** associated index entries. Exactly one of those deletes is the "primary"
83635 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
83636 ** marked with the AUXDELETE flag.
83638 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
83639 ** change count is incremented (otherwise not).
83641 ** P1 must not be pseudo-table. It has to be a real table with
83642 ** multiple rows.
83644 ** If P4 is not NULL then it points to a Table object. In this case either
83645 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
83646 ** have been positioned using OP_NotFound prior to invoking this opcode in
83647 ** this case. Specifically, if one is configured, the pre-update hook is
83648 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
83649 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
83651 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
83652 ** of the memory cell that contains the value that the rowid of the row will
83653 ** be set to by the update.
83655 case OP_Delete: {
83656 VdbeCursor *pC;
83657 const char *zDb;
83658 Table *pTab;
83659 int opflags;
83661 opflags = pOp->p2;
83662 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83663 pC = p->apCsr[pOp->p1];
83664 assert( pC!=0 );
83665 assert( pC->eCurType==CURTYPE_BTREE );
83666 assert( pC->uc.pCursor!=0 );
83667 assert( pC->deferredMoveto==0 );
83669 #ifdef SQLITE_DEBUG
83670 if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
83671 /* If p5 is zero, the seek operation that positioned the cursor prior to
83672 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
83673 ** the row that is being deleted */
83674 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
83675 assert( pC->movetoTarget==iKey );
83677 #endif
83679 /* If the update-hook or pre-update-hook will be invoked, set zDb to
83680 ** the name of the db to pass as to it. Also set local pTab to a copy
83681 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
83682 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
83683 ** VdbeCursor.movetoTarget to the current rowid. */
83684 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
83685 assert( pC->iDb>=0 );
83686 assert( pOp->p4.pTab!=0 );
83687 zDb = db->aDb[pC->iDb].zDbSName;
83688 pTab = pOp->p4.pTab;
83689 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
83690 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
83692 }else{
83693 zDb = 0; /* Not needed. Silence a compiler warning. */
83694 pTab = 0; /* Not needed. Silence a compiler warning. */
83697 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
83698 /* Invoke the pre-update-hook if required. */
83699 if( db->xPreUpdateCallback && pOp->p4.pTab ){
83700 assert( !(opflags & OPFLAG_ISUPDATE)
83701 || HasRowid(pTab)==0
83702 || (aMem[pOp->p3].flags & MEM_Int)
83704 sqlite3VdbePreUpdateHook(p, pC,
83705 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
83706 zDb, pTab, pC->movetoTarget,
83707 pOp->p3
83710 if( opflags & OPFLAG_ISNOOP ) break;
83711 #endif
83713 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
83714 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
83715 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
83716 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
83718 #ifdef SQLITE_DEBUG
83719 if( p->pFrame==0 ){
83720 if( pC->isEphemeral==0
83721 && (pOp->p5 & OPFLAG_AUXDELETE)==0
83722 && (pC->wrFlag & OPFLAG_FORDELETE)==0
83724 nExtraDelete++;
83726 if( pOp->p2 & OPFLAG_NCHANGE ){
83727 nExtraDelete--;
83730 #endif
83732 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
83733 pC->cacheStatus = CACHE_STALE;
83734 pC->seekResult = 0;
83735 if( rc ) goto abort_due_to_error;
83737 /* Invoke the update-hook if required. */
83738 if( opflags & OPFLAG_NCHANGE ){
83739 p->nChange++;
83740 if( db->xUpdateCallback && HasRowid(pTab) ){
83741 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
83742 pC->movetoTarget);
83743 assert( pC->iDb>=0 );
83747 break;
83749 /* Opcode: ResetCount * * * * *
83751 ** The value of the change counter is copied to the database handle
83752 ** change counter (returned by subsequent calls to sqlite3_changes()).
83753 ** Then the VMs internal change counter resets to 0.
83754 ** This is used by trigger programs.
83756 case OP_ResetCount: {
83757 sqlite3VdbeSetChanges(db, p->nChange);
83758 p->nChange = 0;
83759 break;
83762 /* Opcode: SorterCompare P1 P2 P3 P4
83763 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
83765 ** P1 is a sorter cursor. This instruction compares a prefix of the
83766 ** record blob in register P3 against a prefix of the entry that
83767 ** the sorter cursor currently points to. Only the first P4 fields
83768 ** of r[P3] and the sorter record are compared.
83770 ** If either P3 or the sorter contains a NULL in one of their significant
83771 ** fields (not counting the P4 fields at the end which are ignored) then
83772 ** the comparison is assumed to be equal.
83774 ** Fall through to next instruction if the two records compare equal to
83775 ** each other. Jump to P2 if they are different.
83777 case OP_SorterCompare: {
83778 VdbeCursor *pC;
83779 int res;
83780 int nKeyCol;
83782 pC = p->apCsr[pOp->p1];
83783 assert( isSorter(pC) );
83784 assert( pOp->p4type==P4_INT32 );
83785 pIn3 = &aMem[pOp->p3];
83786 nKeyCol = pOp->p4.i;
83787 res = 0;
83788 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
83789 VdbeBranchTaken(res!=0,2);
83790 if( rc ) goto abort_due_to_error;
83791 if( res ) goto jump_to_p2;
83792 break;
83795 /* Opcode: SorterData P1 P2 P3 * *
83796 ** Synopsis: r[P2]=data
83798 ** Write into register P2 the current sorter data for sorter cursor P1.
83799 ** Then clear the column header cache on cursor P3.
83801 ** This opcode is normally use to move a record out of the sorter and into
83802 ** a register that is the source for a pseudo-table cursor created using
83803 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
83804 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
83805 ** us from having to issue a separate NullRow instruction to clear that cache.
83807 case OP_SorterData: {
83808 VdbeCursor *pC;
83810 pOut = &aMem[pOp->p2];
83811 pC = p->apCsr[pOp->p1];
83812 assert( isSorter(pC) );
83813 rc = sqlite3VdbeSorterRowkey(pC, pOut);
83814 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
83815 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83816 if( rc ) goto abort_due_to_error;
83817 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
83818 break;
83821 /* Opcode: RowData P1 P2 P3 * *
83822 ** Synopsis: r[P2]=data
83824 ** Write into register P2 the complete row content for the row at
83825 ** which cursor P1 is currently pointing.
83826 ** There is no interpretation of the data.
83827 ** It is just copied onto the P2 register exactly as
83828 ** it is found in the database file.
83830 ** If cursor P1 is an index, then the content is the key of the row.
83831 ** If cursor P2 is a table, then the content extracted is the data.
83833 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
83834 ** of a real table, not a pseudo-table.
83836 ** If P3!=0 then this opcode is allowed to make an ephermeral pointer
83837 ** into the database page. That means that the content of the output
83838 ** register will be invalidated as soon as the cursor moves - including
83839 ** moves caused by other cursors that "save" the the current cursors
83840 ** position in order that they can write to the same table. If P3==0
83841 ** then a copy of the data is made into memory. P3!=0 is faster, but
83842 ** P3==0 is safer.
83844 ** If P3!=0 then the content of the P2 register is unsuitable for use
83845 ** in OP_Result and any OP_Result will invalidate the P2 register content.
83846 ** The P2 register content is invalidated by opcodes like OP_Function or
83847 ** by any use of another cursor pointing to the same table.
83849 case OP_RowData: {
83850 VdbeCursor *pC;
83851 BtCursor *pCrsr;
83852 u32 n;
83854 pOut = out2Prerelease(p, pOp);
83856 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83857 pC = p->apCsr[pOp->p1];
83858 assert( pC!=0 );
83859 assert( pC->eCurType==CURTYPE_BTREE );
83860 assert( isSorter(pC)==0 );
83861 assert( pC->nullRow==0 );
83862 assert( pC->uc.pCursor!=0 );
83863 pCrsr = pC->uc.pCursor;
83865 /* The OP_RowData opcodes always follow OP_NotExists or
83866 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
83867 ** that might invalidate the cursor.
83868 ** If this where not the case, on of the following assert()s
83869 ** would fail. Should this ever change (because of changes in the code
83870 ** generator) then the fix would be to insert a call to
83871 ** sqlite3VdbeCursorMoveto().
83873 assert( pC->deferredMoveto==0 );
83874 assert( sqlite3BtreeCursorIsValid(pCrsr) );
83875 #if 0 /* Not required due to the previous to assert() statements */
83876 rc = sqlite3VdbeCursorMoveto(pC);
83877 if( rc!=SQLITE_OK ) goto abort_due_to_error;
83878 #endif
83880 n = sqlite3BtreePayloadSize(pCrsr);
83881 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
83882 goto too_big;
83884 testcase( n==0 );
83885 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
83886 if( rc ) goto abort_due_to_error;
83887 if( !pOp->p3 ) Deephemeralize(pOut);
83888 UPDATE_MAX_BLOBSIZE(pOut);
83889 REGISTER_TRACE(pOp->p2, pOut);
83890 break;
83893 /* Opcode: Rowid P1 P2 * * *
83894 ** Synopsis: r[P2]=rowid
83896 ** Store in register P2 an integer which is the key of the table entry that
83897 ** P1 is currently point to.
83899 ** P1 can be either an ordinary table or a virtual table. There used to
83900 ** be a separate OP_VRowid opcode for use with virtual tables, but this
83901 ** one opcode now works for both table types.
83903 case OP_Rowid: { /* out2 */
83904 VdbeCursor *pC;
83905 i64 v;
83906 sqlite3_vtab *pVtab;
83907 const sqlite3_module *pModule;
83909 pOut = out2Prerelease(p, pOp);
83910 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83911 pC = p->apCsr[pOp->p1];
83912 assert( pC!=0 );
83913 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
83914 if( pC->nullRow ){
83915 pOut->flags = MEM_Null;
83916 break;
83917 }else if( pC->deferredMoveto ){
83918 v = pC->movetoTarget;
83919 #ifndef SQLITE_OMIT_VIRTUALTABLE
83920 }else if( pC->eCurType==CURTYPE_VTAB ){
83921 assert( pC->uc.pVCur!=0 );
83922 pVtab = pC->uc.pVCur->pVtab;
83923 pModule = pVtab->pModule;
83924 assert( pModule->xRowid );
83925 rc = pModule->xRowid(pC->uc.pVCur, &v);
83926 sqlite3VtabImportErrmsg(p, pVtab);
83927 if( rc ) goto abort_due_to_error;
83928 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83929 }else{
83930 assert( pC->eCurType==CURTYPE_BTREE );
83931 assert( pC->uc.pCursor!=0 );
83932 rc = sqlite3VdbeCursorRestore(pC);
83933 if( rc ) goto abort_due_to_error;
83934 if( pC->nullRow ){
83935 pOut->flags = MEM_Null;
83936 break;
83938 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
83940 pOut->u.i = v;
83941 break;
83944 /* Opcode: NullRow P1 * * * *
83946 ** Move the cursor P1 to a null row. Any OP_Column operations
83947 ** that occur while the cursor is on the null row will always
83948 ** write a NULL.
83950 case OP_NullRow: {
83951 VdbeCursor *pC;
83953 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83954 pC = p->apCsr[pOp->p1];
83955 assert( pC!=0 );
83956 pC->nullRow = 1;
83957 pC->cacheStatus = CACHE_STALE;
83958 if( pC->eCurType==CURTYPE_BTREE ){
83959 assert( pC->uc.pCursor!=0 );
83960 sqlite3BtreeClearCursor(pC->uc.pCursor);
83962 break;
83965 /* Opcode: SeekEnd P1 * * * *
83967 ** Position cursor P1 at the end of the btree for the purpose of
83968 ** appending a new entry onto the btree.
83970 ** It is assumed that the cursor is used only for appending and so
83971 ** if the cursor is valid, then the cursor must already be pointing
83972 ** at the end of the btree and so no changes are made to
83973 ** the cursor.
83975 /* Opcode: Last P1 P2 * * *
83977 ** The next use of the Rowid or Column or Prev instruction for P1
83978 ** will refer to the last entry in the database table or index.
83979 ** If the table or index is empty and P2>0, then jump immediately to P2.
83980 ** If P2 is 0 or if the table or index is not empty, fall through
83981 ** to the following instruction.
83983 ** This opcode leaves the cursor configured to move in reverse order,
83984 ** from the end toward the beginning. In other words, the cursor is
83985 ** configured to use Prev, not Next.
83987 case OP_SeekEnd:
83988 case OP_Last: { /* jump */
83989 VdbeCursor *pC;
83990 BtCursor *pCrsr;
83991 int res;
83993 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83994 pC = p->apCsr[pOp->p1];
83995 assert( pC!=0 );
83996 assert( pC->eCurType==CURTYPE_BTREE );
83997 pCrsr = pC->uc.pCursor;
83998 res = 0;
83999 assert( pCrsr!=0 );
84000 #ifdef SQLITE_DEBUG
84001 pC->seekOp = pOp->opcode;
84002 #endif
84003 if( pOp->opcode==OP_SeekEnd ){
84004 assert( pOp->p2==0 );
84005 pC->seekResult = -1;
84006 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
84007 break;
84010 rc = sqlite3BtreeLast(pCrsr, &res);
84011 pC->nullRow = (u8)res;
84012 pC->deferredMoveto = 0;
84013 pC->cacheStatus = CACHE_STALE;
84014 if( rc ) goto abort_due_to_error;
84015 if( pOp->p2>0 ){
84016 VdbeBranchTaken(res!=0,2);
84017 if( res ) goto jump_to_p2;
84019 break;
84022 /* Opcode: IfSmaller P1 P2 P3 * *
84024 ** Estimate the number of rows in the table P1. Jump to P2 if that
84025 ** estimate is less than approximately 2**(0.1*P3).
84027 case OP_IfSmaller: { /* jump */
84028 VdbeCursor *pC;
84029 BtCursor *pCrsr;
84030 int res;
84031 i64 sz;
84033 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84034 pC = p->apCsr[pOp->p1];
84035 assert( pC!=0 );
84036 pCrsr = pC->uc.pCursor;
84037 assert( pCrsr );
84038 rc = sqlite3BtreeFirst(pCrsr, &res);
84039 if( rc ) goto abort_due_to_error;
84040 if( res==0 ){
84041 sz = sqlite3BtreeRowCountEst(pCrsr);
84042 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
84044 VdbeBranchTaken(res!=0,2);
84045 if( res ) goto jump_to_p2;
84046 break;
84050 /* Opcode: SorterSort P1 P2 * * *
84052 ** After all records have been inserted into the Sorter object
84053 ** identified by P1, invoke this opcode to actually do the sorting.
84054 ** Jump to P2 if there are no records to be sorted.
84056 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
84057 ** for Sorter objects.
84059 /* Opcode: Sort P1 P2 * * *
84061 ** This opcode does exactly the same thing as OP_Rewind except that
84062 ** it increments an undocumented global variable used for testing.
84064 ** Sorting is accomplished by writing records into a sorting index,
84065 ** then rewinding that index and playing it back from beginning to
84066 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
84067 ** rewinding so that the global variable will be incremented and
84068 ** regression tests can determine whether or not the optimizer is
84069 ** correctly optimizing out sorts.
84071 case OP_SorterSort: /* jump */
84072 case OP_Sort: { /* jump */
84073 #ifdef SQLITE_TEST
84074 sqlite3_sort_count++;
84075 sqlite3_search_count--;
84076 #endif
84077 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
84078 /* Fall through into OP_Rewind */
84080 /* Opcode: Rewind P1 P2 * * *
84082 ** The next use of the Rowid or Column or Next instruction for P1
84083 ** will refer to the first entry in the database table or index.
84084 ** If the table or index is empty, jump immediately to P2.
84085 ** If the table or index is not empty, fall through to the following
84086 ** instruction.
84088 ** This opcode leaves the cursor configured to move in forward order,
84089 ** from the beginning toward the end. In other words, the cursor is
84090 ** configured to use Next, not Prev.
84092 case OP_Rewind: { /* jump */
84093 VdbeCursor *pC;
84094 BtCursor *pCrsr;
84095 int res;
84097 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84098 pC = p->apCsr[pOp->p1];
84099 assert( pC!=0 );
84100 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
84101 res = 1;
84102 #ifdef SQLITE_DEBUG
84103 pC->seekOp = OP_Rewind;
84104 #endif
84105 if( isSorter(pC) ){
84106 rc = sqlite3VdbeSorterRewind(pC, &res);
84107 }else{
84108 assert( pC->eCurType==CURTYPE_BTREE );
84109 pCrsr = pC->uc.pCursor;
84110 assert( pCrsr );
84111 rc = sqlite3BtreeFirst(pCrsr, &res);
84112 pC->deferredMoveto = 0;
84113 pC->cacheStatus = CACHE_STALE;
84115 if( rc ) goto abort_due_to_error;
84116 pC->nullRow = (u8)res;
84117 assert( pOp->p2>0 && pOp->p2<p->nOp );
84118 VdbeBranchTaken(res!=0,2);
84119 if( res ) goto jump_to_p2;
84120 break;
84123 /* Opcode: Next P1 P2 P3 P4 P5
84125 ** Advance cursor P1 so that it points to the next key/data pair in its
84126 ** table or index. If there are no more key/value pairs then fall through
84127 ** to the following instruction. But if the cursor advance was successful,
84128 ** jump immediately to P2.
84130 ** The Next opcode is only valid following an SeekGT, SeekGE, or
84131 ** OP_Rewind opcode used to position the cursor. Next is not allowed
84132 ** to follow SeekLT, SeekLE, or OP_Last.
84134 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
84135 ** been opened prior to this opcode or the program will segfault.
84137 ** The P3 value is a hint to the btree implementation. If P3==1, that
84138 ** means P1 is an SQL index and that this instruction could have been
84139 ** omitted if that index had been unique. P3 is usually 0. P3 is
84140 ** always either 0 or 1.
84142 ** P4 is always of type P4_ADVANCE. The function pointer points to
84143 ** sqlite3BtreeNext().
84145 ** If P5 is positive and the jump is taken, then event counter
84146 ** number P5-1 in the prepared statement is incremented.
84148 ** See also: Prev, NextIfOpen
84150 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
84152 ** This opcode works just like Next except that if cursor P1 is not
84153 ** open it behaves a no-op.
84155 /* Opcode: Prev P1 P2 P3 P4 P5
84157 ** Back up cursor P1 so that it points to the previous key/data pair in its
84158 ** table or index. If there is no previous key/value pairs then fall through
84159 ** to the following instruction. But if the cursor backup was successful,
84160 ** jump immediately to P2.
84163 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
84164 ** OP_Last opcode used to position the cursor. Prev is not allowed
84165 ** to follow SeekGT, SeekGE, or OP_Rewind.
84167 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
84168 ** not open then the behavior is undefined.
84170 ** The P3 value is a hint to the btree implementation. If P3==1, that
84171 ** means P1 is an SQL index and that this instruction could have been
84172 ** omitted if that index had been unique. P3 is usually 0. P3 is
84173 ** always either 0 or 1.
84175 ** P4 is always of type P4_ADVANCE. The function pointer points to
84176 ** sqlite3BtreePrevious().
84178 ** If P5 is positive and the jump is taken, then event counter
84179 ** number P5-1 in the prepared statement is incremented.
84181 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
84183 ** This opcode works just like Prev except that if cursor P1 is not
84184 ** open it behaves a no-op.
84186 /* Opcode: SorterNext P1 P2 * * P5
84188 ** This opcode works just like OP_Next except that P1 must be a
84189 ** sorter object for which the OP_SorterSort opcode has been
84190 ** invoked. This opcode advances the cursor to the next sorted
84191 ** record, or jumps to P2 if there are no more sorted records.
84193 case OP_SorterNext: { /* jump */
84194 VdbeCursor *pC;
84196 pC = p->apCsr[pOp->p1];
84197 assert( isSorter(pC) );
84198 rc = sqlite3VdbeSorterNext(db, pC);
84199 goto next_tail;
84200 case OP_PrevIfOpen: /* jump */
84201 case OP_NextIfOpen: /* jump */
84202 if( p->apCsr[pOp->p1]==0 ) break;
84203 /* Fall through */
84204 case OP_Prev: /* jump */
84205 case OP_Next: /* jump */
84206 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84207 assert( pOp->p5<ArraySize(p->aCounter) );
84208 pC = p->apCsr[pOp->p1];
84209 assert( pC!=0 );
84210 assert( pC->deferredMoveto==0 );
84211 assert( pC->eCurType==CURTYPE_BTREE );
84212 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
84213 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
84214 assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
84215 assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
84217 /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
84218 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
84219 assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
84220 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
84221 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
84222 assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
84223 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
84224 || pC->seekOp==OP_Last );
84226 rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
84227 next_tail:
84228 pC->cacheStatus = CACHE_STALE;
84229 VdbeBranchTaken(rc==SQLITE_OK,2);
84230 if( rc==SQLITE_OK ){
84231 pC->nullRow = 0;
84232 p->aCounter[pOp->p5]++;
84233 #ifdef SQLITE_TEST
84234 sqlite3_search_count++;
84235 #endif
84236 goto jump_to_p2_and_check_for_interrupt;
84238 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
84239 rc = SQLITE_OK;
84240 pC->nullRow = 1;
84241 goto check_for_interrupt;
84244 /* Opcode: IdxInsert P1 P2 P3 P4 P5
84245 ** Synopsis: key=r[P2]
84247 ** Register P2 holds an SQL index key made using the
84248 ** MakeRecord instructions. This opcode writes that key
84249 ** into the index P1. Data for the entry is nil.
84251 ** If P4 is not zero, then it is the number of values in the unpacked
84252 ** key of reg(P2). In that case, P3 is the index of the first register
84253 ** for the unpacked key. The availability of the unpacked key can sometimes
84254 ** be an optimization.
84256 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
84257 ** that this insert is likely to be an append.
84259 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
84260 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
84261 ** then the change counter is unchanged.
84263 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
84264 ** run faster by avoiding an unnecessary seek on cursor P1. However,
84265 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
84266 ** seeks on the cursor or if the most recent seek used a key equivalent
84267 ** to P2.
84269 ** This instruction only works for indices. The equivalent instruction
84270 ** for tables is OP_Insert.
84272 /* Opcode: SorterInsert P1 P2 * * *
84273 ** Synopsis: key=r[P2]
84275 ** Register P2 holds an SQL index key made using the
84276 ** MakeRecord instructions. This opcode writes that key
84277 ** into the sorter P1. Data for the entry is nil.
84279 case OP_SorterInsert: /* in2 */
84280 case OP_IdxInsert: { /* in2 */
84281 VdbeCursor *pC;
84282 BtreePayload x;
84284 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84285 pC = p->apCsr[pOp->p1];
84286 assert( pC!=0 );
84287 assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
84288 pIn2 = &aMem[pOp->p2];
84289 assert( pIn2->flags & MEM_Blob );
84290 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
84291 assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
84292 assert( pC->isTable==0 );
84293 rc = ExpandBlob(pIn2);
84294 if( rc ) goto abort_due_to_error;
84295 if( pOp->opcode==OP_SorterInsert ){
84296 rc = sqlite3VdbeSorterWrite(pC, pIn2);
84297 }else{
84298 x.nKey = pIn2->n;
84299 x.pKey = pIn2->z;
84300 x.aMem = aMem + pOp->p3;
84301 x.nMem = (u16)pOp->p4.i;
84302 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
84303 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
84304 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
84306 assert( pC->deferredMoveto==0 );
84307 pC->cacheStatus = CACHE_STALE;
84309 if( rc) goto abort_due_to_error;
84310 break;
84313 /* Opcode: IdxDelete P1 P2 P3 * *
84314 ** Synopsis: key=r[P2@P3]
84316 ** The content of P3 registers starting at register P2 form
84317 ** an unpacked index key. This opcode removes that entry from the
84318 ** index opened by cursor P1.
84320 case OP_IdxDelete: {
84321 VdbeCursor *pC;
84322 BtCursor *pCrsr;
84323 int res;
84324 UnpackedRecord r;
84326 assert( pOp->p3>0 );
84327 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
84328 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84329 pC = p->apCsr[pOp->p1];
84330 assert( pC!=0 );
84331 assert( pC->eCurType==CURTYPE_BTREE );
84332 pCrsr = pC->uc.pCursor;
84333 assert( pCrsr!=0 );
84334 assert( pOp->p5==0 );
84335 r.pKeyInfo = pC->pKeyInfo;
84336 r.nField = (u16)pOp->p3;
84337 r.default_rc = 0;
84338 r.aMem = &aMem[pOp->p2];
84339 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
84340 if( rc ) goto abort_due_to_error;
84341 if( res==0 ){
84342 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
84343 if( rc ) goto abort_due_to_error;
84345 assert( pC->deferredMoveto==0 );
84346 pC->cacheStatus = CACHE_STALE;
84347 pC->seekResult = 0;
84348 break;
84351 /* Opcode: DeferredSeek P1 * P3 P4 *
84352 ** Synopsis: Move P3 to P1.rowid if needed
84354 ** P1 is an open index cursor and P3 is a cursor on the corresponding
84355 ** table. This opcode does a deferred seek of the P3 table cursor
84356 ** to the row that corresponds to the current row of P1.
84358 ** This is a deferred seek. Nothing actually happens until
84359 ** the cursor is used to read a record. That way, if no reads
84360 ** occur, no unnecessary I/O happens.
84362 ** P4 may be an array of integers (type P4_INTARRAY) containing
84363 ** one entry for each column in the P3 table. If array entry a(i)
84364 ** is non-zero, then reading column a(i)-1 from cursor P3 is
84365 ** equivalent to performing the deferred seek and then reading column i
84366 ** from P1. This information is stored in P3 and used to redirect
84367 ** reads against P3 over to P1, thus possibly avoiding the need to
84368 ** seek and read cursor P3.
84370 /* Opcode: IdxRowid P1 P2 * * *
84371 ** Synopsis: r[P2]=rowid
84373 ** Write into register P2 an integer which is the last entry in the record at
84374 ** the end of the index key pointed to by cursor P1. This integer should be
84375 ** the rowid of the table entry to which this index entry points.
84377 ** See also: Rowid, MakeRecord.
84379 case OP_DeferredSeek:
84380 case OP_IdxRowid: { /* out2 */
84381 VdbeCursor *pC; /* The P1 index cursor */
84382 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
84383 i64 rowid; /* Rowid that P1 current points to */
84385 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84386 pC = p->apCsr[pOp->p1];
84387 assert( pC!=0 );
84388 assert( pC->eCurType==CURTYPE_BTREE );
84389 assert( pC->uc.pCursor!=0 );
84390 assert( pC->isTable==0 );
84391 assert( pC->deferredMoveto==0 );
84392 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
84394 /* The IdxRowid and Seek opcodes are combined because of the commonality
84395 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
84396 rc = sqlite3VdbeCursorRestore(pC);
84398 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
84399 ** out from under the cursor. That will never happens for an IdxRowid
84400 ** or Seek opcode */
84401 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
84403 if( !pC->nullRow ){
84404 rowid = 0; /* Not needed. Only used to silence a warning. */
84405 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
84406 if( rc!=SQLITE_OK ){
84407 goto abort_due_to_error;
84409 if( pOp->opcode==OP_DeferredSeek ){
84410 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
84411 pTabCur = p->apCsr[pOp->p3];
84412 assert( pTabCur!=0 );
84413 assert( pTabCur->eCurType==CURTYPE_BTREE );
84414 assert( pTabCur->uc.pCursor!=0 );
84415 assert( pTabCur->isTable );
84416 pTabCur->nullRow = 0;
84417 pTabCur->movetoTarget = rowid;
84418 pTabCur->deferredMoveto = 1;
84419 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
84420 pTabCur->aAltMap = pOp->p4.ai;
84421 pTabCur->pAltCursor = pC;
84422 }else{
84423 pOut = out2Prerelease(p, pOp);
84424 pOut->u.i = rowid;
84426 }else{
84427 assert( pOp->opcode==OP_IdxRowid );
84428 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
84430 break;
84433 /* Opcode: IdxGE P1 P2 P3 P4 P5
84434 ** Synopsis: key=r[P3@P4]
84436 ** The P4 register values beginning with P3 form an unpacked index
84437 ** key that omits the PRIMARY KEY. Compare this key value against the index
84438 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
84439 ** fields at the end.
84441 ** If the P1 index entry is greater than or equal to the key value
84442 ** then jump to P2. Otherwise fall through to the next instruction.
84444 /* Opcode: IdxGT P1 P2 P3 P4 P5
84445 ** Synopsis: key=r[P3@P4]
84447 ** The P4 register values beginning with P3 form an unpacked index
84448 ** key that omits the PRIMARY KEY. Compare this key value against the index
84449 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
84450 ** fields at the end.
84452 ** If the P1 index entry is greater than the key value
84453 ** then jump to P2. Otherwise fall through to the next instruction.
84455 /* Opcode: IdxLT P1 P2 P3 P4 P5
84456 ** Synopsis: key=r[P3@P4]
84458 ** The P4 register values beginning with P3 form an unpacked index
84459 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
84460 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
84461 ** ROWID on the P1 index.
84463 ** If the P1 index entry is less than the key value then jump to P2.
84464 ** Otherwise fall through to the next instruction.
84466 /* Opcode: IdxLE P1 P2 P3 P4 P5
84467 ** Synopsis: key=r[P3@P4]
84469 ** The P4 register values beginning with P3 form an unpacked index
84470 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
84471 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
84472 ** ROWID on the P1 index.
84474 ** If the P1 index entry is less than or equal to the key value then jump
84475 ** to P2. Otherwise fall through to the next instruction.
84477 case OP_IdxLE: /* jump */
84478 case OP_IdxGT: /* jump */
84479 case OP_IdxLT: /* jump */
84480 case OP_IdxGE: { /* jump */
84481 VdbeCursor *pC;
84482 int res;
84483 UnpackedRecord r;
84485 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84486 pC = p->apCsr[pOp->p1];
84487 assert( pC!=0 );
84488 assert( pC->isOrdered );
84489 assert( pC->eCurType==CURTYPE_BTREE );
84490 assert( pC->uc.pCursor!=0);
84491 assert( pC->deferredMoveto==0 );
84492 assert( pOp->p5==0 || pOp->p5==1 );
84493 assert( pOp->p4type==P4_INT32 );
84494 r.pKeyInfo = pC->pKeyInfo;
84495 r.nField = (u16)pOp->p4.i;
84496 if( pOp->opcode<OP_IdxLT ){
84497 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
84498 r.default_rc = -1;
84499 }else{
84500 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
84501 r.default_rc = 0;
84503 r.aMem = &aMem[pOp->p3];
84504 #ifdef SQLITE_DEBUG
84505 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
84506 #endif
84507 res = 0; /* Not needed. Only used to silence a warning. */
84508 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
84509 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
84510 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
84511 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
84512 res = -res;
84513 }else{
84514 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
84515 res++;
84517 VdbeBranchTaken(res>0,2);
84518 if( rc ) goto abort_due_to_error;
84519 if( res>0 ) goto jump_to_p2;
84520 break;
84523 /* Opcode: Destroy P1 P2 P3 * *
84525 ** Delete an entire database table or index whose root page in the database
84526 ** file is given by P1.
84528 ** The table being destroyed is in the main database file if P3==0. If
84529 ** P3==1 then the table to be clear is in the auxiliary database file
84530 ** that is used to store tables create using CREATE TEMPORARY TABLE.
84532 ** If AUTOVACUUM is enabled then it is possible that another root page
84533 ** might be moved into the newly deleted root page in order to keep all
84534 ** root pages contiguous at the beginning of the database. The former
84535 ** value of the root page that moved - its value before the move occurred -
84536 ** is stored in register P2. If no page movement was required (because the
84537 ** table being dropped was already the last one in the database) then a
84538 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
84539 ** is stored in register P2.
84541 ** This opcode throws an error if there are any active reader VMs when
84542 ** it is invoked. This is done to avoid the difficulty associated with
84543 ** updating existing cursors when a root page is moved in an AUTOVACUUM
84544 ** database. This error is thrown even if the database is not an AUTOVACUUM
84545 ** db in order to avoid introducing an incompatibility between autovacuum
84546 ** and non-autovacuum modes.
84548 ** See also: Clear
84550 case OP_Destroy: { /* out2 */
84551 int iMoved;
84552 int iDb;
84554 assert( p->readOnly==0 );
84555 assert( pOp->p1>1 );
84556 pOut = out2Prerelease(p, pOp);
84557 pOut->flags = MEM_Null;
84558 if( db->nVdbeRead > db->nVDestroy+1 ){
84559 rc = SQLITE_LOCKED;
84560 p->errorAction = OE_Abort;
84561 goto abort_due_to_error;
84562 }else{
84563 iDb = pOp->p3;
84564 assert( DbMaskTest(p->btreeMask, iDb) );
84565 iMoved = 0; /* Not needed. Only to silence a warning. */
84566 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
84567 pOut->flags = MEM_Int;
84568 pOut->u.i = iMoved;
84569 if( rc ) goto abort_due_to_error;
84570 #ifndef SQLITE_OMIT_AUTOVACUUM
84571 if( iMoved!=0 ){
84572 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
84573 /* All OP_Destroy operations occur on the same btree */
84574 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
84575 resetSchemaOnFault = iDb+1;
84577 #endif
84579 break;
84582 /* Opcode: Clear P1 P2 P3
84584 ** Delete all contents of the database table or index whose root page
84585 ** in the database file is given by P1. But, unlike Destroy, do not
84586 ** remove the table or index from the database file.
84588 ** The table being clear is in the main database file if P2==0. If
84589 ** P2==1 then the table to be clear is in the auxiliary database file
84590 ** that is used to store tables create using CREATE TEMPORARY TABLE.
84592 ** If the P3 value is non-zero, then the table referred to must be an
84593 ** intkey table (an SQL table, not an index). In this case the row change
84594 ** count is incremented by the number of rows in the table being cleared.
84595 ** If P3 is greater than zero, then the value stored in register P3 is
84596 ** also incremented by the number of rows in the table being cleared.
84598 ** See also: Destroy
84600 case OP_Clear: {
84601 int nChange;
84603 nChange = 0;
84604 assert( p->readOnly==0 );
84605 assert( DbMaskTest(p->btreeMask, pOp->p2) );
84606 rc = sqlite3BtreeClearTable(
84607 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
84609 if( pOp->p3 ){
84610 p->nChange += nChange;
84611 if( pOp->p3>0 ){
84612 assert( memIsValid(&aMem[pOp->p3]) );
84613 memAboutToChange(p, &aMem[pOp->p3]);
84614 aMem[pOp->p3].u.i += nChange;
84617 if( rc ) goto abort_due_to_error;
84618 break;
84621 /* Opcode: ResetSorter P1 * * * *
84623 ** Delete all contents from the ephemeral table or sorter
84624 ** that is open on cursor P1.
84626 ** This opcode only works for cursors used for sorting and
84627 ** opened with OP_OpenEphemeral or OP_SorterOpen.
84629 case OP_ResetSorter: {
84630 VdbeCursor *pC;
84632 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84633 pC = p->apCsr[pOp->p1];
84634 assert( pC!=0 );
84635 if( isSorter(pC) ){
84636 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
84637 }else{
84638 assert( pC->eCurType==CURTYPE_BTREE );
84639 assert( pC->isEphemeral );
84640 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
84641 if( rc ) goto abort_due_to_error;
84643 break;
84646 /* Opcode: CreateBtree P1 P2 P3 * *
84647 ** Synopsis: r[P2]=root iDb=P1 flags=P3
84649 ** Allocate a new b-tree in the main database file if P1==0 or in the
84650 ** TEMP database file if P1==1 or in an attached database if
84651 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
84652 ** it must be 2 (BTREE_BLOBKEY) for a index or WITHOUT ROWID table.
84653 ** The root page number of the new b-tree is stored in register P2.
84655 case OP_CreateBtree: { /* out2 */
84656 int pgno;
84657 Db *pDb;
84659 pOut = out2Prerelease(p, pOp);
84660 pgno = 0;
84661 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
84662 assert( pOp->p1>=0 && pOp->p1<db->nDb );
84663 assert( DbMaskTest(p->btreeMask, pOp->p1) );
84664 assert( p->readOnly==0 );
84665 pDb = &db->aDb[pOp->p1];
84666 assert( pDb->pBt!=0 );
84667 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
84668 if( rc ) goto abort_due_to_error;
84669 pOut->u.i = pgno;
84670 break;
84673 /* Opcode: SqlExec * * * P4 *
84675 ** Run the SQL statement or statements specified in the P4 string.
84677 case OP_SqlExec: {
84678 db->nSqlExec++;
84679 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
84680 db->nSqlExec--;
84681 if( rc ) goto abort_due_to_error;
84682 break;
84685 /* Opcode: ParseSchema P1 * * P4 *
84687 ** Read and parse all entries from the SQLITE_MASTER table of database P1
84688 ** that match the WHERE clause P4.
84690 ** This opcode invokes the parser to create a new virtual machine,
84691 ** then runs the new virtual machine. It is thus a re-entrant opcode.
84693 case OP_ParseSchema: {
84694 int iDb;
84695 const char *zMaster;
84696 char *zSql;
84697 InitData initData;
84699 /* Any prepared statement that invokes this opcode will hold mutexes
84700 ** on every btree. This is a prerequisite for invoking
84701 ** sqlite3InitCallback().
84703 #ifdef SQLITE_DEBUG
84704 for(iDb=0; iDb<db->nDb; iDb++){
84705 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
84707 #endif
84709 iDb = pOp->p1;
84710 assert( iDb>=0 && iDb<db->nDb );
84711 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
84712 /* Used to be a conditional */ {
84713 zMaster = MASTER_NAME;
84714 initData.db = db;
84715 initData.iDb = pOp->p1;
84716 initData.pzErrMsg = &p->zErrMsg;
84717 zSql = sqlite3MPrintf(db,
84718 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
84719 db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
84720 if( zSql==0 ){
84721 rc = SQLITE_NOMEM_BKPT;
84722 }else{
84723 assert( db->init.busy==0 );
84724 db->init.busy = 1;
84725 initData.rc = SQLITE_OK;
84726 assert( !db->mallocFailed );
84727 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
84728 if( rc==SQLITE_OK ) rc = initData.rc;
84729 sqlite3DbFreeNN(db, zSql);
84730 db->init.busy = 0;
84733 if( rc ){
84734 sqlite3ResetAllSchemasOfConnection(db);
84735 if( rc==SQLITE_NOMEM ){
84736 goto no_mem;
84738 goto abort_due_to_error;
84740 break;
84743 #if !defined(SQLITE_OMIT_ANALYZE)
84744 /* Opcode: LoadAnalysis P1 * * * *
84746 ** Read the sqlite_stat1 table for database P1 and load the content
84747 ** of that table into the internal index hash table. This will cause
84748 ** the analysis to be used when preparing all subsequent queries.
84750 case OP_LoadAnalysis: {
84751 assert( pOp->p1>=0 && pOp->p1<db->nDb );
84752 rc = sqlite3AnalysisLoad(db, pOp->p1);
84753 if( rc ) goto abort_due_to_error;
84754 break;
84756 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
84758 /* Opcode: DropTable P1 * * P4 *
84760 ** Remove the internal (in-memory) data structures that describe
84761 ** the table named P4 in database P1. This is called after a table
84762 ** is dropped from disk (using the Destroy opcode) in order to keep
84763 ** the internal representation of the
84764 ** schema consistent with what is on disk.
84766 case OP_DropTable: {
84767 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
84768 break;
84771 /* Opcode: DropIndex P1 * * P4 *
84773 ** Remove the internal (in-memory) data structures that describe
84774 ** the index named P4 in database P1. This is called after an index
84775 ** is dropped from disk (using the Destroy opcode)
84776 ** in order to keep the internal representation of the
84777 ** schema consistent with what is on disk.
84779 case OP_DropIndex: {
84780 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
84781 break;
84784 /* Opcode: DropTrigger P1 * * P4 *
84786 ** Remove the internal (in-memory) data structures that describe
84787 ** the trigger named P4 in database P1. This is called after a trigger
84788 ** is dropped from disk (using the Destroy opcode) in order to keep
84789 ** the internal representation of the
84790 ** schema consistent with what is on disk.
84792 case OP_DropTrigger: {
84793 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
84794 break;
84798 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
84799 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
84801 ** Do an analysis of the currently open database. Store in
84802 ** register P1 the text of an error message describing any problems.
84803 ** If no problems are found, store a NULL in register P1.
84805 ** The register P3 contains one less than the maximum number of allowed errors.
84806 ** At most reg(P3) errors will be reported.
84807 ** In other words, the analysis stops as soon as reg(P1) errors are
84808 ** seen. Reg(P1) is updated with the number of errors remaining.
84810 ** The root page numbers of all tables in the database are integers
84811 ** stored in P4_INTARRAY argument.
84813 ** If P5 is not zero, the check is done on the auxiliary database
84814 ** file, not the main database file.
84816 ** This opcode is used to implement the integrity_check pragma.
84818 case OP_IntegrityCk: {
84819 int nRoot; /* Number of tables to check. (Number of root pages.) */
84820 int *aRoot; /* Array of rootpage numbers for tables to be checked */
84821 int nErr; /* Number of errors reported */
84822 char *z; /* Text of the error report */
84823 Mem *pnErr; /* Register keeping track of errors remaining */
84825 assert( p->bIsReader );
84826 nRoot = pOp->p2;
84827 aRoot = pOp->p4.ai;
84828 assert( nRoot>0 );
84829 assert( aRoot[0]==nRoot );
84830 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
84831 pnErr = &aMem[pOp->p3];
84832 assert( (pnErr->flags & MEM_Int)!=0 );
84833 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
84834 pIn1 = &aMem[pOp->p1];
84835 assert( pOp->p5<db->nDb );
84836 assert( DbMaskTest(p->btreeMask, pOp->p5) );
84837 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
84838 (int)pnErr->u.i+1, &nErr);
84839 sqlite3VdbeMemSetNull(pIn1);
84840 if( nErr==0 ){
84841 assert( z==0 );
84842 }else if( z==0 ){
84843 goto no_mem;
84844 }else{
84845 pnErr->u.i -= nErr-1;
84846 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
84848 UPDATE_MAX_BLOBSIZE(pIn1);
84849 sqlite3VdbeChangeEncoding(pIn1, encoding);
84850 break;
84852 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
84854 /* Opcode: RowSetAdd P1 P2 * * *
84855 ** Synopsis: rowset(P1)=r[P2]
84857 ** Insert the integer value held by register P2 into a RowSet object
84858 ** held in register P1.
84860 ** An assertion fails if P2 is not an integer.
84862 case OP_RowSetAdd: { /* in1, in2 */
84863 pIn1 = &aMem[pOp->p1];
84864 pIn2 = &aMem[pOp->p2];
84865 assert( (pIn2->flags & MEM_Int)!=0 );
84866 if( (pIn1->flags & MEM_RowSet)==0 ){
84867 sqlite3VdbeMemSetRowSet(pIn1);
84868 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
84870 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
84871 break;
84874 /* Opcode: RowSetRead P1 P2 P3 * *
84875 ** Synopsis: r[P3]=rowset(P1)
84877 ** Extract the smallest value from the RowSet object in P1
84878 ** and put that value into register P3.
84879 ** Or, if RowSet object P1 is initially empty, leave P3
84880 ** unchanged and jump to instruction P2.
84882 case OP_RowSetRead: { /* jump, in1, out3 */
84883 i64 val;
84885 pIn1 = &aMem[pOp->p1];
84886 if( (pIn1->flags & MEM_RowSet)==0
84887 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
84889 /* The boolean index is empty */
84890 sqlite3VdbeMemSetNull(pIn1);
84891 VdbeBranchTaken(1,2);
84892 goto jump_to_p2_and_check_for_interrupt;
84893 }else{
84894 /* A value was pulled from the index */
84895 VdbeBranchTaken(0,2);
84896 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
84898 goto check_for_interrupt;
84901 /* Opcode: RowSetTest P1 P2 P3 P4
84902 ** Synopsis: if r[P3] in rowset(P1) goto P2
84904 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
84905 ** contains a RowSet object and that RowSet object contains
84906 ** the value held in P3, jump to register P2. Otherwise, insert the
84907 ** integer in P3 into the RowSet and continue on to the
84908 ** next opcode.
84910 ** The RowSet object is optimized for the case where sets of integers
84911 ** are inserted in distinct phases, which each set contains no duplicates.
84912 ** Each set is identified by a unique P4 value. The first set
84913 ** must have P4==0, the final set must have P4==-1, and for all other sets
84914 ** must have P4>0.
84916 ** This allows optimizations: (a) when P4==0 there is no need to test
84917 ** the RowSet object for P3, as it is guaranteed not to contain it,
84918 ** (b) when P4==-1 there is no need to insert the value, as it will
84919 ** never be tested for, and (c) when a value that is part of set X is
84920 ** inserted, there is no need to search to see if the same value was
84921 ** previously inserted as part of set X (only if it was previously
84922 ** inserted as part of some other set).
84924 case OP_RowSetTest: { /* jump, in1, in3 */
84925 int iSet;
84926 int exists;
84928 pIn1 = &aMem[pOp->p1];
84929 pIn3 = &aMem[pOp->p3];
84930 iSet = pOp->p4.i;
84931 assert( pIn3->flags&MEM_Int );
84933 /* If there is anything other than a rowset object in memory cell P1,
84934 ** delete it now and initialize P1 with an empty rowset
84936 if( (pIn1->flags & MEM_RowSet)==0 ){
84937 sqlite3VdbeMemSetRowSet(pIn1);
84938 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
84941 assert( pOp->p4type==P4_INT32 );
84942 assert( iSet==-1 || iSet>=0 );
84943 if( iSet ){
84944 exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
84945 VdbeBranchTaken(exists!=0,2);
84946 if( exists ) goto jump_to_p2;
84948 if( iSet>=0 ){
84949 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
84951 break;
84955 #ifndef SQLITE_OMIT_TRIGGER
84957 /* Opcode: Program P1 P2 P3 P4 P5
84959 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
84961 ** P1 contains the address of the memory cell that contains the first memory
84962 ** cell in an array of values used as arguments to the sub-program. P2
84963 ** contains the address to jump to if the sub-program throws an IGNORE
84964 ** exception using the RAISE() function. Register P3 contains the address
84965 ** of a memory cell in this (the parent) VM that is used to allocate the
84966 ** memory required by the sub-vdbe at runtime.
84968 ** P4 is a pointer to the VM containing the trigger program.
84970 ** If P5 is non-zero, then recursive program invocation is enabled.
84972 case OP_Program: { /* jump */
84973 int nMem; /* Number of memory registers for sub-program */
84974 int nByte; /* Bytes of runtime space required for sub-program */
84975 Mem *pRt; /* Register to allocate runtime space */
84976 Mem *pMem; /* Used to iterate through memory cells */
84977 Mem *pEnd; /* Last memory cell in new array */
84978 VdbeFrame *pFrame; /* New vdbe frame to execute in */
84979 SubProgram *pProgram; /* Sub-program to execute */
84980 void *t; /* Token identifying trigger */
84982 pProgram = pOp->p4.pProgram;
84983 pRt = &aMem[pOp->p3];
84984 assert( pProgram->nOp>0 );
84986 /* If the p5 flag is clear, then recursive invocation of triggers is
84987 ** disabled for backwards compatibility (p5 is set if this sub-program
84988 ** is really a trigger, not a foreign key action, and the flag set
84989 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
84991 ** It is recursive invocation of triggers, at the SQL level, that is
84992 ** disabled. In some cases a single trigger may generate more than one
84993 ** SubProgram (if the trigger may be executed with more than one different
84994 ** ON CONFLICT algorithm). SubProgram structures associated with a
84995 ** single trigger all have the same value for the SubProgram.token
84996 ** variable. */
84997 if( pOp->p5 ){
84998 t = pProgram->token;
84999 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
85000 if( pFrame ) break;
85003 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
85004 rc = SQLITE_ERROR;
85005 sqlite3VdbeError(p, "too many levels of trigger recursion");
85006 goto abort_due_to_error;
85009 /* Register pRt is used to store the memory required to save the state
85010 ** of the current program, and the memory required at runtime to execute
85011 ** the trigger program. If this trigger has been fired before, then pRt
85012 ** is already allocated. Otherwise, it must be initialized. */
85013 if( (pRt->flags&MEM_Frame)==0 ){
85014 /* SubProgram.nMem is set to the number of memory cells used by the
85015 ** program stored in SubProgram.aOp. As well as these, one memory
85016 ** cell is required for each cursor used by the program. Set local
85017 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
85019 nMem = pProgram->nMem + pProgram->nCsr;
85020 assert( nMem>0 );
85021 if( pProgram->nCsr==0 ) nMem++;
85022 nByte = ROUND8(sizeof(VdbeFrame))
85023 + nMem * sizeof(Mem)
85024 + pProgram->nCsr * sizeof(VdbeCursor*)
85025 + (pProgram->nOp + 7)/8;
85026 pFrame = sqlite3DbMallocZero(db, nByte);
85027 if( !pFrame ){
85028 goto no_mem;
85030 sqlite3VdbeMemRelease(pRt);
85031 pRt->flags = MEM_Frame;
85032 pRt->u.pFrame = pFrame;
85034 pFrame->v = p;
85035 pFrame->nChildMem = nMem;
85036 pFrame->nChildCsr = pProgram->nCsr;
85037 pFrame->pc = (int)(pOp - aOp);
85038 pFrame->aMem = p->aMem;
85039 pFrame->nMem = p->nMem;
85040 pFrame->apCsr = p->apCsr;
85041 pFrame->nCursor = p->nCursor;
85042 pFrame->aOp = p->aOp;
85043 pFrame->nOp = p->nOp;
85044 pFrame->token = pProgram->token;
85045 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
85046 pFrame->anExec = p->anExec;
85047 #endif
85049 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
85050 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
85051 pMem->flags = MEM_Undefined;
85052 pMem->db = db;
85054 }else{
85055 pFrame = pRt->u.pFrame;
85056 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
85057 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
85058 assert( pProgram->nCsr==pFrame->nChildCsr );
85059 assert( (int)(pOp - aOp)==pFrame->pc );
85062 p->nFrame++;
85063 pFrame->pParent = p->pFrame;
85064 pFrame->lastRowid = db->lastRowid;
85065 pFrame->nChange = p->nChange;
85066 pFrame->nDbChange = p->db->nChange;
85067 assert( pFrame->pAuxData==0 );
85068 pFrame->pAuxData = p->pAuxData;
85069 p->pAuxData = 0;
85070 p->nChange = 0;
85071 p->pFrame = pFrame;
85072 p->aMem = aMem = VdbeFrameMem(pFrame);
85073 p->nMem = pFrame->nChildMem;
85074 p->nCursor = (u16)pFrame->nChildCsr;
85075 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
85076 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
85077 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
85078 p->aOp = aOp = pProgram->aOp;
85079 p->nOp = pProgram->nOp;
85080 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
85081 p->anExec = 0;
85082 #endif
85083 pOp = &aOp[-1];
85085 break;
85088 /* Opcode: Param P1 P2 * * *
85090 ** This opcode is only ever present in sub-programs called via the
85091 ** OP_Program instruction. Copy a value currently stored in a memory
85092 ** cell of the calling (parent) frame to cell P2 in the current frames
85093 ** address space. This is used by trigger programs to access the new.*
85094 ** and old.* values.
85096 ** The address of the cell in the parent frame is determined by adding
85097 ** the value of the P1 argument to the value of the P1 argument to the
85098 ** calling OP_Program instruction.
85100 case OP_Param: { /* out2 */
85101 VdbeFrame *pFrame;
85102 Mem *pIn;
85103 pOut = out2Prerelease(p, pOp);
85104 pFrame = p->pFrame;
85105 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
85106 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
85107 break;
85110 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
85112 #ifndef SQLITE_OMIT_FOREIGN_KEY
85113 /* Opcode: FkCounter P1 P2 * * *
85114 ** Synopsis: fkctr[P1]+=P2
85116 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
85117 ** If P1 is non-zero, the database constraint counter is incremented
85118 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
85119 ** statement counter is incremented (immediate foreign key constraints).
85121 case OP_FkCounter: {
85122 if( db->flags & SQLITE_DeferFKs ){
85123 db->nDeferredImmCons += pOp->p2;
85124 }else if( pOp->p1 ){
85125 db->nDeferredCons += pOp->p2;
85126 }else{
85127 p->nFkConstraint += pOp->p2;
85129 break;
85132 /* Opcode: FkIfZero P1 P2 * * *
85133 ** Synopsis: if fkctr[P1]==0 goto P2
85135 ** This opcode tests if a foreign key constraint-counter is currently zero.
85136 ** If so, jump to instruction P2. Otherwise, fall through to the next
85137 ** instruction.
85139 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
85140 ** is zero (the one that counts deferred constraint violations). If P1 is
85141 ** zero, the jump is taken if the statement constraint-counter is zero
85142 ** (immediate foreign key constraint violations).
85144 case OP_FkIfZero: { /* jump */
85145 if( pOp->p1 ){
85146 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
85147 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
85148 }else{
85149 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
85150 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
85152 break;
85154 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
85156 #ifndef SQLITE_OMIT_AUTOINCREMENT
85157 /* Opcode: MemMax P1 P2 * * *
85158 ** Synopsis: r[P1]=max(r[P1],r[P2])
85160 ** P1 is a register in the root frame of this VM (the root frame is
85161 ** different from the current frame if this instruction is being executed
85162 ** within a sub-program). Set the value of register P1 to the maximum of
85163 ** its current value and the value in register P2.
85165 ** This instruction throws an error if the memory cell is not initially
85166 ** an integer.
85168 case OP_MemMax: { /* in2 */
85169 VdbeFrame *pFrame;
85170 if( p->pFrame ){
85171 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
85172 pIn1 = &pFrame->aMem[pOp->p1];
85173 }else{
85174 pIn1 = &aMem[pOp->p1];
85176 assert( memIsValid(pIn1) );
85177 sqlite3VdbeMemIntegerify(pIn1);
85178 pIn2 = &aMem[pOp->p2];
85179 sqlite3VdbeMemIntegerify(pIn2);
85180 if( pIn1->u.i<pIn2->u.i){
85181 pIn1->u.i = pIn2->u.i;
85183 break;
85185 #endif /* SQLITE_OMIT_AUTOINCREMENT */
85187 /* Opcode: IfPos P1 P2 P3 * *
85188 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
85190 ** Register P1 must contain an integer.
85191 ** If the value of register P1 is 1 or greater, subtract P3 from the
85192 ** value in P1 and jump to P2.
85194 ** If the initial value of register P1 is less than 1, then the
85195 ** value is unchanged and control passes through to the next instruction.
85197 case OP_IfPos: { /* jump, in1 */
85198 pIn1 = &aMem[pOp->p1];
85199 assert( pIn1->flags&MEM_Int );
85200 VdbeBranchTaken( pIn1->u.i>0, 2);
85201 if( pIn1->u.i>0 ){
85202 pIn1->u.i -= pOp->p3;
85203 goto jump_to_p2;
85205 break;
85208 /* Opcode: OffsetLimit P1 P2 P3 * *
85209 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
85211 ** This opcode performs a commonly used computation associated with
85212 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
85213 ** holds the offset counter. The opcode computes the combined value
85214 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
85215 ** value computed is the total number of rows that will need to be
85216 ** visited in order to complete the query.
85218 ** If r[P3] is zero or negative, that means there is no OFFSET
85219 ** and r[P2] is set to be the value of the LIMIT, r[P1].
85221 ** if r[P1] is zero or negative, that means there is no LIMIT
85222 ** and r[P2] is set to -1.
85224 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
85226 case OP_OffsetLimit: { /* in1, out2, in3 */
85227 i64 x;
85228 pIn1 = &aMem[pOp->p1];
85229 pIn3 = &aMem[pOp->p3];
85230 pOut = out2Prerelease(p, pOp);
85231 assert( pIn1->flags & MEM_Int );
85232 assert( pIn3->flags & MEM_Int );
85233 x = pIn1->u.i;
85234 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
85235 /* If the LIMIT is less than or equal to zero, loop forever. This
85236 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
85237 ** also loop forever. This is undocumented. In fact, one could argue
85238 ** that the loop should terminate. But assuming 1 billion iterations
85239 ** per second (far exceeding the capabilities of any current hardware)
85240 ** it would take nearly 300 years to actually reach the limit. So
85241 ** looping forever is a reasonable approximation. */
85242 pOut->u.i = -1;
85243 }else{
85244 pOut->u.i = x;
85246 break;
85249 /* Opcode: IfNotZero P1 P2 * * *
85250 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
85252 ** Register P1 must contain an integer. If the content of register P1 is
85253 ** initially greater than zero, then decrement the value in register P1.
85254 ** If it is non-zero (negative or positive) and then also jump to P2.
85255 ** If register P1 is initially zero, leave it unchanged and fall through.
85257 case OP_IfNotZero: { /* jump, in1 */
85258 pIn1 = &aMem[pOp->p1];
85259 assert( pIn1->flags&MEM_Int );
85260 VdbeBranchTaken(pIn1->u.i<0, 2);
85261 if( pIn1->u.i ){
85262 if( pIn1->u.i>0 ) pIn1->u.i--;
85263 goto jump_to_p2;
85265 break;
85268 /* Opcode: DecrJumpZero P1 P2 * * *
85269 ** Synopsis: if (--r[P1])==0 goto P2
85271 ** Register P1 must hold an integer. Decrement the value in P1
85272 ** and jump to P2 if the new value is exactly zero.
85274 case OP_DecrJumpZero: { /* jump, in1 */
85275 pIn1 = &aMem[pOp->p1];
85276 assert( pIn1->flags&MEM_Int );
85277 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
85278 VdbeBranchTaken(pIn1->u.i==0, 2);
85279 if( pIn1->u.i==0 ) goto jump_to_p2;
85280 break;
85284 /* Opcode: AggStep0 * P2 P3 P4 P5
85285 ** Synopsis: accum=r[P3] step(r[P2@P5])
85287 ** Execute the step function for an aggregate. The
85288 ** function has P5 arguments. P4 is a pointer to the FuncDef
85289 ** structure that specifies the function. Register P3 is the
85290 ** accumulator.
85292 ** The P5 arguments are taken from register P2 and its
85293 ** successors.
85295 /* Opcode: AggStep * P2 P3 P4 P5
85296 ** Synopsis: accum=r[P3] step(r[P2@P5])
85298 ** Execute the step function for an aggregate. The
85299 ** function has P5 arguments. P4 is a pointer to an sqlite3_context
85300 ** object that is used to run the function. Register P3 is
85301 ** as the accumulator.
85303 ** The P5 arguments are taken from register P2 and its
85304 ** successors.
85306 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
85307 ** the FuncDef stored in P4 is converted into an sqlite3_context and
85308 ** the opcode is changed. In this way, the initialization of the
85309 ** sqlite3_context only happens once, instead of on each call to the
85310 ** step function.
85312 case OP_AggStep0: {
85313 int n;
85314 sqlite3_context *pCtx;
85316 assert( pOp->p4type==P4_FUNCDEF );
85317 n = pOp->p5;
85318 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
85319 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
85320 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
85321 pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
85322 if( pCtx==0 ) goto no_mem;
85323 pCtx->pMem = 0;
85324 pCtx->pFunc = pOp->p4.pFunc;
85325 pCtx->iOp = (int)(pOp - aOp);
85326 pCtx->pVdbe = p;
85327 pCtx->argc = n;
85328 pOp->p4type = P4_FUNCCTX;
85329 pOp->p4.pCtx = pCtx;
85330 pOp->opcode = OP_AggStep;
85331 /* Fall through into OP_AggStep */
85333 case OP_AggStep: {
85334 int i;
85335 sqlite3_context *pCtx;
85336 Mem *pMem;
85337 Mem t;
85339 assert( pOp->p4type==P4_FUNCCTX );
85340 pCtx = pOp->p4.pCtx;
85341 pMem = &aMem[pOp->p3];
85343 /* If this function is inside of a trigger, the register array in aMem[]
85344 ** might change from one evaluation to the next. The next block of code
85345 ** checks to see if the register array has changed, and if so it
85346 ** reinitializes the relavant parts of the sqlite3_context object */
85347 if( pCtx->pMem != pMem ){
85348 pCtx->pMem = pMem;
85349 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
85352 #ifdef SQLITE_DEBUG
85353 for(i=0; i<pCtx->argc; i++){
85354 assert( memIsValid(pCtx->argv[i]) );
85355 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
85357 #endif
85359 pMem->n++;
85360 sqlite3VdbeMemInit(&t, db, MEM_Null);
85361 pCtx->pOut = &t;
85362 pCtx->fErrorOrAux = 0;
85363 pCtx->skipFlag = 0;
85364 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
85365 if( pCtx->fErrorOrAux ){
85366 if( pCtx->isError ){
85367 sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
85368 rc = pCtx->isError;
85370 sqlite3VdbeMemRelease(&t);
85371 if( rc ) goto abort_due_to_error;
85372 }else{
85373 assert( t.flags==MEM_Null );
85375 if( pCtx->skipFlag ){
85376 assert( pOp[-1].opcode==OP_CollSeq );
85377 i = pOp[-1].p1;
85378 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
85380 break;
85383 /* Opcode: AggFinal P1 P2 * P4 *
85384 ** Synopsis: accum=r[P1] N=P2
85386 ** Execute the finalizer function for an aggregate. P1 is
85387 ** the memory location that is the accumulator for the aggregate.
85389 ** P2 is the number of arguments that the step function takes and
85390 ** P4 is a pointer to the FuncDef for this function. The P2
85391 ** argument is not used by this opcode. It is only there to disambiguate
85392 ** functions that can take varying numbers of arguments. The
85393 ** P4 argument is only needed for the degenerate case where
85394 ** the step function was not previously called.
85396 case OP_AggFinal: {
85397 Mem *pMem;
85398 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
85399 pMem = &aMem[pOp->p1];
85400 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
85401 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
85402 if( rc ){
85403 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
85404 goto abort_due_to_error;
85406 sqlite3VdbeChangeEncoding(pMem, encoding);
85407 UPDATE_MAX_BLOBSIZE(pMem);
85408 if( sqlite3VdbeMemTooBig(pMem) ){
85409 goto too_big;
85411 break;
85414 #ifndef SQLITE_OMIT_WAL
85415 /* Opcode: Checkpoint P1 P2 P3 * *
85417 ** Checkpoint database P1. This is a no-op if P1 is not currently in
85418 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
85419 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
85420 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
85421 ** WAL after the checkpoint into mem[P3+1] and the number of pages
85422 ** in the WAL that have been checkpointed after the checkpoint
85423 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
85424 ** mem[P3+2] are initialized to -1.
85426 case OP_Checkpoint: {
85427 int i; /* Loop counter */
85428 int aRes[3]; /* Results */
85429 Mem *pMem; /* Write results here */
85431 assert( p->readOnly==0 );
85432 aRes[0] = 0;
85433 aRes[1] = aRes[2] = -1;
85434 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
85435 || pOp->p2==SQLITE_CHECKPOINT_FULL
85436 || pOp->p2==SQLITE_CHECKPOINT_RESTART
85437 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
85439 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
85440 if( rc ){
85441 if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
85442 rc = SQLITE_OK;
85443 aRes[0] = 1;
85445 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
85446 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
85448 break;
85450 #endif
85452 #ifndef SQLITE_OMIT_PRAGMA
85453 /* Opcode: JournalMode P1 P2 P3 * *
85455 ** Change the journal mode of database P1 to P3. P3 must be one of the
85456 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
85457 ** modes (delete, truncate, persist, off and memory), this is a simple
85458 ** operation. No IO is required.
85460 ** If changing into or out of WAL mode the procedure is more complicated.
85462 ** Write a string containing the final journal-mode to register P2.
85464 case OP_JournalMode: { /* out2 */
85465 Btree *pBt; /* Btree to change journal mode of */
85466 Pager *pPager; /* Pager associated with pBt */
85467 int eNew; /* New journal mode */
85468 int eOld; /* The old journal mode */
85469 #ifndef SQLITE_OMIT_WAL
85470 const char *zFilename; /* Name of database file for pPager */
85471 #endif
85473 pOut = out2Prerelease(p, pOp);
85474 eNew = pOp->p3;
85475 assert( eNew==PAGER_JOURNALMODE_DELETE
85476 || eNew==PAGER_JOURNALMODE_TRUNCATE
85477 || eNew==PAGER_JOURNALMODE_PERSIST
85478 || eNew==PAGER_JOURNALMODE_OFF
85479 || eNew==PAGER_JOURNALMODE_MEMORY
85480 || eNew==PAGER_JOURNALMODE_WAL
85481 || eNew==PAGER_JOURNALMODE_QUERY
85483 assert( pOp->p1>=0 && pOp->p1<db->nDb );
85484 assert( p->readOnly==0 );
85486 pBt = db->aDb[pOp->p1].pBt;
85487 pPager = sqlite3BtreePager(pBt);
85488 eOld = sqlite3PagerGetJournalMode(pPager);
85489 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
85490 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
85492 #ifndef SQLITE_OMIT_WAL
85493 zFilename = sqlite3PagerFilename(pPager, 1);
85495 /* Do not allow a transition to journal_mode=WAL for a database
85496 ** in temporary storage or if the VFS does not support shared memory
85498 if( eNew==PAGER_JOURNALMODE_WAL
85499 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
85500 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
85502 eNew = eOld;
85505 if( (eNew!=eOld)
85506 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
85508 if( !db->autoCommit || db->nVdbeRead>1 ){
85509 rc = SQLITE_ERROR;
85510 sqlite3VdbeError(p,
85511 "cannot change %s wal mode from within a transaction",
85512 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
85514 goto abort_due_to_error;
85515 }else{
85517 if( eOld==PAGER_JOURNALMODE_WAL ){
85518 /* If leaving WAL mode, close the log file. If successful, the call
85519 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
85520 ** file. An EXCLUSIVE lock may still be held on the database file
85521 ** after a successful return.
85523 rc = sqlite3PagerCloseWal(pPager, db);
85524 if( rc==SQLITE_OK ){
85525 sqlite3PagerSetJournalMode(pPager, eNew);
85527 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
85528 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
85529 ** as an intermediate */
85530 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
85533 /* Open a transaction on the database file. Regardless of the journal
85534 ** mode, this transaction always uses a rollback journal.
85536 assert( sqlite3BtreeIsInTrans(pBt)==0 );
85537 if( rc==SQLITE_OK ){
85538 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
85542 #endif /* ifndef SQLITE_OMIT_WAL */
85544 if( rc ) eNew = eOld;
85545 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
85547 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
85548 pOut->z = (char *)sqlite3JournalModename(eNew);
85549 pOut->n = sqlite3Strlen30(pOut->z);
85550 pOut->enc = SQLITE_UTF8;
85551 sqlite3VdbeChangeEncoding(pOut, encoding);
85552 if( rc ) goto abort_due_to_error;
85553 break;
85555 #endif /* SQLITE_OMIT_PRAGMA */
85557 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
85558 /* Opcode: Vacuum P1 * * * *
85560 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
85561 ** for an attached database. The "temp" database may not be vacuumed.
85563 case OP_Vacuum: {
85564 assert( p->readOnly==0 );
85565 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
85566 if( rc ) goto abort_due_to_error;
85567 break;
85569 #endif
85571 #if !defined(SQLITE_OMIT_AUTOVACUUM)
85572 /* Opcode: IncrVacuum P1 P2 * * *
85574 ** Perform a single step of the incremental vacuum procedure on
85575 ** the P1 database. If the vacuum has finished, jump to instruction
85576 ** P2. Otherwise, fall through to the next instruction.
85578 case OP_IncrVacuum: { /* jump */
85579 Btree *pBt;
85581 assert( pOp->p1>=0 && pOp->p1<db->nDb );
85582 assert( DbMaskTest(p->btreeMask, pOp->p1) );
85583 assert( p->readOnly==0 );
85584 pBt = db->aDb[pOp->p1].pBt;
85585 rc = sqlite3BtreeIncrVacuum(pBt);
85586 VdbeBranchTaken(rc==SQLITE_DONE,2);
85587 if( rc ){
85588 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
85589 rc = SQLITE_OK;
85590 goto jump_to_p2;
85592 break;
85594 #endif
85596 /* Opcode: Expire P1 * * * *
85598 ** Cause precompiled statements to expire. When an expired statement
85599 ** is executed using sqlite3_step() it will either automatically
85600 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
85601 ** or it will fail with SQLITE_SCHEMA.
85603 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
85604 ** then only the currently executing statement is expired.
85606 case OP_Expire: {
85607 if( !pOp->p1 ){
85608 sqlite3ExpirePreparedStatements(db);
85609 }else{
85610 p->expired = 1;
85612 break;
85615 #ifndef SQLITE_OMIT_SHARED_CACHE
85616 /* Opcode: TableLock P1 P2 P3 P4 *
85617 ** Synopsis: iDb=P1 root=P2 write=P3
85619 ** Obtain a lock on a particular table. This instruction is only used when
85620 ** the shared-cache feature is enabled.
85622 ** P1 is the index of the database in sqlite3.aDb[] of the database
85623 ** on which the lock is acquired. A readlock is obtained if P3==0 or
85624 ** a write lock if P3==1.
85626 ** P2 contains the root-page of the table to lock.
85628 ** P4 contains a pointer to the name of the table being locked. This is only
85629 ** used to generate an error message if the lock cannot be obtained.
85631 case OP_TableLock: {
85632 u8 isWriteLock = (u8)pOp->p3;
85633 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
85634 int p1 = pOp->p1;
85635 assert( p1>=0 && p1<db->nDb );
85636 assert( DbMaskTest(p->btreeMask, p1) );
85637 assert( isWriteLock==0 || isWriteLock==1 );
85638 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
85639 if( rc ){
85640 if( (rc&0xFF)==SQLITE_LOCKED ){
85641 const char *z = pOp->p4.z;
85642 sqlite3VdbeError(p, "database table is locked: %s", z);
85644 goto abort_due_to_error;
85647 break;
85649 #endif /* SQLITE_OMIT_SHARED_CACHE */
85651 #ifndef SQLITE_OMIT_VIRTUALTABLE
85652 /* Opcode: VBegin * * * P4 *
85654 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
85655 ** xBegin method for that table.
85657 ** Also, whether or not P4 is set, check that this is not being called from
85658 ** within a callback to a virtual table xSync() method. If it is, the error
85659 ** code will be set to SQLITE_LOCKED.
85661 case OP_VBegin: {
85662 VTable *pVTab;
85663 pVTab = pOp->p4.pVtab;
85664 rc = sqlite3VtabBegin(db, pVTab);
85665 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
85666 if( rc ) goto abort_due_to_error;
85667 break;
85669 #endif /* SQLITE_OMIT_VIRTUALTABLE */
85671 #ifndef SQLITE_OMIT_VIRTUALTABLE
85672 /* Opcode: VCreate P1 P2 * * *
85674 ** P2 is a register that holds the name of a virtual table in database
85675 ** P1. Call the xCreate method for that table.
85677 case OP_VCreate: {
85678 Mem sMem; /* For storing the record being decoded */
85679 const char *zTab; /* Name of the virtual table */
85681 memset(&sMem, 0, sizeof(sMem));
85682 sMem.db = db;
85683 /* Because P2 is always a static string, it is impossible for the
85684 ** sqlite3VdbeMemCopy() to fail */
85685 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
85686 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
85687 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
85688 assert( rc==SQLITE_OK );
85689 zTab = (const char*)sqlite3_value_text(&sMem);
85690 assert( zTab || db->mallocFailed );
85691 if( zTab ){
85692 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
85694 sqlite3VdbeMemRelease(&sMem);
85695 if( rc ) goto abort_due_to_error;
85696 break;
85698 #endif /* SQLITE_OMIT_VIRTUALTABLE */
85700 #ifndef SQLITE_OMIT_VIRTUALTABLE
85701 /* Opcode: VDestroy P1 * * P4 *
85703 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
85704 ** of that table.
85706 case OP_VDestroy: {
85707 db->nVDestroy++;
85708 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
85709 db->nVDestroy--;
85710 if( rc ) goto abort_due_to_error;
85711 break;
85713 #endif /* SQLITE_OMIT_VIRTUALTABLE */
85715 #ifndef SQLITE_OMIT_VIRTUALTABLE
85716 /* Opcode: VOpen P1 * * P4 *
85718 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
85719 ** P1 is a cursor number. This opcode opens a cursor to the virtual
85720 ** table and stores that cursor in P1.
85722 case OP_VOpen: {
85723 VdbeCursor *pCur;
85724 sqlite3_vtab_cursor *pVCur;
85725 sqlite3_vtab *pVtab;
85726 const sqlite3_module *pModule;
85728 assert( p->bIsReader );
85729 pCur = 0;
85730 pVCur = 0;
85731 pVtab = pOp->p4.pVtab->pVtab;
85732 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
85733 rc = SQLITE_LOCKED;
85734 goto abort_due_to_error;
85736 pModule = pVtab->pModule;
85737 rc = pModule->xOpen(pVtab, &pVCur);
85738 sqlite3VtabImportErrmsg(p, pVtab);
85739 if( rc ) goto abort_due_to_error;
85741 /* Initialize sqlite3_vtab_cursor base class */
85742 pVCur->pVtab = pVtab;
85744 /* Initialize vdbe cursor object */
85745 pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
85746 if( pCur ){
85747 pCur->uc.pVCur = pVCur;
85748 pVtab->nRef++;
85749 }else{
85750 assert( db->mallocFailed );
85751 pModule->xClose(pVCur);
85752 goto no_mem;
85754 break;
85756 #endif /* SQLITE_OMIT_VIRTUALTABLE */
85758 #ifndef SQLITE_OMIT_VIRTUALTABLE
85759 /* Opcode: VFilter P1 P2 P3 P4 *
85760 ** Synopsis: iplan=r[P3] zplan='P4'
85762 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
85763 ** the filtered result set is empty.
85765 ** P4 is either NULL or a string that was generated by the xBestIndex
85766 ** method of the module. The interpretation of the P4 string is left
85767 ** to the module implementation.
85769 ** This opcode invokes the xFilter method on the virtual table specified
85770 ** by P1. The integer query plan parameter to xFilter is stored in register
85771 ** P3. Register P3+1 stores the argc parameter to be passed to the
85772 ** xFilter method. Registers P3+2..P3+1+argc are the argc
85773 ** additional parameters which are passed to
85774 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
85776 ** A jump is made to P2 if the result set after filtering would be empty.
85778 case OP_VFilter: { /* jump */
85779 int nArg;
85780 int iQuery;
85781 const sqlite3_module *pModule;
85782 Mem *pQuery;
85783 Mem *pArgc;
85784 sqlite3_vtab_cursor *pVCur;
85785 sqlite3_vtab *pVtab;
85786 VdbeCursor *pCur;
85787 int res;
85788 int i;
85789 Mem **apArg;
85791 pQuery = &aMem[pOp->p3];
85792 pArgc = &pQuery[1];
85793 pCur = p->apCsr[pOp->p1];
85794 assert( memIsValid(pQuery) );
85795 REGISTER_TRACE(pOp->p3, pQuery);
85796 assert( pCur->eCurType==CURTYPE_VTAB );
85797 pVCur = pCur->uc.pVCur;
85798 pVtab = pVCur->pVtab;
85799 pModule = pVtab->pModule;
85801 /* Grab the index number and argc parameters */
85802 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
85803 nArg = (int)pArgc->u.i;
85804 iQuery = (int)pQuery->u.i;
85806 /* Invoke the xFilter method */
85807 res = 0;
85808 apArg = p->apArg;
85809 for(i = 0; i<nArg; i++){
85810 apArg[i] = &pArgc[i+1];
85812 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
85813 sqlite3VtabImportErrmsg(p, pVtab);
85814 if( rc ) goto abort_due_to_error;
85815 res = pModule->xEof(pVCur);
85816 pCur->nullRow = 0;
85817 VdbeBranchTaken(res!=0,2);
85818 if( res ) goto jump_to_p2;
85819 break;
85821 #endif /* SQLITE_OMIT_VIRTUALTABLE */
85823 #ifndef SQLITE_OMIT_VIRTUALTABLE
85824 /* Opcode: VColumn P1 P2 P3 * *
85825 ** Synopsis: r[P3]=vcolumn(P2)
85827 ** Store the value of the P2-th column of
85828 ** the row of the virtual-table that the
85829 ** P1 cursor is pointing to into register P3.
85831 case OP_VColumn: {
85832 sqlite3_vtab *pVtab;
85833 const sqlite3_module *pModule;
85834 Mem *pDest;
85835 sqlite3_context sContext;
85837 VdbeCursor *pCur = p->apCsr[pOp->p1];
85838 assert( pCur->eCurType==CURTYPE_VTAB );
85839 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
85840 pDest = &aMem[pOp->p3];
85841 memAboutToChange(p, pDest);
85842 if( pCur->nullRow ){
85843 sqlite3VdbeMemSetNull(pDest);
85844 break;
85846 pVtab = pCur->uc.pVCur->pVtab;
85847 pModule = pVtab->pModule;
85848 assert( pModule->xColumn );
85849 memset(&sContext, 0, sizeof(sContext));
85850 sContext.pOut = pDest;
85851 MemSetTypeFlag(pDest, MEM_Null);
85852 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
85853 sqlite3VtabImportErrmsg(p, pVtab);
85854 if( sContext.isError ){
85855 rc = sContext.isError;
85857 sqlite3VdbeChangeEncoding(pDest, encoding);
85858 REGISTER_TRACE(pOp->p3, pDest);
85859 UPDATE_MAX_BLOBSIZE(pDest);
85861 if( sqlite3VdbeMemTooBig(pDest) ){
85862 goto too_big;
85864 if( rc ) goto abort_due_to_error;
85865 break;
85867 #endif /* SQLITE_OMIT_VIRTUALTABLE */
85869 #ifndef SQLITE_OMIT_VIRTUALTABLE
85870 /* Opcode: VNext P1 P2 * * *
85872 ** Advance virtual table P1 to the next row in its result set and
85873 ** jump to instruction P2. Or, if the virtual table has reached
85874 ** the end of its result set, then fall through to the next instruction.
85876 case OP_VNext: { /* jump */
85877 sqlite3_vtab *pVtab;
85878 const sqlite3_module *pModule;
85879 int res;
85880 VdbeCursor *pCur;
85882 res = 0;
85883 pCur = p->apCsr[pOp->p1];
85884 assert( pCur->eCurType==CURTYPE_VTAB );
85885 if( pCur->nullRow ){
85886 break;
85888 pVtab = pCur->uc.pVCur->pVtab;
85889 pModule = pVtab->pModule;
85890 assert( pModule->xNext );
85892 /* Invoke the xNext() method of the module. There is no way for the
85893 ** underlying implementation to return an error if one occurs during
85894 ** xNext(). Instead, if an error occurs, true is returned (indicating that
85895 ** data is available) and the error code returned when xColumn or
85896 ** some other method is next invoked on the save virtual table cursor.
85898 rc = pModule->xNext(pCur->uc.pVCur);
85899 sqlite3VtabImportErrmsg(p, pVtab);
85900 if( rc ) goto abort_due_to_error;
85901 res = pModule->xEof(pCur->uc.pVCur);
85902 VdbeBranchTaken(!res,2);
85903 if( !res ){
85904 /* If there is data, jump to P2 */
85905 goto jump_to_p2_and_check_for_interrupt;
85907 goto check_for_interrupt;
85909 #endif /* SQLITE_OMIT_VIRTUALTABLE */
85911 #ifndef SQLITE_OMIT_VIRTUALTABLE
85912 /* Opcode: VRename P1 * * P4 *
85914 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
85915 ** This opcode invokes the corresponding xRename method. The value
85916 ** in register P1 is passed as the zName argument to the xRename method.
85918 case OP_VRename: {
85919 sqlite3_vtab *pVtab;
85920 Mem *pName;
85922 pVtab = pOp->p4.pVtab->pVtab;
85923 pName = &aMem[pOp->p1];
85924 assert( pVtab->pModule->xRename );
85925 assert( memIsValid(pName) );
85926 assert( p->readOnly==0 );
85927 REGISTER_TRACE(pOp->p1, pName);
85928 assert( pName->flags & MEM_Str );
85929 testcase( pName->enc==SQLITE_UTF8 );
85930 testcase( pName->enc==SQLITE_UTF16BE );
85931 testcase( pName->enc==SQLITE_UTF16LE );
85932 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
85933 if( rc ) goto abort_due_to_error;
85934 rc = pVtab->pModule->xRename(pVtab, pName->z);
85935 sqlite3VtabImportErrmsg(p, pVtab);
85936 p->expired = 0;
85937 if( rc ) goto abort_due_to_error;
85938 break;
85940 #endif
85942 #ifndef SQLITE_OMIT_VIRTUALTABLE
85943 /* Opcode: VUpdate P1 P2 P3 P4 P5
85944 ** Synopsis: data=r[P3@P2]
85946 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
85947 ** This opcode invokes the corresponding xUpdate method. P2 values
85948 ** are contiguous memory cells starting at P3 to pass to the xUpdate
85949 ** invocation. The value in register (P3+P2-1) corresponds to the
85950 ** p2th element of the argv array passed to xUpdate.
85952 ** The xUpdate method will do a DELETE or an INSERT or both.
85953 ** The argv[0] element (which corresponds to memory cell P3)
85954 ** is the rowid of a row to delete. If argv[0] is NULL then no
85955 ** deletion occurs. The argv[1] element is the rowid of the new
85956 ** row. This can be NULL to have the virtual table select the new
85957 ** rowid for itself. The subsequent elements in the array are
85958 ** the values of columns in the new row.
85960 ** If P2==1 then no insert is performed. argv[0] is the rowid of
85961 ** a row to delete.
85963 ** P1 is a boolean flag. If it is set to true and the xUpdate call
85964 ** is successful, then the value returned by sqlite3_last_insert_rowid()
85965 ** is set to the value of the rowid for the row just inserted.
85967 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
85968 ** apply in the case of a constraint failure on an insert or update.
85970 case OP_VUpdate: {
85971 sqlite3_vtab *pVtab;
85972 const sqlite3_module *pModule;
85973 int nArg;
85974 int i;
85975 sqlite_int64 rowid;
85976 Mem **apArg;
85977 Mem *pX;
85979 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
85980 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
85982 assert( p->readOnly==0 );
85983 pVtab = pOp->p4.pVtab->pVtab;
85984 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
85985 rc = SQLITE_LOCKED;
85986 goto abort_due_to_error;
85988 pModule = pVtab->pModule;
85989 nArg = pOp->p2;
85990 assert( pOp->p4type==P4_VTAB );
85991 if( ALWAYS(pModule->xUpdate) ){
85992 u8 vtabOnConflict = db->vtabOnConflict;
85993 apArg = p->apArg;
85994 pX = &aMem[pOp->p3];
85995 for(i=0; i<nArg; i++){
85996 assert( memIsValid(pX) );
85997 memAboutToChange(p, pX);
85998 apArg[i] = pX;
85999 pX++;
86001 db->vtabOnConflict = pOp->p5;
86002 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
86003 db->vtabOnConflict = vtabOnConflict;
86004 sqlite3VtabImportErrmsg(p, pVtab);
86005 if( rc==SQLITE_OK && pOp->p1 ){
86006 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
86007 db->lastRowid = rowid;
86009 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
86010 if( pOp->p5==OE_Ignore ){
86011 rc = SQLITE_OK;
86012 }else{
86013 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
86015 }else{
86016 p->nChange++;
86018 if( rc ) goto abort_due_to_error;
86020 break;
86022 #endif /* SQLITE_OMIT_VIRTUALTABLE */
86024 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
86025 /* Opcode: Pagecount P1 P2 * * *
86027 ** Write the current number of pages in database P1 to memory cell P2.
86029 case OP_Pagecount: { /* out2 */
86030 pOut = out2Prerelease(p, pOp);
86031 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
86032 break;
86034 #endif
86037 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
86038 /* Opcode: MaxPgcnt P1 P2 P3 * *
86040 ** Try to set the maximum page count for database P1 to the value in P3.
86041 ** Do not let the maximum page count fall below the current page count and
86042 ** do not change the maximum page count value if P3==0.
86044 ** Store the maximum page count after the change in register P2.
86046 case OP_MaxPgcnt: { /* out2 */
86047 unsigned int newMax;
86048 Btree *pBt;
86050 pOut = out2Prerelease(p, pOp);
86051 pBt = db->aDb[pOp->p1].pBt;
86052 newMax = 0;
86053 if( pOp->p3 ){
86054 newMax = sqlite3BtreeLastPage(pBt);
86055 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
86057 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
86058 break;
86060 #endif
86062 /* Opcode: Function0 P1 P2 P3 P4 P5
86063 ** Synopsis: r[P3]=func(r[P2@P5])
86065 ** Invoke a user function (P4 is a pointer to a FuncDef object that
86066 ** defines the function) with P5 arguments taken from register P2 and
86067 ** successors. The result of the function is stored in register P3.
86068 ** Register P3 must not be one of the function inputs.
86070 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
86071 ** function was determined to be constant at compile time. If the first
86072 ** argument was constant then bit 0 of P1 is set. This is used to determine
86073 ** whether meta data associated with a user function argument using the
86074 ** sqlite3_set_auxdata() API may be safely retained until the next
86075 ** invocation of this opcode.
86077 ** See also: Function, AggStep, AggFinal
86079 /* Opcode: Function P1 P2 P3 P4 P5
86080 ** Synopsis: r[P3]=func(r[P2@P5])
86082 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
86083 ** contains a pointer to the function to be run) with P5 arguments taken
86084 ** from register P2 and successors. The result of the function is stored
86085 ** in register P3. Register P3 must not be one of the function inputs.
86087 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
86088 ** function was determined to be constant at compile time. If the first
86089 ** argument was constant then bit 0 of P1 is set. This is used to determine
86090 ** whether meta data associated with a user function argument using the
86091 ** sqlite3_set_auxdata() API may be safely retained until the next
86092 ** invocation of this opcode.
86094 ** SQL functions are initially coded as OP_Function0 with P4 pointing
86095 ** to a FuncDef object. But on first evaluation, the P4 operand is
86096 ** automatically converted into an sqlite3_context object and the operation
86097 ** changed to this OP_Function opcode. In this way, the initialization of
86098 ** the sqlite3_context object occurs only once, rather than once for each
86099 ** evaluation of the function.
86101 ** See also: Function0, AggStep, AggFinal
86103 case OP_PureFunc0:
86104 case OP_Function0: {
86105 int n;
86106 sqlite3_context *pCtx;
86108 assert( pOp->p4type==P4_FUNCDEF );
86109 n = pOp->p5;
86110 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
86111 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
86112 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
86113 pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
86114 if( pCtx==0 ) goto no_mem;
86115 pCtx->pOut = 0;
86116 pCtx->pFunc = pOp->p4.pFunc;
86117 pCtx->iOp = (int)(pOp - aOp);
86118 pCtx->pVdbe = p;
86119 pCtx->argc = n;
86120 pOp->p4type = P4_FUNCCTX;
86121 pOp->p4.pCtx = pCtx;
86122 assert( OP_PureFunc == OP_PureFunc0+2 );
86123 assert( OP_Function == OP_Function0+2 );
86124 pOp->opcode += 2;
86125 /* Fall through into OP_Function */
86127 case OP_PureFunc:
86128 case OP_Function: {
86129 int i;
86130 sqlite3_context *pCtx;
86132 assert( pOp->p4type==P4_FUNCCTX );
86133 pCtx = pOp->p4.pCtx;
86135 /* If this function is inside of a trigger, the register array in aMem[]
86136 ** might change from one evaluation to the next. The next block of code
86137 ** checks to see if the register array has changed, and if so it
86138 ** reinitializes the relavant parts of the sqlite3_context object */
86139 pOut = &aMem[pOp->p3];
86140 if( pCtx->pOut != pOut ){
86141 pCtx->pOut = pOut;
86142 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
86145 memAboutToChange(p, pOut);
86146 #ifdef SQLITE_DEBUG
86147 for(i=0; i<pCtx->argc; i++){
86148 assert( memIsValid(pCtx->argv[i]) );
86149 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
86151 #endif
86152 MemSetTypeFlag(pOut, MEM_Null);
86153 pCtx->fErrorOrAux = 0;
86154 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
86156 /* If the function returned an error, throw an exception */
86157 if( pCtx->fErrorOrAux ){
86158 if( pCtx->isError ){
86159 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
86160 rc = pCtx->isError;
86162 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
86163 if( rc ) goto abort_due_to_error;
86166 /* Copy the result of the function into register P3 */
86167 if( pOut->flags & (MEM_Str|MEM_Blob) ){
86168 sqlite3VdbeChangeEncoding(pOut, encoding);
86169 if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
86172 REGISTER_TRACE(pOp->p3, pOut);
86173 UPDATE_MAX_BLOBSIZE(pOut);
86174 break;
86178 /* Opcode: Init P1 P2 P3 P4 *
86179 ** Synopsis: Start at P2
86181 ** Programs contain a single instance of this opcode as the very first
86182 ** opcode.
86184 ** If tracing is enabled (by the sqlite3_trace()) interface, then
86185 ** the UTF-8 string contained in P4 is emitted on the trace callback.
86186 ** Or if P4 is blank, use the string returned by sqlite3_sql().
86188 ** If P2 is not zero, jump to instruction P2.
86190 ** Increment the value of P1 so that OP_Once opcodes will jump the
86191 ** first time they are evaluated for this run.
86193 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
86194 ** error is encountered.
86196 case OP_Init: { /* jump */
86197 char *zTrace;
86198 int i;
86200 /* If the P4 argument is not NULL, then it must be an SQL comment string.
86201 ** The "--" string is broken up to prevent false-positives with srcck1.c.
86203 ** This assert() provides evidence for:
86204 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
86205 ** would have been returned by the legacy sqlite3_trace() interface by
86206 ** using the X argument when X begins with "--" and invoking
86207 ** sqlite3_expanded_sql(P) otherwise.
86209 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
86210 assert( pOp==p->aOp ); /* Always instruction 0 */
86212 #ifndef SQLITE_OMIT_TRACE
86213 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
86214 && !p->doingRerun
86215 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
86217 #ifndef SQLITE_OMIT_DEPRECATED
86218 if( db->mTrace & SQLITE_TRACE_LEGACY ){
86219 void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
86220 char *z = sqlite3VdbeExpandSql(p, zTrace);
86221 x(db->pTraceArg, z);
86222 sqlite3_free(z);
86223 }else
86224 #endif
86225 if( db->nVdbeExec>1 ){
86226 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
86227 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
86228 sqlite3DbFree(db, z);
86229 }else{
86230 (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
86233 #ifdef SQLITE_USE_FCNTL_TRACE
86234 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
86235 if( zTrace ){
86236 int j;
86237 for(j=0; j<db->nDb; j++){
86238 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
86239 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
86242 #endif /* SQLITE_USE_FCNTL_TRACE */
86243 #ifdef SQLITE_DEBUG
86244 if( (db->flags & SQLITE_SqlTrace)!=0
86245 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
86247 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
86249 #endif /* SQLITE_DEBUG */
86250 #endif /* SQLITE_OMIT_TRACE */
86251 assert( pOp->p2>0 );
86252 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
86253 for(i=1; i<p->nOp; i++){
86254 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
86256 pOp->p1 = 0;
86258 pOp->p1++;
86259 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
86260 goto jump_to_p2;
86263 #ifdef SQLITE_ENABLE_CURSOR_HINTS
86264 /* Opcode: CursorHint P1 * * P4 *
86266 ** Provide a hint to cursor P1 that it only needs to return rows that
86267 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
86268 ** to values currently held in registers. TK_COLUMN terms in the P4
86269 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
86271 case OP_CursorHint: {
86272 VdbeCursor *pC;
86274 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
86275 assert( pOp->p4type==P4_EXPR );
86276 pC = p->apCsr[pOp->p1];
86277 if( pC ){
86278 assert( pC->eCurType==CURTYPE_BTREE );
86279 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
86280 pOp->p4.pExpr, aMem);
86282 break;
86284 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
86286 /* Opcode: Noop * * * * *
86288 ** Do nothing. This instruction is often useful as a jump
86289 ** destination.
86292 ** The magic Explain opcode are only inserted when explain==2 (which
86293 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
86294 ** This opcode records information from the optimizer. It is the
86295 ** the same as a no-op. This opcodesnever appears in a real VM program.
86297 default: { /* This is really OP_Noop and OP_Explain */
86298 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
86299 break;
86302 /*****************************************************************************
86303 ** The cases of the switch statement above this line should all be indented
86304 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
86305 ** readability. From this point on down, the normal indentation rules are
86306 ** restored.
86307 *****************************************************************************/
86310 #ifdef VDBE_PROFILE
86312 u64 endTime = sqlite3Hwtime();
86313 if( endTime>start ) pOrigOp->cycles += endTime - start;
86314 pOrigOp->cnt++;
86316 #endif
86318 /* The following code adds nothing to the actual functionality
86319 ** of the program. It is only here for testing and debugging.
86320 ** On the other hand, it does burn CPU cycles every time through
86321 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
86323 #ifndef NDEBUG
86324 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
86326 #ifdef SQLITE_DEBUG
86327 if( db->flags & SQLITE_VdbeTrace ){
86328 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
86329 if( rc!=0 ) printf("rc=%d\n",rc);
86330 if( opProperty & (OPFLG_OUT2) ){
86331 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
86333 if( opProperty & OPFLG_OUT3 ){
86334 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
86337 #endif /* SQLITE_DEBUG */
86338 #endif /* NDEBUG */
86339 } /* The end of the for(;;) loop the loops through opcodes */
86341 /* If we reach this point, it means that execution is finished with
86342 ** an error of some kind.
86344 abort_due_to_error:
86345 if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
86346 assert( rc );
86347 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
86348 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
86350 p->rc = rc;
86351 sqlite3SystemError(db, rc);
86352 testcase( sqlite3GlobalConfig.xLog!=0 );
86353 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
86354 (int)(pOp - aOp), p->zSql, p->zErrMsg);
86355 sqlite3VdbeHalt(p);
86356 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
86357 rc = SQLITE_ERROR;
86358 if( resetSchemaOnFault>0 ){
86359 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
86362 /* This is the only way out of this procedure. We have to
86363 ** release the mutexes on btrees that were acquired at the
86364 ** top. */
86365 vdbe_return:
86366 testcase( nVmStep>0 );
86367 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
86368 sqlite3VdbeLeave(p);
86369 assert( rc!=SQLITE_OK || nExtraDelete==0
86370 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
86372 return rc;
86374 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
86375 ** is encountered.
86377 too_big:
86378 sqlite3VdbeError(p, "string or blob too big");
86379 rc = SQLITE_TOOBIG;
86380 goto abort_due_to_error;
86382 /* Jump to here if a malloc() fails.
86384 no_mem:
86385 sqlite3OomFault(db);
86386 sqlite3VdbeError(p, "out of memory");
86387 rc = SQLITE_NOMEM_BKPT;
86388 goto abort_due_to_error;
86390 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
86391 ** flag.
86393 abort_due_to_interrupt:
86394 assert( db->u1.isInterrupted );
86395 rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
86396 p->rc = rc;
86397 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
86398 goto abort_due_to_error;
86402 /************** End of vdbe.c ************************************************/
86403 /************** Begin file vdbeblob.c ****************************************/
86405 ** 2007 May 1
86407 ** The author disclaims copyright to this source code. In place of
86408 ** a legal notice, here is a blessing:
86410 ** May you do good and not evil.
86411 ** May you find forgiveness for yourself and forgive others.
86412 ** May you share freely, never taking more than you give.
86414 *************************************************************************
86416 ** This file contains code used to implement incremental BLOB I/O.
86419 /* #include "sqliteInt.h" */
86420 /* #include "vdbeInt.h" */
86422 #ifndef SQLITE_OMIT_INCRBLOB
86425 ** Valid sqlite3_blob* handles point to Incrblob structures.
86427 typedef struct Incrblob Incrblob;
86428 struct Incrblob {
86429 int nByte; /* Size of open blob, in bytes */
86430 int iOffset; /* Byte offset of blob in cursor data */
86431 u16 iCol; /* Table column this handle is open on */
86432 BtCursor *pCsr; /* Cursor pointing at blob row */
86433 sqlite3_stmt *pStmt; /* Statement holding cursor open */
86434 sqlite3 *db; /* The associated database */
86435 char *zDb; /* Database name */
86436 Table *pTab; /* Table object */
86441 ** This function is used by both blob_open() and blob_reopen(). It seeks
86442 ** the b-tree cursor associated with blob handle p to point to row iRow.
86443 ** If successful, SQLITE_OK is returned and subsequent calls to
86444 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
86446 ** If an error occurs, or if the specified row does not exist or does not
86447 ** contain a value of type TEXT or BLOB in the column nominated when the
86448 ** blob handle was opened, then an error code is returned and *pzErr may
86449 ** be set to point to a buffer containing an error message. It is the
86450 ** responsibility of the caller to free the error message buffer using
86451 ** sqlite3DbFree().
86453 ** If an error does occur, then the b-tree cursor is closed. All subsequent
86454 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
86455 ** immediately return SQLITE_ABORT.
86457 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
86458 int rc; /* Error code */
86459 char *zErr = 0; /* Error message */
86460 Vdbe *v = (Vdbe *)p->pStmt;
86462 /* Set the value of register r[1] in the SQL statement to integer iRow.
86463 ** This is done directly as a performance optimization
86465 v->aMem[1].flags = MEM_Int;
86466 v->aMem[1].u.i = iRow;
86468 /* If the statement has been run before (and is paused at the OP_ResultRow)
86469 ** then back it up to the point where it does the OP_NotExists. This could
86470 ** have been down with an extra OP_Goto, but simply setting the program
86471 ** counter is faster. */
86472 if( v->pc>4 ){
86473 v->pc = 4;
86474 assert( v->aOp[v->pc].opcode==OP_NotExists );
86475 rc = sqlite3VdbeExec(v);
86476 }else{
86477 rc = sqlite3_step(p->pStmt);
86479 if( rc==SQLITE_ROW ){
86480 VdbeCursor *pC = v->apCsr[0];
86481 u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
86482 testcase( pC->nHdrParsed==p->iCol );
86483 testcase( pC->nHdrParsed==p->iCol+1 );
86484 if( type<12 ){
86485 zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
86486 type==0?"null": type==7?"real": "integer"
86488 rc = SQLITE_ERROR;
86489 sqlite3_finalize(p->pStmt);
86490 p->pStmt = 0;
86491 }else{
86492 p->iOffset = pC->aType[p->iCol + pC->nField];
86493 p->nByte = sqlite3VdbeSerialTypeLen(type);
86494 p->pCsr = pC->uc.pCursor;
86495 sqlite3BtreeIncrblobCursor(p->pCsr);
86499 if( rc==SQLITE_ROW ){
86500 rc = SQLITE_OK;
86501 }else if( p->pStmt ){
86502 rc = sqlite3_finalize(p->pStmt);
86503 p->pStmt = 0;
86504 if( rc==SQLITE_OK ){
86505 zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
86506 rc = SQLITE_ERROR;
86507 }else{
86508 zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
86512 assert( rc!=SQLITE_OK || zErr==0 );
86513 assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
86515 *pzErr = zErr;
86516 return rc;
86520 ** Open a blob handle.
86522 SQLITE_API int sqlite3_blob_open(
86523 sqlite3* db, /* The database connection */
86524 const char *zDb, /* The attached database containing the blob */
86525 const char *zTable, /* The table containing the blob */
86526 const char *zColumn, /* The column containing the blob */
86527 sqlite_int64 iRow, /* The row containing the glob */
86528 int wrFlag, /* True -> read/write access, false -> read-only */
86529 sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
86531 int nAttempt = 0;
86532 int iCol; /* Index of zColumn in row-record */
86533 int rc = SQLITE_OK;
86534 char *zErr = 0;
86535 Table *pTab;
86536 Incrblob *pBlob = 0;
86537 Parse sParse;
86539 #ifdef SQLITE_ENABLE_API_ARMOR
86540 if( ppBlob==0 ){
86541 return SQLITE_MISUSE_BKPT;
86543 #endif
86544 *ppBlob = 0;
86545 #ifdef SQLITE_ENABLE_API_ARMOR
86546 if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
86547 return SQLITE_MISUSE_BKPT;
86549 #endif
86550 wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
86552 sqlite3_mutex_enter(db->mutex);
86554 pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
86555 do {
86556 memset(&sParse, 0, sizeof(Parse));
86557 if( !pBlob ) goto blob_open_out;
86558 sParse.db = db;
86559 sqlite3DbFree(db, zErr);
86560 zErr = 0;
86562 sqlite3BtreeEnterAll(db);
86563 pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
86564 if( pTab && IsVirtual(pTab) ){
86565 pTab = 0;
86566 sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
86568 if( pTab && !HasRowid(pTab) ){
86569 pTab = 0;
86570 sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
86572 #ifndef SQLITE_OMIT_VIEW
86573 if( pTab && pTab->pSelect ){
86574 pTab = 0;
86575 sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
86577 #endif
86578 if( !pTab ){
86579 if( sParse.zErrMsg ){
86580 sqlite3DbFree(db, zErr);
86581 zErr = sParse.zErrMsg;
86582 sParse.zErrMsg = 0;
86584 rc = SQLITE_ERROR;
86585 sqlite3BtreeLeaveAll(db);
86586 goto blob_open_out;
86588 pBlob->pTab = pTab;
86589 pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
86591 /* Now search pTab for the exact column. */
86592 for(iCol=0; iCol<pTab->nCol; iCol++) {
86593 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
86594 break;
86597 if( iCol==pTab->nCol ){
86598 sqlite3DbFree(db, zErr);
86599 zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
86600 rc = SQLITE_ERROR;
86601 sqlite3BtreeLeaveAll(db);
86602 goto blob_open_out;
86605 /* If the value is being opened for writing, check that the
86606 ** column is not indexed, and that it is not part of a foreign key.
86608 if( wrFlag ){
86609 const char *zFault = 0;
86610 Index *pIdx;
86611 #ifndef SQLITE_OMIT_FOREIGN_KEY
86612 if( db->flags&SQLITE_ForeignKeys ){
86613 /* Check that the column is not part of an FK child key definition. It
86614 ** is not necessary to check if it is part of a parent key, as parent
86615 ** key columns must be indexed. The check below will pick up this
86616 ** case. */
86617 FKey *pFKey;
86618 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
86619 int j;
86620 for(j=0; j<pFKey->nCol; j++){
86621 if( pFKey->aCol[j].iFrom==iCol ){
86622 zFault = "foreign key";
86627 #endif
86628 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86629 int j;
86630 for(j=0; j<pIdx->nKeyCol; j++){
86631 /* FIXME: Be smarter about indexes that use expressions */
86632 if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
86633 zFault = "indexed";
86637 if( zFault ){
86638 sqlite3DbFree(db, zErr);
86639 zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
86640 rc = SQLITE_ERROR;
86641 sqlite3BtreeLeaveAll(db);
86642 goto blob_open_out;
86646 pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
86647 assert( pBlob->pStmt || db->mallocFailed );
86648 if( pBlob->pStmt ){
86650 /* This VDBE program seeks a btree cursor to the identified
86651 ** db/table/row entry. The reason for using a vdbe program instead
86652 ** of writing code to use the b-tree layer directly is that the
86653 ** vdbe program will take advantage of the various transaction,
86654 ** locking and error handling infrastructure built into the vdbe.
86656 ** After seeking the cursor, the vdbe executes an OP_ResultRow.
86657 ** Code external to the Vdbe then "borrows" the b-tree cursor and
86658 ** uses it to implement the blob_read(), blob_write() and
86659 ** blob_bytes() functions.
86661 ** The sqlite3_blob_close() function finalizes the vdbe program,
86662 ** which closes the b-tree cursor and (possibly) commits the
86663 ** transaction.
86665 static const int iLn = VDBE_OFFSET_LINENO(2);
86666 static const VdbeOpList openBlob[] = {
86667 {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
86668 {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
86669 /* blobSeekToRow() will initialize r[1] to the desired rowid */
86670 {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
86671 {OP_Column, 0, 0, 1}, /* 3 */
86672 {OP_ResultRow, 1, 0, 0}, /* 4 */
86673 {OP_Halt, 0, 0, 0}, /* 5 */
86675 Vdbe *v = (Vdbe *)pBlob->pStmt;
86676 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86677 VdbeOp *aOp;
86679 sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
86680 pTab->pSchema->schema_cookie,
86681 pTab->pSchema->iGeneration);
86682 sqlite3VdbeChangeP5(v, 1);
86683 assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
86684 aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
86686 /* Make sure a mutex is held on the table to be accessed */
86687 sqlite3VdbeUsesBtree(v, iDb);
86689 if( db->mallocFailed==0 ){
86690 assert( aOp!=0 );
86691 /* Configure the OP_TableLock instruction */
86692 #ifdef SQLITE_OMIT_SHARED_CACHE
86693 aOp[0].opcode = OP_Noop;
86694 #else
86695 aOp[0].p1 = iDb;
86696 aOp[0].p2 = pTab->tnum;
86697 aOp[0].p3 = wrFlag;
86698 sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
86700 if( db->mallocFailed==0 ){
86701 #endif
86703 /* Remove either the OP_OpenWrite or OpenRead. Set the P2
86704 ** parameter of the other to pTab->tnum. */
86705 if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
86706 aOp[1].p2 = pTab->tnum;
86707 aOp[1].p3 = iDb;
86709 /* Configure the number of columns. Configure the cursor to
86710 ** think that the table has one more column than it really
86711 ** does. An OP_Column to retrieve this imaginary column will
86712 ** always return an SQL NULL. This is useful because it means
86713 ** we can invoke OP_Column to fill in the vdbe cursors type
86714 ** and offset cache without causing any IO.
86716 aOp[1].p4type = P4_INT32;
86717 aOp[1].p4.i = pTab->nCol+1;
86718 aOp[3].p2 = pTab->nCol;
86720 sParse.nVar = 0;
86721 sParse.nMem = 1;
86722 sParse.nTab = 1;
86723 sqlite3VdbeMakeReady(v, &sParse);
86727 pBlob->iCol = iCol;
86728 pBlob->db = db;
86729 sqlite3BtreeLeaveAll(db);
86730 if( db->mallocFailed ){
86731 goto blob_open_out;
86733 rc = blobSeekToRow(pBlob, iRow, &zErr);
86734 } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
86736 blob_open_out:
86737 if( rc==SQLITE_OK && db->mallocFailed==0 ){
86738 *ppBlob = (sqlite3_blob *)pBlob;
86739 }else{
86740 if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
86741 sqlite3DbFree(db, pBlob);
86743 sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
86744 sqlite3DbFree(db, zErr);
86745 sqlite3ParserReset(&sParse);
86746 rc = sqlite3ApiExit(db, rc);
86747 sqlite3_mutex_leave(db->mutex);
86748 return rc;
86752 ** Close a blob handle that was previously created using
86753 ** sqlite3_blob_open().
86755 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
86756 Incrblob *p = (Incrblob *)pBlob;
86757 int rc;
86758 sqlite3 *db;
86760 if( p ){
86761 db = p->db;
86762 sqlite3_mutex_enter(db->mutex);
86763 rc = sqlite3_finalize(p->pStmt);
86764 sqlite3DbFree(db, p);
86765 sqlite3_mutex_leave(db->mutex);
86766 }else{
86767 rc = SQLITE_OK;
86769 return rc;
86773 ** Perform a read or write operation on a blob
86775 static int blobReadWrite(
86776 sqlite3_blob *pBlob,
86777 void *z,
86778 int n,
86779 int iOffset,
86780 int (*xCall)(BtCursor*, u32, u32, void*)
86782 int rc;
86783 Incrblob *p = (Incrblob *)pBlob;
86784 Vdbe *v;
86785 sqlite3 *db;
86787 if( p==0 ) return SQLITE_MISUSE_BKPT;
86788 db = p->db;
86789 sqlite3_mutex_enter(db->mutex);
86790 v = (Vdbe*)p->pStmt;
86792 if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
86793 /* Request is out of range. Return a transient error. */
86794 rc = SQLITE_ERROR;
86795 }else if( v==0 ){
86796 /* If there is no statement handle, then the blob-handle has
86797 ** already been invalidated. Return SQLITE_ABORT in this case.
86799 rc = SQLITE_ABORT;
86800 }else{
86801 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
86802 ** returned, clean-up the statement handle.
86804 assert( db == v->db );
86805 sqlite3BtreeEnterCursor(p->pCsr);
86807 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
86808 if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
86809 /* If a pre-update hook is registered and this is a write cursor,
86810 ** invoke it here.
86812 ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
86813 ** operation should really be an SQLITE_UPDATE. This is probably
86814 ** incorrect, but is convenient because at this point the new.* values
86815 ** are not easily obtainable. And for the sessions module, an
86816 ** SQLITE_UPDATE where the PK columns do not change is handled in the
86817 ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
86818 ** slightly more efficient). Since you cannot write to a PK column
86819 ** using the incremental-blob API, this works. For the sessions module
86820 ** anyhow.
86822 sqlite3_int64 iKey;
86823 iKey = sqlite3BtreeIntegerKey(p->pCsr);
86824 sqlite3VdbePreUpdateHook(
86825 v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
86828 #endif
86830 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
86831 sqlite3BtreeLeaveCursor(p->pCsr);
86832 if( rc==SQLITE_ABORT ){
86833 sqlite3VdbeFinalize(v);
86834 p->pStmt = 0;
86835 }else{
86836 v->rc = rc;
86839 sqlite3Error(db, rc);
86840 rc = sqlite3ApiExit(db, rc);
86841 sqlite3_mutex_leave(db->mutex);
86842 return rc;
86846 ** Read data from a blob handle.
86848 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
86849 return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
86853 ** Write data to a blob handle.
86855 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
86856 return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
86860 ** Query a blob handle for the size of the data.
86862 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
86863 ** so no mutex is required for access.
86865 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
86866 Incrblob *p = (Incrblob *)pBlob;
86867 return (p && p->pStmt) ? p->nByte : 0;
86871 ** Move an existing blob handle to point to a different row of the same
86872 ** database table.
86874 ** If an error occurs, or if the specified row does not exist or does not
86875 ** contain a blob or text value, then an error code is returned and the
86876 ** database handle error code and message set. If this happens, then all
86877 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
86878 ** immediately return SQLITE_ABORT.
86880 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
86881 int rc;
86882 Incrblob *p = (Incrblob *)pBlob;
86883 sqlite3 *db;
86885 if( p==0 ) return SQLITE_MISUSE_BKPT;
86886 db = p->db;
86887 sqlite3_mutex_enter(db->mutex);
86889 if( p->pStmt==0 ){
86890 /* If there is no statement handle, then the blob-handle has
86891 ** already been invalidated. Return SQLITE_ABORT in this case.
86893 rc = SQLITE_ABORT;
86894 }else{
86895 char *zErr;
86896 rc = blobSeekToRow(p, iRow, &zErr);
86897 if( rc!=SQLITE_OK ){
86898 sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
86899 sqlite3DbFree(db, zErr);
86901 assert( rc!=SQLITE_SCHEMA );
86904 rc = sqlite3ApiExit(db, rc);
86905 assert( rc==SQLITE_OK || p->pStmt==0 );
86906 sqlite3_mutex_leave(db->mutex);
86907 return rc;
86910 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
86912 /************** End of vdbeblob.c ********************************************/
86913 /************** Begin file vdbesort.c ****************************************/
86915 ** 2011-07-09
86917 ** The author disclaims copyright to this source code. In place of
86918 ** a legal notice, here is a blessing:
86920 ** May you do good and not evil.
86921 ** May you find forgiveness for yourself and forgive others.
86922 ** May you share freely, never taking more than you give.
86924 *************************************************************************
86925 ** This file contains code for the VdbeSorter object, used in concert with
86926 ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
86927 ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
86928 ** using indexes and without LIMIT clauses.
86930 ** The VdbeSorter object implements a multi-threaded external merge sort
86931 ** algorithm that is efficient even if the number of elements being sorted
86932 ** exceeds the available memory.
86934 ** Here is the (internal, non-API) interface between this module and the
86935 ** rest of the SQLite system:
86937 ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
86939 ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
86940 ** object. The row is a binary blob in the
86941 ** OP_MakeRecord format that contains both
86942 ** the ORDER BY key columns and result columns
86943 ** in the case of a SELECT w/ ORDER BY, or
86944 ** the complete record for an index entry
86945 ** in the case of a CREATE INDEX.
86947 ** sqlite3VdbeSorterRewind() Sort all content previously added.
86948 ** Position the read cursor on the
86949 ** first sorted element.
86951 ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
86952 ** element.
86954 ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
86955 ** row currently under the read cursor.
86957 ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
86958 ** currently under the read cursor against
86959 ** another binary blob X and report if
86960 ** X is strictly less than the read cursor.
86961 ** Used to enforce uniqueness in a
86962 ** CREATE UNIQUE INDEX statement.
86964 ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
86965 ** all resources.
86967 ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
86968 ** is like Close() followed by Init() only
86969 ** much faster.
86971 ** The interfaces above must be called in a particular order. Write() can
86972 ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
86973 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
86975 ** Init()
86976 ** for each record: Write()
86977 ** Rewind()
86978 ** Rowkey()/Compare()
86979 ** Next()
86980 ** Close()
86982 ** Algorithm:
86984 ** Records passed to the sorter via calls to Write() are initially held
86985 ** unsorted in main memory. Assuming the amount of memory used never exceeds
86986 ** a threshold, when Rewind() is called the set of records is sorted using
86987 ** an in-memory merge sort. In this case, no temporary files are required
86988 ** and subsequent calls to Rowkey(), Next() and Compare() read records
86989 ** directly from main memory.
86991 ** If the amount of space used to store records in main memory exceeds the
86992 ** threshold, then the set of records currently in memory are sorted and
86993 ** written to a temporary file in "Packed Memory Array" (PMA) format.
86994 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
86995 ** of PMAs may be created by merging existing PMAs together - for example
86996 ** merging two or more level-0 PMAs together creates a level-1 PMA.
86998 ** The threshold for the amount of main memory to use before flushing
86999 ** records to a PMA is roughly the same as the limit configured for the
87000 ** page-cache of the main database. Specifically, the threshold is set to
87001 ** the value returned by "PRAGMA main.page_size" multipled by
87002 ** that returned by "PRAGMA main.cache_size", in bytes.
87004 ** If the sorter is running in single-threaded mode, then all PMAs generated
87005 ** are appended to a single temporary file. Or, if the sorter is running in
87006 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
87007 ** N is the configured number of worker threads. In this case, instead of
87008 ** sorting the records and writing the PMA to a temporary file itself, the
87009 ** calling thread usually launches a worker thread to do so. Except, if
87010 ** there are already N worker threads running, the main thread does the work
87011 ** itself.
87013 ** The sorter is running in multi-threaded mode if (a) the library was built
87014 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
87015 ** than zero, and (b) worker threads have been enabled at runtime by calling
87016 ** "PRAGMA threads=N" with some value of N greater than 0.
87018 ** When Rewind() is called, any data remaining in memory is flushed to a
87019 ** final PMA. So at this point the data is stored in some number of sorted
87020 ** PMAs within temporary files on disk.
87022 ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
87023 ** sorter is running in single-threaded mode, then these PMAs are merged
87024 ** incrementally as keys are retreived from the sorter by the VDBE. The
87025 ** MergeEngine object, described in further detail below, performs this
87026 ** merge.
87028 ** Or, if running in multi-threaded mode, then a background thread is
87029 ** launched to merge the existing PMAs. Once the background thread has
87030 ** merged T bytes of data into a single sorted PMA, the main thread
87031 ** begins reading keys from that PMA while the background thread proceeds
87032 ** with merging the next T bytes of data. And so on.
87034 ** Parameter T is set to half the value of the memory threshold used
87035 ** by Write() above to determine when to create a new PMA.
87037 ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
87038 ** Rewind() is called, then a hierarchy of incremental-merges is used.
87039 ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
87040 ** disk are merged together. Then T bytes of data from the second set, and
87041 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
87042 ** PMAs at a time. This done is to improve locality.
87044 ** If running in multi-threaded mode and there are more than
87045 ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
87046 ** than one background thread may be created. Specifically, there may be
87047 ** one background thread for each temporary file on disk, and one background
87048 ** thread to merge the output of each of the others to a single PMA for
87049 ** the main thread to read from.
87051 /* #include "sqliteInt.h" */
87052 /* #include "vdbeInt.h" */
87055 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
87056 ** messages to stderr that may be helpful in understanding the performance
87057 ** characteristics of the sorter in multi-threaded mode.
87059 #if 0
87060 # define SQLITE_DEBUG_SORTER_THREADS 1
87061 #endif
87064 ** Hard-coded maximum amount of data to accumulate in memory before flushing
87065 ** to a level 0 PMA. The purpose of this limit is to prevent various integer
87066 ** overflows. 512MiB.
87068 #define SQLITE_MAX_PMASZ (1<<29)
87071 ** Private objects used by the sorter
87073 typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
87074 typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
87075 typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
87076 typedef struct SorterRecord SorterRecord; /* A record being sorted */
87077 typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
87078 typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
87079 typedef struct SorterList SorterList; /* In-memory list of records */
87080 typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
87083 ** A container for a temp file handle and the current amount of data
87084 ** stored in the file.
87086 struct SorterFile {
87087 sqlite3_file *pFd; /* File handle */
87088 i64 iEof; /* Bytes of data stored in pFd */
87092 ** An in-memory list of objects to be sorted.
87094 ** If aMemory==0 then each object is allocated separately and the objects
87095 ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
87096 ** are stored in the aMemory[] bulk memory, one right after the other, and
87097 ** are connected using SorterRecord.u.iNext.
87099 struct SorterList {
87100 SorterRecord *pList; /* Linked list of records */
87101 u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
87102 int szPMA; /* Size of pList as PMA in bytes */
87106 ** The MergeEngine object is used to combine two or more smaller PMAs into
87107 ** one big PMA using a merge operation. Separate PMAs all need to be
87108 ** combined into one big PMA in order to be able to step through the sorted
87109 ** records in order.
87111 ** The aReadr[] array contains a PmaReader object for each of the PMAs being
87112 ** merged. An aReadr[] object either points to a valid key or else is at EOF.
87113 ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
87114 ** For the purposes of the paragraphs below, we assume that the array is
87115 ** actually N elements in size, where N is the smallest power of 2 greater
87116 ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
87117 ** are treated as if they are empty (always at EOF).
87119 ** The aTree[] array is also N elements in size. The value of N is stored in
87120 ** the MergeEngine.nTree variable.
87122 ** The final (N/2) elements of aTree[] contain the results of comparing
87123 ** pairs of PMA keys together. Element i contains the result of
87124 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
87125 ** aTree element is set to the index of it.
87127 ** For the purposes of this comparison, EOF is considered greater than any
87128 ** other key value. If the keys are equal (only possible with two EOF
87129 ** values), it doesn't matter which index is stored.
87131 ** The (N/4) elements of aTree[] that precede the final (N/2) described
87132 ** above contains the index of the smallest of each block of 4 PmaReaders
87133 ** And so on. So that aTree[1] contains the index of the PmaReader that
87134 ** currently points to the smallest key value. aTree[0] is unused.
87136 ** Example:
87138 ** aReadr[0] -> Banana
87139 ** aReadr[1] -> Feijoa
87140 ** aReadr[2] -> Elderberry
87141 ** aReadr[3] -> Currant
87142 ** aReadr[4] -> Grapefruit
87143 ** aReadr[5] -> Apple
87144 ** aReadr[6] -> Durian
87145 ** aReadr[7] -> EOF
87147 ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
87149 ** The current element is "Apple" (the value of the key indicated by
87150 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
87151 ** be advanced to the next key in its segment. Say the next key is
87152 ** "Eggplant":
87154 ** aReadr[5] -> Eggplant
87156 ** The contents of aTree[] are updated first by comparing the new PmaReader
87157 ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
87158 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
87159 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
87160 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
87161 ** so the value written into element 1 of the array is 0. As follows:
87163 ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
87165 ** In other words, each time we advance to the next sorter element, log2(N)
87166 ** key comparison operations are required, where N is the number of segments
87167 ** being merged (rounded up to the next power of 2).
87169 struct MergeEngine {
87170 int nTree; /* Used size of aTree/aReadr (power of 2) */
87171 SortSubtask *pTask; /* Used by this thread only */
87172 int *aTree; /* Current state of incremental merge */
87173 PmaReader *aReadr; /* Array of PmaReaders to merge data from */
87177 ** This object represents a single thread of control in a sort operation.
87178 ** Exactly VdbeSorter.nTask instances of this object are allocated
87179 ** as part of each VdbeSorter object. Instances are never allocated any
87180 ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
87181 ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
87182 ** single-threaded operation, there is exactly one instance of this object
87183 ** and for multi-threaded operation there are two or more instances.
87185 ** Essentially, this structure contains all those fields of the VdbeSorter
87186 ** structure for which each thread requires a separate instance. For example,
87187 ** each thread requries its own UnpackedRecord object to unpack records in
87188 ** as part of comparison operations.
87190 ** Before a background thread is launched, variable bDone is set to 0. Then,
87191 ** right before it exits, the thread itself sets bDone to 1. This is used for
87192 ** two purposes:
87194 ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
87195 ** attempt to select a SortSubtask for which there is not already an
87196 ** active background thread (since doing so causes the main thread
87197 ** to block until it finishes).
87199 ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
87200 ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
87201 ** block provoke debugging output.
87203 ** In both cases, the effects of the main thread seeing (bDone==0) even
87204 ** after the thread has finished are not dire. So we don't worry about
87205 ** memory barriers and such here.
87207 typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
87208 struct SortSubtask {
87209 SQLiteThread *pThread; /* Background thread, if any */
87210 int bDone; /* Set if thread is finished but not joined */
87211 VdbeSorter *pSorter; /* Sorter that owns this sub-task */
87212 UnpackedRecord *pUnpacked; /* Space to unpack a record */
87213 SorterList list; /* List for thread to write to a PMA */
87214 int nPMA; /* Number of PMAs currently in file */
87215 SorterCompare xCompare; /* Compare function to use */
87216 SorterFile file; /* Temp file for level-0 PMAs */
87217 SorterFile file2; /* Space for other PMAs */
87222 ** Main sorter structure. A single instance of this is allocated for each
87223 ** sorter cursor created by the VDBE.
87225 ** mxKeysize:
87226 ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
87227 ** this variable is updated so as to be set to the size on disk of the
87228 ** largest record in the sorter.
87230 struct VdbeSorter {
87231 int mnPmaSize; /* Minimum PMA size, in bytes */
87232 int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
87233 int mxKeysize; /* Largest serialized key seen so far */
87234 int pgsz; /* Main database page size */
87235 PmaReader *pReader; /* Readr data from here after Rewind() */
87236 MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
87237 sqlite3 *db; /* Database connection */
87238 KeyInfo *pKeyInfo; /* How to compare records */
87239 UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
87240 SorterList list; /* List of in-memory records */
87241 int iMemory; /* Offset of free space in list.aMemory */
87242 int nMemory; /* Size of list.aMemory allocation in bytes */
87243 u8 bUsePMA; /* True if one or more PMAs created */
87244 u8 bUseThreads; /* True to use background threads */
87245 u8 iPrev; /* Previous thread used to flush PMA */
87246 u8 nTask; /* Size of aTask[] array */
87247 u8 typeMask;
87248 SortSubtask aTask[1]; /* One or more subtasks */
87251 #define SORTER_TYPE_INTEGER 0x01
87252 #define SORTER_TYPE_TEXT 0x02
87255 ** An instance of the following object is used to read records out of a
87256 ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
87257 ** aKey might point into aMap or into aBuffer. If neither of those locations
87258 ** contain a contiguous representation of the key, then aAlloc is allocated
87259 ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
87261 ** pFd==0 at EOF.
87263 struct PmaReader {
87264 i64 iReadOff; /* Current read offset */
87265 i64 iEof; /* 1 byte past EOF for this PmaReader */
87266 int nAlloc; /* Bytes of space at aAlloc */
87267 int nKey; /* Number of bytes in key */
87268 sqlite3_file *pFd; /* File handle we are reading from */
87269 u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
87270 u8 *aKey; /* Pointer to current key */
87271 u8 *aBuffer; /* Current read buffer */
87272 int nBuffer; /* Size of read buffer in bytes */
87273 u8 *aMap; /* Pointer to mapping of entire file */
87274 IncrMerger *pIncr; /* Incremental merger */
87278 ** Normally, a PmaReader object iterates through an existing PMA stored
87279 ** within a temp file. However, if the PmaReader.pIncr variable points to
87280 ** an object of the following type, it may be used to iterate/merge through
87281 ** multiple PMAs simultaneously.
87283 ** There are two types of IncrMerger object - single (bUseThread==0) and
87284 ** multi-threaded (bUseThread==1).
87286 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
87287 ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
87288 ** size. When the IncrMerger is initialized, it reads enough data from
87289 ** pMerger to populate aFile[0]. It then sets variables within the
87290 ** corresponding PmaReader object to read from that file and kicks off
87291 ** a background thread to populate aFile[1] with the next mxSz bytes of
87292 ** sorted record data from pMerger.
87294 ** When the PmaReader reaches the end of aFile[0], it blocks until the
87295 ** background thread has finished populating aFile[1]. It then exchanges
87296 ** the contents of the aFile[0] and aFile[1] variables within this structure,
87297 ** sets the PmaReader fields to read from the new aFile[0] and kicks off
87298 ** another background thread to populate the new aFile[1]. And so on, until
87299 ** the contents of pMerger are exhausted.
87301 ** A single-threaded IncrMerger does not open any temporary files of its
87302 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
87303 ** at offset iStartOff of file pTask->file2. And instead of using a
87304 ** background thread to prepare data for the PmaReader, with a single
87305 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
87306 ** keys from pMerger by the calling thread whenever the PmaReader runs out
87307 ** of data.
87309 struct IncrMerger {
87310 SortSubtask *pTask; /* Task that owns this merger */
87311 MergeEngine *pMerger; /* Merge engine thread reads data from */
87312 i64 iStartOff; /* Offset to start writing file at */
87313 int mxSz; /* Maximum bytes of data to store */
87314 int bEof; /* Set to true when merge is finished */
87315 int bUseThread; /* True to use a bg thread for this object */
87316 SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
87320 ** An instance of this object is used for writing a PMA.
87322 ** The PMA is written one record at a time. Each record is of an arbitrary
87323 ** size. But I/O is more efficient if it occurs in page-sized blocks where
87324 ** each block is aligned on a page boundary. This object caches writes to
87325 ** the PMA so that aligned, page-size blocks are written.
87327 struct PmaWriter {
87328 int eFWErr; /* Non-zero if in an error state */
87329 u8 *aBuffer; /* Pointer to write buffer */
87330 int nBuffer; /* Size of write buffer in bytes */
87331 int iBufStart; /* First byte of buffer to write */
87332 int iBufEnd; /* Last byte of buffer to write */
87333 i64 iWriteOff; /* Offset of start of buffer in file */
87334 sqlite3_file *pFd; /* File handle to write to */
87338 ** This object is the header on a single record while that record is being
87339 ** held in memory and prior to being written out as part of a PMA.
87341 ** How the linked list is connected depends on how memory is being managed
87342 ** by this module. If using a separate allocation for each in-memory record
87343 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
87344 ** SorterRecord.u.pNext pointers.
87346 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
87347 ** then while records are being accumulated the list is linked using the
87348 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
87349 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
87350 ** has finished passing records to the sorter, or when the in-memory buffer
87351 ** is full, the list is sorted. As part of the sorting process, it is
87352 ** converted to use the SorterRecord.u.pNext pointers. See function
87353 ** vdbeSorterSort() for details.
87355 struct SorterRecord {
87356 int nVal; /* Size of the record in bytes */
87357 union {
87358 SorterRecord *pNext; /* Pointer to next record in list */
87359 int iNext; /* Offset within aMemory of next record */
87360 } u;
87361 /* The data for the record immediately follows this header */
87364 /* Return a pointer to the buffer containing the record data for SorterRecord
87365 ** object p. Should be used as if:
87367 ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
87369 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
87372 /* Maximum number of PMAs that a single MergeEngine can merge */
87373 #define SORTER_MAX_MERGE_COUNT 16
87375 static int vdbeIncrSwap(IncrMerger*);
87376 static void vdbeIncrFree(IncrMerger *);
87379 ** Free all memory belonging to the PmaReader object passed as the
87380 ** argument. All structure fields are set to zero before returning.
87382 static void vdbePmaReaderClear(PmaReader *pReadr){
87383 sqlite3_free(pReadr->aAlloc);
87384 sqlite3_free(pReadr->aBuffer);
87385 if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
87386 vdbeIncrFree(pReadr->pIncr);
87387 memset(pReadr, 0, sizeof(PmaReader));
87391 ** Read the next nByte bytes of data from the PMA p.
87392 ** If successful, set *ppOut to point to a buffer containing the data
87393 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
87394 ** error code.
87396 ** The buffer returned in *ppOut is only valid until the
87397 ** next call to this function.
87399 static int vdbePmaReadBlob(
87400 PmaReader *p, /* PmaReader from which to take the blob */
87401 int nByte, /* Bytes of data to read */
87402 u8 **ppOut /* OUT: Pointer to buffer containing data */
87404 int iBuf; /* Offset within buffer to read from */
87405 int nAvail; /* Bytes of data available in buffer */
87407 if( p->aMap ){
87408 *ppOut = &p->aMap[p->iReadOff];
87409 p->iReadOff += nByte;
87410 return SQLITE_OK;
87413 assert( p->aBuffer );
87415 /* If there is no more data to be read from the buffer, read the next
87416 ** p->nBuffer bytes of data from the file into it. Or, if there are less
87417 ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
87418 iBuf = p->iReadOff % p->nBuffer;
87419 if( iBuf==0 ){
87420 int nRead; /* Bytes to read from disk */
87421 int rc; /* sqlite3OsRead() return code */
87423 /* Determine how many bytes of data to read. */
87424 if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
87425 nRead = p->nBuffer;
87426 }else{
87427 nRead = (int)(p->iEof - p->iReadOff);
87429 assert( nRead>0 );
87431 /* Readr data from the file. Return early if an error occurs. */
87432 rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
87433 assert( rc!=SQLITE_IOERR_SHORT_READ );
87434 if( rc!=SQLITE_OK ) return rc;
87436 nAvail = p->nBuffer - iBuf;
87438 if( nByte<=nAvail ){
87439 /* The requested data is available in the in-memory buffer. In this
87440 ** case there is no need to make a copy of the data, just return a
87441 ** pointer into the buffer to the caller. */
87442 *ppOut = &p->aBuffer[iBuf];
87443 p->iReadOff += nByte;
87444 }else{
87445 /* The requested data is not all available in the in-memory buffer.
87446 ** In this case, allocate space at p->aAlloc[] to copy the requested
87447 ** range into. Then return a copy of pointer p->aAlloc to the caller. */
87448 int nRem; /* Bytes remaining to copy */
87450 /* Extend the p->aAlloc[] allocation if required. */
87451 if( p->nAlloc<nByte ){
87452 u8 *aNew;
87453 int nNew = MAX(128, p->nAlloc*2);
87454 while( nByte>nNew ) nNew = nNew*2;
87455 aNew = sqlite3Realloc(p->aAlloc, nNew);
87456 if( !aNew ) return SQLITE_NOMEM_BKPT;
87457 p->nAlloc = nNew;
87458 p->aAlloc = aNew;
87461 /* Copy as much data as is available in the buffer into the start of
87462 ** p->aAlloc[]. */
87463 memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
87464 p->iReadOff += nAvail;
87465 nRem = nByte - nAvail;
87467 /* The following loop copies up to p->nBuffer bytes per iteration into
87468 ** the p->aAlloc[] buffer. */
87469 while( nRem>0 ){
87470 int rc; /* vdbePmaReadBlob() return code */
87471 int nCopy; /* Number of bytes to copy */
87472 u8 *aNext; /* Pointer to buffer to copy data from */
87474 nCopy = nRem;
87475 if( nRem>p->nBuffer ) nCopy = p->nBuffer;
87476 rc = vdbePmaReadBlob(p, nCopy, &aNext);
87477 if( rc!=SQLITE_OK ) return rc;
87478 assert( aNext!=p->aAlloc );
87479 memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
87480 nRem -= nCopy;
87483 *ppOut = p->aAlloc;
87486 return SQLITE_OK;
87490 ** Read a varint from the stream of data accessed by p. Set *pnOut to
87491 ** the value read.
87493 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
87494 int iBuf;
87496 if( p->aMap ){
87497 p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
87498 }else{
87499 iBuf = p->iReadOff % p->nBuffer;
87500 if( iBuf && (p->nBuffer-iBuf)>=9 ){
87501 p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
87502 }else{
87503 u8 aVarint[16], *a;
87504 int i = 0, rc;
87506 rc = vdbePmaReadBlob(p, 1, &a);
87507 if( rc ) return rc;
87508 aVarint[(i++)&0xf] = a[0];
87509 }while( (a[0]&0x80)!=0 );
87510 sqlite3GetVarint(aVarint, pnOut);
87514 return SQLITE_OK;
87518 ** Attempt to memory map file pFile. If successful, set *pp to point to the
87519 ** new mapping and return SQLITE_OK. If the mapping is not attempted
87520 ** (because the file is too large or the VFS layer is configured not to use
87521 ** mmap), return SQLITE_OK and set *pp to NULL.
87523 ** Or, if an error occurs, return an SQLite error code. The final value of
87524 ** *pp is undefined in this case.
87526 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
87527 int rc = SQLITE_OK;
87528 if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
87529 sqlite3_file *pFd = pFile->pFd;
87530 if( pFd->pMethods->iVersion>=3 ){
87531 rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
87532 testcase( rc!=SQLITE_OK );
87535 return rc;
87539 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
87540 ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
87541 ** if successful, or an SQLite error code if an error occurs.
87543 static int vdbePmaReaderSeek(
87544 SortSubtask *pTask, /* Task context */
87545 PmaReader *pReadr, /* Reader whose cursor is to be moved */
87546 SorterFile *pFile, /* Sorter file to read from */
87547 i64 iOff /* Offset in pFile */
87549 int rc = SQLITE_OK;
87551 assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
87553 if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
87554 if( pReadr->aMap ){
87555 sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
87556 pReadr->aMap = 0;
87558 pReadr->iReadOff = iOff;
87559 pReadr->iEof = pFile->iEof;
87560 pReadr->pFd = pFile->pFd;
87562 rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
87563 if( rc==SQLITE_OK && pReadr->aMap==0 ){
87564 int pgsz = pTask->pSorter->pgsz;
87565 int iBuf = pReadr->iReadOff % pgsz;
87566 if( pReadr->aBuffer==0 ){
87567 pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
87568 if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
87569 pReadr->nBuffer = pgsz;
87571 if( rc==SQLITE_OK && iBuf ){
87572 int nRead = pgsz - iBuf;
87573 if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
87574 nRead = (int)(pReadr->iEof - pReadr->iReadOff);
87576 rc = sqlite3OsRead(
87577 pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
87579 testcase( rc!=SQLITE_OK );
87583 return rc;
87587 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
87588 ** no error occurs, or an SQLite error code if one does.
87590 static int vdbePmaReaderNext(PmaReader *pReadr){
87591 int rc = SQLITE_OK; /* Return Code */
87592 u64 nRec = 0; /* Size of record in bytes */
87595 if( pReadr->iReadOff>=pReadr->iEof ){
87596 IncrMerger *pIncr = pReadr->pIncr;
87597 int bEof = 1;
87598 if( pIncr ){
87599 rc = vdbeIncrSwap(pIncr);
87600 if( rc==SQLITE_OK && pIncr->bEof==0 ){
87601 rc = vdbePmaReaderSeek(
87602 pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
87604 bEof = 0;
87608 if( bEof ){
87609 /* This is an EOF condition */
87610 vdbePmaReaderClear(pReadr);
87611 testcase( rc!=SQLITE_OK );
87612 return rc;
87616 if( rc==SQLITE_OK ){
87617 rc = vdbePmaReadVarint(pReadr, &nRec);
87619 if( rc==SQLITE_OK ){
87620 pReadr->nKey = (int)nRec;
87621 rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
87622 testcase( rc!=SQLITE_OK );
87625 return rc;
87629 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
87630 ** starting at offset iStart and ending at offset iEof-1. This function
87631 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
87632 ** PMA is empty).
87634 ** If the pnByte parameter is NULL, then it is assumed that the file
87635 ** contains a single PMA, and that that PMA omits the initial length varint.
87637 static int vdbePmaReaderInit(
87638 SortSubtask *pTask, /* Task context */
87639 SorterFile *pFile, /* Sorter file to read from */
87640 i64 iStart, /* Start offset in pFile */
87641 PmaReader *pReadr, /* PmaReader to populate */
87642 i64 *pnByte /* IN/OUT: Increment this value by PMA size */
87644 int rc;
87646 assert( pFile->iEof>iStart );
87647 assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
87648 assert( pReadr->aBuffer==0 );
87649 assert( pReadr->aMap==0 );
87651 rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
87652 if( rc==SQLITE_OK ){
87653 u64 nByte = 0; /* Size of PMA in bytes */
87654 rc = vdbePmaReadVarint(pReadr, &nByte);
87655 pReadr->iEof = pReadr->iReadOff + nByte;
87656 *pnByte += nByte;
87659 if( rc==SQLITE_OK ){
87660 rc = vdbePmaReaderNext(pReadr);
87662 return rc;
87666 ** A version of vdbeSorterCompare() that assumes that it has already been
87667 ** determined that the first field of key1 is equal to the first field of
87668 ** key2.
87670 static int vdbeSorterCompareTail(
87671 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
87672 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
87673 const void *pKey1, int nKey1, /* Left side of comparison */
87674 const void *pKey2, int nKey2 /* Right side of comparison */
87676 UnpackedRecord *r2 = pTask->pUnpacked;
87677 if( *pbKey2Cached==0 ){
87678 sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
87679 *pbKey2Cached = 1;
87681 return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
87685 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
87686 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
87687 ** used by the comparison. Return the result of the comparison.
87689 ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
87690 ** it is assumed that (pTask->pUnpacked) contains the unpacked version
87691 ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
87692 ** version of key2 and *pbKey2Cached set to true before returning.
87694 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
87695 ** to SQLITE_NOMEM.
87697 static int vdbeSorterCompare(
87698 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
87699 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
87700 const void *pKey1, int nKey1, /* Left side of comparison */
87701 const void *pKey2, int nKey2 /* Right side of comparison */
87703 UnpackedRecord *r2 = pTask->pUnpacked;
87704 if( !*pbKey2Cached ){
87705 sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
87706 *pbKey2Cached = 1;
87708 return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
87712 ** A specially optimized version of vdbeSorterCompare() that assumes that
87713 ** the first field of each key is a TEXT value and that the collation
87714 ** sequence to compare them with is BINARY.
87716 static int vdbeSorterCompareText(
87717 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
87718 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
87719 const void *pKey1, int nKey1, /* Left side of comparison */
87720 const void *pKey2, int nKey2 /* Right side of comparison */
87722 const u8 * const p1 = (const u8 * const)pKey1;
87723 const u8 * const p2 = (const u8 * const)pKey2;
87724 const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
87725 const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
87727 int n1;
87728 int n2;
87729 int res;
87731 getVarint32(&p1[1], n1);
87732 getVarint32(&p2[1], n2);
87733 res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
87734 if( res==0 ){
87735 res = n1 - n2;
87738 if( res==0 ){
87739 if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
87740 res = vdbeSorterCompareTail(
87741 pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
87744 }else{
87745 if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
87746 res = res * -1;
87750 return res;
87754 ** A specially optimized version of vdbeSorterCompare() that assumes that
87755 ** the first field of each key is an INTEGER value.
87757 static int vdbeSorterCompareInt(
87758 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
87759 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
87760 const void *pKey1, int nKey1, /* Left side of comparison */
87761 const void *pKey2, int nKey2 /* Right side of comparison */
87763 const u8 * const p1 = (const u8 * const)pKey1;
87764 const u8 * const p2 = (const u8 * const)pKey2;
87765 const int s1 = p1[1]; /* Left hand serial type */
87766 const int s2 = p2[1]; /* Right hand serial type */
87767 const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
87768 const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
87769 int res; /* Return value */
87771 assert( (s1>0 && s1<7) || s1==8 || s1==9 );
87772 assert( (s2>0 && s2<7) || s2==8 || s2==9 );
87774 if( s1==s2 ){
87775 /* The two values have the same sign. Compare using memcmp(). */
87776 static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
87777 const u8 n = aLen[s1];
87778 int i;
87779 res = 0;
87780 for(i=0; i<n; i++){
87781 if( (res = v1[i] - v2[i])!=0 ){
87782 if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
87783 res = v1[0] & 0x80 ? -1 : +1;
87785 break;
87788 }else if( s1>7 && s2>7 ){
87789 res = s1 - s2;
87790 }else{
87791 if( s2>7 ){
87792 res = +1;
87793 }else if( s1>7 ){
87794 res = -1;
87795 }else{
87796 res = s1 - s2;
87798 assert( res!=0 );
87800 if( res>0 ){
87801 if( *v1 & 0x80 ) res = -1;
87802 }else{
87803 if( *v2 & 0x80 ) res = +1;
87807 if( res==0 ){
87808 if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
87809 res = vdbeSorterCompareTail(
87810 pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
87813 }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
87814 res = res * -1;
87817 return res;
87821 ** Initialize the temporary index cursor just opened as a sorter cursor.
87823 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
87824 ** to determine the number of fields that should be compared from the
87825 ** records being sorted. However, if the value passed as argument nField
87826 ** is non-zero and the sorter is able to guarantee a stable sort, nField
87827 ** is used instead. This is used when sorting records for a CREATE INDEX
87828 ** statement. In this case, keys are always delivered to the sorter in
87829 ** order of the primary key, which happens to be make up the final part
87830 ** of the records being sorted. So if the sort is stable, there is never
87831 ** any reason to compare PK fields and they can be ignored for a small
87832 ** performance boost.
87834 ** The sorter can guarantee a stable sort when running in single-threaded
87835 ** mode, but not in multi-threaded mode.
87837 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
87839 SQLITE_PRIVATE int sqlite3VdbeSorterInit(
87840 sqlite3 *db, /* Database connection (for malloc()) */
87841 int nField, /* Number of key fields in each record */
87842 VdbeCursor *pCsr /* Cursor that holds the new sorter */
87844 int pgsz; /* Page size of main database */
87845 int i; /* Used to iterate through aTask[] */
87846 VdbeSorter *pSorter; /* The new sorter */
87847 KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
87848 int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
87849 int sz; /* Size of pSorter in bytes */
87850 int rc = SQLITE_OK;
87851 #if SQLITE_MAX_WORKER_THREADS==0
87852 # define nWorker 0
87853 #else
87854 int nWorker;
87855 #endif
87857 /* Initialize the upper limit on the number of worker threads */
87858 #if SQLITE_MAX_WORKER_THREADS>0
87859 if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
87860 nWorker = 0;
87861 }else{
87862 nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
87864 #endif
87866 /* Do not allow the total number of threads (main thread + all workers)
87867 ** to exceed the maximum merge count */
87868 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
87869 if( nWorker>=SORTER_MAX_MERGE_COUNT ){
87870 nWorker = SORTER_MAX_MERGE_COUNT-1;
87872 #endif
87874 assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
87875 assert( pCsr->eCurType==CURTYPE_SORTER );
87876 szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
87877 sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
87879 pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
87880 pCsr->uc.pSorter = pSorter;
87881 if( pSorter==0 ){
87882 rc = SQLITE_NOMEM_BKPT;
87883 }else{
87884 pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
87885 memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
87886 pKeyInfo->db = 0;
87887 if( nField && nWorker==0 ){
87888 pKeyInfo->nKeyField = nField;
87890 pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
87891 pSorter->nTask = nWorker + 1;
87892 pSorter->iPrev = (u8)(nWorker - 1);
87893 pSorter->bUseThreads = (pSorter->nTask>1);
87894 pSorter->db = db;
87895 for(i=0; i<pSorter->nTask; i++){
87896 SortSubtask *pTask = &pSorter->aTask[i];
87897 pTask->pSorter = pSorter;
87900 if( !sqlite3TempInMemory(db) ){
87901 i64 mxCache; /* Cache size in bytes*/
87902 u32 szPma = sqlite3GlobalConfig.szPma;
87903 pSorter->mnPmaSize = szPma * pgsz;
87905 mxCache = db->aDb[0].pSchema->cache_size;
87906 if( mxCache<0 ){
87907 /* A negative cache-size value C indicates that the cache is abs(C)
87908 ** KiB in size. */
87909 mxCache = mxCache * -1024;
87910 }else{
87911 mxCache = mxCache * pgsz;
87913 mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
87914 pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
87916 /* Avoid large memory allocations if the application has requested
87917 ** SQLITE_CONFIG_SMALL_MALLOC. */
87918 if( sqlite3GlobalConfig.bSmallMalloc==0 ){
87919 assert( pSorter->iMemory==0 );
87920 pSorter->nMemory = pgsz;
87921 pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
87922 if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
87926 if( pKeyInfo->nAllField<13
87927 && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
87929 pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
87933 return rc;
87935 #undef nWorker /* Defined at the top of this function */
87938 ** Free the list of sorted records starting at pRecord.
87940 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
87941 SorterRecord *p;
87942 SorterRecord *pNext;
87943 for(p=pRecord; p; p=pNext){
87944 pNext = p->u.pNext;
87945 sqlite3DbFree(db, p);
87950 ** Free all resources owned by the object indicated by argument pTask. All
87951 ** fields of *pTask are zeroed before returning.
87953 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
87954 sqlite3DbFree(db, pTask->pUnpacked);
87955 #if SQLITE_MAX_WORKER_THREADS>0
87956 /* pTask->list.aMemory can only be non-zero if it was handed memory
87957 ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
87958 if( pTask->list.aMemory ){
87959 sqlite3_free(pTask->list.aMemory);
87960 }else
87961 #endif
87963 assert( pTask->list.aMemory==0 );
87964 vdbeSorterRecordFree(0, pTask->list.pList);
87966 if( pTask->file.pFd ){
87967 sqlite3OsCloseFree(pTask->file.pFd);
87969 if( pTask->file2.pFd ){
87970 sqlite3OsCloseFree(pTask->file2.pFd);
87972 memset(pTask, 0, sizeof(SortSubtask));
87975 #ifdef SQLITE_DEBUG_SORTER_THREADS
87976 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
87977 i64 t;
87978 int iTask = (pTask - pTask->pSorter->aTask);
87979 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
87980 fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
87982 static void vdbeSorterRewindDebug(const char *zEvent){
87983 i64 t;
87984 sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
87985 fprintf(stderr, "%lld:X %s\n", t, zEvent);
87987 static void vdbeSorterPopulateDebug(
87988 SortSubtask *pTask,
87989 const char *zEvent
87991 i64 t;
87992 int iTask = (pTask - pTask->pSorter->aTask);
87993 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
87994 fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
87996 static void vdbeSorterBlockDebug(
87997 SortSubtask *pTask,
87998 int bBlocked,
87999 const char *zEvent
88001 if( bBlocked ){
88002 i64 t;
88003 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
88004 fprintf(stderr, "%lld:main %s\n", t, zEvent);
88007 #else
88008 # define vdbeSorterWorkDebug(x,y)
88009 # define vdbeSorterRewindDebug(y)
88010 # define vdbeSorterPopulateDebug(x,y)
88011 # define vdbeSorterBlockDebug(x,y,z)
88012 #endif
88014 #if SQLITE_MAX_WORKER_THREADS>0
88016 ** Join thread pTask->thread.
88018 static int vdbeSorterJoinThread(SortSubtask *pTask){
88019 int rc = SQLITE_OK;
88020 if( pTask->pThread ){
88021 #ifdef SQLITE_DEBUG_SORTER_THREADS
88022 int bDone = pTask->bDone;
88023 #endif
88024 void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
88025 vdbeSorterBlockDebug(pTask, !bDone, "enter");
88026 (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
88027 vdbeSorterBlockDebug(pTask, !bDone, "exit");
88028 rc = SQLITE_PTR_TO_INT(pRet);
88029 assert( pTask->bDone==1 );
88030 pTask->bDone = 0;
88031 pTask->pThread = 0;
88033 return rc;
88037 ** Launch a background thread to run xTask(pIn).
88039 static int vdbeSorterCreateThread(
88040 SortSubtask *pTask, /* Thread will use this task object */
88041 void *(*xTask)(void*), /* Routine to run in a separate thread */
88042 void *pIn /* Argument passed into xTask() */
88044 assert( pTask->pThread==0 && pTask->bDone==0 );
88045 return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
88049 ** Join all outstanding threads launched by SorterWrite() to create
88050 ** level-0 PMAs.
88052 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
88053 int rc = rcin;
88054 int i;
88056 /* This function is always called by the main user thread.
88058 ** If this function is being called after SorterRewind() has been called,
88059 ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
88060 ** is currently attempt to join one of the other threads. To avoid a race
88061 ** condition where this thread also attempts to join the same object, join
88062 ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
88063 for(i=pSorter->nTask-1; i>=0; i--){
88064 SortSubtask *pTask = &pSorter->aTask[i];
88065 int rc2 = vdbeSorterJoinThread(pTask);
88066 if( rc==SQLITE_OK ) rc = rc2;
88068 return rc;
88070 #else
88071 # define vdbeSorterJoinAll(x,rcin) (rcin)
88072 # define vdbeSorterJoinThread(pTask) SQLITE_OK
88073 #endif
88076 ** Allocate a new MergeEngine object capable of handling up to
88077 ** nReader PmaReader inputs.
88079 ** nReader is automatically rounded up to the next power of two.
88080 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
88082 static MergeEngine *vdbeMergeEngineNew(int nReader){
88083 int N = 2; /* Smallest power of two >= nReader */
88084 int nByte; /* Total bytes of space to allocate */
88085 MergeEngine *pNew; /* Pointer to allocated object to return */
88087 assert( nReader<=SORTER_MAX_MERGE_COUNT );
88089 while( N<nReader ) N += N;
88090 nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
88092 pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
88093 if( pNew ){
88094 pNew->nTree = N;
88095 pNew->pTask = 0;
88096 pNew->aReadr = (PmaReader*)&pNew[1];
88097 pNew->aTree = (int*)&pNew->aReadr[N];
88099 return pNew;
88103 ** Free the MergeEngine object passed as the only argument.
88105 static void vdbeMergeEngineFree(MergeEngine *pMerger){
88106 int i;
88107 if( pMerger ){
88108 for(i=0; i<pMerger->nTree; i++){
88109 vdbePmaReaderClear(&pMerger->aReadr[i]);
88112 sqlite3_free(pMerger);
88116 ** Free all resources associated with the IncrMerger object indicated by
88117 ** the first argument.
88119 static void vdbeIncrFree(IncrMerger *pIncr){
88120 if( pIncr ){
88121 #if SQLITE_MAX_WORKER_THREADS>0
88122 if( pIncr->bUseThread ){
88123 vdbeSorterJoinThread(pIncr->pTask);
88124 if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
88125 if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
88127 #endif
88128 vdbeMergeEngineFree(pIncr->pMerger);
88129 sqlite3_free(pIncr);
88134 ** Reset a sorting cursor back to its original empty state.
88136 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
88137 int i;
88138 (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
88139 assert( pSorter->bUseThreads || pSorter->pReader==0 );
88140 #if SQLITE_MAX_WORKER_THREADS>0
88141 if( pSorter->pReader ){
88142 vdbePmaReaderClear(pSorter->pReader);
88143 sqlite3DbFree(db, pSorter->pReader);
88144 pSorter->pReader = 0;
88146 #endif
88147 vdbeMergeEngineFree(pSorter->pMerger);
88148 pSorter->pMerger = 0;
88149 for(i=0; i<pSorter->nTask; i++){
88150 SortSubtask *pTask = &pSorter->aTask[i];
88151 vdbeSortSubtaskCleanup(db, pTask);
88152 pTask->pSorter = pSorter;
88154 if( pSorter->list.aMemory==0 ){
88155 vdbeSorterRecordFree(0, pSorter->list.pList);
88157 pSorter->list.pList = 0;
88158 pSorter->list.szPMA = 0;
88159 pSorter->bUsePMA = 0;
88160 pSorter->iMemory = 0;
88161 pSorter->mxKeysize = 0;
88162 sqlite3DbFree(db, pSorter->pUnpacked);
88163 pSorter->pUnpacked = 0;
88167 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
88169 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
88170 VdbeSorter *pSorter;
88171 assert( pCsr->eCurType==CURTYPE_SORTER );
88172 pSorter = pCsr->uc.pSorter;
88173 if( pSorter ){
88174 sqlite3VdbeSorterReset(db, pSorter);
88175 sqlite3_free(pSorter->list.aMemory);
88176 sqlite3DbFree(db, pSorter);
88177 pCsr->uc.pSorter = 0;
88181 #if SQLITE_MAX_MMAP_SIZE>0
88183 ** The first argument is a file-handle open on a temporary file. The file
88184 ** is guaranteed to be nByte bytes or smaller in size. This function
88185 ** attempts to extend the file to nByte bytes in size and to ensure that
88186 ** the VFS has memory mapped it.
88188 ** Whether or not the file does end up memory mapped of course depends on
88189 ** the specific VFS implementation.
88191 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
88192 if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
88193 void *p = 0;
88194 int chunksize = 4*1024;
88195 sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
88196 sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
88197 sqlite3OsFetch(pFd, 0, (int)nByte, &p);
88198 sqlite3OsUnfetch(pFd, 0, p);
88201 #else
88202 # define vdbeSorterExtendFile(x,y,z)
88203 #endif
88206 ** Allocate space for a file-handle and open a temporary file. If successful,
88207 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
88208 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
88210 static int vdbeSorterOpenTempFile(
88211 sqlite3 *db, /* Database handle doing sort */
88212 i64 nExtend, /* Attempt to extend file to this size */
88213 sqlite3_file **ppFd
88215 int rc;
88216 if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
88217 rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
88218 SQLITE_OPEN_TEMP_JOURNAL |
88219 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
88220 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
88222 if( rc==SQLITE_OK ){
88223 i64 max = SQLITE_MAX_MMAP_SIZE;
88224 sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
88225 if( nExtend>0 ){
88226 vdbeSorterExtendFile(db, *ppFd, nExtend);
88229 return rc;
88233 ** If it has not already been allocated, allocate the UnpackedRecord
88234 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
88235 ** if no allocation was required), or SQLITE_NOMEM otherwise.
88237 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
88238 if( pTask->pUnpacked==0 ){
88239 pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
88240 if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
88241 pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
88242 pTask->pUnpacked->errCode = 0;
88244 return SQLITE_OK;
88249 ** Merge the two sorted lists p1 and p2 into a single list.
88251 static SorterRecord *vdbeSorterMerge(
88252 SortSubtask *pTask, /* Calling thread context */
88253 SorterRecord *p1, /* First list to merge */
88254 SorterRecord *p2 /* Second list to merge */
88256 SorterRecord *pFinal = 0;
88257 SorterRecord **pp = &pFinal;
88258 int bCached = 0;
88260 assert( p1!=0 && p2!=0 );
88261 for(;;){
88262 int res;
88263 res = pTask->xCompare(
88264 pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
88267 if( res<=0 ){
88268 *pp = p1;
88269 pp = &p1->u.pNext;
88270 p1 = p1->u.pNext;
88271 if( p1==0 ){
88272 *pp = p2;
88273 break;
88275 }else{
88276 *pp = p2;
88277 pp = &p2->u.pNext;
88278 p2 = p2->u.pNext;
88279 bCached = 0;
88280 if( p2==0 ){
88281 *pp = p1;
88282 break;
88286 return pFinal;
88290 ** Return the SorterCompare function to compare values collected by the
88291 ** sorter object passed as the only argument.
88293 static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
88294 if( p->typeMask==SORTER_TYPE_INTEGER ){
88295 return vdbeSorterCompareInt;
88296 }else if( p->typeMask==SORTER_TYPE_TEXT ){
88297 return vdbeSorterCompareText;
88299 return vdbeSorterCompare;
88303 ** Sort the linked list of records headed at pTask->pList. Return
88304 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
88305 ** an error occurs.
88307 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
88308 int i;
88309 SorterRecord **aSlot;
88310 SorterRecord *p;
88311 int rc;
88313 rc = vdbeSortAllocUnpacked(pTask);
88314 if( rc!=SQLITE_OK ) return rc;
88316 p = pList->pList;
88317 pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
88319 aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
88320 if( !aSlot ){
88321 return SQLITE_NOMEM_BKPT;
88324 while( p ){
88325 SorterRecord *pNext;
88326 if( pList->aMemory ){
88327 if( (u8*)p==pList->aMemory ){
88328 pNext = 0;
88329 }else{
88330 assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
88331 pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
88333 }else{
88334 pNext = p->u.pNext;
88337 p->u.pNext = 0;
88338 for(i=0; aSlot[i]; i++){
88339 p = vdbeSorterMerge(pTask, p, aSlot[i]);
88340 aSlot[i] = 0;
88342 aSlot[i] = p;
88343 p = pNext;
88346 p = 0;
88347 for(i=0; i<64; i++){
88348 if( aSlot[i]==0 ) continue;
88349 p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
88351 pList->pList = p;
88353 sqlite3_free(aSlot);
88354 assert( pTask->pUnpacked->errCode==SQLITE_OK
88355 || pTask->pUnpacked->errCode==SQLITE_NOMEM
88357 return pTask->pUnpacked->errCode;
88361 ** Initialize a PMA-writer object.
88363 static void vdbePmaWriterInit(
88364 sqlite3_file *pFd, /* File handle to write to */
88365 PmaWriter *p, /* Object to populate */
88366 int nBuf, /* Buffer size */
88367 i64 iStart /* Offset of pFd to begin writing at */
88369 memset(p, 0, sizeof(PmaWriter));
88370 p->aBuffer = (u8*)sqlite3Malloc(nBuf);
88371 if( !p->aBuffer ){
88372 p->eFWErr = SQLITE_NOMEM_BKPT;
88373 }else{
88374 p->iBufEnd = p->iBufStart = (iStart % nBuf);
88375 p->iWriteOff = iStart - p->iBufStart;
88376 p->nBuffer = nBuf;
88377 p->pFd = pFd;
88382 ** Write nData bytes of data to the PMA. Return SQLITE_OK
88383 ** if successful, or an SQLite error code if an error occurs.
88385 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
88386 int nRem = nData;
88387 while( nRem>0 && p->eFWErr==0 ){
88388 int nCopy = nRem;
88389 if( nCopy>(p->nBuffer - p->iBufEnd) ){
88390 nCopy = p->nBuffer - p->iBufEnd;
88393 memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
88394 p->iBufEnd += nCopy;
88395 if( p->iBufEnd==p->nBuffer ){
88396 p->eFWErr = sqlite3OsWrite(p->pFd,
88397 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
88398 p->iWriteOff + p->iBufStart
88400 p->iBufStart = p->iBufEnd = 0;
88401 p->iWriteOff += p->nBuffer;
88403 assert( p->iBufEnd<p->nBuffer );
88405 nRem -= nCopy;
88410 ** Flush any buffered data to disk and clean up the PMA-writer object.
88411 ** The results of using the PMA-writer after this call are undefined.
88412 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
88413 ** required. Otherwise, return an SQLite error code.
88415 ** Before returning, set *piEof to the offset immediately following the
88416 ** last byte written to the file.
88418 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
88419 int rc;
88420 if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
88421 p->eFWErr = sqlite3OsWrite(p->pFd,
88422 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
88423 p->iWriteOff + p->iBufStart
88426 *piEof = (p->iWriteOff + p->iBufEnd);
88427 sqlite3_free(p->aBuffer);
88428 rc = p->eFWErr;
88429 memset(p, 0, sizeof(PmaWriter));
88430 return rc;
88434 ** Write value iVal encoded as a varint to the PMA. Return
88435 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
88437 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
88438 int nByte;
88439 u8 aByte[10];
88440 nByte = sqlite3PutVarint(aByte, iVal);
88441 vdbePmaWriteBlob(p, aByte, nByte);
88445 ** Write the current contents of in-memory linked-list pList to a level-0
88446 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
88447 ** successful, or an SQLite error code otherwise.
88449 ** The format of a PMA is:
88451 ** * A varint. This varint contains the total number of bytes of content
88452 ** in the PMA (not including the varint itself).
88454 ** * One or more records packed end-to-end in order of ascending keys.
88455 ** Each record consists of a varint followed by a blob of data (the
88456 ** key). The varint is the number of bytes in the blob of data.
88458 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
88459 sqlite3 *db = pTask->pSorter->db;
88460 int rc = SQLITE_OK; /* Return code */
88461 PmaWriter writer; /* Object used to write to the file */
88463 #ifdef SQLITE_DEBUG
88464 /* Set iSz to the expected size of file pTask->file after writing the PMA.
88465 ** This is used by an assert() statement at the end of this function. */
88466 i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
88467 #endif
88469 vdbeSorterWorkDebug(pTask, "enter");
88470 memset(&writer, 0, sizeof(PmaWriter));
88471 assert( pList->szPMA>0 );
88473 /* If the first temporary PMA file has not been opened, open it now. */
88474 if( pTask->file.pFd==0 ){
88475 rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
88476 assert( rc!=SQLITE_OK || pTask->file.pFd );
88477 assert( pTask->file.iEof==0 );
88478 assert( pTask->nPMA==0 );
88481 /* Try to get the file to memory map */
88482 if( rc==SQLITE_OK ){
88483 vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
88486 /* Sort the list */
88487 if( rc==SQLITE_OK ){
88488 rc = vdbeSorterSort(pTask, pList);
88491 if( rc==SQLITE_OK ){
88492 SorterRecord *p;
88493 SorterRecord *pNext = 0;
88495 vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
88496 pTask->file.iEof);
88497 pTask->nPMA++;
88498 vdbePmaWriteVarint(&writer, pList->szPMA);
88499 for(p=pList->pList; p; p=pNext){
88500 pNext = p->u.pNext;
88501 vdbePmaWriteVarint(&writer, p->nVal);
88502 vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
88503 if( pList->aMemory==0 ) sqlite3_free(p);
88505 pList->pList = p;
88506 rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
88509 vdbeSorterWorkDebug(pTask, "exit");
88510 assert( rc!=SQLITE_OK || pList->pList==0 );
88511 assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
88512 return rc;
88516 ** Advance the MergeEngine to its next entry.
88517 ** Set *pbEof to true there is no next entry because
88518 ** the MergeEngine has reached the end of all its inputs.
88520 ** Return SQLITE_OK if successful or an error code if an error occurs.
88522 static int vdbeMergeEngineStep(
88523 MergeEngine *pMerger, /* The merge engine to advance to the next row */
88524 int *pbEof /* Set TRUE at EOF. Set false for more content */
88526 int rc;
88527 int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
88528 SortSubtask *pTask = pMerger->pTask;
88530 /* Advance the current PmaReader */
88531 rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
88533 /* Update contents of aTree[] */
88534 if( rc==SQLITE_OK ){
88535 int i; /* Index of aTree[] to recalculate */
88536 PmaReader *pReadr1; /* First PmaReader to compare */
88537 PmaReader *pReadr2; /* Second PmaReader to compare */
88538 int bCached = 0;
88540 /* Find the first two PmaReaders to compare. The one that was just
88541 ** advanced (iPrev) and the one next to it in the array. */
88542 pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
88543 pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
88545 for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
88546 /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
88547 int iRes;
88548 if( pReadr1->pFd==0 ){
88549 iRes = +1;
88550 }else if( pReadr2->pFd==0 ){
88551 iRes = -1;
88552 }else{
88553 iRes = pTask->xCompare(pTask, &bCached,
88554 pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
88558 /* If pReadr1 contained the smaller value, set aTree[i] to its index.
88559 ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
88560 ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
88561 ** pKey2 to point to the record belonging to pReadr2.
88563 ** Alternatively, if pReadr2 contains the smaller of the two values,
88564 ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
88565 ** was actually called above, then pTask->pUnpacked now contains
88566 ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
88567 ** vdbeSorterCompare() from decoding pReadr2 again.
88569 ** If the two values were equal, then the value from the oldest
88570 ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
88571 ** is sorted from oldest to newest, so pReadr1 contains older values
88572 ** than pReadr2 iff (pReadr1<pReadr2). */
88573 if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
88574 pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
88575 pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
88576 bCached = 0;
88577 }else{
88578 if( pReadr1->pFd ) bCached = 0;
88579 pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
88580 pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
88583 *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
88586 return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
88589 #if SQLITE_MAX_WORKER_THREADS>0
88591 ** The main routine for background threads that write level-0 PMAs.
88593 static void *vdbeSorterFlushThread(void *pCtx){
88594 SortSubtask *pTask = (SortSubtask*)pCtx;
88595 int rc; /* Return code */
88596 assert( pTask->bDone==0 );
88597 rc = vdbeSorterListToPMA(pTask, &pTask->list);
88598 pTask->bDone = 1;
88599 return SQLITE_INT_TO_PTR(rc);
88601 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
88604 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
88605 ** using a background thread.
88607 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
88608 #if SQLITE_MAX_WORKER_THREADS==0
88609 pSorter->bUsePMA = 1;
88610 return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
88611 #else
88612 int rc = SQLITE_OK;
88613 int i;
88614 SortSubtask *pTask = 0; /* Thread context used to create new PMA */
88615 int nWorker = (pSorter->nTask-1);
88617 /* Set the flag to indicate that at least one PMA has been written.
88618 ** Or will be, anyhow. */
88619 pSorter->bUsePMA = 1;
88621 /* Select a sub-task to sort and flush the current list of in-memory
88622 ** records to disk. If the sorter is running in multi-threaded mode,
88623 ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
88624 ** the background thread from a sub-tasks previous turn is still running,
88625 ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
88626 ** fall back to using the final sub-task. The first (pSorter->nTask-1)
88627 ** sub-tasks are prefered as they use background threads - the final
88628 ** sub-task uses the main thread. */
88629 for(i=0; i<nWorker; i++){
88630 int iTest = (pSorter->iPrev + i + 1) % nWorker;
88631 pTask = &pSorter->aTask[iTest];
88632 if( pTask->bDone ){
88633 rc = vdbeSorterJoinThread(pTask);
88635 if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
88638 if( rc==SQLITE_OK ){
88639 if( i==nWorker ){
88640 /* Use the foreground thread for this operation */
88641 rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
88642 }else{
88643 /* Launch a background thread for this operation */
88644 u8 *aMem = pTask->list.aMemory;
88645 void *pCtx = (void*)pTask;
88647 assert( pTask->pThread==0 && pTask->bDone==0 );
88648 assert( pTask->list.pList==0 );
88649 assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
88651 pSorter->iPrev = (u8)(pTask - pSorter->aTask);
88652 pTask->list = pSorter->list;
88653 pSorter->list.pList = 0;
88654 pSorter->list.szPMA = 0;
88655 if( aMem ){
88656 pSorter->list.aMemory = aMem;
88657 pSorter->nMemory = sqlite3MallocSize(aMem);
88658 }else if( pSorter->list.aMemory ){
88659 pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
88660 if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
88663 rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
88667 return rc;
88668 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
88672 ** Add a record to the sorter.
88674 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
88675 const VdbeCursor *pCsr, /* Sorter cursor */
88676 Mem *pVal /* Memory cell containing record */
88678 VdbeSorter *pSorter;
88679 int rc = SQLITE_OK; /* Return Code */
88680 SorterRecord *pNew; /* New list element */
88681 int bFlush; /* True to flush contents of memory to PMA */
88682 int nReq; /* Bytes of memory required */
88683 int nPMA; /* Bytes of PMA space required */
88684 int t; /* serial type of first record field */
88686 assert( pCsr->eCurType==CURTYPE_SORTER );
88687 pSorter = pCsr->uc.pSorter;
88688 getVarint32((const u8*)&pVal->z[1], t);
88689 if( t>0 && t<10 && t!=7 ){
88690 pSorter->typeMask &= SORTER_TYPE_INTEGER;
88691 }else if( t>10 && (t & 0x01) ){
88692 pSorter->typeMask &= SORTER_TYPE_TEXT;
88693 }else{
88694 pSorter->typeMask = 0;
88697 assert( pSorter );
88699 /* Figure out whether or not the current contents of memory should be
88700 ** flushed to a PMA before continuing. If so, do so.
88702 ** If using the single large allocation mode (pSorter->aMemory!=0), then
88703 ** flush the contents of memory to a new PMA if (a) at least one value is
88704 ** already in memory and (b) the new value will not fit in memory.
88706 ** Or, if using separate allocations for each record, flush the contents
88707 ** of memory to a PMA if either of the following are true:
88709 ** * The total memory allocated for the in-memory list is greater
88710 ** than (page-size * cache-size), or
88712 ** * The total memory allocated for the in-memory list is greater
88713 ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
88715 nReq = pVal->n + sizeof(SorterRecord);
88716 nPMA = pVal->n + sqlite3VarintLen(pVal->n);
88717 if( pSorter->mxPmaSize ){
88718 if( pSorter->list.aMemory ){
88719 bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
88720 }else{
88721 bFlush = (
88722 (pSorter->list.szPMA > pSorter->mxPmaSize)
88723 || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
88726 if( bFlush ){
88727 rc = vdbeSorterFlushPMA(pSorter);
88728 pSorter->list.szPMA = 0;
88729 pSorter->iMemory = 0;
88730 assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
88734 pSorter->list.szPMA += nPMA;
88735 if( nPMA>pSorter->mxKeysize ){
88736 pSorter->mxKeysize = nPMA;
88739 if( pSorter->list.aMemory ){
88740 int nMin = pSorter->iMemory + nReq;
88742 if( nMin>pSorter->nMemory ){
88743 u8 *aNew;
88744 int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
88745 int nNew = pSorter->nMemory * 2;
88746 while( nNew < nMin ) nNew = nNew*2;
88747 if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
88748 if( nNew < nMin ) nNew = nMin;
88750 aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
88751 if( !aNew ) return SQLITE_NOMEM_BKPT;
88752 pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
88753 pSorter->list.aMemory = aNew;
88754 pSorter->nMemory = nNew;
88757 pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
88758 pSorter->iMemory += ROUND8(nReq);
88759 if( pSorter->list.pList ){
88760 pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
88762 }else{
88763 pNew = (SorterRecord *)sqlite3Malloc(nReq);
88764 if( pNew==0 ){
88765 return SQLITE_NOMEM_BKPT;
88767 pNew->u.pNext = pSorter->list.pList;
88770 memcpy(SRVAL(pNew), pVal->z, pVal->n);
88771 pNew->nVal = pVal->n;
88772 pSorter->list.pList = pNew;
88774 return rc;
88778 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
88779 ** of the data stored in aFile[1] is the same as that used by regular PMAs,
88780 ** except that the number-of-bytes varint is omitted from the start.
88782 static int vdbeIncrPopulate(IncrMerger *pIncr){
88783 int rc = SQLITE_OK;
88784 int rc2;
88785 i64 iStart = pIncr->iStartOff;
88786 SorterFile *pOut = &pIncr->aFile[1];
88787 SortSubtask *pTask = pIncr->pTask;
88788 MergeEngine *pMerger = pIncr->pMerger;
88789 PmaWriter writer;
88790 assert( pIncr->bEof==0 );
88792 vdbeSorterPopulateDebug(pTask, "enter");
88794 vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
88795 while( rc==SQLITE_OK ){
88796 int dummy;
88797 PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
88798 int nKey = pReader->nKey;
88799 i64 iEof = writer.iWriteOff + writer.iBufEnd;
88801 /* Check if the output file is full or if the input has been exhausted.
88802 ** In either case exit the loop. */
88803 if( pReader->pFd==0 ) break;
88804 if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
88806 /* Write the next key to the output. */
88807 vdbePmaWriteVarint(&writer, nKey);
88808 vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
88809 assert( pIncr->pMerger->pTask==pTask );
88810 rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
88813 rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
88814 if( rc==SQLITE_OK ) rc = rc2;
88815 vdbeSorterPopulateDebug(pTask, "exit");
88816 return rc;
88819 #if SQLITE_MAX_WORKER_THREADS>0
88821 ** The main routine for background threads that populate aFile[1] of
88822 ** multi-threaded IncrMerger objects.
88824 static void *vdbeIncrPopulateThread(void *pCtx){
88825 IncrMerger *pIncr = (IncrMerger*)pCtx;
88826 void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
88827 pIncr->pTask->bDone = 1;
88828 return pRet;
88832 ** Launch a background thread to populate aFile[1] of pIncr.
88834 static int vdbeIncrBgPopulate(IncrMerger *pIncr){
88835 void *p = (void*)pIncr;
88836 assert( pIncr->bUseThread );
88837 return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
88839 #endif
88842 ** This function is called when the PmaReader corresponding to pIncr has
88843 ** finished reading the contents of aFile[0]. Its purpose is to "refill"
88844 ** aFile[0] such that the PmaReader should start rereading it from the
88845 ** beginning.
88847 ** For single-threaded objects, this is accomplished by literally reading
88848 ** keys from pIncr->pMerger and repopulating aFile[0].
88850 ** For multi-threaded objects, all that is required is to wait until the
88851 ** background thread is finished (if it is not already) and then swap
88852 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
88853 ** been exhausted, this function also launches a new background thread
88854 ** to populate the new aFile[1].
88856 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
88858 static int vdbeIncrSwap(IncrMerger *pIncr){
88859 int rc = SQLITE_OK;
88861 #if SQLITE_MAX_WORKER_THREADS>0
88862 if( pIncr->bUseThread ){
88863 rc = vdbeSorterJoinThread(pIncr->pTask);
88865 if( rc==SQLITE_OK ){
88866 SorterFile f0 = pIncr->aFile[0];
88867 pIncr->aFile[0] = pIncr->aFile[1];
88868 pIncr->aFile[1] = f0;
88871 if( rc==SQLITE_OK ){
88872 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
88873 pIncr->bEof = 1;
88874 }else{
88875 rc = vdbeIncrBgPopulate(pIncr);
88878 }else
88879 #endif
88881 rc = vdbeIncrPopulate(pIncr);
88882 pIncr->aFile[0] = pIncr->aFile[1];
88883 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
88884 pIncr->bEof = 1;
88888 return rc;
88892 ** Allocate and return a new IncrMerger object to read data from pMerger.
88894 ** If an OOM condition is encountered, return NULL. In this case free the
88895 ** pMerger argument before returning.
88897 static int vdbeIncrMergerNew(
88898 SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
88899 MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
88900 IncrMerger **ppOut /* Write the new IncrMerger here */
88902 int rc = SQLITE_OK;
88903 IncrMerger *pIncr = *ppOut = (IncrMerger*)
88904 (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
88905 if( pIncr ){
88906 pIncr->pMerger = pMerger;
88907 pIncr->pTask = pTask;
88908 pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
88909 pTask->file2.iEof += pIncr->mxSz;
88910 }else{
88911 vdbeMergeEngineFree(pMerger);
88912 rc = SQLITE_NOMEM_BKPT;
88914 return rc;
88917 #if SQLITE_MAX_WORKER_THREADS>0
88919 ** Set the "use-threads" flag on object pIncr.
88921 static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
88922 pIncr->bUseThread = 1;
88923 pIncr->pTask->file2.iEof -= pIncr->mxSz;
88925 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
88930 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
88931 ** two PmaReaders that feed that entry. Neither of the PmaReaders
88932 ** are advanced. This routine merely does the comparison.
88934 static void vdbeMergeEngineCompare(
88935 MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
88936 int iOut /* Store the result in pMerger->aTree[iOut] */
88938 int i1;
88939 int i2;
88940 int iRes;
88941 PmaReader *p1;
88942 PmaReader *p2;
88944 assert( iOut<pMerger->nTree && iOut>0 );
88946 if( iOut>=(pMerger->nTree/2) ){
88947 i1 = (iOut - pMerger->nTree/2) * 2;
88948 i2 = i1 + 1;
88949 }else{
88950 i1 = pMerger->aTree[iOut*2];
88951 i2 = pMerger->aTree[iOut*2+1];
88954 p1 = &pMerger->aReadr[i1];
88955 p2 = &pMerger->aReadr[i2];
88957 if( p1->pFd==0 ){
88958 iRes = i2;
88959 }else if( p2->pFd==0 ){
88960 iRes = i1;
88961 }else{
88962 SortSubtask *pTask = pMerger->pTask;
88963 int bCached = 0;
88964 int res;
88965 assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
88966 res = pTask->xCompare(
88967 pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
88969 if( res<=0 ){
88970 iRes = i1;
88971 }else{
88972 iRes = i2;
88976 pMerger->aTree[iOut] = iRes;
88980 ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
88981 ** and vdbePmaReaderIncrMergeInit().
88983 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
88984 ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
88985 ** when there exists one or more separate worker threads.
88987 #define INCRINIT_NORMAL 0
88988 #define INCRINIT_TASK 1
88989 #define INCRINIT_ROOT 2
88992 ** Forward reference required as the vdbeIncrMergeInit() and
88993 ** vdbePmaReaderIncrInit() routines are called mutually recursively when
88994 ** building a merge tree.
88996 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
88999 ** Initialize the MergeEngine object passed as the second argument. Once this
89000 ** function returns, the first key of merged data may be read from the
89001 ** MergeEngine object in the usual fashion.
89003 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
89004 ** objects attached to the PmaReader objects that the merger reads from have
89005 ** already been populated, but that they have not yet populated aFile[0] and
89006 ** set the PmaReader objects up to read from it. In this case all that is
89007 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
89008 ** its first key.
89010 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
89011 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
89012 ** to pMerger.
89014 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
89016 static int vdbeMergeEngineInit(
89017 SortSubtask *pTask, /* Thread that will run pMerger */
89018 MergeEngine *pMerger, /* MergeEngine to initialize */
89019 int eMode /* One of the INCRINIT_XXX constants */
89021 int rc = SQLITE_OK; /* Return code */
89022 int i; /* For looping over PmaReader objects */
89023 int nTree = pMerger->nTree;
89025 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
89026 assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
89028 /* Verify that the MergeEngine is assigned to a single thread */
89029 assert( pMerger->pTask==0 );
89030 pMerger->pTask = pTask;
89032 for(i=0; i<nTree; i++){
89033 if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
89034 /* PmaReaders should be normally initialized in order, as if they are
89035 ** reading from the same temp file this makes for more linear file IO.
89036 ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
89037 ** in use it will block the vdbePmaReaderNext() call while it uses
89038 ** the main thread to fill its buffer. So calling PmaReaderNext()
89039 ** on this PmaReader before any of the multi-threaded PmaReaders takes
89040 ** better advantage of multi-processor hardware. */
89041 rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
89042 }else{
89043 rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
89045 if( rc!=SQLITE_OK ) return rc;
89048 for(i=pMerger->nTree-1; i>0; i--){
89049 vdbeMergeEngineCompare(pMerger, i);
89051 return pTask->pUnpacked->errCode;
89055 ** The PmaReader passed as the first argument is guaranteed to be an
89056 ** incremental-reader (pReadr->pIncr!=0). This function serves to open
89057 ** and/or initialize the temp file related fields of the IncrMerge
89058 ** object at (pReadr->pIncr).
89060 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
89061 ** in the sub-tree headed by pReadr are also initialized. Data is then
89062 ** loaded into the buffers belonging to pReadr and it is set to point to
89063 ** the first key in its range.
89065 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
89066 ** to be a multi-threaded PmaReader and this function is being called in a
89067 ** background thread. In this case all PmaReaders in the sub-tree are
89068 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
89069 ** pReadr is populated. However, pReadr itself is not set up to point
89070 ** to its first key. A call to vdbePmaReaderNext() is still required to do
89071 ** that.
89073 ** The reason this function does not call vdbePmaReaderNext() immediately
89074 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
89075 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
89076 ** this entire function is being run by thread (pTask->thread), that will
89077 ** lead to the current background thread attempting to join itself.
89079 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
89080 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
89081 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
89082 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
89083 ** the current PmaReader set to point to the first key in its range.
89085 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
89087 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
89088 int rc = SQLITE_OK;
89089 IncrMerger *pIncr = pReadr->pIncr;
89090 SortSubtask *pTask = pIncr->pTask;
89091 sqlite3 *db = pTask->pSorter->db;
89093 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
89094 assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
89096 rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
89098 /* Set up the required files for pIncr. A multi-theaded IncrMerge object
89099 ** requires two temp files to itself, whereas a single-threaded object
89100 ** only requires a region of pTask->file2. */
89101 if( rc==SQLITE_OK ){
89102 int mxSz = pIncr->mxSz;
89103 #if SQLITE_MAX_WORKER_THREADS>0
89104 if( pIncr->bUseThread ){
89105 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
89106 if( rc==SQLITE_OK ){
89107 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
89109 }else
89110 #endif
89111 /*if( !pIncr->bUseThread )*/{
89112 if( pTask->file2.pFd==0 ){
89113 assert( pTask->file2.iEof>0 );
89114 rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
89115 pTask->file2.iEof = 0;
89117 if( rc==SQLITE_OK ){
89118 pIncr->aFile[1].pFd = pTask->file2.pFd;
89119 pIncr->iStartOff = pTask->file2.iEof;
89120 pTask->file2.iEof += mxSz;
89125 #if SQLITE_MAX_WORKER_THREADS>0
89126 if( rc==SQLITE_OK && pIncr->bUseThread ){
89127 /* Use the current thread to populate aFile[1], even though this
89128 ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
89129 ** then this function is already running in background thread
89130 ** pIncr->pTask->thread.
89132 ** If this is the INCRINIT_ROOT object, then it is running in the
89133 ** main VDBE thread. But that is Ok, as that thread cannot return
89134 ** control to the VDBE or proceed with anything useful until the
89135 ** first results are ready from this merger object anyway.
89137 assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
89138 rc = vdbeIncrPopulate(pIncr);
89140 #endif
89142 if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
89143 rc = vdbePmaReaderNext(pReadr);
89146 return rc;
89149 #if SQLITE_MAX_WORKER_THREADS>0
89151 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
89152 ** background threads.
89154 static void *vdbePmaReaderBgIncrInit(void *pCtx){
89155 PmaReader *pReader = (PmaReader*)pCtx;
89156 void *pRet = SQLITE_INT_TO_PTR(
89157 vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
89159 pReader->pIncr->pTask->bDone = 1;
89160 return pRet;
89162 #endif
89165 ** If the PmaReader passed as the first argument is not an incremental-reader
89166 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
89167 ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
89168 ** this routine to initialize the incremental merge.
89170 ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
89171 ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
89172 ** Or, if the IncrMerger is single threaded, the same function is called
89173 ** using the current thread.
89175 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
89176 IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
89177 int rc = SQLITE_OK; /* Return code */
89178 if( pIncr ){
89179 #if SQLITE_MAX_WORKER_THREADS>0
89180 assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
89181 if( pIncr->bUseThread ){
89182 void *pCtx = (void*)pReadr;
89183 rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
89184 }else
89185 #endif
89187 rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
89190 return rc;
89194 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
89195 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
89196 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
89197 ** to NULL and return an SQLite error code.
89199 ** When this function is called, *piOffset is set to the offset of the
89200 ** first PMA to read from pTask->file. Assuming no error occurs, it is
89201 ** set to the offset immediately following the last byte of the last
89202 ** PMA before returning. If an error does occur, then the final value of
89203 ** *piOffset is undefined.
89205 static int vdbeMergeEngineLevel0(
89206 SortSubtask *pTask, /* Sorter task to read from */
89207 int nPMA, /* Number of PMAs to read */
89208 i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
89209 MergeEngine **ppOut /* OUT: New merge-engine */
89211 MergeEngine *pNew; /* Merge engine to return */
89212 i64 iOff = *piOffset;
89213 int i;
89214 int rc = SQLITE_OK;
89216 *ppOut = pNew = vdbeMergeEngineNew(nPMA);
89217 if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
89219 for(i=0; i<nPMA && rc==SQLITE_OK; i++){
89220 i64 nDummy = 0;
89221 PmaReader *pReadr = &pNew->aReadr[i];
89222 rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
89223 iOff = pReadr->iEof;
89226 if( rc!=SQLITE_OK ){
89227 vdbeMergeEngineFree(pNew);
89228 *ppOut = 0;
89230 *piOffset = iOff;
89231 return rc;
89235 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
89236 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
89238 ** i.e.
89240 ** nPMA<=16 -> TreeDepth() == 0
89241 ** nPMA<=256 -> TreeDepth() == 1
89242 ** nPMA<=65536 -> TreeDepth() == 2
89244 static int vdbeSorterTreeDepth(int nPMA){
89245 int nDepth = 0;
89246 i64 nDiv = SORTER_MAX_MERGE_COUNT;
89247 while( nDiv < (i64)nPMA ){
89248 nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
89249 nDepth++;
89251 return nDepth;
89255 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
89256 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
89257 ** tree, counting from zero. This function adds pLeaf to the tree.
89259 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
89260 ** code is returned and pLeaf is freed.
89262 static int vdbeSorterAddToTree(
89263 SortSubtask *pTask, /* Task context */
89264 int nDepth, /* Depth of tree according to TreeDepth() */
89265 int iSeq, /* Sequence number of leaf within tree */
89266 MergeEngine *pRoot, /* Root of tree */
89267 MergeEngine *pLeaf /* Leaf to add to tree */
89269 int rc = SQLITE_OK;
89270 int nDiv = 1;
89271 int i;
89272 MergeEngine *p = pRoot;
89273 IncrMerger *pIncr;
89275 rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
89277 for(i=1; i<nDepth; i++){
89278 nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
89281 for(i=1; i<nDepth && rc==SQLITE_OK; i++){
89282 int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
89283 PmaReader *pReadr = &p->aReadr[iIter];
89285 if( pReadr->pIncr==0 ){
89286 MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
89287 if( pNew==0 ){
89288 rc = SQLITE_NOMEM_BKPT;
89289 }else{
89290 rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
89293 if( rc==SQLITE_OK ){
89294 p = pReadr->pIncr->pMerger;
89295 nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
89299 if( rc==SQLITE_OK ){
89300 p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
89301 }else{
89302 vdbeIncrFree(pIncr);
89304 return rc;
89308 ** This function is called as part of a SorterRewind() operation on a sorter
89309 ** that has already written two or more level-0 PMAs to one or more temp
89310 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
89311 ** can be used to incrementally merge all PMAs on disk.
89313 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
89314 ** MergeEngine object at the root of the tree before returning. Or, if an
89315 ** error occurs, an SQLite error code is returned and the final value
89316 ** of *ppOut is undefined.
89318 static int vdbeSorterMergeTreeBuild(
89319 VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
89320 MergeEngine **ppOut /* Write the MergeEngine here */
89322 MergeEngine *pMain = 0;
89323 int rc = SQLITE_OK;
89324 int iTask;
89326 #if SQLITE_MAX_WORKER_THREADS>0
89327 /* If the sorter uses more than one task, then create the top-level
89328 ** MergeEngine here. This MergeEngine will read data from exactly
89329 ** one PmaReader per sub-task. */
89330 assert( pSorter->bUseThreads || pSorter->nTask==1 );
89331 if( pSorter->nTask>1 ){
89332 pMain = vdbeMergeEngineNew(pSorter->nTask);
89333 if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
89335 #endif
89337 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
89338 SortSubtask *pTask = &pSorter->aTask[iTask];
89339 assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
89340 if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
89341 MergeEngine *pRoot = 0; /* Root node of tree for this task */
89342 int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
89343 i64 iReadOff = 0;
89345 if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
89346 rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
89347 }else{
89348 int i;
89349 int iSeq = 0;
89350 pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
89351 if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
89352 for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
89353 MergeEngine *pMerger = 0; /* New level-0 PMA merger */
89354 int nReader; /* Number of level-0 PMAs to merge */
89356 nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
89357 rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
89358 if( rc==SQLITE_OK ){
89359 rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
89364 if( rc==SQLITE_OK ){
89365 #if SQLITE_MAX_WORKER_THREADS>0
89366 if( pMain!=0 ){
89367 rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
89368 }else
89369 #endif
89371 assert( pMain==0 );
89372 pMain = pRoot;
89374 }else{
89375 vdbeMergeEngineFree(pRoot);
89380 if( rc!=SQLITE_OK ){
89381 vdbeMergeEngineFree(pMain);
89382 pMain = 0;
89384 *ppOut = pMain;
89385 return rc;
89389 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
89390 ** on a sorter that has written two or more PMAs to temporary files. It sets
89391 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
89392 ** (for multi-threaded sorters) so that it can be used to iterate through
89393 ** all records stored in the sorter.
89395 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
89397 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
89398 int rc; /* Return code */
89399 SortSubtask *pTask0 = &pSorter->aTask[0];
89400 MergeEngine *pMain = 0;
89401 #if SQLITE_MAX_WORKER_THREADS
89402 sqlite3 *db = pTask0->pSorter->db;
89403 int i;
89404 SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
89405 for(i=0; i<pSorter->nTask; i++){
89406 pSorter->aTask[i].xCompare = xCompare;
89408 #endif
89410 rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
89411 if( rc==SQLITE_OK ){
89412 #if SQLITE_MAX_WORKER_THREADS
89413 assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
89414 if( pSorter->bUseThreads ){
89415 int iTask;
89416 PmaReader *pReadr = 0;
89417 SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
89418 rc = vdbeSortAllocUnpacked(pLast);
89419 if( rc==SQLITE_OK ){
89420 pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
89421 pSorter->pReader = pReadr;
89422 if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
89424 if( rc==SQLITE_OK ){
89425 rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
89426 if( rc==SQLITE_OK ){
89427 vdbeIncrMergerSetThreads(pReadr->pIncr);
89428 for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
89429 IncrMerger *pIncr;
89430 if( (pIncr = pMain->aReadr[iTask].pIncr) ){
89431 vdbeIncrMergerSetThreads(pIncr);
89432 assert( pIncr->pTask!=pLast );
89435 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
89436 /* Check that:
89438 ** a) The incremental merge object is configured to use the
89439 ** right task, and
89440 ** b) If it is using task (nTask-1), it is configured to run
89441 ** in single-threaded mode. This is important, as the
89442 ** root merge (INCRINIT_ROOT) will be using the same task
89443 ** object.
89445 PmaReader *p = &pMain->aReadr[iTask];
89446 assert( p->pIncr==0 || (
89447 (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
89448 && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
89450 rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
89453 pMain = 0;
89455 if( rc==SQLITE_OK ){
89456 rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
89458 }else
89459 #endif
89461 rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
89462 pSorter->pMerger = pMain;
89463 pMain = 0;
89467 if( rc!=SQLITE_OK ){
89468 vdbeMergeEngineFree(pMain);
89470 return rc;
89475 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
89476 ** this function is called to prepare for iterating through the records
89477 ** in sorted order.
89479 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
89480 VdbeSorter *pSorter;
89481 int rc = SQLITE_OK; /* Return code */
89483 assert( pCsr->eCurType==CURTYPE_SORTER );
89484 pSorter = pCsr->uc.pSorter;
89485 assert( pSorter );
89487 /* If no data has been written to disk, then do not do so now. Instead,
89488 ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
89489 ** from the in-memory list. */
89490 if( pSorter->bUsePMA==0 ){
89491 if( pSorter->list.pList ){
89492 *pbEof = 0;
89493 rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
89494 }else{
89495 *pbEof = 1;
89497 return rc;
89500 /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
89501 ** function flushes the contents of memory to disk, it immediately always
89502 ** creates a new list consisting of a single key immediately afterwards.
89503 ** So the list is never empty at this point. */
89504 assert( pSorter->list.pList );
89505 rc = vdbeSorterFlushPMA(pSorter);
89507 /* Join all threads */
89508 rc = vdbeSorterJoinAll(pSorter, rc);
89510 vdbeSorterRewindDebug("rewind");
89512 /* Assuming no errors have occurred, set up a merger structure to
89513 ** incrementally read and merge all remaining PMAs. */
89514 assert( pSorter->pReader==0 );
89515 if( rc==SQLITE_OK ){
89516 rc = vdbeSorterSetupMerge(pSorter);
89517 *pbEof = 0;
89520 vdbeSorterRewindDebug("rewinddone");
89521 return rc;
89525 ** Advance to the next element in the sorter. Return value:
89527 ** SQLITE_OK success
89528 ** SQLITE_DONE end of data
89529 ** otherwise some kind of error.
89531 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
89532 VdbeSorter *pSorter;
89533 int rc; /* Return code */
89535 assert( pCsr->eCurType==CURTYPE_SORTER );
89536 pSorter = pCsr->uc.pSorter;
89537 assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
89538 if( pSorter->bUsePMA ){
89539 assert( pSorter->pReader==0 || pSorter->pMerger==0 );
89540 assert( pSorter->bUseThreads==0 || pSorter->pReader );
89541 assert( pSorter->bUseThreads==1 || pSorter->pMerger );
89542 #if SQLITE_MAX_WORKER_THREADS>0
89543 if( pSorter->bUseThreads ){
89544 rc = vdbePmaReaderNext(pSorter->pReader);
89545 if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
89546 }else
89547 #endif
89548 /*if( !pSorter->bUseThreads )*/ {
89549 int res = 0;
89550 assert( pSorter->pMerger!=0 );
89551 assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
89552 rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
89553 if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
89555 }else{
89556 SorterRecord *pFree = pSorter->list.pList;
89557 pSorter->list.pList = pFree->u.pNext;
89558 pFree->u.pNext = 0;
89559 if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
89560 rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
89562 return rc;
89566 ** Return a pointer to a buffer owned by the sorter that contains the
89567 ** current key.
89569 static void *vdbeSorterRowkey(
89570 const VdbeSorter *pSorter, /* Sorter object */
89571 int *pnKey /* OUT: Size of current key in bytes */
89573 void *pKey;
89574 if( pSorter->bUsePMA ){
89575 PmaReader *pReader;
89576 #if SQLITE_MAX_WORKER_THREADS>0
89577 if( pSorter->bUseThreads ){
89578 pReader = pSorter->pReader;
89579 }else
89580 #endif
89581 /*if( !pSorter->bUseThreads )*/{
89582 pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
89584 *pnKey = pReader->nKey;
89585 pKey = pReader->aKey;
89586 }else{
89587 *pnKey = pSorter->list.pList->nVal;
89588 pKey = SRVAL(pSorter->list.pList);
89590 return pKey;
89594 ** Copy the current sorter key into the memory cell pOut.
89596 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
89597 VdbeSorter *pSorter;
89598 void *pKey; int nKey; /* Sorter key to copy into pOut */
89600 assert( pCsr->eCurType==CURTYPE_SORTER );
89601 pSorter = pCsr->uc.pSorter;
89602 pKey = vdbeSorterRowkey(pSorter, &nKey);
89603 if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
89604 return SQLITE_NOMEM_BKPT;
89606 pOut->n = nKey;
89607 MemSetTypeFlag(pOut, MEM_Blob);
89608 memcpy(pOut->z, pKey, nKey);
89610 return SQLITE_OK;
89614 ** Compare the key in memory cell pVal with the key that the sorter cursor
89615 ** passed as the first argument currently points to. For the purposes of
89616 ** the comparison, ignore the rowid field at the end of each record.
89618 ** If the sorter cursor key contains any NULL values, consider it to be
89619 ** less than pVal. Even if pVal also contains NULL values.
89621 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
89622 ** Otherwise, set *pRes to a negative, zero or positive value if the
89623 ** key in pVal is smaller than, equal to or larger than the current sorter
89624 ** key.
89626 ** This routine forms the core of the OP_SorterCompare opcode, which in
89627 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
89629 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
89630 const VdbeCursor *pCsr, /* Sorter cursor */
89631 Mem *pVal, /* Value to compare to current sorter key */
89632 int nKeyCol, /* Compare this many columns */
89633 int *pRes /* OUT: Result of comparison */
89635 VdbeSorter *pSorter;
89636 UnpackedRecord *r2;
89637 KeyInfo *pKeyInfo;
89638 int i;
89639 void *pKey; int nKey; /* Sorter key to compare pVal with */
89641 assert( pCsr->eCurType==CURTYPE_SORTER );
89642 pSorter = pCsr->uc.pSorter;
89643 r2 = pSorter->pUnpacked;
89644 pKeyInfo = pCsr->pKeyInfo;
89645 if( r2==0 ){
89646 r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
89647 if( r2==0 ) return SQLITE_NOMEM_BKPT;
89648 r2->nField = nKeyCol;
89650 assert( r2->nField==nKeyCol );
89652 pKey = vdbeSorterRowkey(pSorter, &nKey);
89653 sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
89654 for(i=0; i<nKeyCol; i++){
89655 if( r2->aMem[i].flags & MEM_Null ){
89656 *pRes = -1;
89657 return SQLITE_OK;
89661 *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
89662 return SQLITE_OK;
89665 /************** End of vdbesort.c ********************************************/
89666 /************** Begin file memjournal.c **************************************/
89668 ** 2008 October 7
89670 ** The author disclaims copyright to this source code. In place of
89671 ** a legal notice, here is a blessing:
89673 ** May you do good and not evil.
89674 ** May you find forgiveness for yourself and forgive others.
89675 ** May you share freely, never taking more than you give.
89677 *************************************************************************
89679 ** This file contains code use to implement an in-memory rollback journal.
89680 ** The in-memory rollback journal is used to journal transactions for
89681 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
89683 ** Update: The in-memory journal is also used to temporarily cache
89684 ** smaller journals that are not critical for power-loss recovery.
89685 ** For example, statement journals that are not too big will be held
89686 ** entirely in memory, thus reducing the number of file I/O calls, and
89687 ** more importantly, reducing temporary file creation events. If these
89688 ** journals become too large for memory, they are spilled to disk. But
89689 ** in the common case, they are usually small and no file I/O needs to
89690 ** occur.
89692 /* #include "sqliteInt.h" */
89694 /* Forward references to internal structures */
89695 typedef struct MemJournal MemJournal;
89696 typedef struct FilePoint FilePoint;
89697 typedef struct FileChunk FileChunk;
89700 ** The rollback journal is composed of a linked list of these structures.
89702 ** The zChunk array is always at least 8 bytes in size - usually much more.
89703 ** Its actual size is stored in the MemJournal.nChunkSize variable.
89705 struct FileChunk {
89706 FileChunk *pNext; /* Next chunk in the journal */
89707 u8 zChunk[8]; /* Content of this chunk */
89711 ** By default, allocate this many bytes of memory for each FileChunk object.
89713 #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
89716 ** For chunk size nChunkSize, return the number of bytes that should
89717 ** be allocated for each FileChunk structure.
89719 #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
89722 ** An instance of this object serves as a cursor into the rollback journal.
89723 ** The cursor can be either for reading or writing.
89725 struct FilePoint {
89726 sqlite3_int64 iOffset; /* Offset from the beginning of the file */
89727 FileChunk *pChunk; /* Specific chunk into which cursor points */
89731 ** This structure is a subclass of sqlite3_file. Each open memory-journal
89732 ** is an instance of this class.
89734 struct MemJournal {
89735 const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
89736 int nChunkSize; /* In-memory chunk-size */
89738 int nSpill; /* Bytes of data before flushing */
89739 int nSize; /* Bytes of data currently in memory */
89740 FileChunk *pFirst; /* Head of in-memory chunk-list */
89741 FilePoint endpoint; /* Pointer to the end of the file */
89742 FilePoint readpoint; /* Pointer to the end of the last xRead() */
89744 int flags; /* xOpen flags */
89745 sqlite3_vfs *pVfs; /* The "real" underlying VFS */
89746 const char *zJournal; /* Name of the journal file */
89750 ** Read data from the in-memory journal file. This is the implementation
89751 ** of the sqlite3_vfs.xRead method.
89753 static int memjrnlRead(
89754 sqlite3_file *pJfd, /* The journal file from which to read */
89755 void *zBuf, /* Put the results here */
89756 int iAmt, /* Number of bytes to read */
89757 sqlite_int64 iOfst /* Begin reading at this offset */
89759 MemJournal *p = (MemJournal *)pJfd;
89760 u8 *zOut = zBuf;
89761 int nRead = iAmt;
89762 int iChunkOffset;
89763 FileChunk *pChunk;
89765 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
89766 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
89767 if( (iAmt+iOfst)>p->endpoint.iOffset ){
89768 return SQLITE_IOERR_SHORT_READ;
89770 #endif
89772 assert( (iAmt+iOfst)<=p->endpoint.iOffset );
89773 assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
89774 if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
89775 sqlite3_int64 iOff = 0;
89776 for(pChunk=p->pFirst;
89777 ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
89778 pChunk=pChunk->pNext
89780 iOff += p->nChunkSize;
89782 }else{
89783 pChunk = p->readpoint.pChunk;
89784 assert( pChunk!=0 );
89787 iChunkOffset = (int)(iOfst%p->nChunkSize);
89788 do {
89789 int iSpace = p->nChunkSize - iChunkOffset;
89790 int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
89791 memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
89792 zOut += nCopy;
89793 nRead -= iSpace;
89794 iChunkOffset = 0;
89795 } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
89796 p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
89797 p->readpoint.pChunk = pChunk;
89799 return SQLITE_OK;
89803 ** Free the list of FileChunk structures headed at MemJournal.pFirst.
89805 static void memjrnlFreeChunks(MemJournal *p){
89806 FileChunk *pIter;
89807 FileChunk *pNext;
89808 for(pIter=p->pFirst; pIter; pIter=pNext){
89809 pNext = pIter->pNext;
89810 sqlite3_free(pIter);
89812 p->pFirst = 0;
89816 ** Flush the contents of memory to a real file on disk.
89818 static int memjrnlCreateFile(MemJournal *p){
89819 int rc;
89820 sqlite3_file *pReal = (sqlite3_file*)p;
89821 MemJournal copy = *p;
89823 memset(p, 0, sizeof(MemJournal));
89824 rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
89825 if( rc==SQLITE_OK ){
89826 int nChunk = copy.nChunkSize;
89827 i64 iOff = 0;
89828 FileChunk *pIter;
89829 for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
89830 if( iOff + nChunk > copy.endpoint.iOffset ){
89831 nChunk = copy.endpoint.iOffset - iOff;
89833 rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
89834 if( rc ) break;
89835 iOff += nChunk;
89837 if( rc==SQLITE_OK ){
89838 /* No error has occurred. Free the in-memory buffers. */
89839 memjrnlFreeChunks(&copy);
89842 if( rc!=SQLITE_OK ){
89843 /* If an error occurred while creating or writing to the file, restore
89844 ** the original before returning. This way, SQLite uses the in-memory
89845 ** journal data to roll back changes made to the internal page-cache
89846 ** before this function was called. */
89847 sqlite3OsClose(pReal);
89848 *p = copy;
89850 return rc;
89855 ** Write data to the file.
89857 static int memjrnlWrite(
89858 sqlite3_file *pJfd, /* The journal file into which to write */
89859 const void *zBuf, /* Take data to be written from here */
89860 int iAmt, /* Number of bytes to write */
89861 sqlite_int64 iOfst /* Begin writing at this offset into the file */
89863 MemJournal *p = (MemJournal *)pJfd;
89864 int nWrite = iAmt;
89865 u8 *zWrite = (u8 *)zBuf;
89867 /* If the file should be created now, create it and write the new data
89868 ** into the file on disk. */
89869 if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
89870 int rc = memjrnlCreateFile(p);
89871 if( rc==SQLITE_OK ){
89872 rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
89874 return rc;
89877 /* If the contents of this write should be stored in memory */
89878 else{
89879 /* An in-memory journal file should only ever be appended to. Random
89880 ** access writes are not required. The only exception to this is when
89881 ** the in-memory journal is being used by a connection using the
89882 ** atomic-write optimization. In this case the first 28 bytes of the
89883 ** journal file may be written as part of committing the transaction. */
89884 assert( iOfst==p->endpoint.iOffset || iOfst==0 );
89885 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
89886 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
89887 if( iOfst==0 && p->pFirst ){
89888 assert( p->nChunkSize>iAmt );
89889 memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
89890 }else
89891 #else
89892 assert( iOfst>0 || p->pFirst==0 );
89893 #endif
89895 while( nWrite>0 ){
89896 FileChunk *pChunk = p->endpoint.pChunk;
89897 int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
89898 int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
89900 if( iChunkOffset==0 ){
89901 /* New chunk is required to extend the file. */
89902 FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
89903 if( !pNew ){
89904 return SQLITE_IOERR_NOMEM_BKPT;
89906 pNew->pNext = 0;
89907 if( pChunk ){
89908 assert( p->pFirst );
89909 pChunk->pNext = pNew;
89910 }else{
89911 assert( !p->pFirst );
89912 p->pFirst = pNew;
89914 p->endpoint.pChunk = pNew;
89917 memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
89918 zWrite += iSpace;
89919 nWrite -= iSpace;
89920 p->endpoint.iOffset += iSpace;
89922 p->nSize = iAmt + iOfst;
89926 return SQLITE_OK;
89930 ** Truncate the file.
89932 ** If the journal file is already on disk, truncate it there. Or, if it
89933 ** is still in main memory but is being truncated to zero bytes in size,
89934 ** ignore
89936 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
89937 MemJournal *p = (MemJournal *)pJfd;
89938 if( ALWAYS(size==0) ){
89939 memjrnlFreeChunks(p);
89940 p->nSize = 0;
89941 p->endpoint.pChunk = 0;
89942 p->endpoint.iOffset = 0;
89943 p->readpoint.pChunk = 0;
89944 p->readpoint.iOffset = 0;
89946 return SQLITE_OK;
89950 ** Close the file.
89952 static int memjrnlClose(sqlite3_file *pJfd){
89953 MemJournal *p = (MemJournal *)pJfd;
89954 memjrnlFreeChunks(p);
89955 return SQLITE_OK;
89959 ** Sync the file.
89961 ** If the real file has been created, call its xSync method. Otherwise,
89962 ** syncing an in-memory journal is a no-op.
89964 static int memjrnlSync(sqlite3_file *pJfd, int flags){
89965 UNUSED_PARAMETER2(pJfd, flags);
89966 return SQLITE_OK;
89970 ** Query the size of the file in bytes.
89972 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
89973 MemJournal *p = (MemJournal *)pJfd;
89974 *pSize = (sqlite_int64) p->endpoint.iOffset;
89975 return SQLITE_OK;
89979 ** Table of methods for MemJournal sqlite3_file object.
89981 static const struct sqlite3_io_methods MemJournalMethods = {
89982 1, /* iVersion */
89983 memjrnlClose, /* xClose */
89984 memjrnlRead, /* xRead */
89985 memjrnlWrite, /* xWrite */
89986 memjrnlTruncate, /* xTruncate */
89987 memjrnlSync, /* xSync */
89988 memjrnlFileSize, /* xFileSize */
89989 0, /* xLock */
89990 0, /* xUnlock */
89991 0, /* xCheckReservedLock */
89992 0, /* xFileControl */
89993 0, /* xSectorSize */
89994 0, /* xDeviceCharacteristics */
89995 0, /* xShmMap */
89996 0, /* xShmLock */
89997 0, /* xShmBarrier */
89998 0, /* xShmUnmap */
89999 0, /* xFetch */
90000 0 /* xUnfetch */
90004 ** Open a journal file.
90006 ** The behaviour of the journal file depends on the value of parameter
90007 ** nSpill. If nSpill is 0, then the journal file is always create and
90008 ** accessed using the underlying VFS. If nSpill is less than zero, then
90009 ** all content is always stored in main-memory. Finally, if nSpill is a
90010 ** positive value, then the journal file is initially created in-memory
90011 ** but may be flushed to disk later on. In this case the journal file is
90012 ** flushed to disk either when it grows larger than nSpill bytes in size,
90013 ** or when sqlite3JournalCreate() is called.
90015 SQLITE_PRIVATE int sqlite3JournalOpen(
90016 sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
90017 const char *zName, /* Name of the journal file */
90018 sqlite3_file *pJfd, /* Preallocated, blank file handle */
90019 int flags, /* Opening flags */
90020 int nSpill /* Bytes buffered before opening the file */
90022 MemJournal *p = (MemJournal*)pJfd;
90024 /* Zero the file-handle object. If nSpill was passed zero, initialize
90025 ** it using the sqlite3OsOpen() function of the underlying VFS. In this
90026 ** case none of the code in this module is executed as a result of calls
90027 ** made on the journal file-handle. */
90028 memset(p, 0, sizeof(MemJournal));
90029 if( nSpill==0 ){
90030 return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
90033 if( nSpill>0 ){
90034 p->nChunkSize = nSpill;
90035 }else{
90036 p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
90037 assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
90040 p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
90041 p->nSpill = nSpill;
90042 p->flags = flags;
90043 p->zJournal = zName;
90044 p->pVfs = pVfs;
90045 return SQLITE_OK;
90049 ** Open an in-memory journal file.
90051 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
90052 sqlite3JournalOpen(0, 0, pJfd, 0, -1);
90055 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
90056 || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
90058 ** If the argument p points to a MemJournal structure that is not an
90059 ** in-memory-only journal file (i.e. is one that was opened with a +ve
90060 ** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
90061 ** file has not yet been created, create it now.
90063 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
90064 int rc = SQLITE_OK;
90065 MemJournal *p = (MemJournal*)pJfd;
90066 if( p->pMethod==&MemJournalMethods && (
90067 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
90068 p->nSpill>0
90069 #else
90070 /* While this appears to not be possible without ATOMIC_WRITE, the
90071 ** paths are complex, so it seems prudent to leave the test in as
90072 ** a NEVER(), in case our analysis is subtly flawed. */
90073 NEVER(p->nSpill>0)
90074 #endif
90075 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
90076 || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
90077 #endif
90079 rc = memjrnlCreateFile(p);
90081 return rc;
90083 #endif
90086 ** The file-handle passed as the only argument is open on a journal file.
90087 ** Return true if this "journal file" is currently stored in heap memory,
90088 ** or false otherwise.
90090 SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
90091 return p->pMethods==&MemJournalMethods;
90095 ** Return the number of bytes required to store a JournalFile that uses vfs
90096 ** pVfs to create the underlying on-disk files.
90098 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
90099 return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
90102 /************** End of memjournal.c ******************************************/
90103 /************** Begin file walker.c ******************************************/
90105 ** 2008 August 16
90107 ** The author disclaims copyright to this source code. In place of
90108 ** a legal notice, here is a blessing:
90110 ** May you do good and not evil.
90111 ** May you find forgiveness for yourself and forgive others.
90112 ** May you share freely, never taking more than you give.
90114 *************************************************************************
90115 ** This file contains routines used for walking the parser tree for
90116 ** an SQL statement.
90118 /* #include "sqliteInt.h" */
90119 /* #include <stdlib.h> */
90120 /* #include <string.h> */
90124 ** Walk an expression tree. Invoke the callback once for each node
90125 ** of the expression, while descending. (In other words, the callback
90126 ** is invoked before visiting children.)
90128 ** The return value from the callback should be one of the WRC_*
90129 ** constants to specify how to proceed with the walk.
90131 ** WRC_Continue Continue descending down the tree.
90133 ** WRC_Prune Do not descend into child nodes, but allow
90134 ** the walk to continue with sibling nodes.
90136 ** WRC_Abort Do no more callbacks. Unwind the stack and
90137 ** return from the top-level walk call.
90139 ** The return value from this routine is WRC_Abort to abandon the tree walk
90140 ** and WRC_Continue to continue.
90142 static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
90143 int rc;
90144 testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
90145 testcase( ExprHasProperty(pExpr, EP_Reduced) );
90146 while(1){
90147 rc = pWalker->xExprCallback(pWalker, pExpr);
90148 if( rc ) return rc & WRC_Abort;
90149 if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
90150 if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
90151 assert( pExpr->x.pList==0 || pExpr->pRight==0 );
90152 if( pExpr->pRight ){
90153 pExpr = pExpr->pRight;
90154 continue;
90155 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
90156 if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
90157 }else if( pExpr->x.pList ){
90158 if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
90161 break;
90163 return WRC_Continue;
90165 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
90166 return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
90170 ** Call sqlite3WalkExpr() for every expression in list p or until
90171 ** an abort request is seen.
90173 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
90174 int i;
90175 struct ExprList_item *pItem;
90176 if( p ){
90177 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
90178 if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
90181 return WRC_Continue;
90185 ** Walk all expressions associated with SELECT statement p. Do
90186 ** not invoke the SELECT callback on p, but do (of course) invoke
90187 ** any expr callbacks and SELECT callbacks that come from subqueries.
90188 ** Return WRC_Abort or WRC_Continue.
90190 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
90191 if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
90192 if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
90193 if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
90194 if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
90195 if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
90196 if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
90197 if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
90198 return WRC_Continue;
90202 ** Walk the parse trees associated with all subqueries in the
90203 ** FROM clause of SELECT statement p. Do not invoke the select
90204 ** callback on p, but do invoke it on each FROM clause subquery
90205 ** and on any subqueries further down in the tree. Return
90206 ** WRC_Abort or WRC_Continue;
90208 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
90209 SrcList *pSrc;
90210 int i;
90211 struct SrcList_item *pItem;
90213 pSrc = p->pSrc;
90214 if( ALWAYS(pSrc) ){
90215 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
90216 if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
90217 return WRC_Abort;
90219 if( pItem->fg.isTabFunc
90220 && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
90222 return WRC_Abort;
90226 return WRC_Continue;
90230 ** Call sqlite3WalkExpr() for every expression in Select statement p.
90231 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
90232 ** on the compound select chain, p->pPrior.
90234 ** If it is not NULL, the xSelectCallback() callback is invoked before
90235 ** the walk of the expressions and FROM clause. The xSelectCallback2()
90236 ** method is invoked following the walk of the expressions and FROM clause,
90237 ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
90238 ** and if the expressions and FROM clause both return WRC_Continue;
90240 ** Return WRC_Continue under normal conditions. Return WRC_Abort if
90241 ** there is an abort request.
90243 ** If the Walker does not have an xSelectCallback() then this routine
90244 ** is a no-op returning WRC_Continue.
90246 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
90247 int rc;
90248 if( p==0 ) return WRC_Continue;
90249 if( pWalker->xSelectCallback==0 ) return WRC_Continue;
90251 rc = pWalker->xSelectCallback(pWalker, p);
90252 if( rc ) return rc & WRC_Abort;
90253 if( sqlite3WalkSelectExpr(pWalker, p)
90254 || sqlite3WalkSelectFrom(pWalker, p)
90256 return WRC_Abort;
90258 if( pWalker->xSelectCallback2 ){
90259 pWalker->xSelectCallback2(pWalker, p);
90261 p = p->pPrior;
90262 }while( p!=0 );
90263 return WRC_Continue;
90266 /************** End of walker.c **********************************************/
90267 /************** Begin file resolve.c *****************************************/
90269 ** 2008 August 18
90271 ** The author disclaims copyright to this source code. In place of
90272 ** a legal notice, here is a blessing:
90274 ** May you do good and not evil.
90275 ** May you find forgiveness for yourself and forgive others.
90276 ** May you share freely, never taking more than you give.
90278 *************************************************************************
90280 ** This file contains routines used for walking the parser tree and
90281 ** resolve all identifiers by associating them with a particular
90282 ** table and column.
90284 /* #include "sqliteInt.h" */
90287 ** Walk the expression tree pExpr and increase the aggregate function
90288 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
90289 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
90290 ** outer query into an inner subquery.
90292 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
90293 ** is a helper function - a callback for the tree walker.
90295 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
90296 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
90297 return WRC_Continue;
90299 static void incrAggFunctionDepth(Expr *pExpr, int N){
90300 if( N>0 ){
90301 Walker w;
90302 memset(&w, 0, sizeof(w));
90303 w.xExprCallback = incrAggDepth;
90304 w.u.n = N;
90305 sqlite3WalkExpr(&w, pExpr);
90310 ** Turn the pExpr expression into an alias for the iCol-th column of the
90311 ** result set in pEList.
90313 ** If the reference is followed by a COLLATE operator, then make sure
90314 ** the COLLATE operator is preserved. For example:
90316 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
90318 ** Should be transformed into:
90320 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
90322 ** The nSubquery parameter specifies how many levels of subquery the
90323 ** alias is removed from the original expression. The usual value is
90324 ** zero but it might be more if the alias is contained within a subquery
90325 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
90326 ** structures must be increased by the nSubquery amount.
90328 static void resolveAlias(
90329 Parse *pParse, /* Parsing context */
90330 ExprList *pEList, /* A result set */
90331 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
90332 Expr *pExpr, /* Transform this into an alias to the result set */
90333 const char *zType, /* "GROUP" or "ORDER" or "" */
90334 int nSubquery /* Number of subqueries that the label is moving */
90336 Expr *pOrig; /* The iCol-th column of the result set */
90337 Expr *pDup; /* Copy of pOrig */
90338 sqlite3 *db; /* The database connection */
90340 assert( iCol>=0 && iCol<pEList->nExpr );
90341 pOrig = pEList->a[iCol].pExpr;
90342 assert( pOrig!=0 );
90343 db = pParse->db;
90344 pDup = sqlite3ExprDup(db, pOrig, 0);
90345 if( pDup==0 ) return;
90346 if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
90347 if( pExpr->op==TK_COLLATE ){
90348 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
90350 ExprSetProperty(pDup, EP_Alias);
90352 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
90353 ** prevents ExprDelete() from deleting the Expr structure itself,
90354 ** allowing it to be repopulated by the memcpy() on the following line.
90355 ** The pExpr->u.zToken might point into memory that will be freed by the
90356 ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
90357 ** make a copy of the token before doing the sqlite3DbFree().
90359 ExprSetProperty(pExpr, EP_Static);
90360 sqlite3ExprDelete(db, pExpr);
90361 memcpy(pExpr, pDup, sizeof(*pExpr));
90362 if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
90363 assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
90364 pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
90365 pExpr->flags |= EP_MemToken;
90367 sqlite3DbFree(db, pDup);
90372 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
90374 ** Return FALSE if the USING clause is NULL or if it does not contain
90375 ** zCol.
90377 static int nameInUsingClause(IdList *pUsing, const char *zCol){
90378 if( pUsing ){
90379 int k;
90380 for(k=0; k<pUsing->nId; k++){
90381 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
90384 return 0;
90388 ** Subqueries stores the original database, table and column names for their
90389 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
90390 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
90391 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
90392 ** match anything.
90394 SQLITE_PRIVATE int sqlite3MatchSpanName(
90395 const char *zSpan,
90396 const char *zCol,
90397 const char *zTab,
90398 const char *zDb
90400 int n;
90401 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
90402 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
90403 return 0;
90405 zSpan += n+1;
90406 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
90407 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
90408 return 0;
90410 zSpan += n+1;
90411 if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
90412 return 0;
90414 return 1;
90418 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
90419 ** that name in the set of source tables in pSrcList and make the pExpr
90420 ** expression node refer back to that source column. The following changes
90421 ** are made to pExpr:
90423 ** pExpr->iDb Set the index in db->aDb[] of the database X
90424 ** (even if X is implied).
90425 ** pExpr->iTable Set to the cursor number for the table obtained
90426 ** from pSrcList.
90427 ** pExpr->pTab Points to the Table structure of X.Y (even if
90428 ** X and/or Y are implied.)
90429 ** pExpr->iColumn Set to the column number within the table.
90430 ** pExpr->op Set to TK_COLUMN.
90431 ** pExpr->pLeft Any expression this points to is deleted
90432 ** pExpr->pRight Any expression this points to is deleted.
90434 ** The zDb variable is the name of the database (the "X"). This value may be
90435 ** NULL meaning that name is of the form Y.Z or Z. Any available database
90436 ** can be used. The zTable variable is the name of the table (the "Y"). This
90437 ** value can be NULL if zDb is also NULL. If zTable is NULL it
90438 ** means that the form of the name is Z and that columns from any table
90439 ** can be used.
90441 ** If the name cannot be resolved unambiguously, leave an error message
90442 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
90444 static int lookupName(
90445 Parse *pParse, /* The parsing context */
90446 const char *zDb, /* Name of the database containing table, or NULL */
90447 const char *zTab, /* Name of table containing column, or NULL */
90448 const char *zCol, /* Name of the column. */
90449 NameContext *pNC, /* The name context used to resolve the name */
90450 Expr *pExpr /* Make this EXPR node point to the selected column */
90452 int i, j; /* Loop counters */
90453 int cnt = 0; /* Number of matching column names */
90454 int cntTab = 0; /* Number of matching table names */
90455 int nSubquery = 0; /* How many levels of subquery */
90456 sqlite3 *db = pParse->db; /* The database connection */
90457 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
90458 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
90459 NameContext *pTopNC = pNC; /* First namecontext in the list */
90460 Schema *pSchema = 0; /* Schema of the expression */
90461 int isTrigger = 0; /* True if resolved to a trigger column */
90462 Table *pTab = 0; /* Table hold the row */
90463 Column *pCol; /* A column of pTab */
90465 assert( pNC ); /* the name context cannot be NULL. */
90466 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
90467 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
90469 /* Initialize the node to no-match */
90470 pExpr->iTable = -1;
90471 pExpr->pTab = 0;
90472 ExprSetVVAProperty(pExpr, EP_NoReduce);
90474 /* Translate the schema name in zDb into a pointer to the corresponding
90475 ** schema. If not found, pSchema will remain NULL and nothing will match
90476 ** resulting in an appropriate error message toward the end of this routine
90478 if( zDb ){
90479 testcase( pNC->ncFlags & NC_PartIdx );
90480 testcase( pNC->ncFlags & NC_IsCheck );
90481 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
90482 /* Silently ignore database qualifiers inside CHECK constraints and
90483 ** partial indices. Do not raise errors because that might break
90484 ** legacy and because it does not hurt anything to just ignore the
90485 ** database name. */
90486 zDb = 0;
90487 }else{
90488 for(i=0; i<db->nDb; i++){
90489 assert( db->aDb[i].zDbSName );
90490 if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
90491 pSchema = db->aDb[i].pSchema;
90492 break;
90498 /* Start at the inner-most context and move outward until a match is found */
90499 assert( pNC && cnt==0 );
90501 ExprList *pEList;
90502 SrcList *pSrcList = pNC->pSrcList;
90504 if( pSrcList ){
90505 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
90506 pTab = pItem->pTab;
90507 assert( pTab!=0 && pTab->zName!=0 );
90508 assert( pTab->nCol>0 );
90509 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
90510 int hit = 0;
90511 pEList = pItem->pSelect->pEList;
90512 for(j=0; j<pEList->nExpr; j++){
90513 if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
90514 cnt++;
90515 cntTab = 2;
90516 pMatch = pItem;
90517 pExpr->iColumn = j;
90518 hit = 1;
90521 if( hit || zTab==0 ) continue;
90523 if( zDb && pTab->pSchema!=pSchema ){
90524 continue;
90526 if( zTab ){
90527 const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
90528 assert( zTabName!=0 );
90529 if( sqlite3StrICmp(zTabName, zTab)!=0 ){
90530 continue;
90533 if( 0==(cntTab++) ){
90534 pMatch = pItem;
90536 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
90537 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
90538 /* If there has been exactly one prior match and this match
90539 ** is for the right-hand table of a NATURAL JOIN or is in a
90540 ** USING clause, then skip this match.
90542 if( cnt==1 ){
90543 if( pItem->fg.jointype & JT_NATURAL ) continue;
90544 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
90546 cnt++;
90547 pMatch = pItem;
90548 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
90549 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
90550 break;
90554 if( pMatch ){
90555 pExpr->iTable = pMatch->iCursor;
90556 pExpr->pTab = pMatch->pTab;
90557 /* RIGHT JOIN not (yet) supported */
90558 assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
90559 if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
90560 ExprSetProperty(pExpr, EP_CanBeNull);
90562 pSchema = pExpr->pTab->pSchema;
90564 } /* if( pSrcList ) */
90566 #ifndef SQLITE_OMIT_TRIGGER
90567 /* If we have not already resolved the name, then maybe
90568 ** it is a new.* or old.* trigger argument reference
90570 if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
90571 int op = pParse->eTriggerOp;
90572 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
90573 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
90574 pExpr->iTable = 1;
90575 pTab = pParse->pTriggerTab;
90576 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
90577 pExpr->iTable = 0;
90578 pTab = pParse->pTriggerTab;
90579 }else{
90580 pTab = 0;
90583 if( pTab ){
90584 int iCol;
90585 pSchema = pTab->pSchema;
90586 cntTab++;
90587 for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
90588 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
90589 if( iCol==pTab->iPKey ){
90590 iCol = -1;
90592 break;
90595 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
90596 /* IMP: R-51414-32910 */
90597 iCol = -1;
90599 if( iCol<pTab->nCol ){
90600 cnt++;
90601 if( iCol<0 ){
90602 pExpr->affinity = SQLITE_AFF_INTEGER;
90603 }else if( pExpr->iTable==0 ){
90604 testcase( iCol==31 );
90605 testcase( iCol==32 );
90606 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
90607 }else{
90608 testcase( iCol==31 );
90609 testcase( iCol==32 );
90610 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
90612 pExpr->iColumn = (i16)iCol;
90613 pExpr->pTab = pTab;
90614 isTrigger = 1;
90618 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
90621 ** Perhaps the name is a reference to the ROWID
90623 if( cnt==0
90624 && cntTab==1
90625 && pMatch
90626 && (pNC->ncFlags & NC_IdxExpr)==0
90627 && sqlite3IsRowid(zCol)
90628 && VisibleRowid(pMatch->pTab)
90630 cnt = 1;
90631 pExpr->iColumn = -1;
90632 pExpr->affinity = SQLITE_AFF_INTEGER;
90636 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
90637 ** might refer to an result-set alias. This happens, for example, when
90638 ** we are resolving names in the WHERE clause of the following command:
90640 ** SELECT a+b AS x FROM table WHERE x<10;
90642 ** In cases like this, replace pExpr with a copy of the expression that
90643 ** forms the result set entry ("a+b" in the example) and return immediately.
90644 ** Note that the expression in the result set should have already been
90645 ** resolved by the time the WHERE clause is resolved.
90647 ** The ability to use an output result-set column in the WHERE, GROUP BY,
90648 ** or HAVING clauses, or as part of a larger expression in the ORDER BY
90649 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
90650 ** is supported for backwards compatibility only. Hence, we issue a warning
90651 ** on sqlite3_log() whenever the capability is used.
90653 if( (pEList = pNC->pEList)!=0
90654 && zTab==0
90655 && cnt==0
90657 for(j=0; j<pEList->nExpr; j++){
90658 char *zAs = pEList->a[j].zName;
90659 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
90660 Expr *pOrig;
90661 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
90662 assert( pExpr->x.pList==0 );
90663 assert( pExpr->x.pSelect==0 );
90664 pOrig = pEList->a[j].pExpr;
90665 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
90666 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
90667 return WRC_Abort;
90669 if( sqlite3ExprVectorSize(pOrig)!=1 ){
90670 sqlite3ErrorMsg(pParse, "row value misused");
90671 return WRC_Abort;
90673 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
90674 cnt = 1;
90675 pMatch = 0;
90676 assert( zTab==0 && zDb==0 );
90677 goto lookupname_end;
90682 /* Advance to the next name context. The loop will exit when either
90683 ** we have a match (cnt>0) or when we run out of name contexts.
90685 if( cnt ) break;
90686 pNC = pNC->pNext;
90687 nSubquery++;
90688 }while( pNC );
90692 ** If X and Y are NULL (in other words if only the column name Z is
90693 ** supplied) and the value of Z is enclosed in double-quotes, then
90694 ** Z is a string literal if it doesn't match any column names. In that
90695 ** case, we need to return right away and not make any changes to
90696 ** pExpr.
90698 ** Because no reference was made to outer contexts, the pNC->nRef
90699 ** fields are not changed in any context.
90701 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
90702 pExpr->op = TK_STRING;
90703 pExpr->pTab = 0;
90704 return WRC_Prune;
90708 ** cnt==0 means there was not match. cnt>1 means there were two or
90709 ** more matches. Either way, we have an error.
90711 if( cnt!=1 ){
90712 const char *zErr;
90713 zErr = cnt==0 ? "no such column" : "ambiguous column name";
90714 if( zDb ){
90715 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
90716 }else if( zTab ){
90717 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
90718 }else{
90719 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
90721 pParse->checkSchema = 1;
90722 pTopNC->nErr++;
90725 /* If a column from a table in pSrcList is referenced, then record
90726 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
90727 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
90728 ** column number is greater than the number of bits in the bitmask
90729 ** then set the high-order bit of the bitmask.
90731 if( pExpr->iColumn>=0 && pMatch!=0 ){
90732 int n = pExpr->iColumn;
90733 testcase( n==BMS-1 );
90734 if( n>=BMS ){
90735 n = BMS-1;
90737 assert( pMatch->iCursor==pExpr->iTable );
90738 pMatch->colUsed |= ((Bitmask)1)<<n;
90741 /* Clean up and return
90743 sqlite3ExprDelete(db, pExpr->pLeft);
90744 pExpr->pLeft = 0;
90745 sqlite3ExprDelete(db, pExpr->pRight);
90746 pExpr->pRight = 0;
90747 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
90748 ExprSetProperty(pExpr, EP_Leaf);
90749 lookupname_end:
90750 if( cnt==1 ){
90751 assert( pNC!=0 );
90752 if( !ExprHasProperty(pExpr, EP_Alias) ){
90753 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
90755 /* Increment the nRef value on all name contexts from TopNC up to
90756 ** the point where the name matched. */
90757 for(;;){
90758 assert( pTopNC!=0 );
90759 pTopNC->nRef++;
90760 if( pTopNC==pNC ) break;
90761 pTopNC = pTopNC->pNext;
90763 return WRC_Prune;
90764 } else {
90765 return WRC_Abort;
90770 ** Allocate and return a pointer to an expression to load the column iCol
90771 ** from datasource iSrc in SrcList pSrc.
90773 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
90774 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
90775 if( p ){
90776 struct SrcList_item *pItem = &pSrc->a[iSrc];
90777 p->pTab = pItem->pTab;
90778 p->iTable = pItem->iCursor;
90779 if( p->pTab->iPKey==iCol ){
90780 p->iColumn = -1;
90781 }else{
90782 p->iColumn = (ynVar)iCol;
90783 testcase( iCol==BMS );
90784 testcase( iCol==BMS-1 );
90785 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
90788 return p;
90792 ** Report an error that an expression is not valid for some set of
90793 ** pNC->ncFlags values determined by validMask.
90795 static void notValid(
90796 Parse *pParse, /* Leave error message here */
90797 NameContext *pNC, /* The name context */
90798 const char *zMsg, /* Type of error */
90799 int validMask /* Set of contexts for which prohibited */
90801 assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
90802 if( (pNC->ncFlags & validMask)!=0 ){
90803 const char *zIn = "partial index WHERE clauses";
90804 if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
90805 #ifndef SQLITE_OMIT_CHECK
90806 else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
90807 #endif
90808 sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
90813 ** Expression p should encode a floating point value between 1.0 and 0.0.
90814 ** Return 1024 times this value. Or return -1 if p is not a floating point
90815 ** value between 1.0 and 0.0.
90817 static int exprProbability(Expr *p){
90818 double r = -1.0;
90819 if( p->op!=TK_FLOAT ) return -1;
90820 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
90821 assert( r>=0.0 );
90822 if( r>1.0 ) return -1;
90823 return (int)(r*134217728.0);
90827 ** This routine is callback for sqlite3WalkExpr().
90829 ** Resolve symbolic names into TK_COLUMN operators for the current
90830 ** node in the expression tree. Return 0 to continue the search down
90831 ** the tree or 2 to abort the tree walk.
90833 ** This routine also does error checking and name resolution for
90834 ** function names. The operator for aggregate functions is changed
90835 ** to TK_AGG_FUNCTION.
90837 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
90838 NameContext *pNC;
90839 Parse *pParse;
90841 pNC = pWalker->u.pNC;
90842 assert( pNC!=0 );
90843 pParse = pNC->pParse;
90844 assert( pParse==pWalker->pParse );
90846 #ifndef NDEBUG
90847 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
90848 SrcList *pSrcList = pNC->pSrcList;
90849 int i;
90850 for(i=0; i<pNC->pSrcList->nSrc; i++){
90851 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
90854 #endif
90855 switch( pExpr->op ){
90857 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
90858 /* The special operator TK_ROW means use the rowid for the first
90859 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
90860 ** clause processing on UPDATE and DELETE statements.
90862 case TK_ROW: {
90863 SrcList *pSrcList = pNC->pSrcList;
90864 struct SrcList_item *pItem;
90865 assert( pSrcList && pSrcList->nSrc==1 );
90866 pItem = pSrcList->a;
90867 pExpr->op = TK_COLUMN;
90868 pExpr->pTab = pItem->pTab;
90869 pExpr->iTable = pItem->iCursor;
90870 pExpr->iColumn = -1;
90871 pExpr->affinity = SQLITE_AFF_INTEGER;
90872 break;
90874 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
90875 && !defined(SQLITE_OMIT_SUBQUERY) */
90877 /* A column name: ID
90878 ** Or table name and column name: ID.ID
90879 ** Or a database, table and column: ID.ID.ID
90881 ** The TK_ID and TK_OUT cases are combined so that there will only
90882 ** be one call to lookupName(). Then the compiler will in-line
90883 ** lookupName() for a size reduction and performance increase.
90885 case TK_ID:
90886 case TK_DOT: {
90887 const char *zColumn;
90888 const char *zTable;
90889 const char *zDb;
90890 Expr *pRight;
90892 if( pExpr->op==TK_ID ){
90893 zDb = 0;
90894 zTable = 0;
90895 zColumn = pExpr->u.zToken;
90896 }else{
90897 notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
90898 pRight = pExpr->pRight;
90899 if( pRight->op==TK_ID ){
90900 zDb = 0;
90901 zTable = pExpr->pLeft->u.zToken;
90902 zColumn = pRight->u.zToken;
90903 }else{
90904 assert( pRight->op==TK_DOT );
90905 zDb = pExpr->pLeft->u.zToken;
90906 zTable = pRight->pLeft->u.zToken;
90907 zColumn = pRight->pRight->u.zToken;
90910 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
90913 /* Resolve function names
90915 case TK_FUNCTION: {
90916 ExprList *pList = pExpr->x.pList; /* The argument list */
90917 int n = pList ? pList->nExpr : 0; /* Number of arguments */
90918 int no_such_func = 0; /* True if no such function exists */
90919 int wrong_num_args = 0; /* True if wrong number of arguments */
90920 int is_agg = 0; /* True if is an aggregate function */
90921 int nId; /* Number of characters in function name */
90922 const char *zId; /* The function name. */
90923 FuncDef *pDef; /* Information about the function */
90924 u8 enc = ENC(pParse->db); /* The database encoding */
90926 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
90927 zId = pExpr->u.zToken;
90928 nId = sqlite3Strlen30(zId);
90929 pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
90930 if( pDef==0 ){
90931 pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
90932 if( pDef==0 ){
90933 no_such_func = 1;
90934 }else{
90935 wrong_num_args = 1;
90937 }else{
90938 is_agg = pDef->xFinalize!=0;
90939 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
90940 ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
90941 if( n==2 ){
90942 pExpr->iTable = exprProbability(pList->a[1].pExpr);
90943 if( pExpr->iTable<0 ){
90944 sqlite3ErrorMsg(pParse,
90945 "second argument to likelihood() must be a "
90946 "constant between 0.0 and 1.0");
90947 pNC->nErr++;
90949 }else{
90950 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
90951 ** equivalent to likelihood(X, 0.0625).
90952 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
90953 ** short-hand for likelihood(X,0.0625).
90954 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
90955 ** for likelihood(X,0.9375).
90956 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
90957 ** to likelihood(X,0.9375). */
90958 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
90959 pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
90962 #ifndef SQLITE_OMIT_AUTHORIZATION
90964 int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
90965 if( auth!=SQLITE_OK ){
90966 if( auth==SQLITE_DENY ){
90967 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
90968 pDef->zName);
90969 pNC->nErr++;
90971 pExpr->op = TK_NULL;
90972 return WRC_Prune;
90975 #endif
90976 if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
90977 /* For the purposes of the EP_ConstFunc flag, date and time
90978 ** functions and other functions that change slowly are considered
90979 ** constant because they are constant for the duration of one query */
90980 ExprSetProperty(pExpr,EP_ConstFunc);
90982 if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
90983 /* Date/time functions that use 'now', and other functions like
90984 ** sqlite_version() that might change over time cannot be used
90985 ** in an index. */
90986 notValid(pParse, pNC, "non-deterministic functions",
90987 NC_IdxExpr|NC_PartIdx);
90990 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
90991 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
90992 pNC->nErr++;
90993 is_agg = 0;
90994 }else if( no_such_func && pParse->db->init.busy==0
90995 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
90996 && pParse->explain==0
90997 #endif
90999 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
91000 pNC->nErr++;
91001 }else if( wrong_num_args ){
91002 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
91003 nId, zId);
91004 pNC->nErr++;
91006 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
91007 sqlite3WalkExprList(pWalker, pList);
91008 if( is_agg ){
91009 NameContext *pNC2 = pNC;
91010 pExpr->op = TK_AGG_FUNCTION;
91011 pExpr->op2 = 0;
91012 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
91013 pExpr->op2++;
91014 pNC2 = pNC2->pNext;
91016 assert( pDef!=0 );
91017 if( pNC2 ){
91018 assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
91019 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
91020 pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
91023 pNC->ncFlags |= NC_AllowAgg;
91025 /* FIX ME: Compute pExpr->affinity based on the expected return
91026 ** type of the function
91028 return WRC_Prune;
91030 #ifndef SQLITE_OMIT_SUBQUERY
91031 case TK_SELECT:
91032 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
91033 #endif
91034 case TK_IN: {
91035 testcase( pExpr->op==TK_IN );
91036 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
91037 int nRef = pNC->nRef;
91038 notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
91039 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
91040 assert( pNC->nRef>=nRef );
91041 if( nRef!=pNC->nRef ){
91042 ExprSetProperty(pExpr, EP_VarSelect);
91043 pNC->ncFlags |= NC_VarSelect;
91046 break;
91048 case TK_VARIABLE: {
91049 notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
91050 break;
91052 case TK_BETWEEN:
91053 case TK_EQ:
91054 case TK_NE:
91055 case TK_LT:
91056 case TK_LE:
91057 case TK_GT:
91058 case TK_GE:
91059 case TK_IS:
91060 case TK_ISNOT: {
91061 int nLeft, nRight;
91062 if( pParse->db->mallocFailed ) break;
91063 assert( pExpr->pLeft!=0 );
91064 nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
91065 if( pExpr->op==TK_BETWEEN ){
91066 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
91067 if( nRight==nLeft ){
91068 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
91070 }else{
91071 assert( pExpr->pRight!=0 );
91072 nRight = sqlite3ExprVectorSize(pExpr->pRight);
91074 if( nLeft!=nRight ){
91075 testcase( pExpr->op==TK_EQ );
91076 testcase( pExpr->op==TK_NE );
91077 testcase( pExpr->op==TK_LT );
91078 testcase( pExpr->op==TK_LE );
91079 testcase( pExpr->op==TK_GT );
91080 testcase( pExpr->op==TK_GE );
91081 testcase( pExpr->op==TK_IS );
91082 testcase( pExpr->op==TK_ISNOT );
91083 testcase( pExpr->op==TK_BETWEEN );
91084 sqlite3ErrorMsg(pParse, "row value misused");
91086 break;
91089 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
91093 ** pEList is a list of expressions which are really the result set of the
91094 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
91095 ** This routine checks to see if pE is a simple identifier which corresponds
91096 ** to the AS-name of one of the terms of the expression list. If it is,
91097 ** this routine return an integer between 1 and N where N is the number of
91098 ** elements in pEList, corresponding to the matching entry. If there is
91099 ** no match, or if pE is not a simple identifier, then this routine
91100 ** return 0.
91102 ** pEList has been resolved. pE has not.
91104 static int resolveAsName(
91105 Parse *pParse, /* Parsing context for error messages */
91106 ExprList *pEList, /* List of expressions to scan */
91107 Expr *pE /* Expression we are trying to match */
91109 int i; /* Loop counter */
91111 UNUSED_PARAMETER(pParse);
91113 if( pE->op==TK_ID ){
91114 char *zCol = pE->u.zToken;
91115 for(i=0; i<pEList->nExpr; i++){
91116 char *zAs = pEList->a[i].zName;
91117 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
91118 return i+1;
91122 return 0;
91126 ** pE is a pointer to an expression which is a single term in the
91127 ** ORDER BY of a compound SELECT. The expression has not been
91128 ** name resolved.
91130 ** At the point this routine is called, we already know that the
91131 ** ORDER BY term is not an integer index into the result set. That
91132 ** case is handled by the calling routine.
91134 ** Attempt to match pE against result set columns in the left-most
91135 ** SELECT statement. Return the index i of the matching column,
91136 ** as an indication to the caller that it should sort by the i-th column.
91137 ** The left-most column is 1. In other words, the value returned is the
91138 ** same integer value that would be used in the SQL statement to indicate
91139 ** the column.
91141 ** If there is no match, return 0. Return -1 if an error occurs.
91143 static int resolveOrderByTermToExprList(
91144 Parse *pParse, /* Parsing context for error messages */
91145 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
91146 Expr *pE /* The specific ORDER BY term */
91148 int i; /* Loop counter */
91149 ExprList *pEList; /* The columns of the result set */
91150 NameContext nc; /* Name context for resolving pE */
91151 sqlite3 *db; /* Database connection */
91152 int rc; /* Return code from subprocedures */
91153 u8 savedSuppErr; /* Saved value of db->suppressErr */
91155 assert( sqlite3ExprIsInteger(pE, &i)==0 );
91156 pEList = pSelect->pEList;
91158 /* Resolve all names in the ORDER BY term expression
91160 memset(&nc, 0, sizeof(nc));
91161 nc.pParse = pParse;
91162 nc.pSrcList = pSelect->pSrc;
91163 nc.pEList = pEList;
91164 nc.ncFlags = NC_AllowAgg;
91165 nc.nErr = 0;
91166 db = pParse->db;
91167 savedSuppErr = db->suppressErr;
91168 db->suppressErr = 1;
91169 rc = sqlite3ResolveExprNames(&nc, pE);
91170 db->suppressErr = savedSuppErr;
91171 if( rc ) return 0;
91173 /* Try to match the ORDER BY expression against an expression
91174 ** in the result set. Return an 1-based index of the matching
91175 ** result-set entry.
91177 for(i=0; i<pEList->nExpr; i++){
91178 if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
91179 return i+1;
91183 /* If no match, return 0. */
91184 return 0;
91188 ** Generate an ORDER BY or GROUP BY term out-of-range error.
91190 static void resolveOutOfRangeError(
91191 Parse *pParse, /* The error context into which to write the error */
91192 const char *zType, /* "ORDER" or "GROUP" */
91193 int i, /* The index (1-based) of the term out of range */
91194 int mx /* Largest permissible value of i */
91196 sqlite3ErrorMsg(pParse,
91197 "%r %s BY term out of range - should be "
91198 "between 1 and %d", i, zType, mx);
91202 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
91203 ** each term of the ORDER BY clause is a constant integer between 1
91204 ** and N where N is the number of columns in the compound SELECT.
91206 ** ORDER BY terms that are already an integer between 1 and N are
91207 ** unmodified. ORDER BY terms that are integers outside the range of
91208 ** 1 through N generate an error. ORDER BY terms that are expressions
91209 ** are matched against result set expressions of compound SELECT
91210 ** beginning with the left-most SELECT and working toward the right.
91211 ** At the first match, the ORDER BY expression is transformed into
91212 ** the integer column number.
91214 ** Return the number of errors seen.
91216 static int resolveCompoundOrderBy(
91217 Parse *pParse, /* Parsing context. Leave error messages here */
91218 Select *pSelect /* The SELECT statement containing the ORDER BY */
91220 int i;
91221 ExprList *pOrderBy;
91222 ExprList *pEList;
91223 sqlite3 *db;
91224 int moreToDo = 1;
91226 pOrderBy = pSelect->pOrderBy;
91227 if( pOrderBy==0 ) return 0;
91228 db = pParse->db;
91229 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
91230 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
91231 return 1;
91233 for(i=0; i<pOrderBy->nExpr; i++){
91234 pOrderBy->a[i].done = 0;
91236 pSelect->pNext = 0;
91237 while( pSelect->pPrior ){
91238 pSelect->pPrior->pNext = pSelect;
91239 pSelect = pSelect->pPrior;
91241 while( pSelect && moreToDo ){
91242 struct ExprList_item *pItem;
91243 moreToDo = 0;
91244 pEList = pSelect->pEList;
91245 assert( pEList!=0 );
91246 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
91247 int iCol = -1;
91248 Expr *pE, *pDup;
91249 if( pItem->done ) continue;
91250 pE = sqlite3ExprSkipCollate(pItem->pExpr);
91251 if( sqlite3ExprIsInteger(pE, &iCol) ){
91252 if( iCol<=0 || iCol>pEList->nExpr ){
91253 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
91254 return 1;
91256 }else{
91257 iCol = resolveAsName(pParse, pEList, pE);
91258 if( iCol==0 ){
91259 pDup = sqlite3ExprDup(db, pE, 0);
91260 if( !db->mallocFailed ){
91261 assert(pDup);
91262 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
91264 sqlite3ExprDelete(db, pDup);
91267 if( iCol>0 ){
91268 /* Convert the ORDER BY term into an integer column number iCol,
91269 ** taking care to preserve the COLLATE clause if it exists */
91270 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
91271 if( pNew==0 ) return 1;
91272 pNew->flags |= EP_IntValue;
91273 pNew->u.iValue = iCol;
91274 if( pItem->pExpr==pE ){
91275 pItem->pExpr = pNew;
91276 }else{
91277 Expr *pParent = pItem->pExpr;
91278 assert( pParent->op==TK_COLLATE );
91279 while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
91280 assert( pParent->pLeft==pE );
91281 pParent->pLeft = pNew;
91283 sqlite3ExprDelete(db, pE);
91284 pItem->u.x.iOrderByCol = (u16)iCol;
91285 pItem->done = 1;
91286 }else{
91287 moreToDo = 1;
91290 pSelect = pSelect->pNext;
91292 for(i=0; i<pOrderBy->nExpr; i++){
91293 if( pOrderBy->a[i].done==0 ){
91294 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
91295 "column in the result set", i+1);
91296 return 1;
91299 return 0;
91303 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
91304 ** the SELECT statement pSelect. If any term is reference to a
91305 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
91306 ** field) then convert that term into a copy of the corresponding result set
91307 ** column.
91309 ** If any errors are detected, add an error message to pParse and
91310 ** return non-zero. Return zero if no errors are seen.
91312 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
91313 Parse *pParse, /* Parsing context. Leave error messages here */
91314 Select *pSelect, /* The SELECT statement containing the clause */
91315 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
91316 const char *zType /* "ORDER" or "GROUP" */
91318 int i;
91319 sqlite3 *db = pParse->db;
91320 ExprList *pEList;
91321 struct ExprList_item *pItem;
91323 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
91324 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
91325 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
91326 return 1;
91328 pEList = pSelect->pEList;
91329 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
91330 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
91331 if( pItem->u.x.iOrderByCol ){
91332 if( pItem->u.x.iOrderByCol>pEList->nExpr ){
91333 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
91334 return 1;
91336 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
91337 zType,0);
91340 return 0;
91344 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
91345 ** The Name context of the SELECT statement is pNC. zType is either
91346 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
91348 ** This routine resolves each term of the clause into an expression.
91349 ** If the order-by term is an integer I between 1 and N (where N is the
91350 ** number of columns in the result set of the SELECT) then the expression
91351 ** in the resolution is a copy of the I-th result-set expression. If
91352 ** the order-by term is an identifier that corresponds to the AS-name of
91353 ** a result-set expression, then the term resolves to a copy of the
91354 ** result-set expression. Otherwise, the expression is resolved in
91355 ** the usual way - using sqlite3ResolveExprNames().
91357 ** This routine returns the number of errors. If errors occur, then
91358 ** an appropriate error message might be left in pParse. (OOM errors
91359 ** excepted.)
91361 static int resolveOrderGroupBy(
91362 NameContext *pNC, /* The name context of the SELECT statement */
91363 Select *pSelect, /* The SELECT statement holding pOrderBy */
91364 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
91365 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
91367 int i, j; /* Loop counters */
91368 int iCol; /* Column number */
91369 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
91370 Parse *pParse; /* Parsing context */
91371 int nResult; /* Number of terms in the result set */
91373 if( pOrderBy==0 ) return 0;
91374 nResult = pSelect->pEList->nExpr;
91375 pParse = pNC->pParse;
91376 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
91377 Expr *pE = pItem->pExpr;
91378 Expr *pE2 = sqlite3ExprSkipCollate(pE);
91379 if( zType[0]!='G' ){
91380 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
91381 if( iCol>0 ){
91382 /* If an AS-name match is found, mark this ORDER BY column as being
91383 ** a copy of the iCol-th result-set column. The subsequent call to
91384 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
91385 ** copy of the iCol-th result-set expression. */
91386 pItem->u.x.iOrderByCol = (u16)iCol;
91387 continue;
91390 if( sqlite3ExprIsInteger(pE2, &iCol) ){
91391 /* The ORDER BY term is an integer constant. Again, set the column
91392 ** number so that sqlite3ResolveOrderGroupBy() will convert the
91393 ** order-by term to a copy of the result-set expression */
91394 if( iCol<1 || iCol>0xffff ){
91395 resolveOutOfRangeError(pParse, zType, i+1, nResult);
91396 return 1;
91398 pItem->u.x.iOrderByCol = (u16)iCol;
91399 continue;
91402 /* Otherwise, treat the ORDER BY term as an ordinary expression */
91403 pItem->u.x.iOrderByCol = 0;
91404 if( sqlite3ResolveExprNames(pNC, pE) ){
91405 return 1;
91407 for(j=0; j<pSelect->pEList->nExpr; j++){
91408 if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
91409 pItem->u.x.iOrderByCol = j+1;
91413 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
91417 ** Resolve names in the SELECT statement p and all of its descendants.
91419 static int resolveSelectStep(Walker *pWalker, Select *p){
91420 NameContext *pOuterNC; /* Context that contains this SELECT */
91421 NameContext sNC; /* Name context of this SELECT */
91422 int isCompound; /* True if p is a compound select */
91423 int nCompound; /* Number of compound terms processed so far */
91424 Parse *pParse; /* Parsing context */
91425 int i; /* Loop counter */
91426 ExprList *pGroupBy; /* The GROUP BY clause */
91427 Select *pLeftmost; /* Left-most of SELECT of a compound */
91428 sqlite3 *db; /* Database connection */
91431 assert( p!=0 );
91432 if( p->selFlags & SF_Resolved ){
91433 return WRC_Prune;
91435 pOuterNC = pWalker->u.pNC;
91436 pParse = pWalker->pParse;
91437 db = pParse->db;
91439 /* Normally sqlite3SelectExpand() will be called first and will have
91440 ** already expanded this SELECT. However, if this is a subquery within
91441 ** an expression, sqlite3ResolveExprNames() will be called without a
91442 ** prior call to sqlite3SelectExpand(). When that happens, let
91443 ** sqlite3SelectPrep() do all of the processing for this SELECT.
91444 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
91445 ** this routine in the correct order.
91447 if( (p->selFlags & SF_Expanded)==0 ){
91448 sqlite3SelectPrep(pParse, p, pOuterNC);
91449 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
91452 isCompound = p->pPrior!=0;
91453 nCompound = 0;
91454 pLeftmost = p;
91455 while( p ){
91456 assert( (p->selFlags & SF_Expanded)!=0 );
91457 assert( (p->selFlags & SF_Resolved)==0 );
91458 p->selFlags |= SF_Resolved;
91460 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
91461 ** are not allowed to refer to any names, so pass an empty NameContext.
91463 memset(&sNC, 0, sizeof(sNC));
91464 sNC.pParse = pParse;
91465 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
91466 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
91467 return WRC_Abort;
91470 /* If the SF_Converted flags is set, then this Select object was
91471 ** was created by the convertCompoundSelectToSubquery() function.
91472 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
91473 ** as if it were part of the sub-query, not the parent. This block
91474 ** moves the pOrderBy down to the sub-query. It will be moved back
91475 ** after the names have been resolved. */
91476 if( p->selFlags & SF_Converted ){
91477 Select *pSub = p->pSrc->a[0].pSelect;
91478 assert( p->pSrc->nSrc==1 && p->pOrderBy );
91479 assert( pSub->pPrior && pSub->pOrderBy==0 );
91480 pSub->pOrderBy = p->pOrderBy;
91481 p->pOrderBy = 0;
91484 /* Recursively resolve names in all subqueries
91486 for(i=0; i<p->pSrc->nSrc; i++){
91487 struct SrcList_item *pItem = &p->pSrc->a[i];
91488 if( pItem->pSelect ){
91489 NameContext *pNC; /* Used to iterate name contexts */
91490 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
91491 const char *zSavedContext = pParse->zAuthContext;
91493 /* Count the total number of references to pOuterNC and all of its
91494 ** parent contexts. After resolving references to expressions in
91495 ** pItem->pSelect, check if this value has changed. If so, then
91496 ** SELECT statement pItem->pSelect must be correlated. Set the
91497 ** pItem->fg.isCorrelated flag if this is the case. */
91498 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
91500 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
91501 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
91502 pParse->zAuthContext = zSavedContext;
91503 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
91505 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
91506 assert( pItem->fg.isCorrelated==0 && nRef<=0 );
91507 pItem->fg.isCorrelated = (nRef!=0);
91511 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
91512 ** resolve the result-set expression list.
91514 sNC.ncFlags = NC_AllowAgg;
91515 sNC.pSrcList = p->pSrc;
91516 sNC.pNext = pOuterNC;
91518 /* Resolve names in the result set. */
91519 if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
91521 /* If there are no aggregate functions in the result-set, and no GROUP BY
91522 ** expression, do not allow aggregates in any of the other expressions.
91524 assert( (p->selFlags & SF_Aggregate)==0 );
91525 pGroupBy = p->pGroupBy;
91526 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
91527 assert( NC_MinMaxAgg==SF_MinMaxAgg );
91528 p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
91529 }else{
91530 sNC.ncFlags &= ~NC_AllowAgg;
91533 /* If a HAVING clause is present, then there must be a GROUP BY clause.
91535 if( p->pHaving && !pGroupBy ){
91536 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
91537 return WRC_Abort;
91540 /* Add the output column list to the name-context before parsing the
91541 ** other expressions in the SELECT statement. This is so that
91542 ** expressions in the WHERE clause (etc.) can refer to expressions by
91543 ** aliases in the result set.
91545 ** Minor point: If this is the case, then the expression will be
91546 ** re-evaluated for each reference to it.
91548 sNC.pEList = p->pEList;
91549 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
91550 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
91552 /* Resolve names in table-valued-function arguments */
91553 for(i=0; i<p->pSrc->nSrc; i++){
91554 struct SrcList_item *pItem = &p->pSrc->a[i];
91555 if( pItem->fg.isTabFunc
91556 && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
91558 return WRC_Abort;
91562 /* The ORDER BY and GROUP BY clauses may not refer to terms in
91563 ** outer queries
91565 sNC.pNext = 0;
91566 sNC.ncFlags |= NC_AllowAgg;
91568 /* If this is a converted compound query, move the ORDER BY clause from
91569 ** the sub-query back to the parent query. At this point each term
91570 ** within the ORDER BY clause has been transformed to an integer value.
91571 ** These integers will be replaced by copies of the corresponding result
91572 ** set expressions by the call to resolveOrderGroupBy() below. */
91573 if( p->selFlags & SF_Converted ){
91574 Select *pSub = p->pSrc->a[0].pSelect;
91575 p->pOrderBy = pSub->pOrderBy;
91576 pSub->pOrderBy = 0;
91579 /* Process the ORDER BY clause for singleton SELECT statements.
91580 ** The ORDER BY clause for compounds SELECT statements is handled
91581 ** below, after all of the result-sets for all of the elements of
91582 ** the compound have been resolved.
91584 ** If there is an ORDER BY clause on a term of a compound-select other
91585 ** than the right-most term, then that is a syntax error. But the error
91586 ** is not detected until much later, and so we need to go ahead and
91587 ** resolve those symbols on the incorrect ORDER BY for consistency.
91589 if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
91590 && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
91592 return WRC_Abort;
91594 if( db->mallocFailed ){
91595 return WRC_Abort;
91598 /* Resolve the GROUP BY clause. At the same time, make sure
91599 ** the GROUP BY clause does not contain aggregate functions.
91601 if( pGroupBy ){
91602 struct ExprList_item *pItem;
91604 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
91605 return WRC_Abort;
91607 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
91608 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
91609 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
91610 "the GROUP BY clause");
91611 return WRC_Abort;
91616 /* If this is part of a compound SELECT, check that it has the right
91617 ** number of expressions in the select list. */
91618 if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
91619 sqlite3SelectWrongNumTermsError(pParse, p->pNext);
91620 return WRC_Abort;
91623 /* Advance to the next term of the compound
91625 p = p->pPrior;
91626 nCompound++;
91629 /* Resolve the ORDER BY on a compound SELECT after all terms of
91630 ** the compound have been resolved.
91632 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
91633 return WRC_Abort;
91636 return WRC_Prune;
91640 ** This routine walks an expression tree and resolves references to
91641 ** table columns and result-set columns. At the same time, do error
91642 ** checking on function usage and set a flag if any aggregate functions
91643 ** are seen.
91645 ** To resolve table columns references we look for nodes (or subtrees) of the
91646 ** form X.Y.Z or Y.Z or just Z where
91648 ** X: The name of a database. Ex: "main" or "temp" or
91649 ** the symbolic name assigned to an ATTACH-ed database.
91651 ** Y: The name of a table in a FROM clause. Or in a trigger
91652 ** one of the special names "old" or "new".
91654 ** Z: The name of a column in table Y.
91656 ** The node at the root of the subtree is modified as follows:
91658 ** Expr.op Changed to TK_COLUMN
91659 ** Expr.pTab Points to the Table object for X.Y
91660 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
91661 ** Expr.iTable The VDBE cursor number for X.Y
91664 ** To resolve result-set references, look for expression nodes of the
91665 ** form Z (with no X and Y prefix) where the Z matches the right-hand
91666 ** size of an AS clause in the result-set of a SELECT. The Z expression
91667 ** is replaced by a copy of the left-hand side of the result-set expression.
91668 ** Table-name and function resolution occurs on the substituted expression
91669 ** tree. For example, in:
91671 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
91673 ** The "x" term of the order by is replaced by "a+b" to render:
91675 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
91677 ** Function calls are checked to make sure that the function is
91678 ** defined and that the correct number of arguments are specified.
91679 ** If the function is an aggregate function, then the NC_HasAgg flag is
91680 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
91681 ** If an expression contains aggregate functions then the EP_Agg
91682 ** property on the expression is set.
91684 ** An error message is left in pParse if anything is amiss. The number
91685 ** if errors is returned.
91687 SQLITE_PRIVATE int sqlite3ResolveExprNames(
91688 NameContext *pNC, /* Namespace to resolve expressions in. */
91689 Expr *pExpr /* The expression to be analyzed. */
91691 u16 savedHasAgg;
91692 Walker w;
91694 if( pExpr==0 ) return SQLITE_OK;
91695 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
91696 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
91697 w.pParse = pNC->pParse;
91698 w.xExprCallback = resolveExprStep;
91699 w.xSelectCallback = resolveSelectStep;
91700 w.xSelectCallback2 = 0;
91701 w.u.pNC = pNC;
91702 #if SQLITE_MAX_EXPR_DEPTH>0
91703 w.pParse->nHeight += pExpr->nHeight;
91704 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
91705 return SQLITE_ERROR;
91707 #endif
91708 sqlite3WalkExpr(&w, pExpr);
91709 #if SQLITE_MAX_EXPR_DEPTH>0
91710 w.pParse->nHeight -= pExpr->nHeight;
91711 #endif
91712 if( pNC->ncFlags & NC_HasAgg ){
91713 ExprSetProperty(pExpr, EP_Agg);
91715 pNC->ncFlags |= savedHasAgg;
91716 return pNC->nErr>0 || w.pParse->nErr>0;
91720 ** Resolve all names for all expression in an expression list. This is
91721 ** just like sqlite3ResolveExprNames() except that it works for an expression
91722 ** list rather than a single expression.
91724 SQLITE_PRIVATE int sqlite3ResolveExprListNames(
91725 NameContext *pNC, /* Namespace to resolve expressions in. */
91726 ExprList *pList /* The expression list to be analyzed. */
91728 int i;
91729 if( pList ){
91730 for(i=0; i<pList->nExpr; i++){
91731 if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
91734 return WRC_Continue;
91738 ** Resolve all names in all expressions of a SELECT and in all
91739 ** decendents of the SELECT, including compounds off of p->pPrior,
91740 ** subqueries in expressions, and subqueries used as FROM clause
91741 ** terms.
91743 ** See sqlite3ResolveExprNames() for a description of the kinds of
91744 ** transformations that occur.
91746 ** All SELECT statements should have been expanded using
91747 ** sqlite3SelectExpand() prior to invoking this routine.
91749 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
91750 Parse *pParse, /* The parser context */
91751 Select *p, /* The SELECT statement being coded. */
91752 NameContext *pOuterNC /* Name context for parent SELECT statement */
91754 Walker w;
91756 assert( p!=0 );
91757 w.xExprCallback = resolveExprStep;
91758 w.xSelectCallback = resolveSelectStep;
91759 w.xSelectCallback2 = 0;
91760 w.pParse = pParse;
91761 w.u.pNC = pOuterNC;
91762 sqlite3WalkSelect(&w, p);
91766 ** Resolve names in expressions that can only reference a single table:
91768 ** * CHECK constraints
91769 ** * WHERE clauses on partial indices
91771 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
91772 ** is set to -1 and the Expr.iColumn value is set to the column number.
91774 ** Any errors cause an error message to be set in pParse.
91776 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
91777 Parse *pParse, /* Parsing context */
91778 Table *pTab, /* The table being referenced */
91779 int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
91780 Expr *pExpr, /* Expression to resolve. May be NULL. */
91781 ExprList *pList /* Expression list to resolve. May be NUL. */
91783 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
91784 NameContext sNC; /* Name context for pParse->pNewTable */
91786 assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
91787 memset(&sNC, 0, sizeof(sNC));
91788 memset(&sSrc, 0, sizeof(sSrc));
91789 sSrc.nSrc = 1;
91790 sSrc.a[0].zName = pTab->zName;
91791 sSrc.a[0].pTab = pTab;
91792 sSrc.a[0].iCursor = -1;
91793 sNC.pParse = pParse;
91794 sNC.pSrcList = &sSrc;
91795 sNC.ncFlags = type;
91796 if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
91797 if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
91800 /************** End of resolve.c *********************************************/
91801 /************** Begin file expr.c ********************************************/
91803 ** 2001 September 15
91805 ** The author disclaims copyright to this source code. In place of
91806 ** a legal notice, here is a blessing:
91808 ** May you do good and not evil.
91809 ** May you find forgiveness for yourself and forgive others.
91810 ** May you share freely, never taking more than you give.
91812 *************************************************************************
91813 ** This file contains routines used for analyzing expressions and
91814 ** for generating VDBE code that evaluates expressions in SQLite.
91816 /* #include "sqliteInt.h" */
91818 /* Forward declarations */
91819 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
91820 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
91823 ** Return the affinity character for a single column of a table.
91825 SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
91826 assert( iCol<pTab->nCol );
91827 return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
91831 ** Return the 'affinity' of the expression pExpr if any.
91833 ** If pExpr is a column, a reference to a column via an 'AS' alias,
91834 ** or a sub-select with a column as the return value, then the
91835 ** affinity of that column is returned. Otherwise, 0x00 is returned,
91836 ** indicating no affinity for the expression.
91838 ** i.e. the WHERE clause expressions in the following statements all
91839 ** have an affinity:
91841 ** CREATE TABLE t1(a);
91842 ** SELECT * FROM t1 WHERE a;
91843 ** SELECT a AS b FROM t1 WHERE b;
91844 ** SELECT * FROM t1 WHERE (select a from t1);
91846 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
91847 int op;
91848 pExpr = sqlite3ExprSkipCollate(pExpr);
91849 if( pExpr->flags & EP_Generic ) return 0;
91850 op = pExpr->op;
91851 if( op==TK_SELECT ){
91852 assert( pExpr->flags&EP_xIsSelect );
91853 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
91855 if( op==TK_REGISTER ) op = pExpr->op2;
91856 #ifndef SQLITE_OMIT_CAST
91857 if( op==TK_CAST ){
91858 assert( !ExprHasProperty(pExpr, EP_IntValue) );
91859 return sqlite3AffinityType(pExpr->u.zToken, 0);
91861 #endif
91862 if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
91863 return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
91865 if( op==TK_SELECT_COLUMN ){
91866 assert( pExpr->pLeft->flags&EP_xIsSelect );
91867 return sqlite3ExprAffinity(
91868 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
91871 return pExpr->affinity;
91875 ** Set the collating sequence for expression pExpr to be the collating
91876 ** sequence named by pToken. Return a pointer to a new Expr node that
91877 ** implements the COLLATE operator.
91879 ** If a memory allocation error occurs, that fact is recorded in pParse->db
91880 ** and the pExpr parameter is returned unchanged.
91882 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
91883 Parse *pParse, /* Parsing context */
91884 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
91885 const Token *pCollName, /* Name of collating sequence */
91886 int dequote /* True to dequote pCollName */
91888 if( pCollName->n>0 ){
91889 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
91890 if( pNew ){
91891 pNew->pLeft = pExpr;
91892 pNew->flags |= EP_Collate|EP_Skip;
91893 pExpr = pNew;
91896 return pExpr;
91898 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
91899 Token s;
91900 assert( zC!=0 );
91901 sqlite3TokenInit(&s, (char*)zC);
91902 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
91906 ** Skip over any TK_COLLATE operators and any unlikely()
91907 ** or likelihood() function at the root of an expression.
91909 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
91910 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
91911 if( ExprHasProperty(pExpr, EP_Unlikely) ){
91912 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
91913 assert( pExpr->x.pList->nExpr>0 );
91914 assert( pExpr->op==TK_FUNCTION );
91915 pExpr = pExpr->x.pList->a[0].pExpr;
91916 }else{
91917 assert( pExpr->op==TK_COLLATE );
91918 pExpr = pExpr->pLeft;
91921 return pExpr;
91925 ** Return the collation sequence for the expression pExpr. If
91926 ** there is no defined collating sequence, return NULL.
91928 ** See also: sqlite3ExprNNCollSeq()
91930 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
91931 ** default collation if pExpr has no defined collation.
91933 ** The collating sequence might be determined by a COLLATE operator
91934 ** or by the presence of a column with a defined collating sequence.
91935 ** COLLATE operators take first precedence. Left operands take
91936 ** precedence over right operands.
91938 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
91939 sqlite3 *db = pParse->db;
91940 CollSeq *pColl = 0;
91941 Expr *p = pExpr;
91942 while( p ){
91943 int op = p->op;
91944 if( p->flags & EP_Generic ) break;
91945 if( op==TK_CAST || op==TK_UPLUS ){
91946 p = p->pLeft;
91947 continue;
91949 if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
91950 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
91951 break;
91953 if( (op==TK_AGG_COLUMN || op==TK_COLUMN
91954 || op==TK_REGISTER || op==TK_TRIGGER)
91955 && p->pTab!=0
91957 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
91958 ** a TK_COLUMN but was previously evaluated and cached in a register */
91959 int j = p->iColumn;
91960 if( j>=0 ){
91961 const char *zColl = p->pTab->aCol[j].zColl;
91962 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
91964 break;
91966 if( p->flags & EP_Collate ){
91967 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
91968 p = p->pLeft;
91969 }else{
91970 Expr *pNext = p->pRight;
91971 /* The Expr.x union is never used at the same time as Expr.pRight */
91972 assert( p->x.pList==0 || p->pRight==0 );
91973 /* p->flags holds EP_Collate and p->pLeft->flags does not. And
91974 ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
91975 ** least one EP_Collate. Thus the following two ALWAYS. */
91976 if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
91977 int i;
91978 for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
91979 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
91980 pNext = p->x.pList->a[i].pExpr;
91981 break;
91985 p = pNext;
91987 }else{
91988 break;
91991 if( sqlite3CheckCollSeq(pParse, pColl) ){
91992 pColl = 0;
91994 return pColl;
91998 ** Return the collation sequence for the expression pExpr. If
91999 ** there is no defined collating sequence, return a pointer to the
92000 ** defautl collation sequence.
92002 ** See also: sqlite3ExprCollSeq()
92004 ** The sqlite3ExprCollSeq() routine works the same except that it
92005 ** returns NULL if there is no defined collation.
92007 SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
92008 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
92009 if( p==0 ) p = pParse->db->pDfltColl;
92010 assert( p!=0 );
92011 return p;
92015 ** Return TRUE if the two expressions have equivalent collating sequences.
92017 SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
92018 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
92019 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
92020 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
92024 ** pExpr is an operand of a comparison operator. aff2 is the
92025 ** type affinity of the other operand. This routine returns the
92026 ** type affinity that should be used for the comparison operator.
92028 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
92029 char aff1 = sqlite3ExprAffinity(pExpr);
92030 if( aff1 && aff2 ){
92031 /* Both sides of the comparison are columns. If one has numeric
92032 ** affinity, use that. Otherwise use no affinity.
92034 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
92035 return SQLITE_AFF_NUMERIC;
92036 }else{
92037 return SQLITE_AFF_BLOB;
92039 }else if( !aff1 && !aff2 ){
92040 /* Neither side of the comparison is a column. Compare the
92041 ** results directly.
92043 return SQLITE_AFF_BLOB;
92044 }else{
92045 /* One side is a column, the other is not. Use the columns affinity. */
92046 assert( aff1==0 || aff2==0 );
92047 return (aff1 + aff2);
92052 ** pExpr is a comparison operator. Return the type affinity that should
92053 ** be applied to both operands prior to doing the comparison.
92055 static char comparisonAffinity(Expr *pExpr){
92056 char aff;
92057 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
92058 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
92059 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
92060 assert( pExpr->pLeft );
92061 aff = sqlite3ExprAffinity(pExpr->pLeft);
92062 if( pExpr->pRight ){
92063 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
92064 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
92065 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
92066 }else if( aff==0 ){
92067 aff = SQLITE_AFF_BLOB;
92069 return aff;
92073 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
92074 ** idx_affinity is the affinity of an indexed column. Return true
92075 ** if the index with affinity idx_affinity may be used to implement
92076 ** the comparison in pExpr.
92078 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
92079 char aff = comparisonAffinity(pExpr);
92080 switch( aff ){
92081 case SQLITE_AFF_BLOB:
92082 return 1;
92083 case SQLITE_AFF_TEXT:
92084 return idx_affinity==SQLITE_AFF_TEXT;
92085 default:
92086 return sqlite3IsNumericAffinity(idx_affinity);
92091 ** Return the P5 value that should be used for a binary comparison
92092 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
92094 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
92095 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
92096 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
92097 return aff;
92101 ** Return a pointer to the collation sequence that should be used by
92102 ** a binary comparison operator comparing pLeft and pRight.
92104 ** If the left hand expression has a collating sequence type, then it is
92105 ** used. Otherwise the collation sequence for the right hand expression
92106 ** is used, or the default (BINARY) if neither expression has a collating
92107 ** type.
92109 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
92110 ** it is not considered.
92112 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
92113 Parse *pParse,
92114 Expr *pLeft,
92115 Expr *pRight
92117 CollSeq *pColl;
92118 assert( pLeft );
92119 if( pLeft->flags & EP_Collate ){
92120 pColl = sqlite3ExprCollSeq(pParse, pLeft);
92121 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
92122 pColl = sqlite3ExprCollSeq(pParse, pRight);
92123 }else{
92124 pColl = sqlite3ExprCollSeq(pParse, pLeft);
92125 if( !pColl ){
92126 pColl = sqlite3ExprCollSeq(pParse, pRight);
92129 return pColl;
92133 ** Generate code for a comparison operator.
92135 static int codeCompare(
92136 Parse *pParse, /* The parsing (and code generating) context */
92137 Expr *pLeft, /* The left operand */
92138 Expr *pRight, /* The right operand */
92139 int opcode, /* The comparison opcode */
92140 int in1, int in2, /* Register holding operands */
92141 int dest, /* Jump here if true. */
92142 int jumpIfNull /* If true, jump if either operand is NULL */
92144 int p5;
92145 int addr;
92146 CollSeq *p4;
92148 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
92149 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
92150 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
92151 (void*)p4, P4_COLLSEQ);
92152 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
92153 return addr;
92157 ** Return true if expression pExpr is a vector, or false otherwise.
92159 ** A vector is defined as any expression that results in two or more
92160 ** columns of result. Every TK_VECTOR node is an vector because the
92161 ** parser will not generate a TK_VECTOR with fewer than two entries.
92162 ** But a TK_SELECT might be either a vector or a scalar. It is only
92163 ** considered a vector if it has two or more result columns.
92165 SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
92166 return sqlite3ExprVectorSize(pExpr)>1;
92170 ** If the expression passed as the only argument is of type TK_VECTOR
92171 ** return the number of expressions in the vector. Or, if the expression
92172 ** is a sub-select, return the number of columns in the sub-select. For
92173 ** any other type of expression, return 1.
92175 SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
92176 u8 op = pExpr->op;
92177 if( op==TK_REGISTER ) op = pExpr->op2;
92178 if( op==TK_VECTOR ){
92179 return pExpr->x.pList->nExpr;
92180 }else if( op==TK_SELECT ){
92181 return pExpr->x.pSelect->pEList->nExpr;
92182 }else{
92183 return 1;
92188 ** Return a pointer to a subexpression of pVector that is the i-th
92189 ** column of the vector (numbered starting with 0). The caller must
92190 ** ensure that i is within range.
92192 ** If pVector is really a scalar (and "scalar" here includes subqueries
92193 ** that return a single column!) then return pVector unmodified.
92195 ** pVector retains ownership of the returned subexpression.
92197 ** If the vector is a (SELECT ...) then the expression returned is
92198 ** just the expression for the i-th term of the result set, and may
92199 ** not be ready for evaluation because the table cursor has not yet
92200 ** been positioned.
92202 SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
92203 assert( i<sqlite3ExprVectorSize(pVector) );
92204 if( sqlite3ExprIsVector(pVector) ){
92205 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
92206 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
92207 return pVector->x.pSelect->pEList->a[i].pExpr;
92208 }else{
92209 return pVector->x.pList->a[i].pExpr;
92212 return pVector;
92216 ** Compute and return a new Expr object which when passed to
92217 ** sqlite3ExprCode() will generate all necessary code to compute
92218 ** the iField-th column of the vector expression pVector.
92220 ** It is ok for pVector to be a scalar (as long as iField==0).
92221 ** In that case, this routine works like sqlite3ExprDup().
92223 ** The caller owns the returned Expr object and is responsible for
92224 ** ensuring that the returned value eventually gets freed.
92226 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
92227 ** then the returned object will reference pVector and so pVector must remain
92228 ** valid for the life of the returned object. If pVector is a TK_VECTOR
92229 ** or a scalar expression, then it can be deleted as soon as this routine
92230 ** returns.
92232 ** A trick to cause a TK_SELECT pVector to be deleted together with
92233 ** the returned Expr object is to attach the pVector to the pRight field
92234 ** of the returned TK_SELECT_COLUMN Expr object.
92236 SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
92237 Parse *pParse, /* Parsing context */
92238 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
92239 int iField /* Which column of the vector to return */
92241 Expr *pRet;
92242 if( pVector->op==TK_SELECT ){
92243 assert( pVector->flags & EP_xIsSelect );
92244 /* The TK_SELECT_COLUMN Expr node:
92246 ** pLeft: pVector containing TK_SELECT. Not deleted.
92247 ** pRight: not used. But recursively deleted.
92248 ** iColumn: Index of a column in pVector
92249 ** iTable: 0 or the number of columns on the LHS of an assignment
92250 ** pLeft->iTable: First in an array of register holding result, or 0
92251 ** if the result is not yet computed.
92253 ** sqlite3ExprDelete() specifically skips the recursive delete of
92254 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
92255 ** can be attached to pRight to cause this node to take ownership of
92256 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
92257 ** with the same pLeft pointer to the pVector, but only one of them
92258 ** will own the pVector.
92260 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
92261 if( pRet ){
92262 pRet->iColumn = iField;
92263 pRet->pLeft = pVector;
92265 assert( pRet==0 || pRet->iTable==0 );
92266 }else{
92267 if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
92268 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
92270 return pRet;
92274 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
92275 ** it. Return the register in which the result is stored (or, if the
92276 ** sub-select returns more than one column, the first in an array
92277 ** of registers in which the result is stored).
92279 ** If pExpr is not a TK_SELECT expression, return 0.
92281 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
92282 int reg = 0;
92283 #ifndef SQLITE_OMIT_SUBQUERY
92284 if( pExpr->op==TK_SELECT ){
92285 reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
92287 #endif
92288 return reg;
92292 ** Argument pVector points to a vector expression - either a TK_VECTOR
92293 ** or TK_SELECT that returns more than one column. This function returns
92294 ** the register number of a register that contains the value of
92295 ** element iField of the vector.
92297 ** If pVector is a TK_SELECT expression, then code for it must have
92298 ** already been generated using the exprCodeSubselect() routine. In this
92299 ** case parameter regSelect should be the first in an array of registers
92300 ** containing the results of the sub-select.
92302 ** If pVector is of type TK_VECTOR, then code for the requested field
92303 ** is generated. In this case (*pRegFree) may be set to the number of
92304 ** a temporary register to be freed by the caller before returning.
92306 ** Before returning, output parameter (*ppExpr) is set to point to the
92307 ** Expr object corresponding to element iElem of the vector.
92309 static int exprVectorRegister(
92310 Parse *pParse, /* Parse context */
92311 Expr *pVector, /* Vector to extract element from */
92312 int iField, /* Field to extract from pVector */
92313 int regSelect, /* First in array of registers */
92314 Expr **ppExpr, /* OUT: Expression element */
92315 int *pRegFree /* OUT: Temp register to free */
92317 u8 op = pVector->op;
92318 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
92319 if( op==TK_REGISTER ){
92320 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
92321 return pVector->iTable+iField;
92323 if( op==TK_SELECT ){
92324 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
92325 return regSelect+iField;
92327 *ppExpr = pVector->x.pList->a[iField].pExpr;
92328 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
92332 ** Expression pExpr is a comparison between two vector values. Compute
92333 ** the result of the comparison (1, 0, or NULL) and write that
92334 ** result into register dest.
92336 ** The caller must satisfy the following preconditions:
92338 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
92339 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
92340 ** otherwise: op==pExpr->op and p5==0
92342 static void codeVectorCompare(
92343 Parse *pParse, /* Code generator context */
92344 Expr *pExpr, /* The comparison operation */
92345 int dest, /* Write results into this register */
92346 u8 op, /* Comparison operator */
92347 u8 p5 /* SQLITE_NULLEQ or zero */
92349 Vdbe *v = pParse->pVdbe;
92350 Expr *pLeft = pExpr->pLeft;
92351 Expr *pRight = pExpr->pRight;
92352 int nLeft = sqlite3ExprVectorSize(pLeft);
92353 int i;
92354 int regLeft = 0;
92355 int regRight = 0;
92356 u8 opx = op;
92357 int addrDone = sqlite3VdbeMakeLabel(v);
92359 if( nLeft!=sqlite3ExprVectorSize(pRight) ){
92360 sqlite3ErrorMsg(pParse, "row value misused");
92361 return;
92363 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
92364 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
92365 || pExpr->op==TK_LT || pExpr->op==TK_GT
92366 || pExpr->op==TK_LE || pExpr->op==TK_GE
92368 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
92369 || (pExpr->op==TK_ISNOT && op==TK_NE) );
92370 assert( p5==0 || pExpr->op!=op );
92371 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
92373 p5 |= SQLITE_STOREP2;
92374 if( opx==TK_LE ) opx = TK_LT;
92375 if( opx==TK_GE ) opx = TK_GT;
92377 regLeft = exprCodeSubselect(pParse, pLeft);
92378 regRight = exprCodeSubselect(pParse, pRight);
92380 for(i=0; 1 /*Loop exits by "break"*/; i++){
92381 int regFree1 = 0, regFree2 = 0;
92382 Expr *pL, *pR;
92383 int r1, r2;
92384 assert( i>=0 && i<nLeft );
92385 if( i>0 ) sqlite3ExprCachePush(pParse);
92386 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
92387 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
92388 codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
92389 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
92390 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
92391 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
92392 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
92393 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
92394 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
92395 sqlite3ReleaseTempReg(pParse, regFree1);
92396 sqlite3ReleaseTempReg(pParse, regFree2);
92397 if( i>0 ) sqlite3ExprCachePop(pParse);
92398 if( i==nLeft-1 ){
92399 break;
92401 if( opx==TK_EQ ){
92402 sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
92403 p5 |= SQLITE_KEEPNULL;
92404 }else if( opx==TK_NE ){
92405 sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
92406 p5 |= SQLITE_KEEPNULL;
92407 }else{
92408 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
92409 sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
92410 VdbeCoverageIf(v, op==TK_LT);
92411 VdbeCoverageIf(v, op==TK_GT);
92412 VdbeCoverageIf(v, op==TK_LE);
92413 VdbeCoverageIf(v, op==TK_GE);
92414 if( i==nLeft-2 ) opx = op;
92417 sqlite3VdbeResolveLabel(v, addrDone);
92420 #if SQLITE_MAX_EXPR_DEPTH>0
92422 ** Check that argument nHeight is less than or equal to the maximum
92423 ** expression depth allowed. If it is not, leave an error message in
92424 ** pParse.
92426 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
92427 int rc = SQLITE_OK;
92428 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
92429 if( nHeight>mxHeight ){
92430 sqlite3ErrorMsg(pParse,
92431 "Expression tree is too large (maximum depth %d)", mxHeight
92433 rc = SQLITE_ERROR;
92435 return rc;
92438 /* The following three functions, heightOfExpr(), heightOfExprList()
92439 ** and heightOfSelect(), are used to determine the maximum height
92440 ** of any expression tree referenced by the structure passed as the
92441 ** first argument.
92443 ** If this maximum height is greater than the current value pointed
92444 ** to by pnHeight, the second parameter, then set *pnHeight to that
92445 ** value.
92447 static void heightOfExpr(Expr *p, int *pnHeight){
92448 if( p ){
92449 if( p->nHeight>*pnHeight ){
92450 *pnHeight = p->nHeight;
92454 static void heightOfExprList(ExprList *p, int *pnHeight){
92455 if( p ){
92456 int i;
92457 for(i=0; i<p->nExpr; i++){
92458 heightOfExpr(p->a[i].pExpr, pnHeight);
92462 static void heightOfSelect(Select *p, int *pnHeight){
92463 if( p ){
92464 heightOfExpr(p->pWhere, pnHeight);
92465 heightOfExpr(p->pHaving, pnHeight);
92466 heightOfExpr(p->pLimit, pnHeight);
92467 heightOfExpr(p->pOffset, pnHeight);
92468 heightOfExprList(p->pEList, pnHeight);
92469 heightOfExprList(p->pGroupBy, pnHeight);
92470 heightOfExprList(p->pOrderBy, pnHeight);
92471 heightOfSelect(p->pPrior, pnHeight);
92476 ** Set the Expr.nHeight variable in the structure passed as an
92477 ** argument. An expression with no children, Expr.pList or
92478 ** Expr.pSelect member has a height of 1. Any other expression
92479 ** has a height equal to the maximum height of any other
92480 ** referenced Expr plus one.
92482 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
92483 ** if appropriate.
92485 static void exprSetHeight(Expr *p){
92486 int nHeight = 0;
92487 heightOfExpr(p->pLeft, &nHeight);
92488 heightOfExpr(p->pRight, &nHeight);
92489 if( ExprHasProperty(p, EP_xIsSelect) ){
92490 heightOfSelect(p->x.pSelect, &nHeight);
92491 }else if( p->x.pList ){
92492 heightOfExprList(p->x.pList, &nHeight);
92493 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
92495 p->nHeight = nHeight + 1;
92499 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
92500 ** the height is greater than the maximum allowed expression depth,
92501 ** leave an error in pParse.
92503 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
92504 ** Expr.flags.
92506 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
92507 if( pParse->nErr ) return;
92508 exprSetHeight(p);
92509 sqlite3ExprCheckHeight(pParse, p->nHeight);
92513 ** Return the maximum height of any expression tree referenced
92514 ** by the select statement passed as an argument.
92516 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
92517 int nHeight = 0;
92518 heightOfSelect(p, &nHeight);
92519 return nHeight;
92521 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
92523 ** Propagate all EP_Propagate flags from the Expr.x.pList into
92524 ** Expr.flags.
92526 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
92527 if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
92528 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
92531 #define exprSetHeight(y)
92532 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
92535 ** This routine is the core allocator for Expr nodes.
92537 ** Construct a new expression node and return a pointer to it. Memory
92538 ** for this node and for the pToken argument is a single allocation
92539 ** obtained from sqlite3DbMalloc(). The calling function
92540 ** is responsible for making sure the node eventually gets freed.
92542 ** If dequote is true, then the token (if it exists) is dequoted.
92543 ** If dequote is false, no dequoting is performed. The deQuote
92544 ** parameter is ignored if pToken is NULL or if the token does not
92545 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
92546 ** then the EP_DblQuoted flag is set on the expression node.
92548 ** Special case: If op==TK_INTEGER and pToken points to a string that
92549 ** can be translated into a 32-bit integer, then the token is not
92550 ** stored in u.zToken. Instead, the integer values is written
92551 ** into u.iValue and the EP_IntValue flag is set. No extra storage
92552 ** is allocated to hold the integer text and the dequote flag is ignored.
92554 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
92555 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
92556 int op, /* Expression opcode */
92557 const Token *pToken, /* Token argument. Might be NULL */
92558 int dequote /* True to dequote */
92560 Expr *pNew;
92561 int nExtra = 0;
92562 int iValue = 0;
92564 assert( db!=0 );
92565 if( pToken ){
92566 if( op!=TK_INTEGER || pToken->z==0
92567 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
92568 nExtra = pToken->n+1;
92569 assert( iValue>=0 );
92572 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
92573 if( pNew ){
92574 memset(pNew, 0, sizeof(Expr));
92575 pNew->op = (u8)op;
92576 pNew->iAgg = -1;
92577 if( pToken ){
92578 if( nExtra==0 ){
92579 pNew->flags |= EP_IntValue|EP_Leaf;
92580 pNew->u.iValue = iValue;
92581 }else{
92582 pNew->u.zToken = (char*)&pNew[1];
92583 assert( pToken->z!=0 || pToken->n==0 );
92584 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
92585 pNew->u.zToken[pToken->n] = 0;
92586 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
92587 if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
92588 sqlite3Dequote(pNew->u.zToken);
92592 #if SQLITE_MAX_EXPR_DEPTH>0
92593 pNew->nHeight = 1;
92594 #endif
92596 return pNew;
92600 ** Allocate a new expression node from a zero-terminated token that has
92601 ** already been dequoted.
92603 SQLITE_PRIVATE Expr *sqlite3Expr(
92604 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
92605 int op, /* Expression opcode */
92606 const char *zToken /* Token argument. Might be NULL */
92608 Token x;
92609 x.z = zToken;
92610 x.n = sqlite3Strlen30(zToken);
92611 return sqlite3ExprAlloc(db, op, &x, 0);
92615 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
92617 ** If pRoot==NULL that means that a memory allocation error has occurred.
92618 ** In that case, delete the subtrees pLeft and pRight.
92620 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
92621 sqlite3 *db,
92622 Expr *pRoot,
92623 Expr *pLeft,
92624 Expr *pRight
92626 if( pRoot==0 ){
92627 assert( db->mallocFailed );
92628 sqlite3ExprDelete(db, pLeft);
92629 sqlite3ExprDelete(db, pRight);
92630 }else{
92631 if( pRight ){
92632 pRoot->pRight = pRight;
92633 pRoot->flags |= EP_Propagate & pRight->flags;
92635 if( pLeft ){
92636 pRoot->pLeft = pLeft;
92637 pRoot->flags |= EP_Propagate & pLeft->flags;
92639 exprSetHeight(pRoot);
92644 ** Allocate an Expr node which joins as many as two subtrees.
92646 ** One or both of the subtrees can be NULL. Return a pointer to the new
92647 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
92648 ** free the subtrees and return NULL.
92650 SQLITE_PRIVATE Expr *sqlite3PExpr(
92651 Parse *pParse, /* Parsing context */
92652 int op, /* Expression opcode */
92653 Expr *pLeft, /* Left operand */
92654 Expr *pRight /* Right operand */
92656 Expr *p;
92657 if( op==TK_AND && pParse->nErr==0 ){
92658 /* Take advantage of short-circuit false optimization for AND */
92659 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
92660 }else{
92661 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
92662 if( p ){
92663 memset(p, 0, sizeof(Expr));
92664 p->op = op & TKFLG_MASK;
92665 p->iAgg = -1;
92667 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
92669 if( p ) {
92670 sqlite3ExprCheckHeight(pParse, p->nHeight);
92672 return p;
92676 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
92677 ** do a memory allocation failure) then delete the pSelect object.
92679 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
92680 if( pExpr ){
92681 pExpr->x.pSelect = pSelect;
92682 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
92683 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
92684 }else{
92685 assert( pParse->db->mallocFailed );
92686 sqlite3SelectDelete(pParse->db, pSelect);
92692 ** If the expression is always either TRUE or FALSE (respectively),
92693 ** then return 1. If one cannot determine the truth value of the
92694 ** expression at compile-time return 0.
92696 ** This is an optimization. If is OK to return 0 here even if
92697 ** the expression really is always false or false (a false negative).
92698 ** But it is a bug to return 1 if the expression might have different
92699 ** boolean values in different circumstances (a false positive.)
92701 ** Note that if the expression is part of conditional for a
92702 ** LEFT JOIN, then we cannot determine at compile-time whether or not
92703 ** is it true or false, so always return 0.
92705 static int exprAlwaysTrue(Expr *p){
92706 int v = 0;
92707 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
92708 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
92709 return v!=0;
92711 static int exprAlwaysFalse(Expr *p){
92712 int v = 0;
92713 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
92714 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
92715 return v==0;
92719 ** Join two expressions using an AND operator. If either expression is
92720 ** NULL, then just return the other expression.
92722 ** If one side or the other of the AND is known to be false, then instead
92723 ** of returning an AND expression, just return a constant expression with
92724 ** a value of false.
92726 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
92727 if( pLeft==0 ){
92728 return pRight;
92729 }else if( pRight==0 ){
92730 return pLeft;
92731 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
92732 sqlite3ExprDelete(db, pLeft);
92733 sqlite3ExprDelete(db, pRight);
92734 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
92735 }else{
92736 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
92737 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
92738 return pNew;
92743 ** Construct a new expression node for a function with multiple
92744 ** arguments.
92746 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
92747 Expr *pNew;
92748 sqlite3 *db = pParse->db;
92749 assert( pToken );
92750 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
92751 if( pNew==0 ){
92752 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
92753 return 0;
92755 pNew->x.pList = pList;
92756 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
92757 sqlite3ExprSetHeightAndFlags(pParse, pNew);
92758 return pNew;
92762 ** Assign a variable number to an expression that encodes a wildcard
92763 ** in the original SQL statement.
92765 ** Wildcards consisting of a single "?" are assigned the next sequential
92766 ** variable number.
92768 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
92769 ** sure "nnn" is not too big to avoid a denial of service attack when
92770 ** the SQL statement comes from an external source.
92772 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
92773 ** as the previous instance of the same wildcard. Or if this is the first
92774 ** instance of the wildcard, the next sequential variable number is
92775 ** assigned.
92777 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
92778 sqlite3 *db = pParse->db;
92779 const char *z;
92780 ynVar x;
92782 if( pExpr==0 ) return;
92783 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
92784 z = pExpr->u.zToken;
92785 assert( z!=0 );
92786 assert( z[0]!=0 );
92787 assert( n==(u32)sqlite3Strlen30(z) );
92788 if( z[1]==0 ){
92789 /* Wildcard of the form "?". Assign the next variable number */
92790 assert( z[0]=='?' );
92791 x = (ynVar)(++pParse->nVar);
92792 }else{
92793 int doAdd = 0;
92794 if( z[0]=='?' ){
92795 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
92796 ** use it as the variable number */
92797 i64 i;
92798 int bOk;
92799 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
92800 i = z[1]-'0'; /* The common case of ?N for a single digit N */
92801 bOk = 1;
92802 }else{
92803 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
92805 testcase( i==0 );
92806 testcase( i==1 );
92807 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
92808 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
92809 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
92810 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
92811 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
92812 return;
92814 x = (ynVar)i;
92815 if( x>pParse->nVar ){
92816 pParse->nVar = (int)x;
92817 doAdd = 1;
92818 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
92819 doAdd = 1;
92821 }else{
92822 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
92823 ** number as the prior appearance of the same name, or if the name
92824 ** has never appeared before, reuse the same variable number
92826 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
92827 if( x==0 ){
92828 x = (ynVar)(++pParse->nVar);
92829 doAdd = 1;
92832 if( doAdd ){
92833 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
92836 pExpr->iColumn = x;
92837 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
92838 sqlite3ErrorMsg(pParse, "too many SQL variables");
92843 ** Recursively delete an expression tree.
92845 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
92846 assert( p!=0 );
92847 /* Sanity check: Assert that the IntValue is non-negative if it exists */
92848 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
92849 #ifdef SQLITE_DEBUG
92850 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
92851 assert( p->pLeft==0 );
92852 assert( p->pRight==0 );
92853 assert( p->x.pSelect==0 );
92855 #endif
92856 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
92857 /* The Expr.x union is never used at the same time as Expr.pRight */
92858 assert( p->x.pList==0 || p->pRight==0 );
92859 if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
92860 if( p->pRight ){
92861 sqlite3ExprDeleteNN(db, p->pRight);
92862 }else if( ExprHasProperty(p, EP_xIsSelect) ){
92863 sqlite3SelectDelete(db, p->x.pSelect);
92864 }else{
92865 sqlite3ExprListDelete(db, p->x.pList);
92868 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
92869 if( !ExprHasProperty(p, EP_Static) ){
92870 sqlite3DbFreeNN(db, p);
92873 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
92874 if( p ) sqlite3ExprDeleteNN(db, p);
92878 ** Return the number of bytes allocated for the expression structure
92879 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
92880 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
92882 static int exprStructSize(Expr *p){
92883 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
92884 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
92885 return EXPR_FULLSIZE;
92889 ** The dupedExpr*Size() routines each return the number of bytes required
92890 ** to store a copy of an expression or expression tree. They differ in
92891 ** how much of the tree is measured.
92893 ** dupedExprStructSize() Size of only the Expr structure
92894 ** dupedExprNodeSize() Size of Expr + space for token
92895 ** dupedExprSize() Expr + token + subtree components
92897 ***************************************************************************
92899 ** The dupedExprStructSize() function returns two values OR-ed together:
92900 ** (1) the space required for a copy of the Expr structure only and
92901 ** (2) the EP_xxx flags that indicate what the structure size should be.
92902 ** The return values is always one of:
92904 ** EXPR_FULLSIZE
92905 ** EXPR_REDUCEDSIZE | EP_Reduced
92906 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
92908 ** The size of the structure can be found by masking the return value
92909 ** of this routine with 0xfff. The flags can be found by masking the
92910 ** return value with EP_Reduced|EP_TokenOnly.
92912 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
92913 ** (unreduced) Expr objects as they or originally constructed by the parser.
92914 ** During expression analysis, extra information is computed and moved into
92915 ** later parts of teh Expr object and that extra information might get chopped
92916 ** off if the expression is reduced. Note also that it does not work to
92917 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
92918 ** to reduce a pristine expression tree from the parser. The implementation
92919 ** of dupedExprStructSize() contain multiple assert() statements that attempt
92920 ** to enforce this constraint.
92922 static int dupedExprStructSize(Expr *p, int flags){
92923 int nSize;
92924 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
92925 assert( EXPR_FULLSIZE<=0xfff );
92926 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
92927 if( 0==flags || p->op==TK_SELECT_COLUMN ){
92928 nSize = EXPR_FULLSIZE;
92929 }else{
92930 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
92931 assert( !ExprHasProperty(p, EP_FromJoin) );
92932 assert( !ExprHasProperty(p, EP_MemToken) );
92933 assert( !ExprHasProperty(p, EP_NoReduce) );
92934 if( p->pLeft || p->x.pList ){
92935 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
92936 }else{
92937 assert( p->pRight==0 );
92938 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
92941 return nSize;
92945 ** This function returns the space in bytes required to store the copy
92946 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
92947 ** string is defined.)
92949 static int dupedExprNodeSize(Expr *p, int flags){
92950 int nByte = dupedExprStructSize(p, flags) & 0xfff;
92951 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
92952 nByte += sqlite3Strlen30(p->u.zToken)+1;
92954 return ROUND8(nByte);
92958 ** Return the number of bytes required to create a duplicate of the
92959 ** expression passed as the first argument. The second argument is a
92960 ** mask containing EXPRDUP_XXX flags.
92962 ** The value returned includes space to create a copy of the Expr struct
92963 ** itself and the buffer referred to by Expr.u.zToken, if any.
92965 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
92966 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
92967 ** and Expr.pRight variables (but not for any structures pointed to or
92968 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
92970 static int dupedExprSize(Expr *p, int flags){
92971 int nByte = 0;
92972 if( p ){
92973 nByte = dupedExprNodeSize(p, flags);
92974 if( flags&EXPRDUP_REDUCE ){
92975 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
92978 return nByte;
92982 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
92983 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
92984 ** to store the copy of expression p, the copies of p->u.zToken
92985 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
92986 ** if any. Before returning, *pzBuffer is set to the first byte past the
92987 ** portion of the buffer copied into by this function.
92989 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
92990 Expr *pNew; /* Value to return */
92991 u8 *zAlloc; /* Memory space from which to build Expr object */
92992 u32 staticFlag; /* EP_Static if space not obtained from malloc */
92994 assert( db!=0 );
92995 assert( p );
92996 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
92997 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
92999 /* Figure out where to write the new Expr structure. */
93000 if( pzBuffer ){
93001 zAlloc = *pzBuffer;
93002 staticFlag = EP_Static;
93003 }else{
93004 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
93005 staticFlag = 0;
93007 pNew = (Expr *)zAlloc;
93009 if( pNew ){
93010 /* Set nNewSize to the size allocated for the structure pointed to
93011 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
93012 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
93013 ** by the copy of the p->u.zToken string (if any).
93015 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
93016 const int nNewSize = nStructSize & 0xfff;
93017 int nToken;
93018 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
93019 nToken = sqlite3Strlen30(p->u.zToken) + 1;
93020 }else{
93021 nToken = 0;
93023 if( dupFlags ){
93024 assert( ExprHasProperty(p, EP_Reduced)==0 );
93025 memcpy(zAlloc, p, nNewSize);
93026 }else{
93027 u32 nSize = (u32)exprStructSize(p);
93028 memcpy(zAlloc, p, nSize);
93029 if( nSize<EXPR_FULLSIZE ){
93030 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
93034 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
93035 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
93036 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
93037 pNew->flags |= staticFlag;
93039 /* Copy the p->u.zToken string, if any. */
93040 if( nToken ){
93041 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
93042 memcpy(zToken, p->u.zToken, nToken);
93045 if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
93046 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
93047 if( ExprHasProperty(p, EP_xIsSelect) ){
93048 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
93049 }else{
93050 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
93054 /* Fill in pNew->pLeft and pNew->pRight. */
93055 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
93056 zAlloc += dupedExprNodeSize(p, dupFlags);
93057 if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
93058 pNew->pLeft = p->pLeft ?
93059 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
93060 pNew->pRight = p->pRight ?
93061 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
93063 if( pzBuffer ){
93064 *pzBuffer = zAlloc;
93066 }else{
93067 if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
93068 if( pNew->op==TK_SELECT_COLUMN ){
93069 pNew->pLeft = p->pLeft;
93070 assert( p->iColumn==0 || p->pRight==0 );
93071 assert( p->pRight==0 || p->pRight==p->pLeft );
93072 }else{
93073 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
93075 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
93079 return pNew;
93083 ** Create and return a deep copy of the object passed as the second
93084 ** argument. If an OOM condition is encountered, NULL is returned
93085 ** and the db->mallocFailed flag set.
93087 #ifndef SQLITE_OMIT_CTE
93088 static With *withDup(sqlite3 *db, With *p){
93089 With *pRet = 0;
93090 if( p ){
93091 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
93092 pRet = sqlite3DbMallocZero(db, nByte);
93093 if( pRet ){
93094 int i;
93095 pRet->nCte = p->nCte;
93096 for(i=0; i<p->nCte; i++){
93097 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
93098 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
93099 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
93103 return pRet;
93105 #else
93106 # define withDup(x,y) 0
93107 #endif
93110 ** The following group of routines make deep copies of expressions,
93111 ** expression lists, ID lists, and select statements. The copies can
93112 ** be deleted (by being passed to their respective ...Delete() routines)
93113 ** without effecting the originals.
93115 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
93116 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
93117 ** by subsequent calls to sqlite*ListAppend() routines.
93119 ** Any tables that the SrcList might point to are not duplicated.
93121 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
93122 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
93123 ** truncated version of the usual Expr structure that will be stored as
93124 ** part of the in-memory representation of the database schema.
93126 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
93127 assert( flags==0 || flags==EXPRDUP_REDUCE );
93128 return p ? exprDup(db, p, flags, 0) : 0;
93130 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
93131 ExprList *pNew;
93132 struct ExprList_item *pItem, *pOldItem;
93133 int i;
93134 Expr *pPriorSelectCol = 0;
93135 assert( db!=0 );
93136 if( p==0 ) return 0;
93137 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
93138 if( pNew==0 ) return 0;
93139 pNew->nExpr = p->nExpr;
93140 pItem = pNew->a;
93141 pOldItem = p->a;
93142 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
93143 Expr *pOldExpr = pOldItem->pExpr;
93144 Expr *pNewExpr;
93145 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
93146 if( pOldExpr
93147 && pOldExpr->op==TK_SELECT_COLUMN
93148 && (pNewExpr = pItem->pExpr)!=0
93150 assert( pNewExpr->iColumn==0 || i>0 );
93151 if( pNewExpr->iColumn==0 ){
93152 assert( pOldExpr->pLeft==pOldExpr->pRight );
93153 pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
93154 }else{
93155 assert( i>0 );
93156 assert( pItem[-1].pExpr!=0 );
93157 assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
93158 assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
93159 pNewExpr->pLeft = pPriorSelectCol;
93162 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
93163 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
93164 pItem->sortOrder = pOldItem->sortOrder;
93165 pItem->done = 0;
93166 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
93167 pItem->u = pOldItem->u;
93169 return pNew;
93173 ** If cursors, triggers, views and subqueries are all omitted from
93174 ** the build, then none of the following routines, except for
93175 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
93176 ** called with a NULL argument.
93178 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
93179 || !defined(SQLITE_OMIT_SUBQUERY)
93180 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
93181 SrcList *pNew;
93182 int i;
93183 int nByte;
93184 assert( db!=0 );
93185 if( p==0 ) return 0;
93186 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
93187 pNew = sqlite3DbMallocRawNN(db, nByte );
93188 if( pNew==0 ) return 0;
93189 pNew->nSrc = pNew->nAlloc = p->nSrc;
93190 for(i=0; i<p->nSrc; i++){
93191 struct SrcList_item *pNewItem = &pNew->a[i];
93192 struct SrcList_item *pOldItem = &p->a[i];
93193 Table *pTab;
93194 pNewItem->pSchema = pOldItem->pSchema;
93195 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
93196 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
93197 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
93198 pNewItem->fg = pOldItem->fg;
93199 pNewItem->iCursor = pOldItem->iCursor;
93200 pNewItem->addrFillSub = pOldItem->addrFillSub;
93201 pNewItem->regReturn = pOldItem->regReturn;
93202 if( pNewItem->fg.isIndexedBy ){
93203 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
93205 pNewItem->pIBIndex = pOldItem->pIBIndex;
93206 if( pNewItem->fg.isTabFunc ){
93207 pNewItem->u1.pFuncArg =
93208 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
93210 pTab = pNewItem->pTab = pOldItem->pTab;
93211 if( pTab ){
93212 pTab->nTabRef++;
93214 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
93215 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
93216 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
93217 pNewItem->colUsed = pOldItem->colUsed;
93219 return pNew;
93221 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
93222 IdList *pNew;
93223 int i;
93224 assert( db!=0 );
93225 if( p==0 ) return 0;
93226 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
93227 if( pNew==0 ) return 0;
93228 pNew->nId = p->nId;
93229 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
93230 if( pNew->a==0 ){
93231 sqlite3DbFreeNN(db, pNew);
93232 return 0;
93234 /* Note that because the size of the allocation for p->a[] is not
93235 ** necessarily a power of two, sqlite3IdListAppend() may not be called
93236 ** on the duplicate created by this function. */
93237 for(i=0; i<p->nId; i++){
93238 struct IdList_item *pNewItem = &pNew->a[i];
93239 struct IdList_item *pOldItem = &p->a[i];
93240 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
93241 pNewItem->idx = pOldItem->idx;
93243 return pNew;
93245 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
93246 Select *pRet = 0;
93247 Select *pNext = 0;
93248 Select **pp = &pRet;
93249 Select *p;
93251 assert( db!=0 );
93252 for(p=pDup; p; p=p->pPrior){
93253 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
93254 if( pNew==0 ) break;
93255 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
93256 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
93257 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
93258 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
93259 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
93260 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
93261 pNew->op = p->op;
93262 pNew->pNext = pNext;
93263 pNew->pPrior = 0;
93264 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
93265 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
93266 pNew->iLimit = 0;
93267 pNew->iOffset = 0;
93268 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
93269 pNew->addrOpenEphm[0] = -1;
93270 pNew->addrOpenEphm[1] = -1;
93271 pNew->nSelectRow = p->nSelectRow;
93272 pNew->pWith = withDup(db, p->pWith);
93273 sqlite3SelectSetName(pNew, p->zSelName);
93274 *pp = pNew;
93275 pp = &pNew->pPrior;
93276 pNext = pNew;
93279 return pRet;
93281 #else
93282 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
93283 assert( p==0 );
93284 return 0;
93286 #endif
93290 ** Add a new element to the end of an expression list. If pList is
93291 ** initially NULL, then create a new expression list.
93293 ** The pList argument must be either NULL or a pointer to an ExprList
93294 ** obtained from a prior call to sqlite3ExprListAppend(). This routine
93295 ** may not be used with an ExprList obtained from sqlite3ExprListDup().
93296 ** Reason: This routine assumes that the number of slots in pList->a[]
93297 ** is a power of two. That is true for sqlite3ExprListAppend() returns
93298 ** but is not necessarily true from the return value of sqlite3ExprListDup().
93300 ** If a memory allocation error occurs, the entire list is freed and
93301 ** NULL is returned. If non-NULL is returned, then it is guaranteed
93302 ** that the new entry was successfully appended.
93304 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
93305 Parse *pParse, /* Parsing context */
93306 ExprList *pList, /* List to which to append. Might be NULL */
93307 Expr *pExpr /* Expression to be appended. Might be NULL */
93309 struct ExprList_item *pItem;
93310 sqlite3 *db = pParse->db;
93311 assert( db!=0 );
93312 if( pList==0 ){
93313 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
93314 if( pList==0 ){
93315 goto no_mem;
93317 pList->nExpr = 0;
93318 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
93319 ExprList *pNew;
93320 pNew = sqlite3DbRealloc(db, pList,
93321 sizeof(*pList)+(2*pList->nExpr - 1)*sizeof(pList->a[0]));
93322 if( pNew==0 ){
93323 goto no_mem;
93325 pList = pNew;
93327 pItem = &pList->a[pList->nExpr++];
93328 assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
93329 assert( offsetof(struct ExprList_item,pExpr)==0 );
93330 memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
93331 pItem->pExpr = pExpr;
93332 return pList;
93334 no_mem:
93335 /* Avoid leaking memory if malloc has failed. */
93336 sqlite3ExprDelete(db, pExpr);
93337 sqlite3ExprListDelete(db, pList);
93338 return 0;
93342 ** pColumns and pExpr form a vector assignment which is part of the SET
93343 ** clause of an UPDATE statement. Like this:
93345 ** (a,b,c) = (expr1,expr2,expr3)
93346 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
93348 ** For each term of the vector assignment, append new entries to the
93349 ** expression list pList. In the case of a subquery on the RHS, append
93350 ** TK_SELECT_COLUMN expressions.
93352 SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
93353 Parse *pParse, /* Parsing context */
93354 ExprList *pList, /* List to which to append. Might be NULL */
93355 IdList *pColumns, /* List of names of LHS of the assignment */
93356 Expr *pExpr /* Vector expression to be appended. Might be NULL */
93358 sqlite3 *db = pParse->db;
93359 int n;
93360 int i;
93361 int iFirst = pList ? pList->nExpr : 0;
93362 /* pColumns can only be NULL due to an OOM but an OOM will cause an
93363 ** exit prior to this routine being invoked */
93364 if( NEVER(pColumns==0) ) goto vector_append_error;
93365 if( pExpr==0 ) goto vector_append_error;
93367 /* If the RHS is a vector, then we can immediately check to see that
93368 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
93369 ** wildcards ("*") in the result set of the SELECT must be expanded before
93370 ** we can do the size check, so defer the size check until code generation.
93372 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
93373 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
93374 pColumns->nId, n);
93375 goto vector_append_error;
93378 for(i=0; i<pColumns->nId; i++){
93379 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
93380 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
93381 if( pList ){
93382 assert( pList->nExpr==iFirst+i+1 );
93383 pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
93384 pColumns->a[i].zName = 0;
93388 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
93389 Expr *pFirst = pList->a[iFirst].pExpr;
93390 assert( pFirst!=0 );
93391 assert( pFirst->op==TK_SELECT_COLUMN );
93393 /* Store the SELECT statement in pRight so it will be deleted when
93394 ** sqlite3ExprListDelete() is called */
93395 pFirst->pRight = pExpr;
93396 pExpr = 0;
93398 /* Remember the size of the LHS in iTable so that we can check that
93399 ** the RHS and LHS sizes match during code generation. */
93400 pFirst->iTable = pColumns->nId;
93403 vector_append_error:
93404 sqlite3ExprDelete(db, pExpr);
93405 sqlite3IdListDelete(db, pColumns);
93406 return pList;
93410 ** Set the sort order for the last element on the given ExprList.
93412 SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
93413 if( p==0 ) return;
93414 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
93415 assert( p->nExpr>0 );
93416 if( iSortOrder<0 ){
93417 assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
93418 return;
93420 p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
93424 ** Set the ExprList.a[].zName element of the most recently added item
93425 ** on the expression list.
93427 ** pList might be NULL following an OOM error. But pName should never be
93428 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
93429 ** is set.
93431 SQLITE_PRIVATE void sqlite3ExprListSetName(
93432 Parse *pParse, /* Parsing context */
93433 ExprList *pList, /* List to which to add the span. */
93434 Token *pName, /* Name to be added */
93435 int dequote /* True to cause the name to be dequoted */
93437 assert( pList!=0 || pParse->db->mallocFailed!=0 );
93438 if( pList ){
93439 struct ExprList_item *pItem;
93440 assert( pList->nExpr>0 );
93441 pItem = &pList->a[pList->nExpr-1];
93442 assert( pItem->zName==0 );
93443 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
93444 if( dequote ) sqlite3Dequote(pItem->zName);
93449 ** Set the ExprList.a[].zSpan element of the most recently added item
93450 ** on the expression list.
93452 ** pList might be NULL following an OOM error. But pSpan should never be
93453 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
93454 ** is set.
93456 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
93457 Parse *pParse, /* Parsing context */
93458 ExprList *pList, /* List to which to add the span. */
93459 ExprSpan *pSpan /* The span to be added */
93461 sqlite3 *db = pParse->db;
93462 assert( pList!=0 || db->mallocFailed!=0 );
93463 if( pList ){
93464 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
93465 assert( pList->nExpr>0 );
93466 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
93467 sqlite3DbFree(db, pItem->zSpan);
93468 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
93469 (int)(pSpan->zEnd - pSpan->zStart));
93474 ** If the expression list pEList contains more than iLimit elements,
93475 ** leave an error message in pParse.
93477 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
93478 Parse *pParse,
93479 ExprList *pEList,
93480 const char *zObject
93482 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
93483 testcase( pEList && pEList->nExpr==mx );
93484 testcase( pEList && pEList->nExpr==mx+1 );
93485 if( pEList && pEList->nExpr>mx ){
93486 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
93491 ** Delete an entire expression list.
93493 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
93494 int i = pList->nExpr;
93495 struct ExprList_item *pItem = pList->a;
93496 assert( pList->nExpr>0 );
93498 sqlite3ExprDelete(db, pItem->pExpr);
93499 sqlite3DbFree(db, pItem->zName);
93500 sqlite3DbFree(db, pItem->zSpan);
93501 pItem++;
93502 }while( --i>0 );
93503 sqlite3DbFreeNN(db, pList);
93505 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
93506 if( pList ) exprListDeleteNN(db, pList);
93510 ** Return the bitwise-OR of all Expr.flags fields in the given
93511 ** ExprList.
93513 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
93514 int i;
93515 u32 m = 0;
93516 assert( pList!=0 );
93517 for(i=0; i<pList->nExpr; i++){
93518 Expr *pExpr = pList->a[i].pExpr;
93519 assert( pExpr!=0 );
93520 m |= pExpr->flags;
93522 return m;
93526 ** This is a SELECT-node callback for the expression walker that
93527 ** always "fails". By "fail" in this case, we mean set
93528 ** pWalker->eCode to zero and abort.
93530 ** This callback is used by multiple expression walkers.
93532 SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
93533 UNUSED_PARAMETER(NotUsed);
93534 pWalker->eCode = 0;
93535 return WRC_Abort;
93539 ** These routines are Walker callbacks used to check expressions to
93540 ** see if they are "constant" for some definition of constant. The
93541 ** Walker.eCode value determines the type of "constant" we are looking
93542 ** for.
93544 ** These callback routines are used to implement the following:
93546 ** sqlite3ExprIsConstant() pWalker->eCode==1
93547 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
93548 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
93549 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
93551 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
93552 ** is found to not be a constant.
93554 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
93555 ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
93556 ** an existing schema and 4 when processing a new statement. A bound
93557 ** parameter raises an error for new statements, but is silently converted
93558 ** to NULL for existing schemas. This allows sqlite_master tables that
93559 ** contain a bound parameter because they were generated by older versions
93560 ** of SQLite to be parsed by newer versions of SQLite without raising a
93561 ** malformed schema error.
93563 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
93565 /* If pWalker->eCode is 2 then any term of the expression that comes from
93566 ** the ON or USING clauses of a left join disqualifies the expression
93567 ** from being considered constant. */
93568 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
93569 pWalker->eCode = 0;
93570 return WRC_Abort;
93573 switch( pExpr->op ){
93574 /* Consider functions to be constant if all their arguments are constant
93575 ** and either pWalker->eCode==4 or 5 or the function has the
93576 ** SQLITE_FUNC_CONST flag. */
93577 case TK_FUNCTION:
93578 if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
93579 return WRC_Continue;
93580 }else{
93581 pWalker->eCode = 0;
93582 return WRC_Abort;
93584 case TK_ID:
93585 case TK_COLUMN:
93586 case TK_AGG_FUNCTION:
93587 case TK_AGG_COLUMN:
93588 testcase( pExpr->op==TK_ID );
93589 testcase( pExpr->op==TK_COLUMN );
93590 testcase( pExpr->op==TK_AGG_FUNCTION );
93591 testcase( pExpr->op==TK_AGG_COLUMN );
93592 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
93593 return WRC_Continue;
93595 /* Fall through */
93596 case TK_IF_NULL_ROW:
93597 testcase( pExpr->op==TK_IF_NULL_ROW );
93598 pWalker->eCode = 0;
93599 return WRC_Abort;
93600 case TK_VARIABLE:
93601 if( pWalker->eCode==5 ){
93602 /* Silently convert bound parameters that appear inside of CREATE
93603 ** statements into a NULL when parsing the CREATE statement text out
93604 ** of the sqlite_master table */
93605 pExpr->op = TK_NULL;
93606 }else if( pWalker->eCode==4 ){
93607 /* A bound parameter in a CREATE statement that originates from
93608 ** sqlite3_prepare() causes an error */
93609 pWalker->eCode = 0;
93610 return WRC_Abort;
93612 /* Fall through */
93613 default:
93614 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail will disallow */
93615 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail will disallow */
93616 return WRC_Continue;
93619 static int exprIsConst(Expr *p, int initFlag, int iCur){
93620 Walker w;
93621 w.eCode = initFlag;
93622 w.xExprCallback = exprNodeIsConstant;
93623 w.xSelectCallback = sqlite3SelectWalkFail;
93624 #ifdef SQLITE_DEBUG
93625 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
93626 #endif
93627 w.u.iCur = iCur;
93628 sqlite3WalkExpr(&w, p);
93629 return w.eCode;
93633 ** Walk an expression tree. Return non-zero if the expression is constant
93634 ** and 0 if it involves variables or function calls.
93636 ** For the purposes of this function, a double-quoted string (ex: "abc")
93637 ** is considered a variable but a single-quoted string (ex: 'abc') is
93638 ** a constant.
93640 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
93641 return exprIsConst(p, 1, 0);
93645 ** Walk an expression tree. Return non-zero if the expression is constant
93646 ** that does no originate from the ON or USING clauses of a join.
93647 ** Return 0 if it involves variables or function calls or terms from
93648 ** an ON or USING clause.
93650 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
93651 return exprIsConst(p, 2, 0);
93655 ** Walk an expression tree. Return non-zero if the expression is constant
93656 ** for any single row of the table with cursor iCur. In other words, the
93657 ** expression must not refer to any non-deterministic function nor any
93658 ** table other than iCur.
93660 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
93661 return exprIsConst(p, 3, iCur);
93666 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
93668 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
93669 ExprList *pGroupBy = pWalker->u.pGroupBy;
93670 int i;
93672 /* Check if pExpr is identical to any GROUP BY term. If so, consider
93673 ** it constant. */
93674 for(i=0; i<pGroupBy->nExpr; i++){
93675 Expr *p = pGroupBy->a[i].pExpr;
93676 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
93677 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
93678 if( sqlite3_stricmp("BINARY", pColl->zName)==0 ){
93679 return WRC_Prune;
93684 /* Check if pExpr is a sub-select. If so, consider it variable. */
93685 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
93686 pWalker->eCode = 0;
93687 return WRC_Abort;
93690 return exprNodeIsConstant(pWalker, pExpr);
93694 ** Walk the expression tree passed as the first argument. Return non-zero
93695 ** if the expression consists entirely of constants or copies of terms
93696 ** in pGroupBy that sort with the BINARY collation sequence.
93698 ** This routine is used to determine if a term of the HAVING clause can
93699 ** be promoted into the WHERE clause. In order for such a promotion to work,
93700 ** the value of the HAVING clause term must be the same for all members of
93701 ** a "group". The requirement that the GROUP BY term must be BINARY
93702 ** assumes that no other collating sequence will have a finer-grained
93703 ** grouping than binary. In other words (A=B COLLATE binary) implies
93704 ** A=B in every other collating sequence. The requirement that the
93705 ** GROUP BY be BINARY is stricter than necessary. It would also work
93706 ** to promote HAVING clauses that use the same alternative collating
93707 ** sequence as the GROUP BY term, but that is much harder to check,
93708 ** alternative collating sequences are uncommon, and this is only an
93709 ** optimization, so we take the easy way out and simply require the
93710 ** GROUP BY to use the BINARY collating sequence.
93712 SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
93713 Walker w;
93714 w.eCode = 1;
93715 w.xExprCallback = exprNodeIsConstantOrGroupBy;
93716 w.xSelectCallback = 0;
93717 w.u.pGroupBy = pGroupBy;
93718 w.pParse = pParse;
93719 sqlite3WalkExpr(&w, p);
93720 return w.eCode;
93724 ** Walk an expression tree. Return non-zero if the expression is constant
93725 ** or a function call with constant arguments. Return and 0 if there
93726 ** are any variables.
93728 ** For the purposes of this function, a double-quoted string (ex: "abc")
93729 ** is considered a variable but a single-quoted string (ex: 'abc') is
93730 ** a constant.
93732 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
93733 assert( isInit==0 || isInit==1 );
93734 return exprIsConst(p, 4+isInit, 0);
93737 #ifdef SQLITE_ENABLE_CURSOR_HINTS
93739 ** Walk an expression tree. Return 1 if the expression contains a
93740 ** subquery of some kind. Return 0 if there are no subqueries.
93742 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
93743 Walker w;
93744 w.eCode = 1;
93745 w.xExprCallback = sqlite3ExprWalkNoop;
93746 w.xSelectCallback = sqlite3SelectWalkFail;
93747 #ifdef SQLITE_DEBUG
93748 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
93749 #endif
93750 sqlite3WalkExpr(&w, p);
93751 return w.eCode==0;
93753 #endif
93756 ** If the expression p codes a constant integer that is small enough
93757 ** to fit in a 32-bit integer, return 1 and put the value of the integer
93758 ** in *pValue. If the expression is not an integer or if it is too big
93759 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
93761 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
93762 int rc = 0;
93763 if( p==0 ) return 0; /* Can only happen following on OOM */
93765 /* If an expression is an integer literal that fits in a signed 32-bit
93766 ** integer, then the EP_IntValue flag will have already been set */
93767 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
93768 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
93770 if( p->flags & EP_IntValue ){
93771 *pValue = p->u.iValue;
93772 return 1;
93774 switch( p->op ){
93775 case TK_UPLUS: {
93776 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
93777 break;
93779 case TK_UMINUS: {
93780 int v;
93781 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
93782 assert( v!=(-2147483647-1) );
93783 *pValue = -v;
93784 rc = 1;
93786 break;
93788 default: break;
93790 return rc;
93794 ** Return FALSE if there is no chance that the expression can be NULL.
93796 ** If the expression might be NULL or if the expression is too complex
93797 ** to tell return TRUE.
93799 ** This routine is used as an optimization, to skip OP_IsNull opcodes
93800 ** when we know that a value cannot be NULL. Hence, a false positive
93801 ** (returning TRUE when in fact the expression can never be NULL) might
93802 ** be a small performance hit but is otherwise harmless. On the other
93803 ** hand, a false negative (returning FALSE when the result could be NULL)
93804 ** will likely result in an incorrect answer. So when in doubt, return
93805 ** TRUE.
93807 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
93808 u8 op;
93809 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
93810 op = p->op;
93811 if( op==TK_REGISTER ) op = p->op2;
93812 switch( op ){
93813 case TK_INTEGER:
93814 case TK_STRING:
93815 case TK_FLOAT:
93816 case TK_BLOB:
93817 return 0;
93818 case TK_COLUMN:
93819 return ExprHasProperty(p, EP_CanBeNull) ||
93820 p->pTab==0 || /* Reference to column of index on expression */
93821 (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
93822 default:
93823 return 1;
93828 ** Return TRUE if the given expression is a constant which would be
93829 ** unchanged by OP_Affinity with the affinity given in the second
93830 ** argument.
93832 ** This routine is used to determine if the OP_Affinity operation
93833 ** can be omitted. When in doubt return FALSE. A false negative
93834 ** is harmless. A false positive, however, can result in the wrong
93835 ** answer.
93837 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
93838 u8 op;
93839 if( aff==SQLITE_AFF_BLOB ) return 1;
93840 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
93841 op = p->op;
93842 if( op==TK_REGISTER ) op = p->op2;
93843 switch( op ){
93844 case TK_INTEGER: {
93845 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
93847 case TK_FLOAT: {
93848 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
93850 case TK_STRING: {
93851 return aff==SQLITE_AFF_TEXT;
93853 case TK_BLOB: {
93854 return 1;
93856 case TK_COLUMN: {
93857 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
93858 return p->iColumn<0
93859 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
93861 default: {
93862 return 0;
93868 ** Return TRUE if the given string is a row-id column name.
93870 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
93871 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
93872 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
93873 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
93874 return 0;
93878 ** pX is the RHS of an IN operator. If pX is a SELECT statement
93879 ** that can be simplified to a direct table access, then return
93880 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
93881 ** or if the SELECT statement needs to be manifested into a transient
93882 ** table, then return NULL.
93884 #ifndef SQLITE_OMIT_SUBQUERY
93885 static Select *isCandidateForInOpt(Expr *pX){
93886 Select *p;
93887 SrcList *pSrc;
93888 ExprList *pEList;
93889 Table *pTab;
93890 int i;
93891 if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
93892 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
93893 p = pX->x.pSelect;
93894 if( p->pPrior ) return 0; /* Not a compound SELECT */
93895 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
93896 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
93897 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
93898 return 0; /* No DISTINCT keyword and no aggregate functions */
93900 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
93901 if( p->pLimit ) return 0; /* Has no LIMIT clause */
93902 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
93903 if( p->pWhere ) return 0; /* Has no WHERE clause */
93904 pSrc = p->pSrc;
93905 assert( pSrc!=0 );
93906 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
93907 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
93908 pTab = pSrc->a[0].pTab;
93909 assert( pTab!=0 );
93910 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
93911 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
93912 pEList = p->pEList;
93913 assert( pEList!=0 );
93914 /* All SELECT results must be columns. */
93915 for(i=0; i<pEList->nExpr; i++){
93916 Expr *pRes = pEList->a[i].pExpr;
93917 if( pRes->op!=TK_COLUMN ) return 0;
93918 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
93920 return p;
93922 #endif /* SQLITE_OMIT_SUBQUERY */
93924 #ifndef SQLITE_OMIT_SUBQUERY
93926 ** Generate code that checks the left-most column of index table iCur to see if
93927 ** it contains any NULL entries. Cause the register at regHasNull to be set
93928 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
93929 ** to be set to NULL if iCur contains one or more NULL values.
93931 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
93932 int addr1;
93933 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
93934 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
93935 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
93936 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
93937 VdbeComment((v, "first_entry_in(%d)", iCur));
93938 sqlite3VdbeJumpHere(v, addr1);
93940 #endif
93943 #ifndef SQLITE_OMIT_SUBQUERY
93945 ** The argument is an IN operator with a list (not a subquery) on the
93946 ** right-hand side. Return TRUE if that list is constant.
93948 static int sqlite3InRhsIsConstant(Expr *pIn){
93949 Expr *pLHS;
93950 int res;
93951 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
93952 pLHS = pIn->pLeft;
93953 pIn->pLeft = 0;
93954 res = sqlite3ExprIsConstant(pIn);
93955 pIn->pLeft = pLHS;
93956 return res;
93958 #endif
93961 ** This function is used by the implementation of the IN (...) operator.
93962 ** The pX parameter is the expression on the RHS of the IN operator, which
93963 ** might be either a list of expressions or a subquery.
93965 ** The job of this routine is to find or create a b-tree object that can
93966 ** be used either to test for membership in the RHS set or to iterate through
93967 ** all members of the RHS set, skipping duplicates.
93969 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
93970 ** and pX->iTable is set to the index of that cursor.
93972 ** The returned value of this function indicates the b-tree type, as follows:
93974 ** IN_INDEX_ROWID - The cursor was opened on a database table.
93975 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
93976 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
93977 ** IN_INDEX_EPH - The cursor was opened on a specially created and
93978 ** populated epheremal table.
93979 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
93980 ** implemented as a sequence of comparisons.
93982 ** An existing b-tree might be used if the RHS expression pX is a simple
93983 ** subquery such as:
93985 ** SELECT <column1>, <column2>... FROM <table>
93987 ** If the RHS of the IN operator is a list or a more complex subquery, then
93988 ** an ephemeral table might need to be generated from the RHS and then
93989 ** pX->iTable made to point to the ephemeral table instead of an
93990 ** existing table.
93992 ** The inFlags parameter must contain exactly one of the bits
93993 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
93994 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
93995 ** fast membership test. When the IN_INDEX_LOOP bit is set, the
93996 ** IN index will be used to loop over all values of the RHS of the
93997 ** IN operator.
93999 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
94000 ** through the set members) then the b-tree must not contain duplicates.
94001 ** An epheremal table must be used unless the selected columns are guaranteed
94002 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
94003 ** a UNIQUE constraint or index.
94005 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
94006 ** for fast set membership tests) then an epheremal table must
94007 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
94008 ** index can be found with the specified <columns> as its left-most.
94010 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
94011 ** if the RHS of the IN operator is a list (not a subquery) then this
94012 ** routine might decide that creating an ephemeral b-tree for membership
94013 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
94014 ** calling routine should implement the IN operator using a sequence
94015 ** of Eq or Ne comparison operations.
94017 ** When the b-tree is being used for membership tests, the calling function
94018 ** might need to know whether or not the RHS side of the IN operator
94019 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
94020 ** if there is any chance that the (...) might contain a NULL value at
94021 ** runtime, then a register is allocated and the register number written
94022 ** to *prRhsHasNull. If there is no chance that the (...) contains a
94023 ** NULL value, then *prRhsHasNull is left unchanged.
94025 ** If a register is allocated and its location stored in *prRhsHasNull, then
94026 ** the value in that register will be NULL if the b-tree contains one or more
94027 ** NULL values, and it will be some non-NULL value if the b-tree contains no
94028 ** NULL values.
94030 ** If the aiMap parameter is not NULL, it must point to an array containing
94031 ** one element for each column returned by the SELECT statement on the RHS
94032 ** of the IN(...) operator. The i'th entry of the array is populated with the
94033 ** offset of the index column that matches the i'th column returned by the
94034 ** SELECT. For example, if the expression and selected index are:
94036 ** (?,?,?) IN (SELECT a, b, c FROM t1)
94037 ** CREATE INDEX i1 ON t1(b, c, a);
94039 ** then aiMap[] is populated with {2, 0, 1}.
94041 #ifndef SQLITE_OMIT_SUBQUERY
94042 SQLITE_PRIVATE int sqlite3FindInIndex(
94043 Parse *pParse, /* Parsing context */
94044 Expr *pX, /* The right-hand side (RHS) of the IN operator */
94045 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
94046 int *prRhsHasNull, /* Register holding NULL status. See notes */
94047 int *aiMap /* Mapping from Index fields to RHS fields */
94049 Select *p; /* SELECT to the right of IN operator */
94050 int eType = 0; /* Type of RHS table. IN_INDEX_* */
94051 int iTab = pParse->nTab++; /* Cursor of the RHS table */
94052 int mustBeUnique; /* True if RHS must be unique */
94053 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
94055 assert( pX->op==TK_IN );
94056 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
94058 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
94059 ** whether or not the SELECT result contains NULL values, check whether
94060 ** or not NULL is actually possible (it may not be, for example, due
94061 ** to NOT NULL constraints in the schema). If no NULL values are possible,
94062 ** set prRhsHasNull to 0 before continuing. */
94063 if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
94064 int i;
94065 ExprList *pEList = pX->x.pSelect->pEList;
94066 for(i=0; i<pEList->nExpr; i++){
94067 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
94069 if( i==pEList->nExpr ){
94070 prRhsHasNull = 0;
94074 /* Check to see if an existing table or index can be used to
94075 ** satisfy the query. This is preferable to generating a new
94076 ** ephemeral table. */
94077 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
94078 sqlite3 *db = pParse->db; /* Database connection */
94079 Table *pTab; /* Table <table>. */
94080 i16 iDb; /* Database idx for pTab */
94081 ExprList *pEList = p->pEList;
94082 int nExpr = pEList->nExpr;
94084 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
94085 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
94086 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
94087 pTab = p->pSrc->a[0].pTab;
94089 /* Code an OP_Transaction and OP_TableLock for <table>. */
94090 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94091 sqlite3CodeVerifySchema(pParse, iDb);
94092 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
94094 assert(v); /* sqlite3GetVdbe() has always been previously called */
94095 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
94096 /* The "x IN (SELECT rowid FROM table)" case */
94097 int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
94098 VdbeCoverage(v);
94100 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
94101 eType = IN_INDEX_ROWID;
94103 sqlite3VdbeJumpHere(v, iAddr);
94104 }else{
94105 Index *pIdx; /* Iterator variable */
94106 int affinity_ok = 1;
94107 int i;
94109 /* Check that the affinity that will be used to perform each
94110 ** comparison is the same as the affinity of each column in table
94111 ** on the RHS of the IN operator. If it not, it is not possible to
94112 ** use any index of the RHS table. */
94113 for(i=0; i<nExpr && affinity_ok; i++){
94114 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
94115 int iCol = pEList->a[i].pExpr->iColumn;
94116 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
94117 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
94118 testcase( cmpaff==SQLITE_AFF_BLOB );
94119 testcase( cmpaff==SQLITE_AFF_TEXT );
94120 switch( cmpaff ){
94121 case SQLITE_AFF_BLOB:
94122 break;
94123 case SQLITE_AFF_TEXT:
94124 /* sqlite3CompareAffinity() only returns TEXT if one side or the
94125 ** other has no affinity and the other side is TEXT. Hence,
94126 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
94127 ** and for the term on the LHS of the IN to have no affinity. */
94128 assert( idxaff==SQLITE_AFF_TEXT );
94129 break;
94130 default:
94131 affinity_ok = sqlite3IsNumericAffinity(idxaff);
94135 if( affinity_ok ){
94136 /* Search for an existing index that will work for this IN operator */
94137 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
94138 Bitmask colUsed; /* Columns of the index used */
94139 Bitmask mCol; /* Mask for the current column */
94140 if( pIdx->nColumn<nExpr ) continue;
94141 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
94142 ** BITMASK(nExpr) without overflowing */
94143 testcase( pIdx->nColumn==BMS-2 );
94144 testcase( pIdx->nColumn==BMS-1 );
94145 if( pIdx->nColumn>=BMS-1 ) continue;
94146 if( mustBeUnique ){
94147 if( pIdx->nKeyCol>nExpr
94148 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
94150 continue; /* This index is not unique over the IN RHS columns */
94154 colUsed = 0; /* Columns of index used so far */
94155 for(i=0; i<nExpr; i++){
94156 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
94157 Expr *pRhs = pEList->a[i].pExpr;
94158 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
94159 int j;
94161 assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
94162 for(j=0; j<nExpr; j++){
94163 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
94164 assert( pIdx->azColl[j] );
94165 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
94166 continue;
94168 break;
94170 if( j==nExpr ) break;
94171 mCol = MASKBIT(j);
94172 if( mCol & colUsed ) break; /* Each column used only once */
94173 colUsed |= mCol;
94174 if( aiMap ) aiMap[i] = j;
94177 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
94178 if( colUsed==(MASKBIT(nExpr)-1) ){
94179 /* If we reach this point, that means the index pIdx is usable */
94180 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
94181 #ifndef SQLITE_OMIT_EXPLAIN
94182 sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
94183 sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
94184 P4_DYNAMIC);
94185 #endif
94186 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
94187 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
94188 VdbeComment((v, "%s", pIdx->zName));
94189 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
94190 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
94192 if( prRhsHasNull ){
94193 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
94194 i64 mask = (1<<nExpr)-1;
94195 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
94196 iTab, 0, 0, (u8*)&mask, P4_INT64);
94197 #endif
94198 *prRhsHasNull = ++pParse->nMem;
94199 if( nExpr==1 ){
94200 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
94203 sqlite3VdbeJumpHere(v, iAddr);
94205 } /* End loop over indexes */
94206 } /* End if( affinity_ok ) */
94207 } /* End if not an rowid index */
94208 } /* End attempt to optimize using an index */
94210 /* If no preexisting index is available for the IN clause
94211 ** and IN_INDEX_NOOP is an allowed reply
94212 ** and the RHS of the IN operator is a list, not a subquery
94213 ** and the RHS is not constant or has two or fewer terms,
94214 ** then it is not worth creating an ephemeral table to evaluate
94215 ** the IN operator so return IN_INDEX_NOOP.
94217 if( eType==0
94218 && (inFlags & IN_INDEX_NOOP_OK)
94219 && !ExprHasProperty(pX, EP_xIsSelect)
94220 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
94222 eType = IN_INDEX_NOOP;
94225 if( eType==0 ){
94226 /* Could not find an existing table or index to use as the RHS b-tree.
94227 ** We will have to generate an ephemeral table to do the job.
94229 u32 savedNQueryLoop = pParse->nQueryLoop;
94230 int rMayHaveNull = 0;
94231 eType = IN_INDEX_EPH;
94232 if( inFlags & IN_INDEX_LOOP ){
94233 pParse->nQueryLoop = 0;
94234 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
94235 eType = IN_INDEX_ROWID;
94237 }else if( prRhsHasNull ){
94238 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
94240 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
94241 pParse->nQueryLoop = savedNQueryLoop;
94242 }else{
94243 pX->iTable = iTab;
94246 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
94247 int i, n;
94248 n = sqlite3ExprVectorSize(pX->pLeft);
94249 for(i=0; i<n; i++) aiMap[i] = i;
94251 return eType;
94253 #endif
94255 #ifndef SQLITE_OMIT_SUBQUERY
94257 ** Argument pExpr is an (?, ?...) IN(...) expression. This
94258 ** function allocates and returns a nul-terminated string containing
94259 ** the affinities to be used for each column of the comparison.
94261 ** It is the responsibility of the caller to ensure that the returned
94262 ** string is eventually freed using sqlite3DbFree().
94264 static char *exprINAffinity(Parse *pParse, Expr *pExpr){
94265 Expr *pLeft = pExpr->pLeft;
94266 int nVal = sqlite3ExprVectorSize(pLeft);
94267 Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
94268 char *zRet;
94270 assert( pExpr->op==TK_IN );
94271 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
94272 if( zRet ){
94273 int i;
94274 for(i=0; i<nVal; i++){
94275 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
94276 char a = sqlite3ExprAffinity(pA);
94277 if( pSelect ){
94278 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
94279 }else{
94280 zRet[i] = a;
94283 zRet[nVal] = '\0';
94285 return zRet;
94287 #endif
94289 #ifndef SQLITE_OMIT_SUBQUERY
94291 ** Load the Parse object passed as the first argument with an error
94292 ** message of the form:
94294 ** "sub-select returns N columns - expected M"
94296 SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
94297 const char *zFmt = "sub-select returns %d columns - expected %d";
94298 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
94300 #endif
94303 ** Expression pExpr is a vector that has been used in a context where
94304 ** it is not permitted. If pExpr is a sub-select vector, this routine
94305 ** loads the Parse object with a message of the form:
94307 ** "sub-select returns N columns - expected 1"
94309 ** Or, if it is a regular scalar vector:
94311 ** "row value misused"
94313 SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
94314 #ifndef SQLITE_OMIT_SUBQUERY
94315 if( pExpr->flags & EP_xIsSelect ){
94316 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
94317 }else
94318 #endif
94320 sqlite3ErrorMsg(pParse, "row value misused");
94325 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
94326 ** or IN operators. Examples:
94328 ** (SELECT a FROM b) -- subquery
94329 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
94330 ** x IN (4,5,11) -- IN operator with list on right-hand side
94331 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
94333 ** The pExpr parameter describes the expression that contains the IN
94334 ** operator or subquery.
94336 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
94337 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
94338 ** to some integer key column of a table B-Tree. In this case, use an
94339 ** intkey B-Tree to store the set of IN(...) values instead of the usual
94340 ** (slower) variable length keys B-Tree.
94342 ** If rMayHaveNull is non-zero, that means that the operation is an IN
94343 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
94344 ** All this routine does is initialize the register given by rMayHaveNull
94345 ** to NULL. Calling routines will take care of changing this register
94346 ** value to non-NULL if the RHS is NULL-free.
94348 ** For a SELECT or EXISTS operator, return the register that holds the
94349 ** result. For a multi-column SELECT, the result is stored in a contiguous
94350 ** array of registers and the return value is the register of the left-most
94351 ** result column. Return 0 for IN operators or if an error occurs.
94353 #ifndef SQLITE_OMIT_SUBQUERY
94354 SQLITE_PRIVATE int sqlite3CodeSubselect(
94355 Parse *pParse, /* Parsing context */
94356 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
94357 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
94358 int isRowid /* If true, LHS of IN operator is a rowid */
94360 int jmpIfDynamic = -1; /* One-time test address */
94361 int rReg = 0; /* Register storing resulting */
94362 Vdbe *v = sqlite3GetVdbe(pParse);
94363 if( NEVER(v==0) ) return 0;
94364 sqlite3ExprCachePush(pParse);
94366 /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
94367 ** is encountered if any of the following is true:
94369 ** * The right-hand side is a correlated subquery
94370 ** * The right-hand side is an expression list containing variables
94371 ** * We are inside a trigger
94373 ** If all of the above are false, then we can run this code just once
94374 ** save the results, and reuse the same result on subsequent invocations.
94376 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
94377 jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
94380 #ifndef SQLITE_OMIT_EXPLAIN
94381 if( pParse->explain==2 ){
94382 char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
94383 jmpIfDynamic>=0?"":"CORRELATED ",
94384 pExpr->op==TK_IN?"LIST":"SCALAR",
94385 pParse->iNextSelectId
94387 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
94389 #endif
94391 switch( pExpr->op ){
94392 case TK_IN: {
94393 int addr; /* Address of OP_OpenEphemeral instruction */
94394 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
94395 KeyInfo *pKeyInfo = 0; /* Key information */
94396 int nVal; /* Size of vector pLeft */
94398 nVal = sqlite3ExprVectorSize(pLeft);
94399 assert( !isRowid || nVal==1 );
94401 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
94402 ** expression it is handled the same way. An ephemeral table is
94403 ** filled with index keys representing the results from the
94404 ** SELECT or the <exprlist>.
94406 ** If the 'x' expression is a column value, or the SELECT...
94407 ** statement returns a column value, then the affinity of that
94408 ** column is used to build the index keys. If both 'x' and the
94409 ** SELECT... statement are columns, then numeric affinity is used
94410 ** if either column has NUMERIC or INTEGER affinity. If neither
94411 ** 'x' nor the SELECT... statement are columns, then numeric affinity
94412 ** is used.
94414 pExpr->iTable = pParse->nTab++;
94415 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
94416 pExpr->iTable, (isRowid?0:nVal));
94417 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
94419 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
94420 /* Case 1: expr IN (SELECT ...)
94422 ** Generate code to write the results of the select into the temporary
94423 ** table allocated and opened above.
94425 Select *pSelect = pExpr->x.pSelect;
94426 ExprList *pEList = pSelect->pEList;
94428 assert( !isRowid );
94429 /* If the LHS and RHS of the IN operator do not match, that
94430 ** error will have been caught long before we reach this point. */
94431 if( ALWAYS(pEList->nExpr==nVal) ){
94432 SelectDest dest;
94433 int i;
94434 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
94435 dest.zAffSdst = exprINAffinity(pParse, pExpr);
94436 pSelect->iLimit = 0;
94437 testcase( pSelect->selFlags & SF_Distinct );
94438 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
94439 if( sqlite3Select(pParse, pSelect, &dest) ){
94440 sqlite3DbFree(pParse->db, dest.zAffSdst);
94441 sqlite3KeyInfoUnref(pKeyInfo);
94442 return 0;
94444 sqlite3DbFree(pParse->db, dest.zAffSdst);
94445 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
94446 assert( pEList!=0 );
94447 assert( pEList->nExpr>0 );
94448 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
94449 for(i=0; i<nVal; i++){
94450 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
94451 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
94452 pParse, p, pEList->a[i].pExpr
94456 }else if( ALWAYS(pExpr->x.pList!=0) ){
94457 /* Case 2: expr IN (exprlist)
94459 ** For each expression, build an index key from the evaluation and
94460 ** store it in the temporary table. If <expr> is a column, then use
94461 ** that columns affinity when building index keys. If <expr> is not
94462 ** a column, use numeric affinity.
94464 char affinity; /* Affinity of the LHS of the IN */
94465 int i;
94466 ExprList *pList = pExpr->x.pList;
94467 struct ExprList_item *pItem;
94468 int r1, r2, r3;
94470 affinity = sqlite3ExprAffinity(pLeft);
94471 if( !affinity ){
94472 affinity = SQLITE_AFF_BLOB;
94474 if( pKeyInfo ){
94475 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
94476 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
94479 /* Loop through each expression in <exprlist>. */
94480 r1 = sqlite3GetTempReg(pParse);
94481 r2 = sqlite3GetTempReg(pParse);
94482 if( isRowid ) sqlite3VdbeAddOp4(v, OP_Blob, 0, r2, 0, "", P4_STATIC);
94483 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
94484 Expr *pE2 = pItem->pExpr;
94485 int iValToIns;
94487 /* If the expression is not constant then we will need to
94488 ** disable the test that was generated above that makes sure
94489 ** this code only executes once. Because for a non-constant
94490 ** expression we need to rerun this code each time.
94492 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
94493 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
94494 jmpIfDynamic = -1;
94497 /* Evaluate the expression and insert it into the temp table */
94498 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
94499 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
94500 }else{
94501 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
94502 if( isRowid ){
94503 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
94504 sqlite3VdbeCurrentAddr(v)+2);
94505 VdbeCoverage(v);
94506 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
94507 }else{
94508 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
94509 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
94510 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
94514 sqlite3ReleaseTempReg(pParse, r1);
94515 sqlite3ReleaseTempReg(pParse, r2);
94517 if( pKeyInfo ){
94518 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
94520 break;
94523 case TK_EXISTS:
94524 case TK_SELECT:
94525 default: {
94526 /* Case 3: (SELECT ... FROM ...)
94527 ** or: EXISTS(SELECT ... FROM ...)
94529 ** For a SELECT, generate code to put the values for all columns of
94530 ** the first row into an array of registers and return the index of
94531 ** the first register.
94533 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
94534 ** into a register and return that register number.
94536 ** In both cases, the query is augmented with "LIMIT 1". Any
94537 ** preexisting limit is discarded in place of the new LIMIT 1.
94539 Select *pSel; /* SELECT statement to encode */
94540 SelectDest dest; /* How to deal with SELECT result */
94541 int nReg; /* Registers to allocate */
94543 testcase( pExpr->op==TK_EXISTS );
94544 testcase( pExpr->op==TK_SELECT );
94545 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
94546 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
94548 pSel = pExpr->x.pSelect;
94549 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
94550 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
94551 pParse->nMem += nReg;
94552 if( pExpr->op==TK_SELECT ){
94553 dest.eDest = SRT_Mem;
94554 dest.iSdst = dest.iSDParm;
94555 dest.nSdst = nReg;
94556 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
94557 VdbeComment((v, "Init subquery result"));
94558 }else{
94559 dest.eDest = SRT_Exists;
94560 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
94561 VdbeComment((v, "Init EXISTS result"));
94563 sqlite3ExprDelete(pParse->db, pSel->pLimit);
94564 pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,
94565 &sqlite3IntTokens[1], 0);
94566 pSel->iLimit = 0;
94567 pSel->selFlags &= ~SF_MultiValue;
94568 if( sqlite3Select(pParse, pSel, &dest) ){
94569 return 0;
94571 rReg = dest.iSDParm;
94572 ExprSetVVAProperty(pExpr, EP_NoReduce);
94573 break;
94577 if( rHasNullFlag ){
94578 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
94581 if( jmpIfDynamic>=0 ){
94582 sqlite3VdbeJumpHere(v, jmpIfDynamic);
94584 sqlite3ExprCachePop(pParse);
94586 return rReg;
94588 #endif /* SQLITE_OMIT_SUBQUERY */
94590 #ifndef SQLITE_OMIT_SUBQUERY
94592 ** Expr pIn is an IN(...) expression. This function checks that the
94593 ** sub-select on the RHS of the IN() operator has the same number of
94594 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
94595 ** a sub-query, that the LHS is a vector of size 1.
94597 SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
94598 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
94599 if( (pIn->flags & EP_xIsSelect) ){
94600 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
94601 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
94602 return 1;
94604 }else if( nVector!=1 ){
94605 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
94606 return 1;
94608 return 0;
94610 #endif
94612 #ifndef SQLITE_OMIT_SUBQUERY
94614 ** Generate code for an IN expression.
94616 ** x IN (SELECT ...)
94617 ** x IN (value, value, ...)
94619 ** The left-hand side (LHS) is a scalar or vector expression. The
94620 ** right-hand side (RHS) is an array of zero or more scalar values, or a
94621 ** subquery. If the RHS is a subquery, the number of result columns must
94622 ** match the number of columns in the vector on the LHS. If the RHS is
94623 ** a list of values, the LHS must be a scalar.
94625 ** The IN operator is true if the LHS value is contained within the RHS.
94626 ** The result is false if the LHS is definitely not in the RHS. The
94627 ** result is NULL if the presence of the LHS in the RHS cannot be
94628 ** determined due to NULLs.
94630 ** This routine generates code that jumps to destIfFalse if the LHS is not
94631 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
94632 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
94633 ** within the RHS then fall through.
94635 ** See the separate in-operator.md documentation file in the canonical
94636 ** SQLite source tree for additional information.
94638 static void sqlite3ExprCodeIN(
94639 Parse *pParse, /* Parsing and code generating context */
94640 Expr *pExpr, /* The IN expression */
94641 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
94642 int destIfNull /* Jump here if the results are unknown due to NULLs */
94644 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
94645 int eType; /* Type of the RHS */
94646 int rLhs; /* Register(s) holding the LHS values */
94647 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
94648 Vdbe *v; /* Statement under construction */
94649 int *aiMap = 0; /* Map from vector field to index column */
94650 char *zAff = 0; /* Affinity string for comparisons */
94651 int nVector; /* Size of vectors for this IN operator */
94652 int iDummy; /* Dummy parameter to exprCodeVector() */
94653 Expr *pLeft; /* The LHS of the IN operator */
94654 int i; /* loop counter */
94655 int destStep2; /* Where to jump when NULLs seen in step 2 */
94656 int destStep6 = 0; /* Start of code for Step 6 */
94657 int addrTruthOp; /* Address of opcode that determines the IN is true */
94658 int destNotNull; /* Jump here if a comparison is not true in step 6 */
94659 int addrTop; /* Top of the step-6 loop */
94661 pLeft = pExpr->pLeft;
94662 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
94663 zAff = exprINAffinity(pParse, pExpr);
94664 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
94665 aiMap = (int*)sqlite3DbMallocZero(
94666 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
94668 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
94670 /* Attempt to compute the RHS. After this step, if anything other than
94671 ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
94672 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
94673 ** the RHS has not yet been coded. */
94674 v = pParse->pVdbe;
94675 assert( v!=0 ); /* OOM detected prior to this routine */
94676 VdbeNoopComment((v, "begin IN expr"));
94677 eType = sqlite3FindInIndex(pParse, pExpr,
94678 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
94679 destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
94681 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
94682 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
94684 #ifdef SQLITE_DEBUG
94685 /* Confirm that aiMap[] contains nVector integer values between 0 and
94686 ** nVector-1. */
94687 for(i=0; i<nVector; i++){
94688 int j, cnt;
94689 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
94690 assert( cnt==1 );
94692 #endif
94694 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
94695 ** vector, then it is stored in an array of nVector registers starting
94696 ** at r1.
94698 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
94699 ** so that the fields are in the same order as an existing index. The
94700 ** aiMap[] array contains a mapping from the original LHS field order to
94701 ** the field order that matches the RHS index.
94703 sqlite3ExprCachePush(pParse);
94704 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
94705 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
94706 if( i==nVector ){
94707 /* LHS fields are not reordered */
94708 rLhs = rLhsOrig;
94709 }else{
94710 /* Need to reorder the LHS fields according to aiMap */
94711 rLhs = sqlite3GetTempRange(pParse, nVector);
94712 for(i=0; i<nVector; i++){
94713 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
94717 /* If sqlite3FindInIndex() did not find or create an index that is
94718 ** suitable for evaluating the IN operator, then evaluate using a
94719 ** sequence of comparisons.
94721 ** This is step (1) in the in-operator.md optimized algorithm.
94723 if( eType==IN_INDEX_NOOP ){
94724 ExprList *pList = pExpr->x.pList;
94725 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
94726 int labelOk = sqlite3VdbeMakeLabel(v);
94727 int r2, regToFree;
94728 int regCkNull = 0;
94729 int ii;
94730 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
94731 if( destIfNull!=destIfFalse ){
94732 regCkNull = sqlite3GetTempReg(pParse);
94733 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
94735 for(ii=0; ii<pList->nExpr; ii++){
94736 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
94737 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
94738 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
94740 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
94741 sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
94742 (void*)pColl, P4_COLLSEQ);
94743 VdbeCoverageIf(v, ii<pList->nExpr-1);
94744 VdbeCoverageIf(v, ii==pList->nExpr-1);
94745 sqlite3VdbeChangeP5(v, zAff[0]);
94746 }else{
94747 assert( destIfNull==destIfFalse );
94748 sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
94749 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
94750 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
94752 sqlite3ReleaseTempReg(pParse, regToFree);
94754 if( regCkNull ){
94755 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
94756 sqlite3VdbeGoto(v, destIfFalse);
94758 sqlite3VdbeResolveLabel(v, labelOk);
94759 sqlite3ReleaseTempReg(pParse, regCkNull);
94760 goto sqlite3ExprCodeIN_finished;
94763 /* Step 2: Check to see if the LHS contains any NULL columns. If the
94764 ** LHS does contain NULLs then the result must be either FALSE or NULL.
94765 ** We will then skip the binary search of the RHS.
94767 if( destIfNull==destIfFalse ){
94768 destStep2 = destIfFalse;
94769 }else{
94770 destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
94772 for(i=0; i<nVector; i++){
94773 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
94774 if( sqlite3ExprCanBeNull(p) ){
94775 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
94776 VdbeCoverage(v);
94780 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
94781 ** of the RHS using the LHS as a probe. If found, the result is
94782 ** true.
94784 if( eType==IN_INDEX_ROWID ){
94785 /* In this case, the RHS is the ROWID of table b-tree and so we also
94786 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
94787 ** into a single opcode. */
94788 sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
94789 VdbeCoverage(v);
94790 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
94791 }else{
94792 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
94793 if( destIfFalse==destIfNull ){
94794 /* Combine Step 3 and Step 5 into a single opcode */
94795 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
94796 rLhs, nVector); VdbeCoverage(v);
94797 goto sqlite3ExprCodeIN_finished;
94799 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
94800 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
94801 rLhs, nVector); VdbeCoverage(v);
94804 /* Step 4. If the RHS is known to be non-NULL and we did not find
94805 ** an match on the search above, then the result must be FALSE.
94807 if( rRhsHasNull && nVector==1 ){
94808 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
94809 VdbeCoverage(v);
94812 /* Step 5. If we do not care about the difference between NULL and
94813 ** FALSE, then just return false.
94815 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
94817 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
94818 ** If any comparison is NULL, then the result is NULL. If all
94819 ** comparisons are FALSE then the final result is FALSE.
94821 ** For a scalar LHS, it is sufficient to check just the first row
94822 ** of the RHS.
94824 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
94825 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
94826 VdbeCoverage(v);
94827 if( nVector>1 ){
94828 destNotNull = sqlite3VdbeMakeLabel(v);
94829 }else{
94830 /* For nVector==1, combine steps 6 and 7 by immediately returning
94831 ** FALSE if the first comparison is not NULL */
94832 destNotNull = destIfFalse;
94834 for(i=0; i<nVector; i++){
94835 Expr *p;
94836 CollSeq *pColl;
94837 int r3 = sqlite3GetTempReg(pParse);
94838 p = sqlite3VectorFieldSubexpr(pLeft, i);
94839 pColl = sqlite3ExprCollSeq(pParse, p);
94840 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
94841 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
94842 (void*)pColl, P4_COLLSEQ);
94843 VdbeCoverage(v);
94844 sqlite3ReleaseTempReg(pParse, r3);
94846 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
94847 if( nVector>1 ){
94848 sqlite3VdbeResolveLabel(v, destNotNull);
94849 sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
94850 VdbeCoverage(v);
94852 /* Step 7: If we reach this point, we know that the result must
94853 ** be false. */
94854 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
94857 /* Jumps here in order to return true. */
94858 sqlite3VdbeJumpHere(v, addrTruthOp);
94860 sqlite3ExprCodeIN_finished:
94861 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
94862 sqlite3ExprCachePop(pParse);
94863 VdbeComment((v, "end IN expr"));
94864 sqlite3ExprCodeIN_oom_error:
94865 sqlite3DbFree(pParse->db, aiMap);
94866 sqlite3DbFree(pParse->db, zAff);
94868 #endif /* SQLITE_OMIT_SUBQUERY */
94870 #ifndef SQLITE_OMIT_FLOATING_POINT
94872 ** Generate an instruction that will put the floating point
94873 ** value described by z[0..n-1] into register iMem.
94875 ** The z[] string will probably not be zero-terminated. But the
94876 ** z[n] character is guaranteed to be something that does not look
94877 ** like the continuation of the number.
94879 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
94880 if( ALWAYS(z!=0) ){
94881 double value;
94882 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
94883 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
94884 if( negateFlag ) value = -value;
94885 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
94888 #endif
94892 ** Generate an instruction that will put the integer describe by
94893 ** text z[0..n-1] into register iMem.
94895 ** Expr.u.zToken is always UTF8 and zero-terminated.
94897 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
94898 Vdbe *v = pParse->pVdbe;
94899 if( pExpr->flags & EP_IntValue ){
94900 int i = pExpr->u.iValue;
94901 assert( i>=0 );
94902 if( negFlag ) i = -i;
94903 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
94904 }else{
94905 int c;
94906 i64 value;
94907 const char *z = pExpr->u.zToken;
94908 assert( z!=0 );
94909 c = sqlite3DecOrHexToI64(z, &value);
94910 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
94911 #ifdef SQLITE_OMIT_FLOATING_POINT
94912 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
94913 #else
94914 #ifndef SQLITE_OMIT_HEX_INTEGER
94915 if( sqlite3_strnicmp(z,"0x",2)==0 ){
94916 sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
94917 }else
94918 #endif
94920 codeReal(v, z, negFlag, iMem);
94922 #endif
94923 }else{
94924 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
94925 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
94931 ** Erase column-cache entry number i
94933 static void cacheEntryClear(Parse *pParse, int i){
94934 if( pParse->aColCache[i].tempReg ){
94935 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
94936 pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
94939 pParse->nColCache--;
94940 if( i<pParse->nColCache ){
94941 pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
94947 ** Record in the column cache that a particular column from a
94948 ** particular table is stored in a particular register.
94950 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
94951 int i;
94952 int minLru;
94953 int idxLru;
94954 struct yColCache *p;
94956 /* Unless an error has occurred, register numbers are always positive. */
94957 assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
94958 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
94960 /* The SQLITE_ColumnCache flag disables the column cache. This is used
94961 ** for testing only - to verify that SQLite always gets the same answer
94962 ** with and without the column cache.
94964 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
94966 /* First replace any existing entry.
94968 ** Actually, the way the column cache is currently used, we are guaranteed
94969 ** that the object will never already be in cache. Verify this guarantee.
94971 #ifndef NDEBUG
94972 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
94973 assert( p->iTable!=iTab || p->iColumn!=iCol );
94975 #endif
94977 /* If the cache is already full, delete the least recently used entry */
94978 if( pParse->nColCache>=SQLITE_N_COLCACHE ){
94979 minLru = 0x7fffffff;
94980 idxLru = -1;
94981 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
94982 if( p->lru<minLru ){
94983 idxLru = i;
94984 minLru = p->lru;
94987 p = &pParse->aColCache[idxLru];
94988 }else{
94989 p = &pParse->aColCache[pParse->nColCache++];
94992 /* Add the new entry to the end of the cache */
94993 p->iLevel = pParse->iCacheLevel;
94994 p->iTable = iTab;
94995 p->iColumn = iCol;
94996 p->iReg = iReg;
94997 p->tempReg = 0;
94998 p->lru = pParse->iCacheCnt++;
95002 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
95003 ** Purge the range of registers from the column cache.
95005 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
95006 int i = 0;
95007 while( i<pParse->nColCache ){
95008 struct yColCache *p = &pParse->aColCache[i];
95009 if( p->iReg >= iReg && p->iReg < iReg+nReg ){
95010 cacheEntryClear(pParse, i);
95011 }else{
95012 i++;
95018 ** Remember the current column cache context. Any new entries added
95019 ** added to the column cache after this call are removed when the
95020 ** corresponding pop occurs.
95022 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
95023 pParse->iCacheLevel++;
95024 #ifdef SQLITE_DEBUG
95025 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
95026 printf("PUSH to %d\n", pParse->iCacheLevel);
95028 #endif
95032 ** Remove from the column cache any entries that were added since the
95033 ** the previous sqlite3ExprCachePush operation. In other words, restore
95034 ** the cache to the state it was in prior the most recent Push.
95036 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
95037 int i = 0;
95038 assert( pParse->iCacheLevel>=1 );
95039 pParse->iCacheLevel--;
95040 #ifdef SQLITE_DEBUG
95041 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
95042 printf("POP to %d\n", pParse->iCacheLevel);
95044 #endif
95045 while( i<pParse->nColCache ){
95046 if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
95047 cacheEntryClear(pParse, i);
95048 }else{
95049 i++;
95055 ** When a cached column is reused, make sure that its register is
95056 ** no longer available as a temp register. ticket #3879: that same
95057 ** register might be in the cache in multiple places, so be sure to
95058 ** get them all.
95060 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
95061 int i;
95062 struct yColCache *p;
95063 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
95064 if( p->iReg==iReg ){
95065 p->tempReg = 0;
95070 /* Generate code that will load into register regOut a value that is
95071 ** appropriate for the iIdxCol-th column of index pIdx.
95073 SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
95074 Parse *pParse, /* The parsing context */
95075 Index *pIdx, /* The index whose column is to be loaded */
95076 int iTabCur, /* Cursor pointing to a table row */
95077 int iIdxCol, /* The column of the index to be loaded */
95078 int regOut /* Store the index column value in this register */
95080 i16 iTabCol = pIdx->aiColumn[iIdxCol];
95081 if( iTabCol==XN_EXPR ){
95082 assert( pIdx->aColExpr );
95083 assert( pIdx->aColExpr->nExpr>iIdxCol );
95084 pParse->iSelfTab = iTabCur + 1;
95085 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
95086 pParse->iSelfTab = 0;
95087 }else{
95088 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
95089 iTabCol, regOut);
95094 ** Generate code to extract the value of the iCol-th column of a table.
95096 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
95097 Vdbe *v, /* The VDBE under construction */
95098 Table *pTab, /* The table containing the value */
95099 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
95100 int iCol, /* Index of the column to extract */
95101 int regOut /* Extract the value into this register */
95103 if( pTab==0 ){
95104 sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
95105 return;
95107 if( iCol<0 || iCol==pTab->iPKey ){
95108 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
95109 }else{
95110 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
95111 int x = iCol;
95112 if( !HasRowid(pTab) && !IsVirtual(pTab) ){
95113 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
95115 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
95117 if( iCol>=0 ){
95118 sqlite3ColumnDefault(v, pTab, iCol, regOut);
95123 ** Generate code that will extract the iColumn-th column from
95124 ** table pTab and store the column value in a register.
95126 ** An effort is made to store the column value in register iReg. This
95127 ** is not garanteeed for GetColumn() - the result can be stored in
95128 ** any register. But the result is guaranteed to land in register iReg
95129 ** for GetColumnToReg().
95131 ** There must be an open cursor to pTab in iTable when this routine
95132 ** is called. If iColumn<0 then code is generated that extracts the rowid.
95134 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
95135 Parse *pParse, /* Parsing and code generating context */
95136 Table *pTab, /* Description of the table we are reading from */
95137 int iColumn, /* Index of the table column */
95138 int iTable, /* The cursor pointing to the table */
95139 int iReg, /* Store results here */
95140 u8 p5 /* P5 value for OP_Column + FLAGS */
95142 Vdbe *v = pParse->pVdbe;
95143 int i;
95144 struct yColCache *p;
95146 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
95147 if( p->iTable==iTable && p->iColumn==iColumn ){
95148 p->lru = pParse->iCacheCnt++;
95149 sqlite3ExprCachePinRegister(pParse, p->iReg);
95150 return p->iReg;
95153 assert( v!=0 );
95154 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
95155 if( p5 ){
95156 sqlite3VdbeChangeP5(v, p5);
95157 }else{
95158 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
95160 return iReg;
95162 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
95163 Parse *pParse, /* Parsing and code generating context */
95164 Table *pTab, /* Description of the table we are reading from */
95165 int iColumn, /* Index of the table column */
95166 int iTable, /* The cursor pointing to the table */
95167 int iReg /* Store results here */
95169 int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
95170 if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
95175 ** Clear all column cache entries.
95177 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
95178 int i;
95180 #ifdef SQLITE_DEBUG
95181 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
95182 printf("CLEAR\n");
95184 #endif
95185 for(i=0; i<pParse->nColCache; i++){
95186 if( pParse->aColCache[i].tempReg
95187 && pParse->nTempReg<ArraySize(pParse->aTempReg)
95189 pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
95192 pParse->nColCache = 0;
95196 ** Record the fact that an affinity change has occurred on iCount
95197 ** registers starting with iStart.
95199 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
95200 sqlite3ExprCacheRemove(pParse, iStart, iCount);
95204 ** Generate code to move content from registers iFrom...iFrom+nReg-1
95205 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
95207 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
95208 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
95209 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
95210 sqlite3ExprCacheRemove(pParse, iFrom, nReg);
95213 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
95215 ** Return true if any register in the range iFrom..iTo (inclusive)
95216 ** is used as part of the column cache.
95218 ** This routine is used within assert() and testcase() macros only
95219 ** and does not appear in a normal build.
95221 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
95222 int i;
95223 struct yColCache *p;
95224 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
95225 int r = p->iReg;
95226 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
95228 return 0;
95230 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
95234 ** Convert a scalar expression node to a TK_REGISTER referencing
95235 ** register iReg. The caller must ensure that iReg already contains
95236 ** the correct value for the expression.
95238 static void exprToRegister(Expr *p, int iReg){
95239 p->op2 = p->op;
95240 p->op = TK_REGISTER;
95241 p->iTable = iReg;
95242 ExprClearProperty(p, EP_Skip);
95246 ** Evaluate an expression (either a vector or a scalar expression) and store
95247 ** the result in continguous temporary registers. Return the index of
95248 ** the first register used to store the result.
95250 ** If the returned result register is a temporary scalar, then also write
95251 ** that register number into *piFreeable. If the returned result register
95252 ** is not a temporary or if the expression is a vector set *piFreeable
95253 ** to 0.
95255 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
95256 int iResult;
95257 int nResult = sqlite3ExprVectorSize(p);
95258 if( nResult==1 ){
95259 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
95260 }else{
95261 *piFreeable = 0;
95262 if( p->op==TK_SELECT ){
95263 #if SQLITE_OMIT_SUBQUERY
95264 iResult = 0;
95265 #else
95266 iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
95267 #endif
95268 }else{
95269 int i;
95270 iResult = pParse->nMem+1;
95271 pParse->nMem += nResult;
95272 for(i=0; i<nResult; i++){
95273 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
95277 return iResult;
95282 ** Generate code into the current Vdbe to evaluate the given
95283 ** expression. Attempt to store the results in register "target".
95284 ** Return the register where results are stored.
95286 ** With this routine, there is no guarantee that results will
95287 ** be stored in target. The result might be stored in some other
95288 ** register if it is convenient to do so. The calling function
95289 ** must check the return code and move the results to the desired
95290 ** register.
95292 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
95293 Vdbe *v = pParse->pVdbe; /* The VM under construction */
95294 int op; /* The opcode being coded */
95295 int inReg = target; /* Results stored in register inReg */
95296 int regFree1 = 0; /* If non-zero free this temporary register */
95297 int regFree2 = 0; /* If non-zero free this temporary register */
95298 int r1, r2; /* Various register numbers */
95299 Expr tempX; /* Temporary expression node */
95300 int p5 = 0;
95302 assert( target>0 && target<=pParse->nMem );
95303 if( v==0 ){
95304 assert( pParse->db->mallocFailed );
95305 return 0;
95308 if( pExpr==0 ){
95309 op = TK_NULL;
95310 }else{
95311 op = pExpr->op;
95313 switch( op ){
95314 case TK_AGG_COLUMN: {
95315 AggInfo *pAggInfo = pExpr->pAggInfo;
95316 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
95317 if( !pAggInfo->directMode ){
95318 assert( pCol->iMem>0 );
95319 return pCol->iMem;
95320 }else if( pAggInfo->useSortingIdx ){
95321 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
95322 pCol->iSorterColumn, target);
95323 return target;
95325 /* Otherwise, fall thru into the TK_COLUMN case */
95327 case TK_COLUMN: {
95328 int iTab = pExpr->iTable;
95329 if( iTab<0 ){
95330 if( pParse->iSelfTab<0 ){
95331 /* Generating CHECK constraints or inserting into partial index */
95332 return pExpr->iColumn - pParse->iSelfTab;
95333 }else{
95334 /* Coding an expression that is part of an index where column names
95335 ** in the index refer to the table to which the index belongs */
95336 iTab = pParse->iSelfTab - 1;
95339 return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
95340 pExpr->iColumn, iTab, target,
95341 pExpr->op2);
95343 case TK_INTEGER: {
95344 codeInteger(pParse, pExpr, 0, target);
95345 return target;
95347 #ifndef SQLITE_OMIT_FLOATING_POINT
95348 case TK_FLOAT: {
95349 assert( !ExprHasProperty(pExpr, EP_IntValue) );
95350 codeReal(v, pExpr->u.zToken, 0, target);
95351 return target;
95353 #endif
95354 case TK_STRING: {
95355 assert( !ExprHasProperty(pExpr, EP_IntValue) );
95356 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
95357 return target;
95359 case TK_NULL: {
95360 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
95361 return target;
95363 #ifndef SQLITE_OMIT_BLOB_LITERAL
95364 case TK_BLOB: {
95365 int n;
95366 const char *z;
95367 char *zBlob;
95368 assert( !ExprHasProperty(pExpr, EP_IntValue) );
95369 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
95370 assert( pExpr->u.zToken[1]=='\'' );
95371 z = &pExpr->u.zToken[2];
95372 n = sqlite3Strlen30(z) - 1;
95373 assert( z[n]=='\'' );
95374 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
95375 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
95376 return target;
95378 #endif
95379 case TK_VARIABLE: {
95380 assert( !ExprHasProperty(pExpr, EP_IntValue) );
95381 assert( pExpr->u.zToken!=0 );
95382 assert( pExpr->u.zToken[0]!=0 );
95383 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
95384 if( pExpr->u.zToken[1]!=0 ){
95385 const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
95386 assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
95387 pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
95388 sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
95390 return target;
95392 case TK_REGISTER: {
95393 return pExpr->iTable;
95395 #ifndef SQLITE_OMIT_CAST
95396 case TK_CAST: {
95397 /* Expressions of the form: CAST(pLeft AS token) */
95398 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
95399 if( inReg!=target ){
95400 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
95401 inReg = target;
95403 sqlite3VdbeAddOp2(v, OP_Cast, target,
95404 sqlite3AffinityType(pExpr->u.zToken, 0));
95405 testcase( usedAsColumnCache(pParse, inReg, inReg) );
95406 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
95407 return inReg;
95409 #endif /* SQLITE_OMIT_CAST */
95410 case TK_IS:
95411 case TK_ISNOT:
95412 op = (op==TK_IS) ? TK_EQ : TK_NE;
95413 p5 = SQLITE_NULLEQ;
95414 /* fall-through */
95415 case TK_LT:
95416 case TK_LE:
95417 case TK_GT:
95418 case TK_GE:
95419 case TK_NE:
95420 case TK_EQ: {
95421 Expr *pLeft = pExpr->pLeft;
95422 if( sqlite3ExprIsVector(pLeft) ){
95423 codeVectorCompare(pParse, pExpr, target, op, p5);
95424 }else{
95425 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
95426 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
95427 codeCompare(pParse, pLeft, pExpr->pRight, op,
95428 r1, r2, inReg, SQLITE_STOREP2 | p5);
95429 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
95430 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
95431 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
95432 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
95433 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
95434 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
95435 testcase( regFree1==0 );
95436 testcase( regFree2==0 );
95438 break;
95440 case TK_AND:
95441 case TK_OR:
95442 case TK_PLUS:
95443 case TK_STAR:
95444 case TK_MINUS:
95445 case TK_REM:
95446 case TK_BITAND:
95447 case TK_BITOR:
95448 case TK_SLASH:
95449 case TK_LSHIFT:
95450 case TK_RSHIFT:
95451 case TK_CONCAT: {
95452 assert( TK_AND==OP_And ); testcase( op==TK_AND );
95453 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
95454 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
95455 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
95456 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
95457 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
95458 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
95459 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
95460 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
95461 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
95462 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
95463 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
95464 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
95465 sqlite3VdbeAddOp3(v, op, r2, r1, target);
95466 testcase( regFree1==0 );
95467 testcase( regFree2==0 );
95468 break;
95470 case TK_UMINUS: {
95471 Expr *pLeft = pExpr->pLeft;
95472 assert( pLeft );
95473 if( pLeft->op==TK_INTEGER ){
95474 codeInteger(pParse, pLeft, 1, target);
95475 return target;
95476 #ifndef SQLITE_OMIT_FLOATING_POINT
95477 }else if( pLeft->op==TK_FLOAT ){
95478 assert( !ExprHasProperty(pExpr, EP_IntValue) );
95479 codeReal(v, pLeft->u.zToken, 1, target);
95480 return target;
95481 #endif
95482 }else{
95483 tempX.op = TK_INTEGER;
95484 tempX.flags = EP_IntValue|EP_TokenOnly;
95485 tempX.u.iValue = 0;
95486 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
95487 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
95488 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
95489 testcase( regFree2==0 );
95491 break;
95493 case TK_BITNOT:
95494 case TK_NOT: {
95495 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
95496 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
95497 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
95498 testcase( regFree1==0 );
95499 sqlite3VdbeAddOp2(v, op, r1, inReg);
95500 break;
95502 case TK_ISNULL:
95503 case TK_NOTNULL: {
95504 int addr;
95505 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
95506 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
95507 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
95508 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
95509 testcase( regFree1==0 );
95510 addr = sqlite3VdbeAddOp1(v, op, r1);
95511 VdbeCoverageIf(v, op==TK_ISNULL);
95512 VdbeCoverageIf(v, op==TK_NOTNULL);
95513 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
95514 sqlite3VdbeJumpHere(v, addr);
95515 break;
95517 case TK_AGG_FUNCTION: {
95518 AggInfo *pInfo = pExpr->pAggInfo;
95519 if( pInfo==0 ){
95520 assert( !ExprHasProperty(pExpr, EP_IntValue) );
95521 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
95522 }else{
95523 return pInfo->aFunc[pExpr->iAgg].iMem;
95525 break;
95527 case TK_FUNCTION: {
95528 ExprList *pFarg; /* List of function arguments */
95529 int nFarg; /* Number of function arguments */
95530 FuncDef *pDef; /* The function definition object */
95531 const char *zId; /* The function name */
95532 u32 constMask = 0; /* Mask of function arguments that are constant */
95533 int i; /* Loop counter */
95534 sqlite3 *db = pParse->db; /* The database connection */
95535 u8 enc = ENC(db); /* The text encoding used by this database */
95536 CollSeq *pColl = 0; /* A collating sequence */
95538 if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
95539 /* SQL functions can be expensive. So try to move constant functions
95540 ** out of the inner loop, even if that means an extra OP_Copy. */
95541 return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
95543 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
95544 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
95545 pFarg = 0;
95546 }else{
95547 pFarg = pExpr->x.pList;
95549 nFarg = pFarg ? pFarg->nExpr : 0;
95550 assert( !ExprHasProperty(pExpr, EP_IntValue) );
95551 zId = pExpr->u.zToken;
95552 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
95553 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
95554 if( pDef==0 && pParse->explain ){
95555 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
95557 #endif
95558 if( pDef==0 || pDef->xFinalize!=0 ){
95559 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
95560 break;
95563 /* Attempt a direct implementation of the built-in COALESCE() and
95564 ** IFNULL() functions. This avoids unnecessary evaluation of
95565 ** arguments past the first non-NULL argument.
95567 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
95568 int endCoalesce = sqlite3VdbeMakeLabel(v);
95569 assert( nFarg>=2 );
95570 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
95571 for(i=1; i<nFarg; i++){
95572 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
95573 VdbeCoverage(v);
95574 sqlite3ExprCacheRemove(pParse, target, 1);
95575 sqlite3ExprCachePush(pParse);
95576 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
95577 sqlite3ExprCachePop(pParse);
95579 sqlite3VdbeResolveLabel(v, endCoalesce);
95580 break;
95583 /* The UNLIKELY() function is a no-op. The result is the value
95584 ** of the first argument.
95586 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
95587 assert( nFarg>=1 );
95588 return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
95591 #ifdef SQLITE_DEBUG
95592 /* The AFFINITY() function evaluates to a string that describes
95593 ** the type affinity of the argument. This is used for testing of
95594 ** the SQLite type logic.
95596 if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
95597 const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
95598 char aff;
95599 assert( nFarg==1 );
95600 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
95601 sqlite3VdbeLoadString(v, target,
95602 aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
95603 return target;
95605 #endif
95607 for(i=0; i<nFarg; i++){
95608 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
95609 testcase( i==31 );
95610 constMask |= MASKBIT32(i);
95612 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
95613 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
95616 if( pFarg ){
95617 if( constMask ){
95618 r1 = pParse->nMem+1;
95619 pParse->nMem += nFarg;
95620 }else{
95621 r1 = sqlite3GetTempRange(pParse, nFarg);
95624 /* For length() and typeof() functions with a column argument,
95625 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
95626 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
95627 ** loading.
95629 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
95630 u8 exprOp;
95631 assert( nFarg==1 );
95632 assert( pFarg->a[0].pExpr!=0 );
95633 exprOp = pFarg->a[0].pExpr->op;
95634 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
95635 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
95636 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
95637 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
95638 pFarg->a[0].pExpr->op2 =
95639 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
95643 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
95644 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
95645 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
95646 sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
95647 }else{
95648 r1 = 0;
95650 #ifndef SQLITE_OMIT_VIRTUALTABLE
95651 /* Possibly overload the function if the first argument is
95652 ** a virtual table column.
95654 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
95655 ** second argument, not the first, as the argument to test to
95656 ** see if it is a column in a virtual table. This is done because
95657 ** the left operand of infix functions (the operand we want to
95658 ** control overloading) ends up as the second argument to the
95659 ** function. The expression "A glob B" is equivalent to
95660 ** "glob(B,A). We want to use the A in "A glob B" to test
95661 ** for function overloading. But we use the B term in "glob(B,A)".
95663 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
95664 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
95665 }else if( nFarg>0 ){
95666 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
95668 #endif
95669 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
95670 if( !pColl ) pColl = db->pDfltColl;
95671 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
95673 sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
95674 constMask, r1, target, (char*)pDef, P4_FUNCDEF);
95675 sqlite3VdbeChangeP5(v, (u8)nFarg);
95676 if( nFarg && constMask==0 ){
95677 sqlite3ReleaseTempRange(pParse, r1, nFarg);
95679 return target;
95681 #ifndef SQLITE_OMIT_SUBQUERY
95682 case TK_EXISTS:
95683 case TK_SELECT: {
95684 int nCol;
95685 testcase( op==TK_EXISTS );
95686 testcase( op==TK_SELECT );
95687 if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
95688 sqlite3SubselectError(pParse, nCol, 1);
95689 }else{
95690 return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
95692 break;
95694 case TK_SELECT_COLUMN: {
95695 int n;
95696 if( pExpr->pLeft->iTable==0 ){
95697 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
95699 assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
95700 if( pExpr->iTable
95701 && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
95703 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
95704 pExpr->iTable, n);
95706 return pExpr->pLeft->iTable + pExpr->iColumn;
95708 case TK_IN: {
95709 int destIfFalse = sqlite3VdbeMakeLabel(v);
95710 int destIfNull = sqlite3VdbeMakeLabel(v);
95711 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
95712 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
95713 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
95714 sqlite3VdbeResolveLabel(v, destIfFalse);
95715 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
95716 sqlite3VdbeResolveLabel(v, destIfNull);
95717 return target;
95719 #endif /* SQLITE_OMIT_SUBQUERY */
95723 ** x BETWEEN y AND z
95725 ** This is equivalent to
95727 ** x>=y AND x<=z
95729 ** X is stored in pExpr->pLeft.
95730 ** Y is stored in pExpr->pList->a[0].pExpr.
95731 ** Z is stored in pExpr->pList->a[1].pExpr.
95733 case TK_BETWEEN: {
95734 exprCodeBetween(pParse, pExpr, target, 0, 0);
95735 return target;
95737 case TK_SPAN:
95738 case TK_COLLATE:
95739 case TK_UPLUS: {
95740 return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
95743 case TK_TRIGGER: {
95744 /* If the opcode is TK_TRIGGER, then the expression is a reference
95745 ** to a column in the new.* or old.* pseudo-tables available to
95746 ** trigger programs. In this case Expr.iTable is set to 1 for the
95747 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
95748 ** is set to the column of the pseudo-table to read, or to -1 to
95749 ** read the rowid field.
95751 ** The expression is implemented using an OP_Param opcode. The p1
95752 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
95753 ** to reference another column of the old.* pseudo-table, where
95754 ** i is the index of the column. For a new.rowid reference, p1 is
95755 ** set to (n+1), where n is the number of columns in each pseudo-table.
95756 ** For a reference to any other column in the new.* pseudo-table, p1
95757 ** is set to (n+2+i), where n and i are as defined previously. For
95758 ** example, if the table on which triggers are being fired is
95759 ** declared as:
95761 ** CREATE TABLE t1(a, b);
95763 ** Then p1 is interpreted as follows:
95765 ** p1==0 -> old.rowid p1==3 -> new.rowid
95766 ** p1==1 -> old.a p1==4 -> new.a
95767 ** p1==2 -> old.b p1==5 -> new.b
95769 Table *pTab = pExpr->pTab;
95770 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
95772 assert( pExpr->iTable==0 || pExpr->iTable==1 );
95773 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
95774 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
95775 assert( p1>=0 && p1<(pTab->nCol*2+2) );
95777 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
95778 VdbeComment((v, "%s.%s -> $%d",
95779 (pExpr->iTable ? "new" : "old"),
95780 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
95781 target
95784 #ifndef SQLITE_OMIT_FLOATING_POINT
95785 /* If the column has REAL affinity, it may currently be stored as an
95786 ** integer. Use OP_RealAffinity to make sure it is really real.
95788 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
95789 ** floating point when extracting it from the record. */
95790 if( pExpr->iColumn>=0
95791 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
95793 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
95795 #endif
95796 break;
95799 case TK_VECTOR: {
95800 sqlite3ErrorMsg(pParse, "row value misused");
95801 break;
95804 case TK_IF_NULL_ROW: {
95805 int addrINR;
95806 addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
95807 sqlite3ExprCachePush(pParse);
95808 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
95809 sqlite3ExprCachePop(pParse);
95810 sqlite3VdbeJumpHere(v, addrINR);
95811 sqlite3VdbeChangeP3(v, addrINR, inReg);
95812 break;
95816 ** Form A:
95817 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
95819 ** Form B:
95820 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
95822 ** Form A is can be transformed into the equivalent form B as follows:
95823 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
95824 ** WHEN x=eN THEN rN ELSE y END
95826 ** X (if it exists) is in pExpr->pLeft.
95827 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
95828 ** odd. The Y is also optional. If the number of elements in x.pList
95829 ** is even, then Y is omitted and the "otherwise" result is NULL.
95830 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
95832 ** The result of the expression is the Ri for the first matching Ei,
95833 ** or if there is no matching Ei, the ELSE term Y, or if there is
95834 ** no ELSE term, NULL.
95836 default: assert( op==TK_CASE ); {
95837 int endLabel; /* GOTO label for end of CASE stmt */
95838 int nextCase; /* GOTO label for next WHEN clause */
95839 int nExpr; /* 2x number of WHEN terms */
95840 int i; /* Loop counter */
95841 ExprList *pEList; /* List of WHEN terms */
95842 struct ExprList_item *aListelem; /* Array of WHEN terms */
95843 Expr opCompare; /* The X==Ei expression */
95844 Expr *pX; /* The X expression */
95845 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
95846 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
95848 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
95849 assert(pExpr->x.pList->nExpr > 0);
95850 pEList = pExpr->x.pList;
95851 aListelem = pEList->a;
95852 nExpr = pEList->nExpr;
95853 endLabel = sqlite3VdbeMakeLabel(v);
95854 if( (pX = pExpr->pLeft)!=0 ){
95855 tempX = *pX;
95856 testcase( pX->op==TK_COLUMN );
95857 exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
95858 testcase( regFree1==0 );
95859 memset(&opCompare, 0, sizeof(opCompare));
95860 opCompare.op = TK_EQ;
95861 opCompare.pLeft = &tempX;
95862 pTest = &opCompare;
95863 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
95864 ** The value in regFree1 might get SCopy-ed into the file result.
95865 ** So make sure that the regFree1 register is not reused for other
95866 ** purposes and possibly overwritten. */
95867 regFree1 = 0;
95869 for(i=0; i<nExpr-1; i=i+2){
95870 sqlite3ExprCachePush(pParse);
95871 if( pX ){
95872 assert( pTest!=0 );
95873 opCompare.pRight = aListelem[i].pExpr;
95874 }else{
95875 pTest = aListelem[i].pExpr;
95877 nextCase = sqlite3VdbeMakeLabel(v);
95878 testcase( pTest->op==TK_COLUMN );
95879 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
95880 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
95881 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
95882 sqlite3VdbeGoto(v, endLabel);
95883 sqlite3ExprCachePop(pParse);
95884 sqlite3VdbeResolveLabel(v, nextCase);
95886 if( (nExpr&1)!=0 ){
95887 sqlite3ExprCachePush(pParse);
95888 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
95889 sqlite3ExprCachePop(pParse);
95890 }else{
95891 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
95893 assert( pParse->db->mallocFailed || pParse->nErr>0
95894 || pParse->iCacheLevel==iCacheLevel );
95895 sqlite3VdbeResolveLabel(v, endLabel);
95896 break;
95898 #ifndef SQLITE_OMIT_TRIGGER
95899 case TK_RAISE: {
95900 assert( pExpr->affinity==OE_Rollback
95901 || pExpr->affinity==OE_Abort
95902 || pExpr->affinity==OE_Fail
95903 || pExpr->affinity==OE_Ignore
95905 if( !pParse->pTriggerTab ){
95906 sqlite3ErrorMsg(pParse,
95907 "RAISE() may only be used within a trigger-program");
95908 return 0;
95910 if( pExpr->affinity==OE_Abort ){
95911 sqlite3MayAbort(pParse);
95913 assert( !ExprHasProperty(pExpr, EP_IntValue) );
95914 if( pExpr->affinity==OE_Ignore ){
95915 sqlite3VdbeAddOp4(
95916 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
95917 VdbeCoverage(v);
95918 }else{
95919 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
95920 pExpr->affinity, pExpr->u.zToken, 0, 0);
95923 break;
95925 #endif
95927 sqlite3ReleaseTempReg(pParse, regFree1);
95928 sqlite3ReleaseTempReg(pParse, regFree2);
95929 return inReg;
95933 ** Factor out the code of the given expression to initialization time.
95935 ** If regDest>=0 then the result is always stored in that register and the
95936 ** result is not reusable. If regDest<0 then this routine is free to
95937 ** store the value whereever it wants. The register where the expression
95938 ** is stored is returned. When regDest<0, two identical expressions will
95939 ** code to the same register.
95941 SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
95942 Parse *pParse, /* Parsing context */
95943 Expr *pExpr, /* The expression to code when the VDBE initializes */
95944 int regDest /* Store the value in this register */
95946 ExprList *p;
95947 assert( ConstFactorOk(pParse) );
95948 p = pParse->pConstExpr;
95949 if( regDest<0 && p ){
95950 struct ExprList_item *pItem;
95951 int i;
95952 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
95953 if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
95954 return pItem->u.iConstExprReg;
95958 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
95959 p = sqlite3ExprListAppend(pParse, p, pExpr);
95960 if( p ){
95961 struct ExprList_item *pItem = &p->a[p->nExpr-1];
95962 pItem->reusable = regDest<0;
95963 if( regDest<0 ) regDest = ++pParse->nMem;
95964 pItem->u.iConstExprReg = regDest;
95966 pParse->pConstExpr = p;
95967 return regDest;
95971 ** Generate code to evaluate an expression and store the results
95972 ** into a register. Return the register number where the results
95973 ** are stored.
95975 ** If the register is a temporary register that can be deallocated,
95976 ** then write its number into *pReg. If the result register is not
95977 ** a temporary, then set *pReg to zero.
95979 ** If pExpr is a constant, then this routine might generate this
95980 ** code to fill the register in the initialization section of the
95981 ** VDBE program, in order to factor it out of the evaluation loop.
95983 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
95984 int r2;
95985 pExpr = sqlite3ExprSkipCollate(pExpr);
95986 if( ConstFactorOk(pParse)
95987 && pExpr->op!=TK_REGISTER
95988 && sqlite3ExprIsConstantNotJoin(pExpr)
95990 *pReg = 0;
95991 r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
95992 }else{
95993 int r1 = sqlite3GetTempReg(pParse);
95994 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
95995 if( r2==r1 ){
95996 *pReg = r1;
95997 }else{
95998 sqlite3ReleaseTempReg(pParse, r1);
95999 *pReg = 0;
96002 return r2;
96006 ** Generate code that will evaluate expression pExpr and store the
96007 ** results in register target. The results are guaranteed to appear
96008 ** in register target.
96010 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
96011 int inReg;
96013 assert( target>0 && target<=pParse->nMem );
96014 if( pExpr && pExpr->op==TK_REGISTER ){
96015 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
96016 }else{
96017 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
96018 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
96019 if( inReg!=target && pParse->pVdbe ){
96020 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
96026 ** Make a transient copy of expression pExpr and then code it using
96027 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
96028 ** except that the input expression is guaranteed to be unchanged.
96030 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
96031 sqlite3 *db = pParse->db;
96032 pExpr = sqlite3ExprDup(db, pExpr, 0);
96033 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
96034 sqlite3ExprDelete(db, pExpr);
96038 ** Generate code that will evaluate expression pExpr and store the
96039 ** results in register target. The results are guaranteed to appear
96040 ** in register target. If the expression is constant, then this routine
96041 ** might choose to code the expression at initialization time.
96043 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
96044 if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
96045 sqlite3ExprCodeAtInit(pParse, pExpr, target);
96046 }else{
96047 sqlite3ExprCode(pParse, pExpr, target);
96052 ** Generate code that evaluates the given expression and puts the result
96053 ** in register target.
96055 ** Also make a copy of the expression results into another "cache" register
96056 ** and modify the expression so that the next time it is evaluated,
96057 ** the result is a copy of the cache register.
96059 ** This routine is used for expressions that are used multiple
96060 ** times. They are evaluated once and the results of the expression
96061 ** are reused.
96063 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
96064 Vdbe *v = pParse->pVdbe;
96065 int iMem;
96067 assert( target>0 );
96068 assert( pExpr->op!=TK_REGISTER );
96069 sqlite3ExprCode(pParse, pExpr, target);
96070 iMem = ++pParse->nMem;
96071 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
96072 exprToRegister(pExpr, iMem);
96076 ** Generate code that pushes the value of every element of the given
96077 ** expression list into a sequence of registers beginning at target.
96079 ** Return the number of elements evaluated. The number returned will
96080 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
96081 ** is defined.
96083 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
96084 ** filled using OP_SCopy. OP_Copy must be used instead.
96086 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
96087 ** factored out into initialization code.
96089 ** The SQLITE_ECEL_REF flag means that expressions in the list with
96090 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
96091 ** in registers at srcReg, and so the value can be copied from there.
96092 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
96093 ** are simply omitted rather than being copied from srcReg.
96095 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
96096 Parse *pParse, /* Parsing context */
96097 ExprList *pList, /* The expression list to be coded */
96098 int target, /* Where to write results */
96099 int srcReg, /* Source registers if SQLITE_ECEL_REF */
96100 u8 flags /* SQLITE_ECEL_* flags */
96102 struct ExprList_item *pItem;
96103 int i, j, n;
96104 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
96105 Vdbe *v = pParse->pVdbe;
96106 assert( pList!=0 );
96107 assert( target>0 );
96108 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
96109 n = pList->nExpr;
96110 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
96111 for(pItem=pList->a, i=0; i<n; i++, pItem++){
96112 Expr *pExpr = pItem->pExpr;
96113 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
96114 if( flags & SQLITE_ECEL_OMITREF ){
96115 i--;
96116 n--;
96117 }else{
96118 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
96120 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
96121 sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
96122 }else{
96123 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
96124 if( inReg!=target+i ){
96125 VdbeOp *pOp;
96126 if( copyOp==OP_Copy
96127 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
96128 && pOp->p1+pOp->p3+1==inReg
96129 && pOp->p2+pOp->p3+1==target+i
96131 pOp->p3++;
96132 }else{
96133 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
96138 return n;
96142 ** Generate code for a BETWEEN operator.
96144 ** x BETWEEN y AND z
96146 ** The above is equivalent to
96148 ** x>=y AND x<=z
96150 ** Code it as such, taking care to do the common subexpression
96151 ** elimination of x.
96153 ** The xJumpIf parameter determines details:
96155 ** NULL: Store the boolean result in reg[dest]
96156 ** sqlite3ExprIfTrue: Jump to dest if true
96157 ** sqlite3ExprIfFalse: Jump to dest if false
96159 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
96161 static void exprCodeBetween(
96162 Parse *pParse, /* Parsing and code generating context */
96163 Expr *pExpr, /* The BETWEEN expression */
96164 int dest, /* Jump destination or storage location */
96165 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
96166 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
96168 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
96169 Expr compLeft; /* The x>=y term */
96170 Expr compRight; /* The x<=z term */
96171 Expr exprX; /* The x subexpression */
96172 int regFree1 = 0; /* Temporary use register */
96175 memset(&compLeft, 0, sizeof(Expr));
96176 memset(&compRight, 0, sizeof(Expr));
96177 memset(&exprAnd, 0, sizeof(Expr));
96179 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
96180 exprX = *pExpr->pLeft;
96181 exprAnd.op = TK_AND;
96182 exprAnd.pLeft = &compLeft;
96183 exprAnd.pRight = &compRight;
96184 compLeft.op = TK_GE;
96185 compLeft.pLeft = &exprX;
96186 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
96187 compRight.op = TK_LE;
96188 compRight.pLeft = &exprX;
96189 compRight.pRight = pExpr->x.pList->a[1].pExpr;
96190 exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
96191 if( xJump ){
96192 xJump(pParse, &exprAnd, dest, jumpIfNull);
96193 }else{
96194 /* Mark the expression is being from the ON or USING clause of a join
96195 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
96196 ** it into the Parse.pConstExpr list. We should use a new bit for this,
96197 ** for clarity, but we are out of bits in the Expr.flags field so we
96198 ** have to reuse the EP_FromJoin bit. Bummer. */
96199 exprX.flags |= EP_FromJoin;
96200 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
96202 sqlite3ReleaseTempReg(pParse, regFree1);
96204 /* Ensure adequate test coverage */
96205 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
96206 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
96207 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
96208 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
96209 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
96210 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
96211 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
96212 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
96213 testcase( xJump==0 );
96217 ** Generate code for a boolean expression such that a jump is made
96218 ** to the label "dest" if the expression is true but execution
96219 ** continues straight thru if the expression is false.
96221 ** If the expression evaluates to NULL (neither true nor false), then
96222 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
96224 ** This code depends on the fact that certain token values (ex: TK_EQ)
96225 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
96226 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
96227 ** the make process cause these values to align. Assert()s in the code
96228 ** below verify that the numbers are aligned correctly.
96230 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
96231 Vdbe *v = pParse->pVdbe;
96232 int op = 0;
96233 int regFree1 = 0;
96234 int regFree2 = 0;
96235 int r1, r2;
96237 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
96238 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
96239 if( NEVER(pExpr==0) ) return; /* No way this can happen */
96240 op = pExpr->op;
96241 switch( op ){
96242 case TK_AND: {
96243 int d2 = sqlite3VdbeMakeLabel(v);
96244 testcase( jumpIfNull==0 );
96245 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
96246 sqlite3ExprCachePush(pParse);
96247 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
96248 sqlite3VdbeResolveLabel(v, d2);
96249 sqlite3ExprCachePop(pParse);
96250 break;
96252 case TK_OR: {
96253 testcase( jumpIfNull==0 );
96254 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
96255 sqlite3ExprCachePush(pParse);
96256 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
96257 sqlite3ExprCachePop(pParse);
96258 break;
96260 case TK_NOT: {
96261 testcase( jumpIfNull==0 );
96262 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
96263 break;
96265 case TK_IS:
96266 case TK_ISNOT:
96267 testcase( op==TK_IS );
96268 testcase( op==TK_ISNOT );
96269 op = (op==TK_IS) ? TK_EQ : TK_NE;
96270 jumpIfNull = SQLITE_NULLEQ;
96271 /* Fall thru */
96272 case TK_LT:
96273 case TK_LE:
96274 case TK_GT:
96275 case TK_GE:
96276 case TK_NE:
96277 case TK_EQ: {
96278 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
96279 testcase( jumpIfNull==0 );
96280 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
96281 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
96282 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
96283 r1, r2, dest, jumpIfNull);
96284 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
96285 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
96286 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
96287 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
96288 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
96289 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
96290 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
96291 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
96292 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
96293 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
96294 testcase( regFree1==0 );
96295 testcase( regFree2==0 );
96296 break;
96298 case TK_ISNULL:
96299 case TK_NOTNULL: {
96300 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
96301 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
96302 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
96303 sqlite3VdbeAddOp2(v, op, r1, dest);
96304 VdbeCoverageIf(v, op==TK_ISNULL);
96305 VdbeCoverageIf(v, op==TK_NOTNULL);
96306 testcase( regFree1==0 );
96307 break;
96309 case TK_BETWEEN: {
96310 testcase( jumpIfNull==0 );
96311 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
96312 break;
96314 #ifndef SQLITE_OMIT_SUBQUERY
96315 case TK_IN: {
96316 int destIfFalse = sqlite3VdbeMakeLabel(v);
96317 int destIfNull = jumpIfNull ? dest : destIfFalse;
96318 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
96319 sqlite3VdbeGoto(v, dest);
96320 sqlite3VdbeResolveLabel(v, destIfFalse);
96321 break;
96323 #endif
96324 default: {
96325 default_expr:
96326 if( exprAlwaysTrue(pExpr) ){
96327 sqlite3VdbeGoto(v, dest);
96328 }else if( exprAlwaysFalse(pExpr) ){
96329 /* No-op */
96330 }else{
96331 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
96332 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
96333 VdbeCoverage(v);
96334 testcase( regFree1==0 );
96335 testcase( jumpIfNull==0 );
96337 break;
96340 sqlite3ReleaseTempReg(pParse, regFree1);
96341 sqlite3ReleaseTempReg(pParse, regFree2);
96345 ** Generate code for a boolean expression such that a jump is made
96346 ** to the label "dest" if the expression is false but execution
96347 ** continues straight thru if the expression is true.
96349 ** If the expression evaluates to NULL (neither true nor false) then
96350 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
96351 ** is 0.
96353 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
96354 Vdbe *v = pParse->pVdbe;
96355 int op = 0;
96356 int regFree1 = 0;
96357 int regFree2 = 0;
96358 int r1, r2;
96360 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
96361 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
96362 if( pExpr==0 ) return;
96364 /* The value of pExpr->op and op are related as follows:
96366 ** pExpr->op op
96367 ** --------- ----------
96368 ** TK_ISNULL OP_NotNull
96369 ** TK_NOTNULL OP_IsNull
96370 ** TK_NE OP_Eq
96371 ** TK_EQ OP_Ne
96372 ** TK_GT OP_Le
96373 ** TK_LE OP_Gt
96374 ** TK_GE OP_Lt
96375 ** TK_LT OP_Ge
96377 ** For other values of pExpr->op, op is undefined and unused.
96378 ** The value of TK_ and OP_ constants are arranged such that we
96379 ** can compute the mapping above using the following expression.
96380 ** Assert()s verify that the computation is correct.
96382 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
96384 /* Verify correct alignment of TK_ and OP_ constants
96386 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
96387 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
96388 assert( pExpr->op!=TK_NE || op==OP_Eq );
96389 assert( pExpr->op!=TK_EQ || op==OP_Ne );
96390 assert( pExpr->op!=TK_LT || op==OP_Ge );
96391 assert( pExpr->op!=TK_LE || op==OP_Gt );
96392 assert( pExpr->op!=TK_GT || op==OP_Le );
96393 assert( pExpr->op!=TK_GE || op==OP_Lt );
96395 switch( pExpr->op ){
96396 case TK_AND: {
96397 testcase( jumpIfNull==0 );
96398 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
96399 sqlite3ExprCachePush(pParse);
96400 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
96401 sqlite3ExprCachePop(pParse);
96402 break;
96404 case TK_OR: {
96405 int d2 = sqlite3VdbeMakeLabel(v);
96406 testcase( jumpIfNull==0 );
96407 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
96408 sqlite3ExprCachePush(pParse);
96409 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
96410 sqlite3VdbeResolveLabel(v, d2);
96411 sqlite3ExprCachePop(pParse);
96412 break;
96414 case TK_NOT: {
96415 testcase( jumpIfNull==0 );
96416 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
96417 break;
96419 case TK_IS:
96420 case TK_ISNOT:
96421 testcase( pExpr->op==TK_IS );
96422 testcase( pExpr->op==TK_ISNOT );
96423 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
96424 jumpIfNull = SQLITE_NULLEQ;
96425 /* Fall thru */
96426 case TK_LT:
96427 case TK_LE:
96428 case TK_GT:
96429 case TK_GE:
96430 case TK_NE:
96431 case TK_EQ: {
96432 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
96433 testcase( jumpIfNull==0 );
96434 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
96435 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
96436 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
96437 r1, r2, dest, jumpIfNull);
96438 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
96439 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
96440 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
96441 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
96442 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
96443 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
96444 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
96445 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
96446 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
96447 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
96448 testcase( regFree1==0 );
96449 testcase( regFree2==0 );
96450 break;
96452 case TK_ISNULL:
96453 case TK_NOTNULL: {
96454 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
96455 sqlite3VdbeAddOp2(v, op, r1, dest);
96456 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
96457 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
96458 testcase( regFree1==0 );
96459 break;
96461 case TK_BETWEEN: {
96462 testcase( jumpIfNull==0 );
96463 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
96464 break;
96466 #ifndef SQLITE_OMIT_SUBQUERY
96467 case TK_IN: {
96468 if( jumpIfNull ){
96469 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
96470 }else{
96471 int destIfNull = sqlite3VdbeMakeLabel(v);
96472 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
96473 sqlite3VdbeResolveLabel(v, destIfNull);
96475 break;
96477 #endif
96478 default: {
96479 default_expr:
96480 if( exprAlwaysFalse(pExpr) ){
96481 sqlite3VdbeGoto(v, dest);
96482 }else if( exprAlwaysTrue(pExpr) ){
96483 /* no-op */
96484 }else{
96485 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
96486 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
96487 VdbeCoverage(v);
96488 testcase( regFree1==0 );
96489 testcase( jumpIfNull==0 );
96491 break;
96494 sqlite3ReleaseTempReg(pParse, regFree1);
96495 sqlite3ReleaseTempReg(pParse, regFree2);
96499 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
96500 ** code generation, and that copy is deleted after code generation. This
96501 ** ensures that the original pExpr is unchanged.
96503 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
96504 sqlite3 *db = pParse->db;
96505 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
96506 if( db->mallocFailed==0 ){
96507 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
96509 sqlite3ExprDelete(db, pCopy);
96513 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
96514 ** type of expression.
96516 ** If pExpr is a simple SQL value - an integer, real, string, blob
96517 ** or NULL value - then the VDBE currently being prepared is configured
96518 ** to re-prepare each time a new value is bound to variable pVar.
96520 ** Additionally, if pExpr is a simple SQL value and the value is the
96521 ** same as that currently bound to variable pVar, non-zero is returned.
96522 ** Otherwise, if the values are not the same or if pExpr is not a simple
96523 ** SQL value, zero is returned.
96525 static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
96526 int res = 0;
96527 int iVar;
96528 sqlite3_value *pL, *pR = 0;
96530 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
96531 if( pR ){
96532 iVar = pVar->iColumn;
96533 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
96534 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
96535 if( pL ){
96536 if( sqlite3_value_type(pL)==SQLITE_TEXT ){
96537 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
96539 res = 0==sqlite3MemCompare(pL, pR, 0);
96541 sqlite3ValueFree(pR);
96542 sqlite3ValueFree(pL);
96545 return res;
96549 ** Do a deep comparison of two expression trees. Return 0 if the two
96550 ** expressions are completely identical. Return 1 if they differ only
96551 ** by a COLLATE operator at the top level. Return 2 if there are differences
96552 ** other than the top-level COLLATE operator.
96554 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
96555 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
96557 ** The pA side might be using TK_REGISTER. If that is the case and pB is
96558 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
96560 ** Sometimes this routine will return 2 even if the two expressions
96561 ** really are equivalent. If we cannot prove that the expressions are
96562 ** identical, we return 2 just to be safe. So if this routine
96563 ** returns 2, then you do not really know for certain if the two
96564 ** expressions are the same. But if you get a 0 or 1 return, then you
96565 ** can be sure the expressions are the same. In the places where
96566 ** this routine is used, it does not hurt to get an extra 2 - that
96567 ** just might result in some slightly slower code. But returning
96568 ** an incorrect 0 or 1 could lead to a malfunction.
96570 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
96571 ** pParse->pReprepare can be matched against literals in pB. The
96572 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
96573 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
96574 ** Argument pParse should normally be NULL. If it is not NULL and pA or
96575 ** pB causes a return value of 2.
96577 SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
96578 u32 combinedFlags;
96579 if( pA==0 || pB==0 ){
96580 return pB==pA ? 0 : 2;
96582 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
96583 return 0;
96585 combinedFlags = pA->flags | pB->flags;
96586 if( combinedFlags & EP_IntValue ){
96587 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
96588 return 0;
96590 return 2;
96592 if( pA->op!=pB->op ){
96593 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
96594 return 1;
96596 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
96597 return 1;
96599 return 2;
96601 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
96602 if( pA->op==TK_FUNCTION ){
96603 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
96604 }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
96605 return pA->op==TK_COLLATE ? 1 : 2;
96608 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
96609 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
96610 if( combinedFlags & EP_xIsSelect ) return 2;
96611 if( sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
96612 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
96613 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
96614 if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
96615 if( pA->iColumn!=pB->iColumn ) return 2;
96616 if( pA->iTable!=pB->iTable
96617 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
96620 return 0;
96624 ** Compare two ExprList objects. Return 0 if they are identical and
96625 ** non-zero if they differ in any way.
96627 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
96628 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
96630 ** This routine might return non-zero for equivalent ExprLists. The
96631 ** only consequence will be disabled optimizations. But this routine
96632 ** must never return 0 if the two ExprList objects are different, or
96633 ** a malfunction will result.
96635 ** Two NULL pointers are considered to be the same. But a NULL pointer
96636 ** always differs from a non-NULL pointer.
96638 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
96639 int i;
96640 if( pA==0 && pB==0 ) return 0;
96641 if( pA==0 || pB==0 ) return 1;
96642 if( pA->nExpr!=pB->nExpr ) return 1;
96643 for(i=0; i<pA->nExpr; i++){
96644 Expr *pExprA = pA->a[i].pExpr;
96645 Expr *pExprB = pB->a[i].pExpr;
96646 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
96647 if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
96649 return 0;
96653 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
96654 ** are ignored.
96656 SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
96657 return sqlite3ExprCompare(0,
96658 sqlite3ExprSkipCollate(pA),
96659 sqlite3ExprSkipCollate(pB),
96660 iTab);
96664 ** Return true if we can prove the pE2 will always be true if pE1 is
96665 ** true. Return false if we cannot complete the proof or if pE2 might
96666 ** be false. Examples:
96668 ** pE1: x==5 pE2: x==5 Result: true
96669 ** pE1: x>0 pE2: x==5 Result: false
96670 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
96671 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
96672 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
96673 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
96674 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
96676 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
96677 ** Expr.iTable<0 then assume a table number given by iTab.
96679 ** If pParse is not NULL, then the values of bound variables in pE1 are
96680 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
96681 ** modified to record which bound variables are referenced. If pParse
96682 ** is NULL, then false will be returned if pE1 contains any bound variables.
96684 ** When in doubt, return false. Returning true might give a performance
96685 ** improvement. Returning false might cause a performance reduction, but
96686 ** it will always give the correct answer and is hence always safe.
96688 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
96689 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
96690 return 1;
96692 if( pE2->op==TK_OR
96693 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
96694 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
96696 return 1;
96698 if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
96699 Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
96700 testcase( pX!=pE1->pLeft );
96701 if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
96703 return 0;
96707 ** An instance of the following structure is used by the tree walker
96708 ** to determine if an expression can be evaluated by reference to the
96709 ** index only, without having to do a search for the corresponding
96710 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
96711 ** is the cursor for the table.
96713 struct IdxCover {
96714 Index *pIdx; /* The index to be tested for coverage */
96715 int iCur; /* Cursor number for the table corresponding to the index */
96719 ** Check to see if there are references to columns in table
96720 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
96721 ** pWalker->u.pIdxCover->pIdx.
96723 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
96724 if( pExpr->op==TK_COLUMN
96725 && pExpr->iTable==pWalker->u.pIdxCover->iCur
96726 && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
96728 pWalker->eCode = 1;
96729 return WRC_Abort;
96731 return WRC_Continue;
96735 ** Determine if an index pIdx on table with cursor iCur contains will
96736 ** the expression pExpr. Return true if the index does cover the
96737 ** expression and false if the pExpr expression references table columns
96738 ** that are not found in the index pIdx.
96740 ** An index covering an expression means that the expression can be
96741 ** evaluated using only the index and without having to lookup the
96742 ** corresponding table entry.
96744 SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
96745 Expr *pExpr, /* The index to be tested */
96746 int iCur, /* The cursor number for the corresponding table */
96747 Index *pIdx /* The index that might be used for coverage */
96749 Walker w;
96750 struct IdxCover xcov;
96751 memset(&w, 0, sizeof(w));
96752 xcov.iCur = iCur;
96753 xcov.pIdx = pIdx;
96754 w.xExprCallback = exprIdxCover;
96755 w.u.pIdxCover = &xcov;
96756 sqlite3WalkExpr(&w, pExpr);
96757 return !w.eCode;
96762 ** An instance of the following structure is used by the tree walker
96763 ** to count references to table columns in the arguments of an
96764 ** aggregate function, in order to implement the
96765 ** sqlite3FunctionThisSrc() routine.
96767 struct SrcCount {
96768 SrcList *pSrc; /* One particular FROM clause in a nested query */
96769 int nThis; /* Number of references to columns in pSrcList */
96770 int nOther; /* Number of references to columns in other FROM clauses */
96774 ** Count the number of references to columns.
96776 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
96777 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
96778 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
96779 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
96780 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
96781 ** NEVER() will need to be removed. */
96782 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
96783 int i;
96784 struct SrcCount *p = pWalker->u.pSrcCount;
96785 SrcList *pSrc = p->pSrc;
96786 int nSrc = pSrc ? pSrc->nSrc : 0;
96787 for(i=0; i<nSrc; i++){
96788 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
96790 if( i<nSrc ){
96791 p->nThis++;
96792 }else{
96793 p->nOther++;
96796 return WRC_Continue;
96800 ** Determine if any of the arguments to the pExpr Function reference
96801 ** pSrcList. Return true if they do. Also return true if the function
96802 ** has no arguments or has only constant arguments. Return false if pExpr
96803 ** references columns but not columns of tables found in pSrcList.
96805 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
96806 Walker w;
96807 struct SrcCount cnt;
96808 assert( pExpr->op==TK_AGG_FUNCTION );
96809 w.xExprCallback = exprSrcCount;
96810 w.xSelectCallback = 0;
96811 w.u.pSrcCount = &cnt;
96812 cnt.pSrc = pSrcList;
96813 cnt.nThis = 0;
96814 cnt.nOther = 0;
96815 sqlite3WalkExprList(&w, pExpr->x.pList);
96816 return cnt.nThis>0 || cnt.nOther==0;
96820 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
96821 ** the new element. Return a negative number if malloc fails.
96823 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
96824 int i;
96825 pInfo->aCol = sqlite3ArrayAllocate(
96827 pInfo->aCol,
96828 sizeof(pInfo->aCol[0]),
96829 &pInfo->nColumn,
96832 return i;
96836 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
96837 ** the new element. Return a negative number if malloc fails.
96839 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
96840 int i;
96841 pInfo->aFunc = sqlite3ArrayAllocate(
96842 db,
96843 pInfo->aFunc,
96844 sizeof(pInfo->aFunc[0]),
96845 &pInfo->nFunc,
96848 return i;
96852 ** This is the xExprCallback for a tree walker. It is used to
96853 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
96854 ** for additional information.
96856 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
96857 int i;
96858 NameContext *pNC = pWalker->u.pNC;
96859 Parse *pParse = pNC->pParse;
96860 SrcList *pSrcList = pNC->pSrcList;
96861 AggInfo *pAggInfo = pNC->pAggInfo;
96863 switch( pExpr->op ){
96864 case TK_AGG_COLUMN:
96865 case TK_COLUMN: {
96866 testcase( pExpr->op==TK_AGG_COLUMN );
96867 testcase( pExpr->op==TK_COLUMN );
96868 /* Check to see if the column is in one of the tables in the FROM
96869 ** clause of the aggregate query */
96870 if( ALWAYS(pSrcList!=0) ){
96871 struct SrcList_item *pItem = pSrcList->a;
96872 for(i=0; i<pSrcList->nSrc; i++, pItem++){
96873 struct AggInfo_col *pCol;
96874 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
96875 if( pExpr->iTable==pItem->iCursor ){
96876 /* If we reach this point, it means that pExpr refers to a table
96877 ** that is in the FROM clause of the aggregate query.
96879 ** Make an entry for the column in pAggInfo->aCol[] if there
96880 ** is not an entry there already.
96882 int k;
96883 pCol = pAggInfo->aCol;
96884 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
96885 if( pCol->iTable==pExpr->iTable &&
96886 pCol->iColumn==pExpr->iColumn ){
96887 break;
96890 if( (k>=pAggInfo->nColumn)
96891 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
96893 pCol = &pAggInfo->aCol[k];
96894 pCol->pTab = pExpr->pTab;
96895 pCol->iTable = pExpr->iTable;
96896 pCol->iColumn = pExpr->iColumn;
96897 pCol->iMem = ++pParse->nMem;
96898 pCol->iSorterColumn = -1;
96899 pCol->pExpr = pExpr;
96900 if( pAggInfo->pGroupBy ){
96901 int j, n;
96902 ExprList *pGB = pAggInfo->pGroupBy;
96903 struct ExprList_item *pTerm = pGB->a;
96904 n = pGB->nExpr;
96905 for(j=0; j<n; j++, pTerm++){
96906 Expr *pE = pTerm->pExpr;
96907 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
96908 pE->iColumn==pExpr->iColumn ){
96909 pCol->iSorterColumn = j;
96910 break;
96914 if( pCol->iSorterColumn<0 ){
96915 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
96918 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
96919 ** because it was there before or because we just created it).
96920 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
96921 ** pAggInfo->aCol[] entry.
96923 ExprSetVVAProperty(pExpr, EP_NoReduce);
96924 pExpr->pAggInfo = pAggInfo;
96925 pExpr->op = TK_AGG_COLUMN;
96926 pExpr->iAgg = (i16)k;
96927 break;
96928 } /* endif pExpr->iTable==pItem->iCursor */
96929 } /* end loop over pSrcList */
96931 return WRC_Prune;
96933 case TK_AGG_FUNCTION: {
96934 if( (pNC->ncFlags & NC_InAggFunc)==0
96935 && pWalker->walkerDepth==pExpr->op2
96937 /* Check to see if pExpr is a duplicate of another aggregate
96938 ** function that is already in the pAggInfo structure
96940 struct AggInfo_func *pItem = pAggInfo->aFunc;
96941 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
96942 if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
96943 break;
96946 if( i>=pAggInfo->nFunc ){
96947 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
96949 u8 enc = ENC(pParse->db);
96950 i = addAggInfoFunc(pParse->db, pAggInfo);
96951 if( i>=0 ){
96952 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
96953 pItem = &pAggInfo->aFunc[i];
96954 pItem->pExpr = pExpr;
96955 pItem->iMem = ++pParse->nMem;
96956 assert( !ExprHasProperty(pExpr, EP_IntValue) );
96957 pItem->pFunc = sqlite3FindFunction(pParse->db,
96958 pExpr->u.zToken,
96959 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
96960 if( pExpr->flags & EP_Distinct ){
96961 pItem->iDistinct = pParse->nTab++;
96962 }else{
96963 pItem->iDistinct = -1;
96967 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
96969 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
96970 ExprSetVVAProperty(pExpr, EP_NoReduce);
96971 pExpr->iAgg = (i16)i;
96972 pExpr->pAggInfo = pAggInfo;
96973 return WRC_Prune;
96974 }else{
96975 return WRC_Continue;
96979 return WRC_Continue;
96981 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
96982 UNUSED_PARAMETER(pSelect);
96983 pWalker->walkerDepth++;
96984 return WRC_Continue;
96986 static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
96987 UNUSED_PARAMETER(pSelect);
96988 pWalker->walkerDepth--;
96992 ** Analyze the pExpr expression looking for aggregate functions and
96993 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
96994 ** points to. Additional entries are made on the AggInfo object as
96995 ** necessary.
96997 ** This routine should only be called after the expression has been
96998 ** analyzed by sqlite3ResolveExprNames().
97000 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
97001 Walker w;
97002 w.xExprCallback = analyzeAggregate;
97003 w.xSelectCallback = analyzeAggregatesInSelect;
97004 w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
97005 w.walkerDepth = 0;
97006 w.u.pNC = pNC;
97007 assert( pNC->pSrcList!=0 );
97008 sqlite3WalkExpr(&w, pExpr);
97012 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
97013 ** expression list. Return the number of errors.
97015 ** If an error is found, the analysis is cut short.
97017 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
97018 struct ExprList_item *pItem;
97019 int i;
97020 if( pList ){
97021 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
97022 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
97028 ** Allocate a single new register for use to hold some intermediate result.
97030 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
97031 if( pParse->nTempReg==0 ){
97032 return ++pParse->nMem;
97034 return pParse->aTempReg[--pParse->nTempReg];
97038 ** Deallocate a register, making available for reuse for some other
97039 ** purpose.
97041 ** If a register is currently being used by the column cache, then
97042 ** the deallocation is deferred until the column cache line that uses
97043 ** the register becomes stale.
97045 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
97046 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
97047 int i;
97048 struct yColCache *p;
97049 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
97050 if( p->iReg==iReg ){
97051 p->tempReg = 1;
97052 return;
97055 pParse->aTempReg[pParse->nTempReg++] = iReg;
97060 ** Allocate or deallocate a block of nReg consecutive registers.
97062 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
97063 int i, n;
97064 if( nReg==1 ) return sqlite3GetTempReg(pParse);
97065 i = pParse->iRangeReg;
97066 n = pParse->nRangeReg;
97067 if( nReg<=n ){
97068 assert( !usedAsColumnCache(pParse, i, i+n-1) );
97069 pParse->iRangeReg += nReg;
97070 pParse->nRangeReg -= nReg;
97071 }else{
97072 i = pParse->nMem+1;
97073 pParse->nMem += nReg;
97075 return i;
97077 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
97078 if( nReg==1 ){
97079 sqlite3ReleaseTempReg(pParse, iReg);
97080 return;
97082 sqlite3ExprCacheRemove(pParse, iReg, nReg);
97083 if( nReg>pParse->nRangeReg ){
97084 pParse->nRangeReg = nReg;
97085 pParse->iRangeReg = iReg;
97090 ** Mark all temporary registers as being unavailable for reuse.
97092 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
97093 pParse->nTempReg = 0;
97094 pParse->nRangeReg = 0;
97098 ** Validate that no temporary register falls within the range of
97099 ** iFirst..iLast, inclusive. This routine is only call from within assert()
97100 ** statements.
97102 #ifdef SQLITE_DEBUG
97103 SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
97104 int i;
97105 if( pParse->nRangeReg>0
97106 && pParse->iRangeReg+pParse->nRangeReg > iFirst
97107 && pParse->iRangeReg <= iLast
97109 return 0;
97111 for(i=0; i<pParse->nTempReg; i++){
97112 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
97113 return 0;
97116 return 1;
97118 #endif /* SQLITE_DEBUG */
97120 /************** End of expr.c ************************************************/
97121 /************** Begin file alter.c *******************************************/
97123 ** 2005 February 15
97125 ** The author disclaims copyright to this source code. In place of
97126 ** a legal notice, here is a blessing:
97128 ** May you do good and not evil.
97129 ** May you find forgiveness for yourself and forgive others.
97130 ** May you share freely, never taking more than you give.
97132 *************************************************************************
97133 ** This file contains C code routines that used to generate VDBE code
97134 ** that implements the ALTER TABLE command.
97136 /* #include "sqliteInt.h" */
97139 ** The code in this file only exists if we are not omitting the
97140 ** ALTER TABLE logic from the build.
97142 #ifndef SQLITE_OMIT_ALTERTABLE
97146 ** This function is used by SQL generated to implement the
97147 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
97148 ** CREATE INDEX command. The second is a table name. The table name in
97149 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
97150 ** argument and the result returned. Examples:
97152 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
97153 ** -> 'CREATE TABLE def(a, b, c)'
97155 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
97156 ** -> 'CREATE INDEX i ON def(a, b, c)'
97158 static void renameTableFunc(
97159 sqlite3_context *context,
97160 int NotUsed,
97161 sqlite3_value **argv
97163 unsigned char const *zSql = sqlite3_value_text(argv[0]);
97164 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
97166 int token;
97167 Token tname;
97168 unsigned char const *zCsr = zSql;
97169 int len = 0;
97170 char *zRet;
97172 sqlite3 *db = sqlite3_context_db_handle(context);
97174 UNUSED_PARAMETER(NotUsed);
97176 /* The principle used to locate the table name in the CREATE TABLE
97177 ** statement is that the table name is the first non-space token that
97178 ** is immediately followed by a TK_LP or TK_USING token.
97180 if( zSql ){
97181 do {
97182 if( !*zCsr ){
97183 /* Ran out of input before finding an opening bracket. Return NULL. */
97184 return;
97187 /* Store the token that zCsr points to in tname. */
97188 tname.z = (char*)zCsr;
97189 tname.n = len;
97191 /* Advance zCsr to the next token. Store that token type in 'token',
97192 ** and its length in 'len' (to be used next iteration of this loop).
97194 do {
97195 zCsr += len;
97196 len = sqlite3GetToken(zCsr, &token);
97197 } while( token==TK_SPACE );
97198 assert( len>0 );
97199 } while( token!=TK_LP && token!=TK_USING );
97201 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
97202 zSql, zTableName, tname.z+tname.n);
97203 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
97208 ** This C function implements an SQL user function that is used by SQL code
97209 ** generated by the ALTER TABLE ... RENAME command to modify the definition
97210 ** of any foreign key constraints that use the table being renamed as the
97211 ** parent table. It is passed three arguments:
97213 ** 1) The complete text of the CREATE TABLE statement being modified,
97214 ** 2) The old name of the table being renamed, and
97215 ** 3) The new name of the table being renamed.
97217 ** It returns the new CREATE TABLE statement. For example:
97219 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
97220 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
97222 #ifndef SQLITE_OMIT_FOREIGN_KEY
97223 static void renameParentFunc(
97224 sqlite3_context *context,
97225 int NotUsed,
97226 sqlite3_value **argv
97228 sqlite3 *db = sqlite3_context_db_handle(context);
97229 char *zOutput = 0;
97230 char *zResult;
97231 unsigned char const *zInput = sqlite3_value_text(argv[0]);
97232 unsigned char const *zOld = sqlite3_value_text(argv[1]);
97233 unsigned char const *zNew = sqlite3_value_text(argv[2]);
97235 unsigned const char *z; /* Pointer to token */
97236 int n; /* Length of token z */
97237 int token; /* Type of token */
97239 UNUSED_PARAMETER(NotUsed);
97240 if( zInput==0 || zOld==0 ) return;
97241 for(z=zInput; *z; z=z+n){
97242 n = sqlite3GetToken(z, &token);
97243 if( token==TK_REFERENCES ){
97244 char *zParent;
97245 do {
97246 z += n;
97247 n = sqlite3GetToken(z, &token);
97248 }while( token==TK_SPACE );
97250 if( token==TK_ILLEGAL ) break;
97251 zParent = sqlite3DbStrNDup(db, (const char *)z, n);
97252 if( zParent==0 ) break;
97253 sqlite3Dequote(zParent);
97254 if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
97255 char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
97256 (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
97258 sqlite3DbFree(db, zOutput);
97259 zOutput = zOut;
97260 zInput = &z[n];
97262 sqlite3DbFree(db, zParent);
97266 zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
97267 sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
97268 sqlite3DbFree(db, zOutput);
97270 #endif
97272 #ifndef SQLITE_OMIT_TRIGGER
97273 /* This function is used by SQL generated to implement the
97274 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
97275 ** statement. The second is a table name. The table name in the CREATE
97276 ** TRIGGER statement is replaced with the third argument and the result
97277 ** returned. This is analagous to renameTableFunc() above, except for CREATE
97278 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
97280 static void renameTriggerFunc(
97281 sqlite3_context *context,
97282 int NotUsed,
97283 sqlite3_value **argv
97285 unsigned char const *zSql = sqlite3_value_text(argv[0]);
97286 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
97288 int token;
97289 Token tname;
97290 int dist = 3;
97291 unsigned char const *zCsr = zSql;
97292 int len = 0;
97293 char *zRet;
97294 sqlite3 *db = sqlite3_context_db_handle(context);
97296 UNUSED_PARAMETER(NotUsed);
97298 /* The principle used to locate the table name in the CREATE TRIGGER
97299 ** statement is that the table name is the first token that is immediately
97300 ** preceded by either TK_ON or TK_DOT and immediately followed by one
97301 ** of TK_WHEN, TK_BEGIN or TK_FOR.
97303 if( zSql ){
97304 do {
97306 if( !*zCsr ){
97307 /* Ran out of input before finding the table name. Return NULL. */
97308 return;
97311 /* Store the token that zCsr points to in tname. */
97312 tname.z = (char*)zCsr;
97313 tname.n = len;
97315 /* Advance zCsr to the next token. Store that token type in 'token',
97316 ** and its length in 'len' (to be used next iteration of this loop).
97318 do {
97319 zCsr += len;
97320 len = sqlite3GetToken(zCsr, &token);
97321 }while( token==TK_SPACE );
97322 assert( len>0 );
97324 /* Variable 'dist' stores the number of tokens read since the most
97325 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
97326 ** token is read and 'dist' equals 2, the condition stated above
97327 ** to be met.
97329 ** Note that ON cannot be a database, table or column name, so
97330 ** there is no need to worry about syntax like
97331 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
97333 dist++;
97334 if( token==TK_DOT || token==TK_ON ){
97335 dist = 0;
97337 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
97339 /* Variable tname now contains the token that is the old table-name
97340 ** in the CREATE TRIGGER statement.
97342 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
97343 zSql, zTableName, tname.z+tname.n);
97344 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
97347 #endif /* !SQLITE_OMIT_TRIGGER */
97350 ** Register built-in functions used to help implement ALTER TABLE
97352 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
97353 static FuncDef aAlterTableFuncs[] = {
97354 FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
97355 #ifndef SQLITE_OMIT_TRIGGER
97356 FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
97357 #endif
97358 #ifndef SQLITE_OMIT_FOREIGN_KEY
97359 FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
97360 #endif
97362 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
97366 ** This function is used to create the text of expressions of the form:
97368 ** name=<constant1> OR name=<constant2> OR ...
97370 ** If argument zWhere is NULL, then a pointer string containing the text
97371 ** "name=<constant>" is returned, where <constant> is the quoted version
97372 ** of the string passed as argument zConstant. The returned buffer is
97373 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
97374 ** caller to ensure that it is eventually freed.
97376 ** If argument zWhere is not NULL, then the string returned is
97377 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
97378 ** In this case zWhere is passed to sqlite3DbFree() before returning.
97381 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
97382 char *zNew;
97383 if( !zWhere ){
97384 zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
97385 }else{
97386 zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
97387 sqlite3DbFree(db, zWhere);
97389 return zNew;
97392 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
97394 ** Generate the text of a WHERE expression which can be used to select all
97395 ** tables that have foreign key constraints that refer to table pTab (i.e.
97396 ** constraints for which pTab is the parent table) from the sqlite_master
97397 ** table.
97399 static char *whereForeignKeys(Parse *pParse, Table *pTab){
97400 FKey *p;
97401 char *zWhere = 0;
97402 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
97403 zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
97405 return zWhere;
97407 #endif
97410 ** Generate the text of a WHERE expression which can be used to select all
97411 ** temporary triggers on table pTab from the sqlite_temp_master table. If
97412 ** table pTab has no temporary triggers, or is itself stored in the
97413 ** temporary database, NULL is returned.
97415 static char *whereTempTriggers(Parse *pParse, Table *pTab){
97416 Trigger *pTrig;
97417 char *zWhere = 0;
97418 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
97420 /* If the table is not located in the temp-db (in which case NULL is
97421 ** returned, loop through the tables list of triggers. For each trigger
97422 ** that is not part of the temp-db schema, add a clause to the WHERE
97423 ** expression being built up in zWhere.
97425 if( pTab->pSchema!=pTempSchema ){
97426 sqlite3 *db = pParse->db;
97427 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
97428 if( pTrig->pSchema==pTempSchema ){
97429 zWhere = whereOrName(db, zWhere, pTrig->zName);
97433 if( zWhere ){
97434 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
97435 sqlite3DbFree(pParse->db, zWhere);
97436 zWhere = zNew;
97438 return zWhere;
97442 ** Generate code to drop and reload the internal representation of table
97443 ** pTab from the database, including triggers and temporary triggers.
97444 ** Argument zName is the name of the table in the database schema at
97445 ** the time the generated code is executed. This can be different from
97446 ** pTab->zName if this function is being called to code part of an
97447 ** "ALTER TABLE RENAME TO" statement.
97449 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
97450 Vdbe *v;
97451 char *zWhere;
97452 int iDb; /* Index of database containing pTab */
97453 #ifndef SQLITE_OMIT_TRIGGER
97454 Trigger *pTrig;
97455 #endif
97457 v = sqlite3GetVdbe(pParse);
97458 if( NEVER(v==0) ) return;
97459 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
97460 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
97461 assert( iDb>=0 );
97463 #ifndef SQLITE_OMIT_TRIGGER
97464 /* Drop any table triggers from the internal schema. */
97465 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
97466 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
97467 assert( iTrigDb==iDb || iTrigDb==1 );
97468 sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
97470 #endif
97472 /* Drop the table and index from the internal schema. */
97473 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
97475 /* Reload the table, index and permanent trigger schemas. */
97476 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
97477 if( !zWhere ) return;
97478 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
97480 #ifndef SQLITE_OMIT_TRIGGER
97481 /* Now, if the table is not stored in the temp database, reload any temp
97482 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
97484 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
97485 sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
97487 #endif
97491 ** Parameter zName is the name of a table that is about to be altered
97492 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
97493 ** If the table is a system table, this function leaves an error message
97494 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
97496 ** Or, if zName is not a system table, zero is returned.
97498 static int isSystemTable(Parse *pParse, const char *zName){
97499 if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
97500 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
97501 return 1;
97503 return 0;
97507 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
97508 ** command.
97510 SQLITE_PRIVATE void sqlite3AlterRenameTable(
97511 Parse *pParse, /* Parser context. */
97512 SrcList *pSrc, /* The table to rename. */
97513 Token *pName /* The new table name. */
97515 int iDb; /* Database that contains the table */
97516 char *zDb; /* Name of database iDb */
97517 Table *pTab; /* Table being renamed */
97518 char *zName = 0; /* NULL-terminated version of pName */
97519 sqlite3 *db = pParse->db; /* Database connection */
97520 int nTabName; /* Number of UTF-8 characters in zTabName */
97521 const char *zTabName; /* Original name of the table */
97522 Vdbe *v;
97523 #ifndef SQLITE_OMIT_TRIGGER
97524 char *zWhere = 0; /* Where clause to locate temp triggers */
97525 #endif
97526 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
97527 u32 savedDbFlags; /* Saved value of db->mDbFlags */
97529 savedDbFlags = db->mDbFlags;
97530 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
97531 assert( pSrc->nSrc==1 );
97532 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
97534 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
97535 if( !pTab ) goto exit_rename_table;
97536 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
97537 zDb = db->aDb[iDb].zDbSName;
97538 db->mDbFlags |= DBFLAG_PreferBuiltin;
97540 /* Get a NULL terminated version of the new table name. */
97541 zName = sqlite3NameFromToken(db, pName);
97542 if( !zName ) goto exit_rename_table;
97544 /* Check that a table or index named 'zName' does not already exist
97545 ** in database iDb. If so, this is an error.
97547 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
97548 sqlite3ErrorMsg(pParse,
97549 "there is already another table or index with this name: %s", zName);
97550 goto exit_rename_table;
97553 /* Make sure it is not a system table being altered, or a reserved name
97554 ** that the table is being renamed to.
97556 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
97557 goto exit_rename_table;
97559 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
97560 exit_rename_table;
97563 #ifndef SQLITE_OMIT_VIEW
97564 if( pTab->pSelect ){
97565 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
97566 goto exit_rename_table;
97568 #endif
97570 #ifndef SQLITE_OMIT_AUTHORIZATION
97571 /* Invoke the authorization callback. */
97572 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
97573 goto exit_rename_table;
97575 #endif
97577 #ifndef SQLITE_OMIT_VIRTUALTABLE
97578 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
97579 goto exit_rename_table;
97581 if( IsVirtual(pTab) ){
97582 pVTab = sqlite3GetVTable(db, pTab);
97583 if( pVTab->pVtab->pModule->xRename==0 ){
97584 pVTab = 0;
97587 #endif
97589 /* Begin a transaction for database iDb.
97590 ** Then modify the schema cookie (since the ALTER TABLE modifies the
97591 ** schema). Open a statement transaction if the table is a virtual
97592 ** table.
97594 v = sqlite3GetVdbe(pParse);
97595 if( v==0 ){
97596 goto exit_rename_table;
97598 sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
97599 sqlite3ChangeCookie(pParse, iDb);
97601 /* If this is a virtual table, invoke the xRename() function if
97602 ** one is defined. The xRename() callback will modify the names
97603 ** of any resources used by the v-table implementation (including other
97604 ** SQLite tables) that are identified by the name of the virtual table.
97606 #ifndef SQLITE_OMIT_VIRTUALTABLE
97607 if( pVTab ){
97608 int i = ++pParse->nMem;
97609 sqlite3VdbeLoadString(v, i, zName);
97610 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
97611 sqlite3MayAbort(pParse);
97613 #endif
97615 /* figure out how many UTF-8 characters are in zName */
97616 zTabName = pTab->zName;
97617 nTabName = sqlite3Utf8CharLen(zTabName, -1);
97619 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
97620 if( db->flags&SQLITE_ForeignKeys ){
97621 /* If foreign-key support is enabled, rewrite the CREATE TABLE
97622 ** statements corresponding to all child tables of foreign key constraints
97623 ** for which the renamed table is the parent table. */
97624 if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
97625 sqlite3NestedParse(pParse,
97626 "UPDATE \"%w\".%s SET "
97627 "sql = sqlite_rename_parent(sql, %Q, %Q) "
97628 "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere);
97629 sqlite3DbFree(db, zWhere);
97632 #endif
97634 /* Modify the sqlite_master table to use the new table name. */
97635 sqlite3NestedParse(pParse,
97636 "UPDATE %Q.%s SET "
97637 #ifdef SQLITE_OMIT_TRIGGER
97638 "sql = sqlite_rename_table(sql, %Q), "
97639 #else
97640 "sql = CASE "
97641 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
97642 "ELSE sqlite_rename_table(sql, %Q) END, "
97643 #endif
97644 "tbl_name = %Q, "
97645 "name = CASE "
97646 "WHEN type='table' THEN %Q "
97647 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
97648 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
97649 "ELSE name END "
97650 "WHERE tbl_name=%Q COLLATE nocase AND "
97651 "(type='table' OR type='index' OR type='trigger');",
97652 zDb, MASTER_NAME, zName, zName, zName,
97653 #ifndef SQLITE_OMIT_TRIGGER
97654 zName,
97655 #endif
97656 zName, nTabName, zTabName
97659 #ifndef SQLITE_OMIT_AUTOINCREMENT
97660 /* If the sqlite_sequence table exists in this database, then update
97661 ** it with the new table name.
97663 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
97664 sqlite3NestedParse(pParse,
97665 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
97666 zDb, zName, pTab->zName);
97668 #endif
97670 #ifndef SQLITE_OMIT_TRIGGER
97671 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
97672 ** table. Don't do this if the table being ALTERed is itself located in
97673 ** the temp database.
97675 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
97676 sqlite3NestedParse(pParse,
97677 "UPDATE sqlite_temp_master SET "
97678 "sql = sqlite_rename_trigger(sql, %Q), "
97679 "tbl_name = %Q "
97680 "WHERE %s;", zName, zName, zWhere);
97681 sqlite3DbFree(db, zWhere);
97683 #endif
97685 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
97686 if( db->flags&SQLITE_ForeignKeys ){
97687 FKey *p;
97688 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
97689 Table *pFrom = p->pFrom;
97690 if( pFrom!=pTab ){
97691 reloadTableSchema(pParse, p->pFrom, pFrom->zName);
97695 #endif
97697 /* Drop and reload the internal table schema. */
97698 reloadTableSchema(pParse, pTab, zName);
97700 exit_rename_table:
97701 sqlite3SrcListDelete(db, pSrc);
97702 sqlite3DbFree(db, zName);
97703 db->mDbFlags = savedDbFlags;
97707 ** This function is called after an "ALTER TABLE ... ADD" statement
97708 ** has been parsed. Argument pColDef contains the text of the new
97709 ** column definition.
97711 ** The Table structure pParse->pNewTable was extended to include
97712 ** the new column during parsing.
97714 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
97715 Table *pNew; /* Copy of pParse->pNewTable */
97716 Table *pTab; /* Table being altered */
97717 int iDb; /* Database number */
97718 const char *zDb; /* Database name */
97719 const char *zTab; /* Table name */
97720 char *zCol; /* Null-terminated column definition */
97721 Column *pCol; /* The new column */
97722 Expr *pDflt; /* Default value for the new column */
97723 sqlite3 *db; /* The database connection; */
97724 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
97725 int r1; /* Temporary registers */
97727 db = pParse->db;
97728 if( pParse->nErr || db->mallocFailed ) return;
97729 assert( v!=0 );
97730 pNew = pParse->pNewTable;
97731 assert( pNew );
97733 assert( sqlite3BtreeHoldsAllMutexes(db) );
97734 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
97735 zDb = db->aDb[iDb].zDbSName;
97736 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
97737 pCol = &pNew->aCol[pNew->nCol-1];
97738 pDflt = pCol->pDflt;
97739 pTab = sqlite3FindTable(db, zTab, zDb);
97740 assert( pTab );
97742 #ifndef SQLITE_OMIT_AUTHORIZATION
97743 /* Invoke the authorization callback. */
97744 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
97745 return;
97747 #endif
97749 /* If the default value for the new column was specified with a
97750 ** literal NULL, then set pDflt to 0. This simplifies checking
97751 ** for an SQL NULL default below.
97753 assert( pDflt==0 || pDflt->op==TK_SPAN );
97754 if( pDflt && pDflt->pLeft->op==TK_NULL ){
97755 pDflt = 0;
97758 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
97759 ** If there is a NOT NULL constraint, then the default value for the
97760 ** column must not be NULL.
97762 if( pCol->colFlags & COLFLAG_PRIMKEY ){
97763 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
97764 return;
97766 if( pNew->pIndex ){
97767 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
97768 return;
97770 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
97771 sqlite3ErrorMsg(pParse,
97772 "Cannot add a REFERENCES column with non-NULL default value");
97773 return;
97775 if( pCol->notNull && !pDflt ){
97776 sqlite3ErrorMsg(pParse,
97777 "Cannot add a NOT NULL column with default value NULL");
97778 return;
97781 /* Ensure the default expression is something that sqlite3ValueFromExpr()
97782 ** can handle (i.e. not CURRENT_TIME etc.)
97784 if( pDflt ){
97785 sqlite3_value *pVal = 0;
97786 int rc;
97787 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
97788 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
97789 if( rc!=SQLITE_OK ){
97790 assert( db->mallocFailed == 1 );
97791 return;
97793 if( !pVal ){
97794 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
97795 return;
97797 sqlite3ValueFree(pVal);
97800 /* Modify the CREATE TABLE statement. */
97801 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
97802 if( zCol ){
97803 char *zEnd = &zCol[pColDef->n-1];
97804 u32 savedDbFlags = db->mDbFlags;
97805 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
97806 *zEnd-- = '\0';
97808 db->mDbFlags |= DBFLAG_PreferBuiltin;
97809 sqlite3NestedParse(pParse,
97810 "UPDATE \"%w\".%s SET "
97811 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
97812 "WHERE type = 'table' AND name = %Q",
97813 zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
97814 zTab
97816 sqlite3DbFree(db, zCol);
97817 db->mDbFlags = savedDbFlags;
97820 /* Make sure the schema version is at least 3. But do not upgrade
97821 ** from less than 3 to 4, as that will corrupt any preexisting DESC
97822 ** index.
97824 r1 = sqlite3GetTempReg(pParse);
97825 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
97826 sqlite3VdbeUsesBtree(v, iDb);
97827 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
97828 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
97829 VdbeCoverage(v);
97830 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
97831 sqlite3ReleaseTempReg(pParse, r1);
97833 /* Reload the schema of the modified table. */
97834 reloadTableSchema(pParse, pTab, pTab->zName);
97838 ** This function is called by the parser after the table-name in
97839 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
97840 ** pSrc is the full-name of the table being altered.
97842 ** This routine makes a (partial) copy of the Table structure
97843 ** for the table being altered and sets Parse.pNewTable to point
97844 ** to it. Routines called by the parser as the column definition
97845 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
97846 ** the copy. The copy of the Table structure is deleted by tokenize.c
97847 ** after parsing is finished.
97849 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
97850 ** coding the "ALTER TABLE ... ADD" statement.
97852 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
97853 Table *pNew;
97854 Table *pTab;
97855 Vdbe *v;
97856 int iDb;
97857 int i;
97858 int nAlloc;
97859 sqlite3 *db = pParse->db;
97861 /* Look up the table being altered. */
97862 assert( pParse->pNewTable==0 );
97863 assert( sqlite3BtreeHoldsAllMutexes(db) );
97864 if( db->mallocFailed ) goto exit_begin_add_column;
97865 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
97866 if( !pTab ) goto exit_begin_add_column;
97868 #ifndef SQLITE_OMIT_VIRTUALTABLE
97869 if( IsVirtual(pTab) ){
97870 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
97871 goto exit_begin_add_column;
97873 #endif
97875 /* Make sure this is not an attempt to ALTER a view. */
97876 if( pTab->pSelect ){
97877 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
97878 goto exit_begin_add_column;
97880 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
97881 goto exit_begin_add_column;
97884 assert( pTab->addColOffset>0 );
97885 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97887 /* Put a copy of the Table struct in Parse.pNewTable for the
97888 ** sqlite3AddColumn() function and friends to modify. But modify
97889 ** the name by adding an "sqlite_altertab_" prefix. By adding this
97890 ** prefix, we insure that the name will not collide with an existing
97891 ** table because user table are not allowed to have the "sqlite_"
97892 ** prefix on their name.
97894 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
97895 if( !pNew ) goto exit_begin_add_column;
97896 pParse->pNewTable = pNew;
97897 pNew->nTabRef = 1;
97898 pNew->nCol = pTab->nCol;
97899 assert( pNew->nCol>0 );
97900 nAlloc = (((pNew->nCol-1)/8)*8)+8;
97901 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
97902 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
97903 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
97904 if( !pNew->aCol || !pNew->zName ){
97905 assert( db->mallocFailed );
97906 goto exit_begin_add_column;
97908 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
97909 for(i=0; i<pNew->nCol; i++){
97910 Column *pCol = &pNew->aCol[i];
97911 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
97912 pCol->zColl = 0;
97913 pCol->pDflt = 0;
97915 pNew->pSchema = db->aDb[iDb].pSchema;
97916 pNew->addColOffset = pTab->addColOffset;
97917 pNew->nTabRef = 1;
97919 /* Begin a transaction and increment the schema cookie. */
97920 sqlite3BeginWriteOperation(pParse, 0, iDb);
97921 v = sqlite3GetVdbe(pParse);
97922 if( !v ) goto exit_begin_add_column;
97923 sqlite3ChangeCookie(pParse, iDb);
97925 exit_begin_add_column:
97926 sqlite3SrcListDelete(db, pSrc);
97927 return;
97929 #endif /* SQLITE_ALTER_TABLE */
97931 /************** End of alter.c ***********************************************/
97932 /************** Begin file analyze.c *****************************************/
97934 ** 2005-07-08
97936 ** The author disclaims copyright to this source code. In place of
97937 ** a legal notice, here is a blessing:
97939 ** May you do good and not evil.
97940 ** May you find forgiveness for yourself and forgive others.
97941 ** May you share freely, never taking more than you give.
97943 *************************************************************************
97944 ** This file contains code associated with the ANALYZE command.
97946 ** The ANALYZE command gather statistics about the content of tables
97947 ** and indices. These statistics are made available to the query planner
97948 ** to help it make better decisions about how to perform queries.
97950 ** The following system tables are or have been supported:
97952 ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
97953 ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
97954 ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
97955 ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
97957 ** Additional tables might be added in future releases of SQLite.
97958 ** The sqlite_stat2 table is not created or used unless the SQLite version
97959 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
97960 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
97961 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
97962 ** created and used by SQLite versions 3.7.9 and later and with
97963 ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
97964 ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
97965 ** version of sqlite_stat3 and is only available when compiled with
97966 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
97967 ** not possible to enable both STAT3 and STAT4 at the same time. If they
97968 ** are both enabled, then STAT4 takes precedence.
97970 ** For most applications, sqlite_stat1 provides all the statistics required
97971 ** for the query planner to make good choices.
97973 ** Format of sqlite_stat1:
97975 ** There is normally one row per index, with the index identified by the
97976 ** name in the idx column. The tbl column is the name of the table to
97977 ** which the index belongs. In each such row, the stat column will be
97978 ** a string consisting of a list of integers. The first integer in this
97979 ** list is the number of rows in the index. (This is the same as the
97980 ** number of rows in the table, except for partial indices.) The second
97981 ** integer is the average number of rows in the index that have the same
97982 ** value in the first column of the index. The third integer is the average
97983 ** number of rows in the index that have the same value for the first two
97984 ** columns. The N-th integer (for N>1) is the average number of rows in
97985 ** the index which have the same value for the first N-1 columns. For
97986 ** a K-column index, there will be K+1 integers in the stat column. If
97987 ** the index is unique, then the last integer will be 1.
97989 ** The list of integers in the stat column can optionally be followed
97990 ** by the keyword "unordered". The "unordered" keyword, if it is present,
97991 ** must be separated from the last integer by a single space. If the
97992 ** "unordered" keyword is present, then the query planner assumes that
97993 ** the index is unordered and will not use the index for a range query.
97995 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
97996 ** column contains a single integer which is the (estimated) number of
97997 ** rows in the table identified by sqlite_stat1.tbl.
97999 ** Format of sqlite_stat2:
98001 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
98002 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
98003 ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
98004 ** about the distribution of keys within an index. The index is identified by
98005 ** the "idx" column and the "tbl" column is the name of the table to which
98006 ** the index belongs. There are usually 10 rows in the sqlite_stat2
98007 ** table for each index.
98009 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
98010 ** inclusive are samples of the left-most key value in the index taken at
98011 ** evenly spaced points along the index. Let the number of samples be S
98012 ** (10 in the standard build) and let C be the number of rows in the index.
98013 ** Then the sampled rows are given by:
98015 ** rownumber = (i*C*2 + C)/(S*2)
98017 ** For i between 0 and S-1. Conceptually, the index space is divided into
98018 ** S uniform buckets and the samples are the middle row from each bucket.
98020 ** The format for sqlite_stat2 is recorded here for legacy reference. This
98021 ** version of SQLite does not support sqlite_stat2. It neither reads nor
98022 ** writes the sqlite_stat2 table. This version of SQLite only supports
98023 ** sqlite_stat3.
98025 ** Format for sqlite_stat3:
98027 ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
98028 ** sqlite_stat4 format will be described first. Further information
98029 ** about sqlite_stat3 follows the sqlite_stat4 description.
98031 ** Format for sqlite_stat4:
98033 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
98034 ** to aid the query planner in choosing good indices based on the values
98035 ** that indexed columns are compared against in the WHERE clauses of
98036 ** queries.
98038 ** The sqlite_stat4 table contains multiple entries for each index.
98039 ** The idx column names the index and the tbl column is the table of the
98040 ** index. If the idx and tbl columns are the same, then the sample is
98041 ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
98042 ** binary encoding of a key from the index. The nEq column is a
98043 ** list of integers. The first integer is the approximate number
98044 ** of entries in the index whose left-most column exactly matches
98045 ** the left-most column of the sample. The second integer in nEq
98046 ** is the approximate number of entries in the index where the
98047 ** first two columns match the first two columns of the sample.
98048 ** And so forth. nLt is another list of integers that show the approximate
98049 ** number of entries that are strictly less than the sample. The first
98050 ** integer in nLt contains the number of entries in the index where the
98051 ** left-most column is less than the left-most column of the sample.
98052 ** The K-th integer in the nLt entry is the number of index entries
98053 ** where the first K columns are less than the first K columns of the
98054 ** sample. The nDLt column is like nLt except that it contains the
98055 ** number of distinct entries in the index that are less than the
98056 ** sample.
98058 ** There can be an arbitrary number of sqlite_stat4 entries per index.
98059 ** The ANALYZE command will typically generate sqlite_stat4 tables
98060 ** that contain between 10 and 40 samples which are distributed across
98061 ** the key space, though not uniformly, and which include samples with
98062 ** large nEq values.
98064 ** Format for sqlite_stat3 redux:
98066 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
98067 ** looks at the left-most column of the index. The sqlite_stat3.sample
98068 ** column contains the actual value of the left-most column instead
98069 ** of a blob encoding of the complete index key as is found in
98070 ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
98071 ** all contain just a single integer which is the same as the first
98072 ** integer in the equivalent columns in sqlite_stat4.
98074 #ifndef SQLITE_OMIT_ANALYZE
98075 /* #include "sqliteInt.h" */
98077 #if defined(SQLITE_ENABLE_STAT4)
98078 # define IsStat4 1
98079 # define IsStat3 0
98080 #elif defined(SQLITE_ENABLE_STAT3)
98081 # define IsStat4 0
98082 # define IsStat3 1
98083 #else
98084 # define IsStat4 0
98085 # define IsStat3 0
98086 # undef SQLITE_STAT4_SAMPLES
98087 # define SQLITE_STAT4_SAMPLES 1
98088 #endif
98089 #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
98092 ** This routine generates code that opens the sqlite_statN tables.
98093 ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
98094 ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
98095 ** appropriate compile-time options are provided.
98097 ** If the sqlite_statN tables do not previously exist, it is created.
98099 ** Argument zWhere may be a pointer to a buffer containing a table name,
98100 ** or it may be a NULL pointer. If it is not NULL, then all entries in
98101 ** the sqlite_statN tables associated with the named table are deleted.
98102 ** If zWhere==0, then code is generated to delete all stat table entries.
98104 static void openStatTable(
98105 Parse *pParse, /* Parsing context */
98106 int iDb, /* The database we are looking in */
98107 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
98108 const char *zWhere, /* Delete entries for this table or index */
98109 const char *zWhereType /* Either "tbl" or "idx" */
98111 static const struct {
98112 const char *zName;
98113 const char *zCols;
98114 } aTable[] = {
98115 { "sqlite_stat1", "tbl,idx,stat" },
98116 #if defined(SQLITE_ENABLE_STAT4)
98117 { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
98118 { "sqlite_stat3", 0 },
98119 #elif defined(SQLITE_ENABLE_STAT3)
98120 { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
98121 { "sqlite_stat4", 0 },
98122 #else
98123 { "sqlite_stat3", 0 },
98124 { "sqlite_stat4", 0 },
98125 #endif
98127 int i;
98128 sqlite3 *db = pParse->db;
98129 Db *pDb;
98130 Vdbe *v = sqlite3GetVdbe(pParse);
98131 int aRoot[ArraySize(aTable)];
98132 u8 aCreateTbl[ArraySize(aTable)];
98134 if( v==0 ) return;
98135 assert( sqlite3BtreeHoldsAllMutexes(db) );
98136 assert( sqlite3VdbeDb(v)==db );
98137 pDb = &db->aDb[iDb];
98139 /* Create new statistic tables if they do not exist, or clear them
98140 ** if they do already exist.
98142 for(i=0; i<ArraySize(aTable); i++){
98143 const char *zTab = aTable[i].zName;
98144 Table *pStat;
98145 if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
98146 if( aTable[i].zCols ){
98147 /* The sqlite_statN table does not exist. Create it. Note that a
98148 ** side-effect of the CREATE TABLE statement is to leave the rootpage
98149 ** of the new table in register pParse->regRoot. This is important
98150 ** because the OpenWrite opcode below will be needing it. */
98151 sqlite3NestedParse(pParse,
98152 "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
98154 aRoot[i] = pParse->regRoot;
98155 aCreateTbl[i] = OPFLAG_P2ISREG;
98157 }else{
98158 /* The table already exists. If zWhere is not NULL, delete all entries
98159 ** associated with the table zWhere. If zWhere is NULL, delete the
98160 ** entire contents of the table. */
98161 aRoot[i] = pStat->tnum;
98162 aCreateTbl[i] = 0;
98163 sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
98164 if( zWhere ){
98165 sqlite3NestedParse(pParse,
98166 "DELETE FROM %Q.%s WHERE %s=%Q",
98167 pDb->zDbSName, zTab, zWhereType, zWhere
98169 }else{
98170 /* The sqlite_stat[134] table already exists. Delete all rows. */
98171 sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
98176 /* Open the sqlite_stat[134] tables for writing. */
98177 for(i=0; aTable[i].zCols; i++){
98178 assert( i<ArraySize(aTable) );
98179 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
98180 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
98181 VdbeComment((v, aTable[i].zName));
98186 ** Recommended number of samples for sqlite_stat4
98188 #ifndef SQLITE_STAT4_SAMPLES
98189 # define SQLITE_STAT4_SAMPLES 24
98190 #endif
98193 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
98194 ** share an instance of the following structure to hold their state
98195 ** information.
98197 typedef struct Stat4Accum Stat4Accum;
98198 typedef struct Stat4Sample Stat4Sample;
98199 struct Stat4Sample {
98200 tRowcnt *anEq; /* sqlite_stat4.nEq */
98201 tRowcnt *anDLt; /* sqlite_stat4.nDLt */
98202 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98203 tRowcnt *anLt; /* sqlite_stat4.nLt */
98204 union {
98205 i64 iRowid; /* Rowid in main table of the key */
98206 u8 *aRowid; /* Key for WITHOUT ROWID tables */
98207 } u;
98208 u32 nRowid; /* Sizeof aRowid[] */
98209 u8 isPSample; /* True if a periodic sample */
98210 int iCol; /* If !isPSample, the reason for inclusion */
98211 u32 iHash; /* Tiebreaker hash */
98212 #endif
98214 struct Stat4Accum {
98215 tRowcnt nRow; /* Number of rows in the entire table */
98216 tRowcnt nPSample; /* How often to do a periodic sample */
98217 int nCol; /* Number of columns in index + pk/rowid */
98218 int nKeyCol; /* Number of index columns w/o the pk/rowid */
98219 int mxSample; /* Maximum number of samples to accumulate */
98220 Stat4Sample current; /* Current row as a Stat4Sample */
98221 u32 iPrn; /* Pseudo-random number used for sampling */
98222 Stat4Sample *aBest; /* Array of nCol best samples */
98223 int iMin; /* Index in a[] of entry with minimum score */
98224 int nSample; /* Current number of samples */
98225 int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
98226 int iGet; /* Index of current sample accessed by stat_get() */
98227 Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
98228 sqlite3 *db; /* Database connection, for malloc() */
98231 /* Reclaim memory used by a Stat4Sample
98233 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98234 static void sampleClear(sqlite3 *db, Stat4Sample *p){
98235 assert( db!=0 );
98236 if( p->nRowid ){
98237 sqlite3DbFree(db, p->u.aRowid);
98238 p->nRowid = 0;
98241 #endif
98243 /* Initialize the BLOB value of a ROWID
98245 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98246 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
98247 assert( db!=0 );
98248 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
98249 p->u.aRowid = sqlite3DbMallocRawNN(db, n);
98250 if( p->u.aRowid ){
98251 p->nRowid = n;
98252 memcpy(p->u.aRowid, pData, n);
98253 }else{
98254 p->nRowid = 0;
98257 #endif
98259 /* Initialize the INTEGER value of a ROWID.
98261 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98262 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
98263 assert( db!=0 );
98264 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
98265 p->nRowid = 0;
98266 p->u.iRowid = iRowid;
98268 #endif
98272 ** Copy the contents of object (*pFrom) into (*pTo).
98274 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98275 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
98276 pTo->isPSample = pFrom->isPSample;
98277 pTo->iCol = pFrom->iCol;
98278 pTo->iHash = pFrom->iHash;
98279 memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
98280 memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
98281 memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
98282 if( pFrom->nRowid ){
98283 sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
98284 }else{
98285 sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
98288 #endif
98291 ** Reclaim all memory of a Stat4Accum structure.
98293 static void stat4Destructor(void *pOld){
98294 Stat4Accum *p = (Stat4Accum*)pOld;
98295 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98296 int i;
98297 for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
98298 for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
98299 sampleClear(p->db, &p->current);
98300 #endif
98301 sqlite3DbFree(p->db, p);
98305 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
98306 ** are:
98307 ** N: The number of columns in the index including the rowid/pk (note 1)
98308 ** K: The number of columns in the index excluding the rowid/pk.
98309 ** C: The number of rows in the index (note 2)
98311 ** Note 1: In the special case of the covering index that implements a
98312 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
98313 ** total number of columns in the table.
98315 ** Note 2: C is only used for STAT3 and STAT4.
98317 ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
98318 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
98319 ** PRIMARY KEY of the table. The covering index that implements the
98320 ** original WITHOUT ROWID table as N==K as a special case.
98322 ** This routine allocates the Stat4Accum object in heap memory. The return
98323 ** value is a pointer to the Stat4Accum object. The datatype of the
98324 ** return value is BLOB, but it is really just a pointer to the Stat4Accum
98325 ** object.
98327 static void statInit(
98328 sqlite3_context *context,
98329 int argc,
98330 sqlite3_value **argv
98332 Stat4Accum *p;
98333 int nCol; /* Number of columns in index being sampled */
98334 int nKeyCol; /* Number of key columns */
98335 int nColUp; /* nCol rounded up for alignment */
98336 int n; /* Bytes of space to allocate */
98337 sqlite3 *db; /* Database connection */
98338 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98339 int mxSample = SQLITE_STAT4_SAMPLES;
98340 #endif
98342 /* Decode the three function arguments */
98343 UNUSED_PARAMETER(argc);
98344 nCol = sqlite3_value_int(argv[0]);
98345 assert( nCol>0 );
98346 nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
98347 nKeyCol = sqlite3_value_int(argv[1]);
98348 assert( nKeyCol<=nCol );
98349 assert( nKeyCol>0 );
98351 /* Allocate the space required for the Stat4Accum object */
98352 n = sizeof(*p)
98353 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
98354 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
98355 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98356 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
98357 + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
98358 + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
98359 #endif
98361 db = sqlite3_context_db_handle(context);
98362 p = sqlite3DbMallocZero(db, n);
98363 if( p==0 ){
98364 sqlite3_result_error_nomem(context);
98365 return;
98368 p->db = db;
98369 p->nRow = 0;
98370 p->nCol = nCol;
98371 p->nKeyCol = nKeyCol;
98372 p->current.anDLt = (tRowcnt*)&p[1];
98373 p->current.anEq = &p->current.anDLt[nColUp];
98375 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98377 u8 *pSpace; /* Allocated space not yet assigned */
98378 int i; /* Used to iterate through p->aSample[] */
98380 p->iGet = -1;
98381 p->mxSample = mxSample;
98382 p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
98383 p->current.anLt = &p->current.anEq[nColUp];
98384 p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
98386 /* Set up the Stat4Accum.a[] and aBest[] arrays */
98387 p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
98388 p->aBest = &p->a[mxSample];
98389 pSpace = (u8*)(&p->a[mxSample+nCol]);
98390 for(i=0; i<(mxSample+nCol); i++){
98391 p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
98392 p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
98393 p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
98395 assert( (pSpace - (u8*)p)==n );
98397 for(i=0; i<nCol; i++){
98398 p->aBest[i].iCol = i;
98401 #endif
98403 /* Return a pointer to the allocated object to the caller. Note that
98404 ** only the pointer (the 2nd parameter) matters. The size of the object
98405 ** (given by the 3rd parameter) is never used and can be any positive
98406 ** value. */
98407 sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
98409 static const FuncDef statInitFuncdef = {
98410 2+IsStat34, /* nArg */
98411 SQLITE_UTF8, /* funcFlags */
98412 0, /* pUserData */
98413 0, /* pNext */
98414 statInit, /* xSFunc */
98415 0, /* xFinalize */
98416 "stat_init", /* zName */
98420 #ifdef SQLITE_ENABLE_STAT4
98422 ** pNew and pOld are both candidate non-periodic samples selected for
98423 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
98424 ** considering only any trailing columns and the sample hash value, this
98425 ** function returns true if sample pNew is to be preferred over pOld.
98426 ** In other words, if we assume that the cardinalities of the selected
98427 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
98429 ** This function assumes that for each argument sample, the contents of
98430 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
98432 static int sampleIsBetterPost(
98433 Stat4Accum *pAccum,
98434 Stat4Sample *pNew,
98435 Stat4Sample *pOld
98437 int nCol = pAccum->nCol;
98438 int i;
98439 assert( pNew->iCol==pOld->iCol );
98440 for(i=pNew->iCol+1; i<nCol; i++){
98441 if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
98442 if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
98444 if( pNew->iHash>pOld->iHash ) return 1;
98445 return 0;
98447 #endif
98449 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98451 ** Return true if pNew is to be preferred over pOld.
98453 ** This function assumes that for each argument sample, the contents of
98454 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
98456 static int sampleIsBetter(
98457 Stat4Accum *pAccum,
98458 Stat4Sample *pNew,
98459 Stat4Sample *pOld
98461 tRowcnt nEqNew = pNew->anEq[pNew->iCol];
98462 tRowcnt nEqOld = pOld->anEq[pOld->iCol];
98464 assert( pOld->isPSample==0 && pNew->isPSample==0 );
98465 assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
98467 if( (nEqNew>nEqOld) ) return 1;
98468 #ifdef SQLITE_ENABLE_STAT4
98469 if( nEqNew==nEqOld ){
98470 if( pNew->iCol<pOld->iCol ) return 1;
98471 return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
98473 return 0;
98474 #else
98475 return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
98476 #endif
98480 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
98481 ** remove the least desirable sample from p->a[] to make room.
98483 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
98484 Stat4Sample *pSample = 0;
98485 int i;
98487 assert( IsStat4 || nEqZero==0 );
98489 #ifdef SQLITE_ENABLE_STAT4
98490 /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
98491 ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
98492 ** other words, if nMaxEqZero is n, then it is guaranteed that there
98493 ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
98494 if( nEqZero>p->nMaxEqZero ){
98495 p->nMaxEqZero = nEqZero;
98497 if( pNew->isPSample==0 ){
98498 Stat4Sample *pUpgrade = 0;
98499 assert( pNew->anEq[pNew->iCol]>0 );
98501 /* This sample is being added because the prefix that ends in column
98502 ** iCol occurs many times in the table. However, if we have already
98503 ** added a sample that shares this prefix, there is no need to add
98504 ** this one. Instead, upgrade the priority of the highest priority
98505 ** existing sample that shares this prefix. */
98506 for(i=p->nSample-1; i>=0; i--){
98507 Stat4Sample *pOld = &p->a[i];
98508 if( pOld->anEq[pNew->iCol]==0 ){
98509 if( pOld->isPSample ) return;
98510 assert( pOld->iCol>pNew->iCol );
98511 assert( sampleIsBetter(p, pNew, pOld) );
98512 if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
98513 pUpgrade = pOld;
98517 if( pUpgrade ){
98518 pUpgrade->iCol = pNew->iCol;
98519 pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
98520 goto find_new_min;
98523 #endif
98525 /* If necessary, remove sample iMin to make room for the new sample. */
98526 if( p->nSample>=p->mxSample ){
98527 Stat4Sample *pMin = &p->a[p->iMin];
98528 tRowcnt *anEq = pMin->anEq;
98529 tRowcnt *anLt = pMin->anLt;
98530 tRowcnt *anDLt = pMin->anDLt;
98531 sampleClear(p->db, pMin);
98532 memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
98533 pSample = &p->a[p->nSample-1];
98534 pSample->nRowid = 0;
98535 pSample->anEq = anEq;
98536 pSample->anDLt = anDLt;
98537 pSample->anLt = anLt;
98538 p->nSample = p->mxSample-1;
98541 /* The "rows less-than" for the rowid column must be greater than that
98542 ** for the last sample in the p->a[] array. Otherwise, the samples would
98543 ** be out of order. */
98544 #ifdef SQLITE_ENABLE_STAT4
98545 assert( p->nSample==0
98546 || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
98547 #endif
98549 /* Insert the new sample */
98550 pSample = &p->a[p->nSample];
98551 sampleCopy(p, pSample, pNew);
98552 p->nSample++;
98554 /* Zero the first nEqZero entries in the anEq[] array. */
98555 memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
98557 #ifdef SQLITE_ENABLE_STAT4
98558 find_new_min:
98559 #endif
98560 if( p->nSample>=p->mxSample ){
98561 int iMin = -1;
98562 for(i=0; i<p->mxSample; i++){
98563 if( p->a[i].isPSample ) continue;
98564 if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
98565 iMin = i;
98568 assert( iMin>=0 );
98569 p->iMin = iMin;
98572 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
98575 ** Field iChng of the index being scanned has changed. So at this point
98576 ** p->current contains a sample that reflects the previous row of the
98577 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
98578 ** correct at this point.
98580 static void samplePushPrevious(Stat4Accum *p, int iChng){
98581 #ifdef SQLITE_ENABLE_STAT4
98582 int i;
98584 /* Check if any samples from the aBest[] array should be pushed
98585 ** into IndexSample.a[] at this point. */
98586 for(i=(p->nCol-2); i>=iChng; i--){
98587 Stat4Sample *pBest = &p->aBest[i];
98588 pBest->anEq[i] = p->current.anEq[i];
98589 if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
98590 sampleInsert(p, pBest, i);
98594 /* Check that no sample contains an anEq[] entry with an index of
98595 ** p->nMaxEqZero or greater set to zero. */
98596 for(i=p->nSample-1; i>=0; i--){
98597 int j;
98598 for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
98601 /* Update the anEq[] fields of any samples already collected. */
98602 if( iChng<p->nMaxEqZero ){
98603 for(i=p->nSample-1; i>=0; i--){
98604 int j;
98605 for(j=iChng; j<p->nCol; j++){
98606 if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
98609 p->nMaxEqZero = iChng;
98611 #endif
98613 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
98614 if( iChng==0 ){
98615 tRowcnt nLt = p->current.anLt[0];
98616 tRowcnt nEq = p->current.anEq[0];
98618 /* Check if this is to be a periodic sample. If so, add it. */
98619 if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
98620 p->current.isPSample = 1;
98621 sampleInsert(p, &p->current, 0);
98622 p->current.isPSample = 0;
98623 }else
98625 /* Or if it is a non-periodic sample. Add it in this case too. */
98626 if( p->nSample<p->mxSample
98627 || sampleIsBetter(p, &p->current, &p->a[p->iMin])
98629 sampleInsert(p, &p->current, 0);
98632 #endif
98634 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
98635 UNUSED_PARAMETER( p );
98636 UNUSED_PARAMETER( iChng );
98637 #endif
98641 ** Implementation of the stat_push SQL function: stat_push(P,C,R)
98642 ** Arguments:
98644 ** P Pointer to the Stat4Accum object created by stat_init()
98645 ** C Index of left-most column to differ from previous row
98646 ** R Rowid for the current row. Might be a key record for
98647 ** WITHOUT ROWID tables.
98649 ** This SQL function always returns NULL. It's purpose it to accumulate
98650 ** statistical data and/or samples in the Stat4Accum object about the
98651 ** index being analyzed. The stat_get() SQL function will later be used to
98652 ** extract relevant information for constructing the sqlite_statN tables.
98654 ** The R parameter is only used for STAT3 and STAT4
98656 static void statPush(
98657 sqlite3_context *context,
98658 int argc,
98659 sqlite3_value **argv
98661 int i;
98663 /* The three function arguments */
98664 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
98665 int iChng = sqlite3_value_int(argv[1]);
98667 UNUSED_PARAMETER( argc );
98668 UNUSED_PARAMETER( context );
98669 assert( p->nCol>0 );
98670 assert( iChng<p->nCol );
98672 if( p->nRow==0 ){
98673 /* This is the first call to this function. Do initialization. */
98674 for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
98675 }else{
98676 /* Second and subsequent calls get processed here */
98677 samplePushPrevious(p, iChng);
98679 /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
98680 ** to the current row of the index. */
98681 for(i=0; i<iChng; i++){
98682 p->current.anEq[i]++;
98684 for(i=iChng; i<p->nCol; i++){
98685 p->current.anDLt[i]++;
98686 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98687 p->current.anLt[i] += p->current.anEq[i];
98688 #endif
98689 p->current.anEq[i] = 1;
98692 p->nRow++;
98693 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98694 if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
98695 sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
98696 }else{
98697 sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
98698 sqlite3_value_blob(argv[2]));
98700 p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
98701 #endif
98703 #ifdef SQLITE_ENABLE_STAT4
98705 tRowcnt nLt = p->current.anLt[p->nCol-1];
98707 /* Check if this is to be a periodic sample. If so, add it. */
98708 if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
98709 p->current.isPSample = 1;
98710 p->current.iCol = 0;
98711 sampleInsert(p, &p->current, p->nCol-1);
98712 p->current.isPSample = 0;
98715 /* Update the aBest[] array. */
98716 for(i=0; i<(p->nCol-1); i++){
98717 p->current.iCol = i;
98718 if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
98719 sampleCopy(p, &p->aBest[i], &p->current);
98723 #endif
98725 static const FuncDef statPushFuncdef = {
98726 2+IsStat34, /* nArg */
98727 SQLITE_UTF8, /* funcFlags */
98728 0, /* pUserData */
98729 0, /* pNext */
98730 statPush, /* xSFunc */
98731 0, /* xFinalize */
98732 "stat_push", /* zName */
98736 #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
98737 #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
98738 #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
98739 #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
98740 #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
98743 ** Implementation of the stat_get(P,J) SQL function. This routine is
98744 ** used to query statistical information that has been gathered into
98745 ** the Stat4Accum object by prior calls to stat_push(). The P parameter
98746 ** has type BLOB but it is really just a pointer to the Stat4Accum object.
98747 ** The content to returned is determined by the parameter J
98748 ** which is one of the STAT_GET_xxxx values defined above.
98750 ** The stat_get(P,J) function is not available to generic SQL. It is
98751 ** inserted as part of a manually constructed bytecode program. (See
98752 ** the callStatGet() routine below.) It is guaranteed that the P
98753 ** parameter will always be a poiner to a Stat4Accum object, never a
98754 ** NULL.
98756 ** If neither STAT3 nor STAT4 are enabled, then J is always
98757 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
98758 ** a one-parameter function, stat_get(P), that always returns the
98759 ** stat1 table entry information.
98761 static void statGet(
98762 sqlite3_context *context,
98763 int argc,
98764 sqlite3_value **argv
98766 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
98767 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98768 /* STAT3 and STAT4 have a parameter on this routine. */
98769 int eCall = sqlite3_value_int(argv[1]);
98770 assert( argc==2 );
98771 assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
98772 || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
98773 || eCall==STAT_GET_NDLT
98775 if( eCall==STAT_GET_STAT1 )
98776 #else
98777 assert( argc==1 );
98778 #endif
98780 /* Return the value to store in the "stat" column of the sqlite_stat1
98781 ** table for this index.
98783 ** The value is a string composed of a list of integers describing
98784 ** the index. The first integer in the list is the total number of
98785 ** entries in the index. There is one additional integer in the list
98786 ** for each indexed column. This additional integer is an estimate of
98787 ** the number of rows matched by a stabbing query on the index using
98788 ** a key with the corresponding number of fields. In other words,
98789 ** if the index is on columns (a,b) and the sqlite_stat1 value is
98790 ** "100 10 2", then SQLite estimates that:
98792 ** * the index contains 100 rows,
98793 ** * "WHERE a=?" matches 10 rows, and
98794 ** * "WHERE a=? AND b=?" matches 2 rows.
98796 ** If D is the count of distinct values and K is the total number of
98797 ** rows, then each estimate is computed as:
98799 ** I = (K+D-1)/D
98801 char *z;
98802 int i;
98804 char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
98805 if( zRet==0 ){
98806 sqlite3_result_error_nomem(context);
98807 return;
98810 sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
98811 z = zRet + sqlite3Strlen30(zRet);
98812 for(i=0; i<p->nKeyCol; i++){
98813 u64 nDistinct = p->current.anDLt[i] + 1;
98814 u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
98815 sqlite3_snprintf(24, z, " %llu", iVal);
98816 z += sqlite3Strlen30(z);
98817 assert( p->current.anEq[i] );
98819 assert( z[0]=='\0' && z>zRet );
98821 sqlite3_result_text(context, zRet, -1, sqlite3_free);
98823 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98824 else if( eCall==STAT_GET_ROWID ){
98825 if( p->iGet<0 ){
98826 samplePushPrevious(p, 0);
98827 p->iGet = 0;
98829 if( p->iGet<p->nSample ){
98830 Stat4Sample *pS = p->a + p->iGet;
98831 if( pS->nRowid==0 ){
98832 sqlite3_result_int64(context, pS->u.iRowid);
98833 }else{
98834 sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
98835 SQLITE_TRANSIENT);
98838 }else{
98839 tRowcnt *aCnt = 0;
98841 assert( p->iGet<p->nSample );
98842 switch( eCall ){
98843 case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
98844 case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
98845 default: {
98846 aCnt = p->a[p->iGet].anDLt;
98847 p->iGet++;
98848 break;
98852 if( IsStat3 ){
98853 sqlite3_result_int64(context, (i64)aCnt[0]);
98854 }else{
98855 char *zRet = sqlite3MallocZero(p->nCol * 25);
98856 if( zRet==0 ){
98857 sqlite3_result_error_nomem(context);
98858 }else{
98859 int i;
98860 char *z = zRet;
98861 for(i=0; i<p->nCol; i++){
98862 sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
98863 z += sqlite3Strlen30(z);
98865 assert( z[0]=='\0' && z>zRet );
98866 z[-1] = '\0';
98867 sqlite3_result_text(context, zRet, -1, sqlite3_free);
98871 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
98872 #ifndef SQLITE_DEBUG
98873 UNUSED_PARAMETER( argc );
98874 #endif
98876 static const FuncDef statGetFuncdef = {
98877 1+IsStat34, /* nArg */
98878 SQLITE_UTF8, /* funcFlags */
98879 0, /* pUserData */
98880 0, /* pNext */
98881 statGet, /* xSFunc */
98882 0, /* xFinalize */
98883 "stat_get", /* zName */
98887 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
98888 assert( regOut!=regStat4 && regOut!=regStat4+1 );
98889 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98890 sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
98891 #elif SQLITE_DEBUG
98892 assert( iParam==STAT_GET_STAT1 );
98893 #else
98894 UNUSED_PARAMETER( iParam );
98895 #endif
98896 sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
98897 (char*)&statGetFuncdef, P4_FUNCDEF);
98898 sqlite3VdbeChangeP5(v, 1 + IsStat34);
98902 ** Generate code to do an analysis of all indices associated with
98903 ** a single table.
98905 static void analyzeOneTable(
98906 Parse *pParse, /* Parser context */
98907 Table *pTab, /* Table whose indices are to be analyzed */
98908 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
98909 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
98910 int iMem, /* Available memory locations begin here */
98911 int iTab /* Next available cursor */
98913 sqlite3 *db = pParse->db; /* Database handle */
98914 Index *pIdx; /* An index to being analyzed */
98915 int iIdxCur; /* Cursor open on index being analyzed */
98916 int iTabCur; /* Table cursor */
98917 Vdbe *v; /* The virtual machine being built up */
98918 int i; /* Loop counter */
98919 int jZeroRows = -1; /* Jump from here if number of rows is zero */
98920 int iDb; /* Index of database containing pTab */
98921 u8 needTableCnt = 1; /* True to count the table */
98922 int regNewRowid = iMem++; /* Rowid for the inserted record */
98923 int regStat4 = iMem++; /* Register to hold Stat4Accum object */
98924 int regChng = iMem++; /* Index of changed index field */
98925 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98926 int regRowid = iMem++; /* Rowid argument passed to stat_push() */
98927 #endif
98928 int regTemp = iMem++; /* Temporary use register */
98929 int regTabname = iMem++; /* Register containing table name */
98930 int regIdxname = iMem++; /* Register containing index name */
98931 int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
98932 int regPrev = iMem; /* MUST BE LAST (see below) */
98934 pParse->nMem = MAX(pParse->nMem, iMem);
98935 v = sqlite3GetVdbe(pParse);
98936 if( v==0 || NEVER(pTab==0) ){
98937 return;
98939 if( pTab->tnum==0 ){
98940 /* Do not gather statistics on views or virtual tables */
98941 return;
98943 if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
98944 /* Do not gather statistics on system tables */
98945 return;
98947 assert( sqlite3BtreeHoldsAllMutexes(db) );
98948 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
98949 assert( iDb>=0 );
98950 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98951 #ifndef SQLITE_OMIT_AUTHORIZATION
98952 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
98953 db->aDb[iDb].zDbSName ) ){
98954 return;
98956 #endif
98958 /* Establish a read-lock on the table at the shared-cache level.
98959 ** Open a read-only cursor on the table. Also allocate a cursor number
98960 ** to use for scanning indexes (iIdxCur). No index cursor is opened at
98961 ** this time though. */
98962 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
98963 iTabCur = iTab++;
98964 iIdxCur = iTab++;
98965 pParse->nTab = MAX(pParse->nTab, iTab);
98966 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
98967 sqlite3VdbeLoadString(v, regTabname, pTab->zName);
98969 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98970 int nCol; /* Number of columns in pIdx. "N" */
98971 int addrRewind; /* Address of "OP_Rewind iIdxCur" */
98972 int addrNextRow; /* Address of "next_row:" */
98973 const char *zIdxName; /* Name of the index */
98974 int nColTest; /* Number of columns to test for changes */
98976 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
98977 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
98978 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
98979 nCol = pIdx->nKeyCol;
98980 zIdxName = pTab->zName;
98981 nColTest = nCol - 1;
98982 }else{
98983 nCol = pIdx->nColumn;
98984 zIdxName = pIdx->zName;
98985 nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
98988 /* Populate the register containing the index name. */
98989 sqlite3VdbeLoadString(v, regIdxname, zIdxName);
98990 VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
98993 ** Pseudo-code for loop that calls stat_push():
98995 ** Rewind csr
98996 ** if eof(csr) goto end_of_scan;
98997 ** regChng = 0
98998 ** goto chng_addr_0;
99000 ** next_row:
99001 ** regChng = 0
99002 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
99003 ** regChng = 1
99004 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
99005 ** ...
99006 ** regChng = N
99007 ** goto chng_addr_N
99009 ** chng_addr_0:
99010 ** regPrev(0) = idx(0)
99011 ** chng_addr_1:
99012 ** regPrev(1) = idx(1)
99013 ** ...
99015 ** endDistinctTest:
99016 ** regRowid = idx(rowid)
99017 ** stat_push(P, regChng, regRowid)
99018 ** Next csr
99019 ** if !eof(csr) goto next_row;
99021 ** end_of_scan:
99024 /* Make sure there are enough memory cells allocated to accommodate
99025 ** the regPrev array and a trailing rowid (the rowid slot is required
99026 ** when building a record to insert into the sample column of
99027 ** the sqlite_stat4 table. */
99028 pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
99030 /* Open a read-only cursor on the index being analyzed. */
99031 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
99032 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
99033 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
99034 VdbeComment((v, "%s", pIdx->zName));
99036 /* Invoke the stat_init() function. The arguments are:
99038 ** (1) the number of columns in the index including the rowid
99039 ** (or for a WITHOUT ROWID table, the number of PK columns),
99040 ** (2) the number of columns in the key without the rowid/pk
99041 ** (3) the number of rows in the index,
99044 ** The third argument is only used for STAT3 and STAT4
99046 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99047 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
99048 #endif
99049 sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
99050 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
99051 sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
99052 (char*)&statInitFuncdef, P4_FUNCDEF);
99053 sqlite3VdbeChangeP5(v, 2+IsStat34);
99055 /* Implementation of the following:
99057 ** Rewind csr
99058 ** if eof(csr) goto end_of_scan;
99059 ** regChng = 0
99060 ** goto next_push_0;
99063 addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
99064 VdbeCoverage(v);
99065 sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
99066 addrNextRow = sqlite3VdbeCurrentAddr(v);
99068 if( nColTest>0 ){
99069 int endDistinctTest = sqlite3VdbeMakeLabel(v);
99070 int *aGotoChng; /* Array of jump instruction addresses */
99071 aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
99072 if( aGotoChng==0 ) continue;
99075 ** next_row:
99076 ** regChng = 0
99077 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
99078 ** regChng = 1
99079 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
99080 ** ...
99081 ** regChng = N
99082 ** goto endDistinctTest
99084 sqlite3VdbeAddOp0(v, OP_Goto);
99085 addrNextRow = sqlite3VdbeCurrentAddr(v);
99086 if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
99087 /* For a single-column UNIQUE index, once we have found a non-NULL
99088 ** row, we know that all the rest will be distinct, so skip
99089 ** subsequent distinctness tests. */
99090 sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
99091 VdbeCoverage(v);
99093 for(i=0; i<nColTest; i++){
99094 char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
99095 sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
99096 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
99097 aGotoChng[i] =
99098 sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
99099 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
99100 VdbeCoverage(v);
99102 sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
99103 sqlite3VdbeGoto(v, endDistinctTest);
99107 ** chng_addr_0:
99108 ** regPrev(0) = idx(0)
99109 ** chng_addr_1:
99110 ** regPrev(1) = idx(1)
99111 ** ...
99113 sqlite3VdbeJumpHere(v, addrNextRow-1);
99114 for(i=0; i<nColTest; i++){
99115 sqlite3VdbeJumpHere(v, aGotoChng[i]);
99116 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
99118 sqlite3VdbeResolveLabel(v, endDistinctTest);
99119 sqlite3DbFree(db, aGotoChng);
99123 ** chng_addr_N:
99124 ** regRowid = idx(rowid) // STAT34 only
99125 ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
99126 ** Next csr
99127 ** if !eof(csr) goto next_row;
99129 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99130 assert( regRowid==(regStat4+2) );
99131 if( HasRowid(pTab) ){
99132 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
99133 }else{
99134 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
99135 int j, k, regKey;
99136 regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
99137 for(j=0; j<pPk->nKeyCol; j++){
99138 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
99139 assert( k>=0 && k<pIdx->nColumn );
99140 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
99141 VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
99143 sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
99144 sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
99146 #endif
99147 assert( regChng==(regStat4+1) );
99148 sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
99149 (char*)&statPushFuncdef, P4_FUNCDEF);
99150 sqlite3VdbeChangeP5(v, 2+IsStat34);
99151 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
99153 /* Add the entry to the stat1 table. */
99154 callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
99155 assert( "BBB"[0]==SQLITE_AFF_TEXT );
99156 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
99157 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
99158 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
99159 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
99161 /* Add the entries to the stat3 or stat4 table. */
99162 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99164 int regEq = regStat1;
99165 int regLt = regStat1+1;
99166 int regDLt = regStat1+2;
99167 int regSample = regStat1+3;
99168 int regCol = regStat1+4;
99169 int regSampleRowid = regCol + nCol;
99170 int addrNext;
99171 int addrIsNull;
99172 u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
99174 pParse->nMem = MAX(pParse->nMem, regCol+nCol);
99176 addrNext = sqlite3VdbeCurrentAddr(v);
99177 callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
99178 addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
99179 VdbeCoverage(v);
99180 callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
99181 callStatGet(v, regStat4, STAT_GET_NLT, regLt);
99182 callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
99183 sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
99184 /* We know that the regSampleRowid row exists because it was read by
99185 ** the previous loop. Thus the not-found jump of seekOp will never
99186 ** be taken */
99187 VdbeCoverageNeverTaken(v);
99188 #ifdef SQLITE_ENABLE_STAT3
99189 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
99190 #else
99191 for(i=0; i<nCol; i++){
99192 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
99194 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
99195 #endif
99196 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
99197 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
99198 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
99199 sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
99200 sqlite3VdbeJumpHere(v, addrIsNull);
99202 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
99204 /* End of analysis */
99205 sqlite3VdbeJumpHere(v, addrRewind);
99209 /* Create a single sqlite_stat1 entry containing NULL as the index
99210 ** name and the row count as the content.
99212 if( pOnlyIdx==0 && needTableCnt ){
99213 VdbeComment((v, "%s", pTab->zName));
99214 sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
99215 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
99216 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
99217 assert( "BBB"[0]==SQLITE_AFF_TEXT );
99218 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
99219 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
99220 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
99221 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
99222 sqlite3VdbeJumpHere(v, jZeroRows);
99228 ** Generate code that will cause the most recent index analysis to
99229 ** be loaded into internal hash tables where is can be used.
99231 static void loadAnalysis(Parse *pParse, int iDb){
99232 Vdbe *v = sqlite3GetVdbe(pParse);
99233 if( v ){
99234 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
99239 ** Generate code that will do an analysis of an entire database
99241 static void analyzeDatabase(Parse *pParse, int iDb){
99242 sqlite3 *db = pParse->db;
99243 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
99244 HashElem *k;
99245 int iStatCur;
99246 int iMem;
99247 int iTab;
99249 sqlite3BeginWriteOperation(pParse, 0, iDb);
99250 iStatCur = pParse->nTab;
99251 pParse->nTab += 3;
99252 openStatTable(pParse, iDb, iStatCur, 0, 0);
99253 iMem = pParse->nMem+1;
99254 iTab = pParse->nTab;
99255 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99256 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
99257 Table *pTab = (Table*)sqliteHashData(k);
99258 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
99260 loadAnalysis(pParse, iDb);
99264 ** Generate code that will do an analysis of a single table in
99265 ** a database. If pOnlyIdx is not NULL then it is a single index
99266 ** in pTab that should be analyzed.
99268 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
99269 int iDb;
99270 int iStatCur;
99272 assert( pTab!=0 );
99273 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
99274 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99275 sqlite3BeginWriteOperation(pParse, 0, iDb);
99276 iStatCur = pParse->nTab;
99277 pParse->nTab += 3;
99278 if( pOnlyIdx ){
99279 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
99280 }else{
99281 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
99283 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
99284 loadAnalysis(pParse, iDb);
99288 ** Generate code for the ANALYZE command. The parser calls this routine
99289 ** when it recognizes an ANALYZE command.
99291 ** ANALYZE -- 1
99292 ** ANALYZE <database> -- 2
99293 ** ANALYZE ?<database>.?<tablename> -- 3
99295 ** Form 1 causes all indices in all attached databases to be analyzed.
99296 ** Form 2 analyzes all indices the single database named.
99297 ** Form 3 analyzes all indices associated with the named table.
99299 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
99300 sqlite3 *db = pParse->db;
99301 int iDb;
99302 int i;
99303 char *z, *zDb;
99304 Table *pTab;
99305 Index *pIdx;
99306 Token *pTableName;
99307 Vdbe *v;
99309 /* Read the database schema. If an error occurs, leave an error message
99310 ** and code in pParse and return NULL. */
99311 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
99312 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
99313 return;
99316 assert( pName2!=0 || pName1==0 );
99317 if( pName1==0 ){
99318 /* Form 1: Analyze everything */
99319 for(i=0; i<db->nDb; i++){
99320 if( i==1 ) continue; /* Do not analyze the TEMP database */
99321 analyzeDatabase(pParse, i);
99323 }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
99324 /* Analyze the schema named as the argument */
99325 analyzeDatabase(pParse, iDb);
99326 }else{
99327 /* Form 3: Analyze the table or index named as an argument */
99328 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
99329 if( iDb>=0 ){
99330 zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
99331 z = sqlite3NameFromToken(db, pTableName);
99332 if( z ){
99333 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
99334 analyzeTable(pParse, pIdx->pTable, pIdx);
99335 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
99336 analyzeTable(pParse, pTab, 0);
99338 sqlite3DbFree(db, z);
99342 if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
99343 sqlite3VdbeAddOp0(v, OP_Expire);
99348 ** Used to pass information from the analyzer reader through to the
99349 ** callback routine.
99351 typedef struct analysisInfo analysisInfo;
99352 struct analysisInfo {
99353 sqlite3 *db;
99354 const char *zDatabase;
99358 ** The first argument points to a nul-terminated string containing a
99359 ** list of space separated integers. Read the first nOut of these into
99360 ** the array aOut[].
99362 static void decodeIntArray(
99363 char *zIntArray, /* String containing int array to decode */
99364 int nOut, /* Number of slots in aOut[] */
99365 tRowcnt *aOut, /* Store integers here */
99366 LogEst *aLog, /* Or, if aOut==0, here */
99367 Index *pIndex /* Handle extra flags for this index, if not NULL */
99369 char *z = zIntArray;
99370 int c;
99371 int i;
99372 tRowcnt v;
99374 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99375 if( z==0 ) z = "";
99376 #else
99377 assert( z!=0 );
99378 #endif
99379 for(i=0; *z && i<nOut; i++){
99380 v = 0;
99381 while( (c=z[0])>='0' && c<='9' ){
99382 v = v*10 + c - '0';
99383 z++;
99385 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99386 if( aOut ) aOut[i] = v;
99387 if( aLog ) aLog[i] = sqlite3LogEst(v);
99388 #else
99389 assert( aOut==0 );
99390 UNUSED_PARAMETER(aOut);
99391 assert( aLog!=0 );
99392 aLog[i] = sqlite3LogEst(v);
99393 #endif
99394 if( *z==' ' ) z++;
99396 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
99397 assert( pIndex!=0 ); {
99398 #else
99399 if( pIndex ){
99400 #endif
99401 pIndex->bUnordered = 0;
99402 pIndex->noSkipScan = 0;
99403 while( z[0] ){
99404 if( sqlite3_strglob("unordered*", z)==0 ){
99405 pIndex->bUnordered = 1;
99406 }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
99407 pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
99408 }else if( sqlite3_strglob("noskipscan*", z)==0 ){
99409 pIndex->noSkipScan = 1;
99411 #ifdef SQLITE_ENABLE_COSTMULT
99412 else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
99413 pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
99415 #endif
99416 while( z[0]!=0 && z[0]!=' ' ) z++;
99417 while( z[0]==' ' ) z++;
99423 ** This callback is invoked once for each index when reading the
99424 ** sqlite_stat1 table.
99426 ** argv[0] = name of the table
99427 ** argv[1] = name of the index (might be NULL)
99428 ** argv[2] = results of analysis - on integer for each column
99430 ** Entries for which argv[1]==NULL simply record the number of rows in
99431 ** the table.
99433 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
99434 analysisInfo *pInfo = (analysisInfo*)pData;
99435 Index *pIndex;
99436 Table *pTable;
99437 const char *z;
99439 assert( argc==3 );
99440 UNUSED_PARAMETER2(NotUsed, argc);
99442 if( argv==0 || argv[0]==0 || argv[2]==0 ){
99443 return 0;
99445 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
99446 if( pTable==0 ){
99447 return 0;
99449 if( argv[1]==0 ){
99450 pIndex = 0;
99451 }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
99452 pIndex = sqlite3PrimaryKeyIndex(pTable);
99453 }else{
99454 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
99456 z = argv[2];
99458 if( pIndex ){
99459 tRowcnt *aiRowEst = 0;
99460 int nCol = pIndex->nKeyCol+1;
99461 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99462 /* Index.aiRowEst may already be set here if there are duplicate
99463 ** sqlite_stat1 entries for this index. In that case just clobber
99464 ** the old data with the new instead of allocating a new array. */
99465 if( pIndex->aiRowEst==0 ){
99466 pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
99467 if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
99469 aiRowEst = pIndex->aiRowEst;
99470 #endif
99471 pIndex->bUnordered = 0;
99472 decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
99473 pIndex->hasStat1 = 1;
99474 if( pIndex->pPartIdxWhere==0 ){
99475 pTable->nRowLogEst = pIndex->aiRowLogEst[0];
99476 pTable->tabFlags |= TF_HasStat1;
99478 }else{
99479 Index fakeIdx;
99480 fakeIdx.szIdxRow = pTable->szTabRow;
99481 #ifdef SQLITE_ENABLE_COSTMULT
99482 fakeIdx.pTable = pTable;
99483 #endif
99484 decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
99485 pTable->szTabRow = fakeIdx.szIdxRow;
99486 pTable->tabFlags |= TF_HasStat1;
99489 return 0;
99493 ** If the Index.aSample variable is not NULL, delete the aSample[] array
99494 ** and its contents.
99496 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
99497 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99498 if( pIdx->aSample ){
99499 int j;
99500 for(j=0; j<pIdx->nSample; j++){
99501 IndexSample *p = &pIdx->aSample[j];
99502 sqlite3DbFree(db, p->p);
99504 sqlite3DbFree(db, pIdx->aSample);
99506 if( db && db->pnBytesFreed==0 ){
99507 pIdx->nSample = 0;
99508 pIdx->aSample = 0;
99510 #else
99511 UNUSED_PARAMETER(db);
99512 UNUSED_PARAMETER(pIdx);
99513 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
99516 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99518 ** Populate the pIdx->aAvgEq[] array based on the samples currently
99519 ** stored in pIdx->aSample[].
99521 static void initAvgEq(Index *pIdx){
99522 if( pIdx ){
99523 IndexSample *aSample = pIdx->aSample;
99524 IndexSample *pFinal = &aSample[pIdx->nSample-1];
99525 int iCol;
99526 int nCol = 1;
99527 if( pIdx->nSampleCol>1 ){
99528 /* If this is stat4 data, then calculate aAvgEq[] values for all
99529 ** sample columns except the last. The last is always set to 1, as
99530 ** once the trailing PK fields are considered all index keys are
99531 ** unique. */
99532 nCol = pIdx->nSampleCol-1;
99533 pIdx->aAvgEq[nCol] = 1;
99535 for(iCol=0; iCol<nCol; iCol++){
99536 int nSample = pIdx->nSample;
99537 int i; /* Used to iterate through samples */
99538 tRowcnt sumEq = 0; /* Sum of the nEq values */
99539 tRowcnt avgEq = 0;
99540 tRowcnt nRow; /* Number of rows in index */
99541 i64 nSum100 = 0; /* Number of terms contributing to sumEq */
99542 i64 nDist100; /* Number of distinct values in index */
99544 if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
99545 nRow = pFinal->anLt[iCol];
99546 nDist100 = (i64)100 * pFinal->anDLt[iCol];
99547 nSample--;
99548 }else{
99549 nRow = pIdx->aiRowEst[0];
99550 nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
99552 pIdx->nRowEst0 = nRow;
99554 /* Set nSum to the number of distinct (iCol+1) field prefixes that
99555 ** occur in the stat4 table for this index. Set sumEq to the sum of
99556 ** the nEq values for column iCol for the same set (adding the value
99557 ** only once where there exist duplicate prefixes). */
99558 for(i=0; i<nSample; i++){
99559 if( i==(pIdx->nSample-1)
99560 || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
99562 sumEq += aSample[i].anEq[iCol];
99563 nSum100 += 100;
99567 if( nDist100>nSum100 && sumEq<nRow ){
99568 avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
99570 if( avgEq==0 ) avgEq = 1;
99571 pIdx->aAvgEq[iCol] = avgEq;
99577 ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
99578 ** is supplied instead, find the PRIMARY KEY index for that table.
99580 static Index *findIndexOrPrimaryKey(
99581 sqlite3 *db,
99582 const char *zName,
99583 const char *zDb
99585 Index *pIdx = sqlite3FindIndex(db, zName, zDb);
99586 if( pIdx==0 ){
99587 Table *pTab = sqlite3FindTable(db, zName, zDb);
99588 if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
99590 return pIdx;
99594 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
99595 ** into the relevant Index.aSample[] arrays.
99597 ** Arguments zSql1 and zSql2 must point to SQL statements that return
99598 ** data equivalent to the following (statements are different for stat3,
99599 ** see the caller of this function for details):
99601 ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
99602 ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
99604 ** where %Q is replaced with the database name before the SQL is executed.
99606 static int loadStatTbl(
99607 sqlite3 *db, /* Database handle */
99608 int bStat3, /* Assume single column records only */
99609 const char *zSql1, /* SQL statement 1 (see above) */
99610 const char *zSql2, /* SQL statement 2 (see above) */
99611 const char *zDb /* Database name (e.g. "main") */
99613 int rc; /* Result codes from subroutines */
99614 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
99615 char *zSql; /* Text of the SQL statement */
99616 Index *pPrevIdx = 0; /* Previous index in the loop */
99617 IndexSample *pSample; /* A slot in pIdx->aSample[] */
99619 assert( db->lookaside.bDisable );
99620 zSql = sqlite3MPrintf(db, zSql1, zDb);
99621 if( !zSql ){
99622 return SQLITE_NOMEM_BKPT;
99624 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
99625 sqlite3DbFree(db, zSql);
99626 if( rc ) return rc;
99628 while( sqlite3_step(pStmt)==SQLITE_ROW ){
99629 int nIdxCol = 1; /* Number of columns in stat4 records */
99631 char *zIndex; /* Index name */
99632 Index *pIdx; /* Pointer to the index object */
99633 int nSample; /* Number of samples */
99634 int nByte; /* Bytes of space required */
99635 int i; /* Bytes of space required */
99636 tRowcnt *pSpace;
99638 zIndex = (char *)sqlite3_column_text(pStmt, 0);
99639 if( zIndex==0 ) continue;
99640 nSample = sqlite3_column_int(pStmt, 1);
99641 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
99642 assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
99643 /* Index.nSample is non-zero at this point if data has already been
99644 ** loaded from the stat4 table. In this case ignore stat3 data. */
99645 if( pIdx==0 || pIdx->nSample ) continue;
99646 if( bStat3==0 ){
99647 assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
99648 if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
99649 nIdxCol = pIdx->nKeyCol;
99650 }else{
99651 nIdxCol = pIdx->nColumn;
99654 pIdx->nSampleCol = nIdxCol;
99655 nByte = sizeof(IndexSample) * nSample;
99656 nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
99657 nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
99659 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
99660 if( pIdx->aSample==0 ){
99661 sqlite3_finalize(pStmt);
99662 return SQLITE_NOMEM_BKPT;
99664 pSpace = (tRowcnt*)&pIdx->aSample[nSample];
99665 pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
99666 for(i=0; i<nSample; i++){
99667 pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
99668 pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
99669 pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
99671 assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
99673 rc = sqlite3_finalize(pStmt);
99674 if( rc ) return rc;
99676 zSql = sqlite3MPrintf(db, zSql2, zDb);
99677 if( !zSql ){
99678 return SQLITE_NOMEM_BKPT;
99680 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
99681 sqlite3DbFree(db, zSql);
99682 if( rc ) return rc;
99684 while( sqlite3_step(pStmt)==SQLITE_ROW ){
99685 char *zIndex; /* Index name */
99686 Index *pIdx; /* Pointer to the index object */
99687 int nCol = 1; /* Number of columns in index */
99689 zIndex = (char *)sqlite3_column_text(pStmt, 0);
99690 if( zIndex==0 ) continue;
99691 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
99692 if( pIdx==0 ) continue;
99693 /* This next condition is true if data has already been loaded from
99694 ** the sqlite_stat4 table. In this case ignore stat3 data. */
99695 nCol = pIdx->nSampleCol;
99696 if( bStat3 && nCol>1 ) continue;
99697 if( pIdx!=pPrevIdx ){
99698 initAvgEq(pPrevIdx);
99699 pPrevIdx = pIdx;
99701 pSample = &pIdx->aSample[pIdx->nSample];
99702 decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
99703 decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
99704 decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
99706 /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
99707 ** This is in case the sample record is corrupted. In that case, the
99708 ** sqlite3VdbeRecordCompare() may read up to two varints past the
99709 ** end of the allocated buffer before it realizes it is dealing with
99710 ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
99711 ** a buffer overread. */
99712 pSample->n = sqlite3_column_bytes(pStmt, 4);
99713 pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
99714 if( pSample->p==0 ){
99715 sqlite3_finalize(pStmt);
99716 return SQLITE_NOMEM_BKPT;
99718 if( pSample->n ){
99719 memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
99721 pIdx->nSample++;
99723 rc = sqlite3_finalize(pStmt);
99724 if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
99725 return rc;
99729 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
99730 ** the Index.aSample[] arrays of all indices.
99732 static int loadStat4(sqlite3 *db, const char *zDb){
99733 int rc = SQLITE_OK; /* Result codes from subroutines */
99735 assert( db->lookaside.bDisable );
99736 if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
99737 rc = loadStatTbl(db, 0,
99738 "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
99739 "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
99744 if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
99745 rc = loadStatTbl(db, 1,
99746 "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
99747 "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
99752 return rc;
99754 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
99757 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
99758 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
99759 ** arrays. The contents of sqlite_stat3/4 are used to populate the
99760 ** Index.aSample[] arrays.
99762 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
99763 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
99764 ** during compilation and the sqlite_stat3/4 table is present, no data is
99765 ** read from it.
99767 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
99768 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
99769 ** returned. However, in this case, data is read from the sqlite_stat1
99770 ** table (if it is present) before returning.
99772 ** If an OOM error occurs, this function always sets db->mallocFailed.
99773 ** This means if the caller does not care about other errors, the return
99774 ** code may be ignored.
99776 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
99777 analysisInfo sInfo;
99778 HashElem *i;
99779 char *zSql;
99780 int rc = SQLITE_OK;
99781 Schema *pSchema = db->aDb[iDb].pSchema;
99783 assert( iDb>=0 && iDb<db->nDb );
99784 assert( db->aDb[iDb].pBt!=0 );
99786 /* Clear any prior statistics */
99787 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99788 for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
99789 Table *pTab = sqliteHashData(i);
99790 pTab->tabFlags &= ~TF_HasStat1;
99792 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
99793 Index *pIdx = sqliteHashData(i);
99794 pIdx->hasStat1 = 0;
99795 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99796 sqlite3DeleteIndexSamples(db, pIdx);
99797 pIdx->aSample = 0;
99798 #endif
99801 /* Load new statistics out of the sqlite_stat1 table */
99802 sInfo.db = db;
99803 sInfo.zDatabase = db->aDb[iDb].zDbSName;
99804 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
99805 zSql = sqlite3MPrintf(db,
99806 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
99807 if( zSql==0 ){
99808 rc = SQLITE_NOMEM_BKPT;
99809 }else{
99810 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
99811 sqlite3DbFree(db, zSql);
99815 /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
99816 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99817 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
99818 Index *pIdx = sqliteHashData(i);
99819 if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
99822 /* Load the statistics from the sqlite_stat4 table. */
99823 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99824 if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
99825 db->lookaside.bDisable++;
99826 rc = loadStat4(db, sInfo.zDatabase);
99827 db->lookaside.bDisable--;
99829 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
99830 Index *pIdx = sqliteHashData(i);
99831 sqlite3_free(pIdx->aiRowEst);
99832 pIdx->aiRowEst = 0;
99834 #endif
99836 if( rc==SQLITE_NOMEM ){
99837 sqlite3OomFault(db);
99839 return rc;
99843 #endif /* SQLITE_OMIT_ANALYZE */
99845 /************** End of analyze.c *********************************************/
99846 /************** Begin file attach.c ******************************************/
99848 ** 2003 April 6
99850 ** The author disclaims copyright to this source code. In place of
99851 ** a legal notice, here is a blessing:
99853 ** May you do good and not evil.
99854 ** May you find forgiveness for yourself and forgive others.
99855 ** May you share freely, never taking more than you give.
99857 *************************************************************************
99858 ** This file contains code used to implement the ATTACH and DETACH commands.
99860 /* #include "sqliteInt.h" */
99862 #ifndef SQLITE_OMIT_ATTACH
99864 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
99865 ** is slightly different from resolving a normal SQL expression, because simple
99866 ** identifiers are treated as strings, not possible column names or aliases.
99868 ** i.e. if the parser sees:
99870 ** ATTACH DATABASE abc AS def
99872 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
99873 ** looking for columns of the same name.
99875 ** This only applies to the root node of pExpr, so the statement:
99877 ** ATTACH DATABASE abc||def AS 'db2'
99879 ** will fail because neither abc or def can be resolved.
99881 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
99883 int rc = SQLITE_OK;
99884 if( pExpr ){
99885 if( pExpr->op!=TK_ID ){
99886 rc = sqlite3ResolveExprNames(pName, pExpr);
99887 }else{
99888 pExpr->op = TK_STRING;
99891 return rc;
99895 ** An SQL user-function registered to do the work of an ATTACH statement. The
99896 ** three arguments to the function come directly from an attach statement:
99898 ** ATTACH DATABASE x AS y KEY z
99900 ** SELECT sqlite_attach(x, y, z)
99902 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
99903 ** third argument.
99905 static void attachFunc(
99906 sqlite3_context *context,
99907 int NotUsed,
99908 sqlite3_value **argv
99910 int i;
99911 int rc = 0;
99912 sqlite3 *db = sqlite3_context_db_handle(context);
99913 const char *zName;
99914 const char *zFile;
99915 char *zPath = 0;
99916 char *zErr = 0;
99917 unsigned int flags;
99918 Db *aNew; /* New array of Db pointers */
99919 Db *pNew; /* Db object for the newly attached database */
99920 char *zErrDyn = 0;
99921 sqlite3_vfs *pVfs;
99923 UNUSED_PARAMETER(NotUsed);
99925 zFile = (const char *)sqlite3_value_text(argv[0]);
99926 zName = (const char *)sqlite3_value_text(argv[1]);
99927 if( zFile==0 ) zFile = "";
99928 if( zName==0 ) zName = "";
99930 /* Check for the following errors:
99932 ** * Too many attached databases,
99933 ** * Transaction currently open
99934 ** * Specified database name already being used.
99936 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
99937 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
99938 db->aLimit[SQLITE_LIMIT_ATTACHED]
99940 goto attach_error;
99942 for(i=0; i<db->nDb; i++){
99943 char *z = db->aDb[i].zDbSName;
99944 assert( z && zName );
99945 if( sqlite3StrICmp(z, zName)==0 ){
99946 zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
99947 goto attach_error;
99951 /* Allocate the new entry in the db->aDb[] array and initialize the schema
99952 ** hash tables.
99954 if( db->aDb==db->aDbStatic ){
99955 aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
99956 if( aNew==0 ) return;
99957 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
99958 }else{
99959 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
99960 if( aNew==0 ) return;
99962 db->aDb = aNew;
99963 pNew = &db->aDb[db->nDb];
99964 memset(pNew, 0, sizeof(*pNew));
99966 /* Open the database file. If the btree is successfully opened, use
99967 ** it to obtain the database schema. At this point the schema may
99968 ** or may not be initialized.
99970 flags = db->openFlags;
99971 rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
99972 if( rc!=SQLITE_OK ){
99973 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
99974 sqlite3_result_error(context, zErr, -1);
99975 sqlite3_free(zErr);
99976 return;
99978 assert( pVfs );
99979 flags |= SQLITE_OPEN_MAIN_DB;
99980 rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
99981 sqlite3_free( zPath );
99982 db->nDb++;
99983 db->skipBtreeMutex = 0;
99984 if( rc==SQLITE_CONSTRAINT ){
99985 rc = SQLITE_ERROR;
99986 zErrDyn = sqlite3MPrintf(db, "database is already attached");
99987 }else if( rc==SQLITE_OK ){
99988 Pager *pPager;
99989 pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
99990 if( !pNew->pSchema ){
99991 rc = SQLITE_NOMEM_BKPT;
99992 }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
99993 zErrDyn = sqlite3MPrintf(db,
99994 "attached databases must use the same text encoding as main database");
99995 rc = SQLITE_ERROR;
99997 sqlite3BtreeEnter(pNew->pBt);
99998 pPager = sqlite3BtreePager(pNew->pBt);
99999 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
100000 sqlite3BtreeSecureDelete(pNew->pBt,
100001 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
100002 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
100003 sqlite3BtreeSetPagerFlags(pNew->pBt,
100004 PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
100005 #endif
100006 sqlite3BtreeLeave(pNew->pBt);
100008 pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
100009 pNew->zDbSName = sqlite3DbStrDup(db, zName);
100010 if( rc==SQLITE_OK && pNew->zDbSName==0 ){
100011 rc = SQLITE_NOMEM_BKPT;
100015 #ifdef SQLITE_HAS_CODEC
100016 if( rc==SQLITE_OK ){
100017 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
100018 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
100019 int nKey;
100020 char *zKey;
100021 int t = sqlite3_value_type(argv[2]);
100022 switch( t ){
100023 case SQLITE_INTEGER:
100024 case SQLITE_FLOAT:
100025 zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
100026 rc = SQLITE_ERROR;
100027 break;
100029 case SQLITE_TEXT:
100030 case SQLITE_BLOB:
100031 nKey = sqlite3_value_bytes(argv[2]);
100032 zKey = (char *)sqlite3_value_blob(argv[2]);
100033 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
100034 break;
100036 case SQLITE_NULL:
100037 /* No key specified. Use the key from the main database */
100038 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
100039 if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
100040 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
100042 break;
100045 #endif
100047 /* If the file was opened successfully, read the schema for the new database.
100048 ** If this fails, or if opening the file failed, then close the file and
100049 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
100050 ** we found it.
100052 if( rc==SQLITE_OK ){
100053 sqlite3BtreeEnterAll(db);
100054 rc = sqlite3Init(db, &zErrDyn);
100055 sqlite3BtreeLeaveAll(db);
100057 #ifdef SQLITE_USER_AUTHENTICATION
100058 if( rc==SQLITE_OK ){
100059 u8 newAuth = 0;
100060 rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
100061 if( newAuth<db->auth.authLevel ){
100062 rc = SQLITE_AUTH_USER;
100065 #endif
100066 if( rc ){
100067 int iDb = db->nDb - 1;
100068 assert( iDb>=2 );
100069 if( db->aDb[iDb].pBt ){
100070 sqlite3BtreeClose(db->aDb[iDb].pBt);
100071 db->aDb[iDb].pBt = 0;
100072 db->aDb[iDb].pSchema = 0;
100074 sqlite3ResetAllSchemasOfConnection(db);
100075 db->nDb = iDb;
100076 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
100077 sqlite3OomFault(db);
100078 sqlite3DbFree(db, zErrDyn);
100079 zErrDyn = sqlite3MPrintf(db, "out of memory");
100080 }else if( zErrDyn==0 ){
100081 zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
100083 goto attach_error;
100086 return;
100088 attach_error:
100089 /* Return an error if we get here */
100090 if( zErrDyn ){
100091 sqlite3_result_error(context, zErrDyn, -1);
100092 sqlite3DbFree(db, zErrDyn);
100094 if( rc ) sqlite3_result_error_code(context, rc);
100098 ** An SQL user-function registered to do the work of an DETACH statement. The
100099 ** three arguments to the function come directly from a detach statement:
100101 ** DETACH DATABASE x
100103 ** SELECT sqlite_detach(x)
100105 static void detachFunc(
100106 sqlite3_context *context,
100107 int NotUsed,
100108 sqlite3_value **argv
100110 const char *zName = (const char *)sqlite3_value_text(argv[0]);
100111 sqlite3 *db = sqlite3_context_db_handle(context);
100112 int i;
100113 Db *pDb = 0;
100114 char zErr[128];
100116 UNUSED_PARAMETER(NotUsed);
100118 if( zName==0 ) zName = "";
100119 for(i=0; i<db->nDb; i++){
100120 pDb = &db->aDb[i];
100121 if( pDb->pBt==0 ) continue;
100122 if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
100125 if( i>=db->nDb ){
100126 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
100127 goto detach_error;
100129 if( i<2 ){
100130 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
100131 goto detach_error;
100133 if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
100134 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
100135 goto detach_error;
100138 sqlite3BtreeClose(pDb->pBt);
100139 pDb->pBt = 0;
100140 pDb->pSchema = 0;
100141 sqlite3CollapseDatabaseArray(db);
100142 return;
100144 detach_error:
100145 sqlite3_result_error(context, zErr, -1);
100149 ** This procedure generates VDBE code for a single invocation of either the
100150 ** sqlite_detach() or sqlite_attach() SQL user functions.
100152 static void codeAttach(
100153 Parse *pParse, /* The parser context */
100154 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
100155 FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
100156 Expr *pAuthArg, /* Expression to pass to authorization callback */
100157 Expr *pFilename, /* Name of database file */
100158 Expr *pDbname, /* Name of the database to use internally */
100159 Expr *pKey /* Database key for encryption extension */
100161 int rc;
100162 NameContext sName;
100163 Vdbe *v;
100164 sqlite3* db = pParse->db;
100165 int regArgs;
100167 if( pParse->nErr ) goto attach_end;
100168 memset(&sName, 0, sizeof(NameContext));
100169 sName.pParse = pParse;
100172 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
100173 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
100174 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
100176 goto attach_end;
100179 #ifndef SQLITE_OMIT_AUTHORIZATION
100180 if( pAuthArg ){
100181 char *zAuthArg;
100182 if( pAuthArg->op==TK_STRING ){
100183 zAuthArg = pAuthArg->u.zToken;
100184 }else{
100185 zAuthArg = 0;
100187 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
100188 if(rc!=SQLITE_OK ){
100189 goto attach_end;
100192 #endif /* SQLITE_OMIT_AUTHORIZATION */
100195 v = sqlite3GetVdbe(pParse);
100196 regArgs = sqlite3GetTempRange(pParse, 4);
100197 sqlite3ExprCode(pParse, pFilename, regArgs);
100198 sqlite3ExprCode(pParse, pDbname, regArgs+1);
100199 sqlite3ExprCode(pParse, pKey, regArgs+2);
100201 assert( v || db->mallocFailed );
100202 if( v ){
100203 sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
100204 (char *)pFunc, P4_FUNCDEF);
100205 assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
100206 sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
100208 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
100209 ** statement only). For DETACH, set it to false (expire all existing
100210 ** statements).
100212 sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
100215 attach_end:
100216 sqlite3ExprDelete(db, pFilename);
100217 sqlite3ExprDelete(db, pDbname);
100218 sqlite3ExprDelete(db, pKey);
100222 ** Called by the parser to compile a DETACH statement.
100224 ** DETACH pDbname
100226 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
100227 static const FuncDef detach_func = {
100228 1, /* nArg */
100229 SQLITE_UTF8, /* funcFlags */
100230 0, /* pUserData */
100231 0, /* pNext */
100232 detachFunc, /* xSFunc */
100233 0, /* xFinalize */
100234 "sqlite_detach", /* zName */
100237 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
100241 ** Called by the parser to compile an ATTACH statement.
100243 ** ATTACH p AS pDbname KEY pKey
100245 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
100246 static const FuncDef attach_func = {
100247 3, /* nArg */
100248 SQLITE_UTF8, /* funcFlags */
100249 0, /* pUserData */
100250 0, /* pNext */
100251 attachFunc, /* xSFunc */
100252 0, /* xFinalize */
100253 "sqlite_attach", /* zName */
100256 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
100258 #endif /* SQLITE_OMIT_ATTACH */
100261 ** Initialize a DbFixer structure. This routine must be called prior
100262 ** to passing the structure to one of the sqliteFixAAAA() routines below.
100264 SQLITE_PRIVATE void sqlite3FixInit(
100265 DbFixer *pFix, /* The fixer to be initialized */
100266 Parse *pParse, /* Error messages will be written here */
100267 int iDb, /* This is the database that must be used */
100268 const char *zType, /* "view", "trigger", or "index" */
100269 const Token *pName /* Name of the view, trigger, or index */
100271 sqlite3 *db;
100273 db = pParse->db;
100274 assert( db->nDb>iDb );
100275 pFix->pParse = pParse;
100276 pFix->zDb = db->aDb[iDb].zDbSName;
100277 pFix->pSchema = db->aDb[iDb].pSchema;
100278 pFix->zType = zType;
100279 pFix->pName = pName;
100280 pFix->bVarOnly = (iDb==1);
100284 ** The following set of routines walk through the parse tree and assign
100285 ** a specific database to all table references where the database name
100286 ** was left unspecified in the original SQL statement. The pFix structure
100287 ** must have been initialized by a prior call to sqlite3FixInit().
100289 ** These routines are used to make sure that an index, trigger, or
100290 ** view in one database does not refer to objects in a different database.
100291 ** (Exception: indices, triggers, and views in the TEMP database are
100292 ** allowed to refer to anything.) If a reference is explicitly made
100293 ** to an object in a different database, an error message is added to
100294 ** pParse->zErrMsg and these routines return non-zero. If everything
100295 ** checks out, these routines return 0.
100297 SQLITE_PRIVATE int sqlite3FixSrcList(
100298 DbFixer *pFix, /* Context of the fixation */
100299 SrcList *pList /* The Source list to check and modify */
100301 int i;
100302 const char *zDb;
100303 struct SrcList_item *pItem;
100305 if( NEVER(pList==0) ) return 0;
100306 zDb = pFix->zDb;
100307 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
100308 if( pFix->bVarOnly==0 ){
100309 if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
100310 sqlite3ErrorMsg(pFix->pParse,
100311 "%s %T cannot reference objects in database %s",
100312 pFix->zType, pFix->pName, pItem->zDatabase);
100313 return 1;
100315 sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
100316 pItem->zDatabase = 0;
100317 pItem->pSchema = pFix->pSchema;
100319 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
100320 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
100321 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
100322 #endif
100324 return 0;
100326 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
100327 SQLITE_PRIVATE int sqlite3FixSelect(
100328 DbFixer *pFix, /* Context of the fixation */
100329 Select *pSelect /* The SELECT statement to be fixed to one database */
100331 while( pSelect ){
100332 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
100333 return 1;
100335 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
100336 return 1;
100338 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
100339 return 1;
100341 if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
100342 return 1;
100344 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
100345 return 1;
100347 if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
100348 return 1;
100350 if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
100351 return 1;
100353 if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
100354 return 1;
100356 pSelect = pSelect->pPrior;
100358 return 0;
100360 SQLITE_PRIVATE int sqlite3FixExpr(
100361 DbFixer *pFix, /* Context of the fixation */
100362 Expr *pExpr /* The expression to be fixed to one database */
100364 while( pExpr ){
100365 if( pExpr->op==TK_VARIABLE ){
100366 if( pFix->pParse->db->init.busy ){
100367 pExpr->op = TK_NULL;
100368 }else{
100369 sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
100370 return 1;
100373 if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
100374 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
100375 if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
100376 }else{
100377 if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
100379 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
100380 return 1;
100382 pExpr = pExpr->pLeft;
100384 return 0;
100386 SQLITE_PRIVATE int sqlite3FixExprList(
100387 DbFixer *pFix, /* Context of the fixation */
100388 ExprList *pList /* The expression to be fixed to one database */
100390 int i;
100391 struct ExprList_item *pItem;
100392 if( pList==0 ) return 0;
100393 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
100394 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
100395 return 1;
100398 return 0;
100400 #endif
100402 #ifndef SQLITE_OMIT_TRIGGER
100403 SQLITE_PRIVATE int sqlite3FixTriggerStep(
100404 DbFixer *pFix, /* Context of the fixation */
100405 TriggerStep *pStep /* The trigger step be fixed to one database */
100407 while( pStep ){
100408 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
100409 return 1;
100411 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
100412 return 1;
100414 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
100415 return 1;
100417 pStep = pStep->pNext;
100419 return 0;
100421 #endif
100423 /************** End of attach.c **********************************************/
100424 /************** Begin file auth.c ********************************************/
100426 ** 2003 January 11
100428 ** The author disclaims copyright to this source code. In place of
100429 ** a legal notice, here is a blessing:
100431 ** May you do good and not evil.
100432 ** May you find forgiveness for yourself and forgive others.
100433 ** May you share freely, never taking more than you give.
100435 *************************************************************************
100436 ** This file contains code used to implement the sqlite3_set_authorizer()
100437 ** API. This facility is an optional feature of the library. Embedded
100438 ** systems that do not need this facility may omit it by recompiling
100439 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
100441 /* #include "sqliteInt.h" */
100444 ** All of the code in this file may be omitted by defining a single
100445 ** macro.
100447 #ifndef SQLITE_OMIT_AUTHORIZATION
100450 ** Set or clear the access authorization function.
100452 ** The access authorization function is be called during the compilation
100453 ** phase to verify that the user has read and/or write access permission on
100454 ** various fields of the database. The first argument to the auth function
100455 ** is a copy of the 3rd argument to this routine. The second argument
100456 ** to the auth function is one of these constants:
100458 ** SQLITE_CREATE_INDEX
100459 ** SQLITE_CREATE_TABLE
100460 ** SQLITE_CREATE_TEMP_INDEX
100461 ** SQLITE_CREATE_TEMP_TABLE
100462 ** SQLITE_CREATE_TEMP_TRIGGER
100463 ** SQLITE_CREATE_TEMP_VIEW
100464 ** SQLITE_CREATE_TRIGGER
100465 ** SQLITE_CREATE_VIEW
100466 ** SQLITE_DELETE
100467 ** SQLITE_DROP_INDEX
100468 ** SQLITE_DROP_TABLE
100469 ** SQLITE_DROP_TEMP_INDEX
100470 ** SQLITE_DROP_TEMP_TABLE
100471 ** SQLITE_DROP_TEMP_TRIGGER
100472 ** SQLITE_DROP_TEMP_VIEW
100473 ** SQLITE_DROP_TRIGGER
100474 ** SQLITE_DROP_VIEW
100475 ** SQLITE_INSERT
100476 ** SQLITE_PRAGMA
100477 ** SQLITE_READ
100478 ** SQLITE_SELECT
100479 ** SQLITE_TRANSACTION
100480 ** SQLITE_UPDATE
100482 ** The third and fourth arguments to the auth function are the name of
100483 ** the table and the column that are being accessed. The auth function
100484 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
100485 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
100486 ** means that the SQL statement will never-run - the sqlite3_exec() call
100487 ** will return with an error. SQLITE_IGNORE means that the SQL statement
100488 ** should run but attempts to read the specified column will return NULL
100489 ** and attempts to write the column will be ignored.
100491 ** Setting the auth function to NULL disables this hook. The default
100492 ** setting of the auth function is NULL.
100494 SQLITE_API int sqlite3_set_authorizer(
100495 sqlite3 *db,
100496 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
100497 void *pArg
100499 #ifdef SQLITE_ENABLE_API_ARMOR
100500 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
100501 #endif
100502 sqlite3_mutex_enter(db->mutex);
100503 db->xAuth = (sqlite3_xauth)xAuth;
100504 db->pAuthArg = pArg;
100505 sqlite3ExpirePreparedStatements(db);
100506 sqlite3_mutex_leave(db->mutex);
100507 return SQLITE_OK;
100511 ** Write an error message into pParse->zErrMsg that explains that the
100512 ** user-supplied authorization function returned an illegal value.
100514 static void sqliteAuthBadReturnCode(Parse *pParse){
100515 sqlite3ErrorMsg(pParse, "authorizer malfunction");
100516 pParse->rc = SQLITE_ERROR;
100520 ** Invoke the authorization callback for permission to read column zCol from
100521 ** table zTab in database zDb. This function assumes that an authorization
100522 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
100524 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
100525 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
100526 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
100528 SQLITE_PRIVATE int sqlite3AuthReadCol(
100529 Parse *pParse, /* The parser context */
100530 const char *zTab, /* Table name */
100531 const char *zCol, /* Column name */
100532 int iDb /* Index of containing database. */
100534 sqlite3 *db = pParse->db; /* Database handle */
100535 char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
100536 int rc; /* Auth callback return code */
100538 if( db->init.busy ) return SQLITE_OK;
100539 rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
100540 #ifdef SQLITE_USER_AUTHENTICATION
100541 ,db->auth.zAuthUser
100542 #endif
100544 if( rc==SQLITE_DENY ){
100545 char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
100546 if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
100547 sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
100548 pParse->rc = SQLITE_AUTH;
100549 }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
100550 sqliteAuthBadReturnCode(pParse);
100552 return rc;
100556 ** The pExpr should be a TK_COLUMN expression. The table referred to
100557 ** is in pTabList or else it is the NEW or OLD table of a trigger.
100558 ** Check to see if it is OK to read this particular column.
100560 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
100561 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
100562 ** then generate an error.
100564 SQLITE_PRIVATE void sqlite3AuthRead(
100565 Parse *pParse, /* The parser context */
100566 Expr *pExpr, /* The expression to check authorization on */
100567 Schema *pSchema, /* The schema of the expression */
100568 SrcList *pTabList /* All table that pExpr might refer to */
100570 sqlite3 *db = pParse->db;
100571 Table *pTab = 0; /* The table being read */
100572 const char *zCol; /* Name of the column of the table */
100573 int iSrc; /* Index in pTabList->a[] of table being read */
100574 int iDb; /* The index of the database the expression refers to */
100575 int iCol; /* Index of column in table */
100577 if( db->xAuth==0 ) return;
100578 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
100579 if( iDb<0 ){
100580 /* An attempt to read a column out of a subquery or other
100581 ** temporary table. */
100582 return;
100585 assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
100586 if( pExpr->op==TK_TRIGGER ){
100587 pTab = pParse->pTriggerTab;
100588 }else{
100589 assert( pTabList );
100590 for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
100591 if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
100592 pTab = pTabList->a[iSrc].pTab;
100593 break;
100597 iCol = pExpr->iColumn;
100598 if( NEVER(pTab==0) ) return;
100600 if( iCol>=0 ){
100601 assert( iCol<pTab->nCol );
100602 zCol = pTab->aCol[iCol].zName;
100603 }else if( pTab->iPKey>=0 ){
100604 assert( pTab->iPKey<pTab->nCol );
100605 zCol = pTab->aCol[pTab->iPKey].zName;
100606 }else{
100607 zCol = "ROWID";
100609 assert( iDb>=0 && iDb<db->nDb );
100610 if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
100611 pExpr->op = TK_NULL;
100616 ** Do an authorization check using the code and arguments given. Return
100617 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
100618 ** is returned, then the error count and error message in pParse are
100619 ** modified appropriately.
100621 SQLITE_PRIVATE int sqlite3AuthCheck(
100622 Parse *pParse,
100623 int code,
100624 const char *zArg1,
100625 const char *zArg2,
100626 const char *zArg3
100628 sqlite3 *db = pParse->db;
100629 int rc;
100631 /* Don't do any authorization checks if the database is initialising
100632 ** or if the parser is being invoked from within sqlite3_declare_vtab.
100634 if( db->init.busy || IN_DECLARE_VTAB ){
100635 return SQLITE_OK;
100638 if( db->xAuth==0 ){
100639 return SQLITE_OK;
100642 /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
100643 ** callback are either NULL pointers or zero-terminated strings that
100644 ** contain additional details about the action to be authorized.
100646 ** The following testcase() macros show that any of the 3rd through 6th
100647 ** parameters can be either NULL or a string. */
100648 testcase( zArg1==0 );
100649 testcase( zArg2==0 );
100650 testcase( zArg3==0 );
100651 testcase( pParse->zAuthContext==0 );
100653 rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
100654 #ifdef SQLITE_USER_AUTHENTICATION
100655 ,db->auth.zAuthUser
100656 #endif
100658 if( rc==SQLITE_DENY ){
100659 sqlite3ErrorMsg(pParse, "not authorized");
100660 pParse->rc = SQLITE_AUTH;
100661 }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
100662 rc = SQLITE_DENY;
100663 sqliteAuthBadReturnCode(pParse);
100665 return rc;
100669 ** Push an authorization context. After this routine is called, the
100670 ** zArg3 argument to authorization callbacks will be zContext until
100671 ** popped. Or if pParse==0, this routine is a no-op.
100673 SQLITE_PRIVATE void sqlite3AuthContextPush(
100674 Parse *pParse,
100675 AuthContext *pContext,
100676 const char *zContext
100678 assert( pParse );
100679 pContext->pParse = pParse;
100680 pContext->zAuthContext = pParse->zAuthContext;
100681 pParse->zAuthContext = zContext;
100685 ** Pop an authorization context that was previously pushed
100686 ** by sqlite3AuthContextPush
100688 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
100689 if( pContext->pParse ){
100690 pContext->pParse->zAuthContext = pContext->zAuthContext;
100691 pContext->pParse = 0;
100695 #endif /* SQLITE_OMIT_AUTHORIZATION */
100697 /************** End of auth.c ************************************************/
100698 /************** Begin file build.c *******************************************/
100700 ** 2001 September 15
100702 ** The author disclaims copyright to this source code. In place of
100703 ** a legal notice, here is a blessing:
100705 ** May you do good and not evil.
100706 ** May you find forgiveness for yourself and forgive others.
100707 ** May you share freely, never taking more than you give.
100709 *************************************************************************
100710 ** This file contains C code routines that are called by the SQLite parser
100711 ** when syntax rules are reduced. The routines in this file handle the
100712 ** following kinds of SQL syntax:
100714 ** CREATE TABLE
100715 ** DROP TABLE
100716 ** CREATE INDEX
100717 ** DROP INDEX
100718 ** creating ID lists
100719 ** BEGIN TRANSACTION
100720 ** COMMIT
100721 ** ROLLBACK
100723 /* #include "sqliteInt.h" */
100725 #ifndef SQLITE_OMIT_SHARED_CACHE
100727 ** The TableLock structure is only used by the sqlite3TableLock() and
100728 ** codeTableLocks() functions.
100730 struct TableLock {
100731 int iDb; /* The database containing the table to be locked */
100732 int iTab; /* The root page of the table to be locked */
100733 u8 isWriteLock; /* True for write lock. False for a read lock */
100734 const char *zLockName; /* Name of the table */
100738 ** Record the fact that we want to lock a table at run-time.
100740 ** The table to be locked has root page iTab and is found in database iDb.
100741 ** A read or a write lock can be taken depending on isWritelock.
100743 ** This routine just records the fact that the lock is desired. The
100744 ** code to make the lock occur is generated by a later call to
100745 ** codeTableLocks() which occurs during sqlite3FinishCoding().
100747 SQLITE_PRIVATE void sqlite3TableLock(
100748 Parse *pParse, /* Parsing context */
100749 int iDb, /* Index of the database containing the table to lock */
100750 int iTab, /* Root page number of the table to be locked */
100751 u8 isWriteLock, /* True for a write lock */
100752 const char *zName /* Name of the table to be locked */
100754 Parse *pToplevel = sqlite3ParseToplevel(pParse);
100755 int i;
100756 int nBytes;
100757 TableLock *p;
100758 assert( iDb>=0 );
100760 if( iDb==1 ) return;
100761 if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
100762 for(i=0; i<pToplevel->nTableLock; i++){
100763 p = &pToplevel->aTableLock[i];
100764 if( p->iDb==iDb && p->iTab==iTab ){
100765 p->isWriteLock = (p->isWriteLock || isWriteLock);
100766 return;
100770 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
100771 pToplevel->aTableLock =
100772 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
100773 if( pToplevel->aTableLock ){
100774 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
100775 p->iDb = iDb;
100776 p->iTab = iTab;
100777 p->isWriteLock = isWriteLock;
100778 p->zLockName = zName;
100779 }else{
100780 pToplevel->nTableLock = 0;
100781 sqlite3OomFault(pToplevel->db);
100786 ** Code an OP_TableLock instruction for each table locked by the
100787 ** statement (configured by calls to sqlite3TableLock()).
100789 static void codeTableLocks(Parse *pParse){
100790 int i;
100791 Vdbe *pVdbe;
100793 pVdbe = sqlite3GetVdbe(pParse);
100794 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
100796 for(i=0; i<pParse->nTableLock; i++){
100797 TableLock *p = &pParse->aTableLock[i];
100798 int p1 = p->iDb;
100799 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
100800 p->zLockName, P4_STATIC);
100803 #else
100804 #define codeTableLocks(x)
100805 #endif
100808 ** Return TRUE if the given yDbMask object is empty - if it contains no
100809 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
100810 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
100812 #if SQLITE_MAX_ATTACHED>30
100813 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
100814 int i;
100815 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
100816 return 1;
100818 #endif
100821 ** This routine is called after a single SQL statement has been
100822 ** parsed and a VDBE program to execute that statement has been
100823 ** prepared. This routine puts the finishing touches on the
100824 ** VDBE program and resets the pParse structure for the next
100825 ** parse.
100827 ** Note that if an error occurred, it might be the case that
100828 ** no VDBE code was generated.
100830 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
100831 sqlite3 *db;
100832 Vdbe *v;
100834 assert( pParse->pToplevel==0 );
100835 db = pParse->db;
100836 if( pParse->nested ) return;
100837 if( db->mallocFailed || pParse->nErr ){
100838 if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
100839 return;
100842 /* Begin by generating some termination code at the end of the
100843 ** vdbe program
100845 v = sqlite3GetVdbe(pParse);
100846 assert( !pParse->isMultiWrite
100847 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
100848 if( v ){
100849 sqlite3VdbeAddOp0(v, OP_Halt);
100851 #if SQLITE_USER_AUTHENTICATION
100852 if( pParse->nTableLock>0 && db->init.busy==0 ){
100853 sqlite3UserAuthInit(db);
100854 if( db->auth.authLevel<UAUTH_User ){
100855 sqlite3ErrorMsg(pParse, "user not authenticated");
100856 pParse->rc = SQLITE_AUTH_USER;
100857 return;
100860 #endif
100862 /* The cookie mask contains one bit for each database file open.
100863 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
100864 ** set for each database that is used. Generate code to start a
100865 ** transaction on each used database and to verify the schema cookie
100866 ** on each used database.
100868 if( db->mallocFailed==0
100869 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
100871 int iDb, i;
100872 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
100873 sqlite3VdbeJumpHere(v, 0);
100874 for(iDb=0; iDb<db->nDb; iDb++){
100875 Schema *pSchema;
100876 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
100877 sqlite3VdbeUsesBtree(v, iDb);
100878 pSchema = db->aDb[iDb].pSchema;
100879 sqlite3VdbeAddOp4Int(v,
100880 OP_Transaction, /* Opcode */
100881 iDb, /* P1 */
100882 DbMaskTest(pParse->writeMask,iDb), /* P2 */
100883 pSchema->schema_cookie, /* P3 */
100884 pSchema->iGeneration /* P4 */
100886 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
100887 VdbeComment((v,
100888 "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
100890 #ifndef SQLITE_OMIT_VIRTUALTABLE
100891 for(i=0; i<pParse->nVtabLock; i++){
100892 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
100893 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
100895 pParse->nVtabLock = 0;
100896 #endif
100898 /* Once all the cookies have been verified and transactions opened,
100899 ** obtain the required table-locks. This is a no-op unless the
100900 ** shared-cache feature is enabled.
100902 codeTableLocks(pParse);
100904 /* Initialize any AUTOINCREMENT data structures required.
100906 sqlite3AutoincrementBegin(pParse);
100908 /* Code constant expressions that where factored out of inner loops */
100909 if( pParse->pConstExpr ){
100910 ExprList *pEL = pParse->pConstExpr;
100911 pParse->okConstFactor = 0;
100912 for(i=0; i<pEL->nExpr; i++){
100913 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
100917 /* Finally, jump back to the beginning of the executable code. */
100918 sqlite3VdbeGoto(v, 1);
100923 /* Get the VDBE program ready for execution
100925 if( v && pParse->nErr==0 && !db->mallocFailed ){
100926 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
100927 /* A minimum of one cursor is required if autoincrement is used
100928 * See ticket [a696379c1f08866] */
100929 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
100930 sqlite3VdbeMakeReady(v, pParse);
100931 pParse->rc = SQLITE_DONE;
100932 }else{
100933 pParse->rc = SQLITE_ERROR;
100938 ** Run the parser and code generator recursively in order to generate
100939 ** code for the SQL statement given onto the end of the pParse context
100940 ** currently under construction. When the parser is run recursively
100941 ** this way, the final OP_Halt is not appended and other initialization
100942 ** and finalization steps are omitted because those are handling by the
100943 ** outermost parser.
100945 ** Not everything is nestable. This facility is designed to permit
100946 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
100947 ** care if you decide to try to use this routine for some other purposes.
100949 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
100950 va_list ap;
100951 char *zSql;
100952 char *zErrMsg = 0;
100953 sqlite3 *db = pParse->db;
100954 char saveBuf[PARSE_TAIL_SZ];
100956 if( pParse->nErr ) return;
100957 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
100958 va_start(ap, zFormat);
100959 zSql = sqlite3VMPrintf(db, zFormat, ap);
100960 va_end(ap);
100961 if( zSql==0 ){
100962 return; /* A malloc must have failed */
100964 pParse->nested++;
100965 memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
100966 memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
100967 sqlite3RunParser(pParse, zSql, &zErrMsg);
100968 sqlite3DbFree(db, zErrMsg);
100969 sqlite3DbFree(db, zSql);
100970 memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
100971 pParse->nested--;
100974 #if SQLITE_USER_AUTHENTICATION
100976 ** Return TRUE if zTable is the name of the system table that stores the
100977 ** list of users and their access credentials.
100979 SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
100980 return sqlite3_stricmp(zTable, "sqlite_user")==0;
100982 #endif
100985 ** Locate the in-memory structure that describes a particular database
100986 ** table given the name of that table and (optionally) the name of the
100987 ** database containing the table. Return NULL if not found.
100989 ** If zDatabase is 0, all databases are searched for the table and the
100990 ** first matching table is returned. (No checking for duplicate table
100991 ** names is done.) The search order is TEMP first, then MAIN, then any
100992 ** auxiliary databases added using the ATTACH command.
100994 ** See also sqlite3LocateTable().
100996 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
100997 Table *p = 0;
100998 int i;
101000 /* All mutexes are required for schema access. Make sure we hold them. */
101001 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
101002 #if SQLITE_USER_AUTHENTICATION
101003 /* Only the admin user is allowed to know that the sqlite_user table
101004 ** exists */
101005 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
101006 return 0;
101008 #endif
101009 while(1){
101010 for(i=OMIT_TEMPDB; i<db->nDb; i++){
101011 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
101012 if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
101013 assert( sqlite3SchemaMutexHeld(db, j, 0) );
101014 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
101015 if( p ) return p;
101018 /* Not found. If the name we were looking for was temp.sqlite_master
101019 ** then change the name to sqlite_temp_master and try again. */
101020 if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
101021 if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
101022 zName = TEMP_MASTER_NAME;
101024 return 0;
101028 ** Locate the in-memory structure that describes a particular database
101029 ** table given the name of that table and (optionally) the name of the
101030 ** database containing the table. Return NULL if not found. Also leave an
101031 ** error message in pParse->zErrMsg.
101033 ** The difference between this routine and sqlite3FindTable() is that this
101034 ** routine leaves an error message in pParse->zErrMsg where
101035 ** sqlite3FindTable() does not.
101037 SQLITE_PRIVATE Table *sqlite3LocateTable(
101038 Parse *pParse, /* context in which to report errors */
101039 u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
101040 const char *zName, /* Name of the table we are looking for */
101041 const char *zDbase /* Name of the database. Might be NULL */
101043 Table *p;
101045 /* Read the database schema. If an error occurs, leave an error message
101046 ** and code in pParse and return NULL. */
101047 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101048 return 0;
101051 p = sqlite3FindTable(pParse->db, zName, zDbase);
101052 if( p==0 ){
101053 const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
101054 #ifndef SQLITE_OMIT_VIRTUALTABLE
101055 if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
101056 /* If zName is the not the name of a table in the schema created using
101057 ** CREATE, then check to see if it is the name of an virtual table that
101058 ** can be an eponymous virtual table. */
101059 Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
101060 if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
101061 pMod = sqlite3PragmaVtabRegister(pParse->db, zName);
101063 if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
101064 return pMod->pEpoTab;
101067 #endif
101068 if( (flags & LOCATE_NOERR)==0 ){
101069 if( zDbase ){
101070 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
101071 }else{
101072 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
101074 pParse->checkSchema = 1;
101078 return p;
101082 ** Locate the table identified by *p.
101084 ** This is a wrapper around sqlite3LocateTable(). The difference between
101085 ** sqlite3LocateTable() and this function is that this function restricts
101086 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
101087 ** non-NULL if it is part of a view or trigger program definition. See
101088 ** sqlite3FixSrcList() for details.
101090 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
101091 Parse *pParse,
101092 u32 flags,
101093 struct SrcList_item *p
101095 const char *zDb;
101096 assert( p->pSchema==0 || p->zDatabase==0 );
101097 if( p->pSchema ){
101098 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
101099 zDb = pParse->db->aDb[iDb].zDbSName;
101100 }else{
101101 zDb = p->zDatabase;
101103 return sqlite3LocateTable(pParse, flags, p->zName, zDb);
101107 ** Locate the in-memory structure that describes
101108 ** a particular index given the name of that index
101109 ** and the name of the database that contains the index.
101110 ** Return NULL if not found.
101112 ** If zDatabase is 0, all databases are searched for the
101113 ** table and the first matching index is returned. (No checking
101114 ** for duplicate index names is done.) The search order is
101115 ** TEMP first, then MAIN, then any auxiliary databases added
101116 ** using the ATTACH command.
101118 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
101119 Index *p = 0;
101120 int i;
101121 /* All mutexes are required for schema access. Make sure we hold them. */
101122 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
101123 for(i=OMIT_TEMPDB; i<db->nDb; i++){
101124 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
101125 Schema *pSchema = db->aDb[j].pSchema;
101126 assert( pSchema );
101127 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
101128 assert( sqlite3SchemaMutexHeld(db, j, 0) );
101129 p = sqlite3HashFind(&pSchema->idxHash, zName);
101130 if( p ) break;
101132 return p;
101136 ** Reclaim the memory used by an index
101138 static void freeIndex(sqlite3 *db, Index *p){
101139 #ifndef SQLITE_OMIT_ANALYZE
101140 sqlite3DeleteIndexSamples(db, p);
101141 #endif
101142 sqlite3ExprDelete(db, p->pPartIdxWhere);
101143 sqlite3ExprListDelete(db, p->aColExpr);
101144 sqlite3DbFree(db, p->zColAff);
101145 if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
101146 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
101147 sqlite3_free(p->aiRowEst);
101148 #endif
101149 sqlite3DbFree(db, p);
101153 ** For the index called zIdxName which is found in the database iDb,
101154 ** unlike that index from its Table then remove the index from
101155 ** the index hash table and free all memory structures associated
101156 ** with the index.
101158 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
101159 Index *pIndex;
101160 Hash *pHash;
101162 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101163 pHash = &db->aDb[iDb].pSchema->idxHash;
101164 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
101165 if( ALWAYS(pIndex) ){
101166 if( pIndex->pTable->pIndex==pIndex ){
101167 pIndex->pTable->pIndex = pIndex->pNext;
101168 }else{
101169 Index *p;
101170 /* Justification of ALWAYS(); The index must be on the list of
101171 ** indices. */
101172 p = pIndex->pTable->pIndex;
101173 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
101174 if( ALWAYS(p && p->pNext==pIndex) ){
101175 p->pNext = pIndex->pNext;
101178 freeIndex(db, pIndex);
101180 db->mDbFlags |= DBFLAG_SchemaChange;
101184 ** Look through the list of open database files in db->aDb[] and if
101185 ** any have been closed, remove them from the list. Reallocate the
101186 ** db->aDb[] structure to a smaller size, if possible.
101188 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
101189 ** are never candidates for being collapsed.
101191 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
101192 int i, j;
101193 for(i=j=2; i<db->nDb; i++){
101194 struct Db *pDb = &db->aDb[i];
101195 if( pDb->pBt==0 ){
101196 sqlite3DbFree(db, pDb->zDbSName);
101197 pDb->zDbSName = 0;
101198 continue;
101200 if( j<i ){
101201 db->aDb[j] = db->aDb[i];
101205 db->nDb = j;
101206 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
101207 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
101208 sqlite3DbFree(db, db->aDb);
101209 db->aDb = db->aDbStatic;
101214 ** Reset the schema for the database at index iDb. Also reset the
101215 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
101216 ** Deferred resets may be run by calling with iDb<0.
101218 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
101219 int i;
101220 assert( iDb<db->nDb );
101222 if( iDb>=0 ){
101223 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101224 DbSetProperty(db, iDb, DB_ResetWanted);
101225 DbSetProperty(db, 1, DB_ResetWanted);
101228 if( db->nSchemaLock==0 ){
101229 for(i=0; i<db->nDb; i++){
101230 if( DbHasProperty(db, i, DB_ResetWanted) ){
101231 sqlite3SchemaClear(db->aDb[i].pSchema);
101238 ** Erase all schema information from all attached databases (including
101239 ** "main" and "temp") for a single database connection.
101241 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
101242 int i;
101243 sqlite3BtreeEnterAll(db);
101244 assert( db->nSchemaLock==0 );
101245 for(i=0; i<db->nDb; i++){
101246 Db *pDb = &db->aDb[i];
101247 if( pDb->pSchema ){
101248 sqlite3SchemaClear(pDb->pSchema);
101251 db->mDbFlags &= ~DBFLAG_SchemaChange;
101252 sqlite3VtabUnlockList(db);
101253 sqlite3BtreeLeaveAll(db);
101254 sqlite3CollapseDatabaseArray(db);
101258 ** This routine is called when a commit occurs.
101260 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
101261 db->mDbFlags &= ~DBFLAG_SchemaChange;
101265 ** Delete memory allocated for the column names of a table or view (the
101266 ** Table.aCol[] array).
101268 SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
101269 int i;
101270 Column *pCol;
101271 assert( pTable!=0 );
101272 if( (pCol = pTable->aCol)!=0 ){
101273 for(i=0; i<pTable->nCol; i++, pCol++){
101274 sqlite3DbFree(db, pCol->zName);
101275 sqlite3ExprDelete(db, pCol->pDflt);
101276 sqlite3DbFree(db, pCol->zColl);
101278 sqlite3DbFree(db, pTable->aCol);
101283 ** Remove the memory data structures associated with the given
101284 ** Table. No changes are made to disk by this routine.
101286 ** This routine just deletes the data structure. It does not unlink
101287 ** the table data structure from the hash table. But it does destroy
101288 ** memory structures of the indices and foreign keys associated with
101289 ** the table.
101291 ** The db parameter is optional. It is needed if the Table object
101292 ** contains lookaside memory. (Table objects in the schema do not use
101293 ** lookaside memory, but some ephemeral Table objects do.) Or the
101294 ** db parameter can be used with db->pnBytesFreed to measure the memory
101295 ** used by the Table object.
101297 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
101298 Index *pIndex, *pNext;
101300 #ifdef SQLITE_DEBUG
101301 /* Record the number of outstanding lookaside allocations in schema Tables
101302 ** prior to doing any free() operations. Since schema Tables do not use
101303 ** lookaside, this number should not change. */
101304 int nLookaside = 0;
101305 if( db && (pTable->tabFlags & TF_Ephemeral)==0 ){
101306 nLookaside = sqlite3LookasideUsed(db, 0);
101308 #endif
101310 /* Delete all indices associated with this table. */
101311 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
101312 pNext = pIndex->pNext;
101313 assert( pIndex->pSchema==pTable->pSchema
101314 || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
101315 if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
101316 char *zName = pIndex->zName;
101317 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
101318 &pIndex->pSchema->idxHash, zName, 0
101320 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
101321 assert( pOld==pIndex || pOld==0 );
101323 freeIndex(db, pIndex);
101326 /* Delete any foreign keys attached to this table. */
101327 sqlite3FkDelete(db, pTable);
101329 /* Delete the Table structure itself.
101331 sqlite3DeleteColumnNames(db, pTable);
101332 sqlite3DbFree(db, pTable->zName);
101333 sqlite3DbFree(db, pTable->zColAff);
101334 sqlite3SelectDelete(db, pTable->pSelect);
101335 sqlite3ExprListDelete(db, pTable->pCheck);
101336 #ifndef SQLITE_OMIT_VIRTUALTABLE
101337 sqlite3VtabClear(db, pTable);
101338 #endif
101339 sqlite3DbFree(db, pTable);
101341 /* Verify that no lookaside memory was used by schema tables */
101342 assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
101344 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
101345 /* Do not delete the table until the reference count reaches zero. */
101346 if( !pTable ) return;
101347 if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
101348 deleteTable(db, pTable);
101353 ** Unlink the given table from the hash tables and the delete the
101354 ** table structure with all its indices and foreign keys.
101356 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
101357 Table *p;
101358 Db *pDb;
101360 assert( db!=0 );
101361 assert( iDb>=0 && iDb<db->nDb );
101362 assert( zTabName );
101363 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101364 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
101365 pDb = &db->aDb[iDb];
101366 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
101367 sqlite3DeleteTable(db, p);
101368 db->mDbFlags |= DBFLAG_SchemaChange;
101372 ** Given a token, return a string that consists of the text of that
101373 ** token. Space to hold the returned string
101374 ** is obtained from sqliteMalloc() and must be freed by the calling
101375 ** function.
101377 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
101378 ** surround the body of the token are removed.
101380 ** Tokens are often just pointers into the original SQL text and so
101381 ** are not \000 terminated and are not persistent. The returned string
101382 ** is \000 terminated and is persistent.
101384 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
101385 char *zName;
101386 if( pName ){
101387 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
101388 sqlite3Dequote(zName);
101389 }else{
101390 zName = 0;
101392 return zName;
101396 ** Open the sqlite_master table stored in database number iDb for
101397 ** writing. The table is opened using cursor 0.
101399 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
101400 Vdbe *v = sqlite3GetVdbe(p);
101401 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
101402 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
101403 if( p->nTab==0 ){
101404 p->nTab = 1;
101409 ** Parameter zName points to a nul-terminated buffer containing the name
101410 ** of a database ("main", "temp" or the name of an attached db). This
101411 ** function returns the index of the named database in db->aDb[], or
101412 ** -1 if the named db cannot be found.
101414 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
101415 int i = -1; /* Database number */
101416 if( zName ){
101417 Db *pDb;
101418 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
101419 if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
101420 /* "main" is always an acceptable alias for the primary database
101421 ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
101422 if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
101425 return i;
101429 ** The token *pName contains the name of a database (either "main" or
101430 ** "temp" or the name of an attached db). This routine returns the
101431 ** index of the named database in db->aDb[], or -1 if the named db
101432 ** does not exist.
101434 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
101435 int i; /* Database number */
101436 char *zName; /* Name we are searching for */
101437 zName = sqlite3NameFromToken(db, pName);
101438 i = sqlite3FindDbName(db, zName);
101439 sqlite3DbFree(db, zName);
101440 return i;
101443 /* The table or view or trigger name is passed to this routine via tokens
101444 ** pName1 and pName2. If the table name was fully qualified, for example:
101446 ** CREATE TABLE xxx.yyy (...);
101448 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
101449 ** the table name is not fully qualified, i.e.:
101451 ** CREATE TABLE yyy(...);
101453 ** Then pName1 is set to "yyy" and pName2 is "".
101455 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
101456 ** pName2) that stores the unqualified table name. The index of the
101457 ** database "xxx" is returned.
101459 SQLITE_PRIVATE int sqlite3TwoPartName(
101460 Parse *pParse, /* Parsing and code generating context */
101461 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
101462 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
101463 Token **pUnqual /* Write the unqualified object name here */
101465 int iDb; /* Database holding the object */
101466 sqlite3 *db = pParse->db;
101468 assert( pName2!=0 );
101469 if( pName2->n>0 ){
101470 if( db->init.busy ) {
101471 sqlite3ErrorMsg(pParse, "corrupt database");
101472 return -1;
101474 *pUnqual = pName2;
101475 iDb = sqlite3FindDb(db, pName1);
101476 if( iDb<0 ){
101477 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
101478 return -1;
101480 }else{
101481 assert( db->init.iDb==0 || db->init.busy
101482 || (db->mDbFlags & DBFLAG_Vacuum)!=0);
101483 iDb = db->init.iDb;
101484 *pUnqual = pName1;
101486 return iDb;
101490 ** This routine is used to check if the UTF-8 string zName is a legal
101491 ** unqualified name for a new schema object (table, index, view or
101492 ** trigger). All names are legal except those that begin with the string
101493 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
101494 ** is reserved for internal use.
101496 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
101497 if( !pParse->db->init.busy && pParse->nested==0
101498 && (pParse->db->flags & SQLITE_WriteSchema)==0
101499 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
101500 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
101501 return SQLITE_ERROR;
101503 return SQLITE_OK;
101507 ** Return the PRIMARY KEY index of a table
101509 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
101510 Index *p;
101511 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
101512 return p;
101516 ** Return the column of index pIdx that corresponds to table
101517 ** column iCol. Return -1 if not found.
101519 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
101520 int i;
101521 for(i=0; i<pIdx->nColumn; i++){
101522 if( iCol==pIdx->aiColumn[i] ) return i;
101524 return -1;
101528 ** Begin constructing a new table representation in memory. This is
101529 ** the first of several action routines that get called in response
101530 ** to a CREATE TABLE statement. In particular, this routine is called
101531 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
101532 ** flag is true if the table should be stored in the auxiliary database
101533 ** file instead of in the main database file. This is normally the case
101534 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
101535 ** CREATE and TABLE.
101537 ** The new table record is initialized and put in pParse->pNewTable.
101538 ** As more of the CREATE TABLE statement is parsed, additional action
101539 ** routines will be called to add more information to this record.
101540 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
101541 ** is called to complete the construction of the new table record.
101543 SQLITE_PRIVATE void sqlite3StartTable(
101544 Parse *pParse, /* Parser context */
101545 Token *pName1, /* First part of the name of the table or view */
101546 Token *pName2, /* Second part of the name of the table or view */
101547 int isTemp, /* True if this is a TEMP table */
101548 int isView, /* True if this is a VIEW */
101549 int isVirtual, /* True if this is a VIRTUAL table */
101550 int noErr /* Do nothing if table already exists */
101552 Table *pTable;
101553 char *zName = 0; /* The name of the new table */
101554 sqlite3 *db = pParse->db;
101555 Vdbe *v;
101556 int iDb; /* Database number to create the table in */
101557 Token *pName; /* Unqualified name of the table to create */
101559 if( db->init.busy && db->init.newTnum==1 ){
101560 /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
101561 iDb = db->init.iDb;
101562 zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
101563 pName = pName1;
101564 }else{
101565 /* The common case */
101566 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
101567 if( iDb<0 ) return;
101568 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
101569 /* If creating a temp table, the name may not be qualified. Unless
101570 ** the database name is "temp" anyway. */
101571 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
101572 return;
101574 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
101575 zName = sqlite3NameFromToken(db, pName);
101577 pParse->sNameToken = *pName;
101578 if( zName==0 ) return;
101579 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
101580 goto begin_table_error;
101582 if( db->init.iDb==1 ) isTemp = 1;
101583 #ifndef SQLITE_OMIT_AUTHORIZATION
101584 assert( isTemp==0 || isTemp==1 );
101585 assert( isView==0 || isView==1 );
101587 static const u8 aCode[] = {
101588 SQLITE_CREATE_TABLE,
101589 SQLITE_CREATE_TEMP_TABLE,
101590 SQLITE_CREATE_VIEW,
101591 SQLITE_CREATE_TEMP_VIEW
101593 char *zDb = db->aDb[iDb].zDbSName;
101594 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
101595 goto begin_table_error;
101597 if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
101598 zName, 0, zDb) ){
101599 goto begin_table_error;
101602 #endif
101604 /* Make sure the new table name does not collide with an existing
101605 ** index or table name in the same database. Issue an error message if
101606 ** it does. The exception is if the statement being parsed was passed
101607 ** to an sqlite3_declare_vtab() call. In that case only the column names
101608 ** and types will be used, so there is no need to test for namespace
101609 ** collisions.
101611 if( !IN_DECLARE_VTAB ){
101612 char *zDb = db->aDb[iDb].zDbSName;
101613 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101614 goto begin_table_error;
101616 pTable = sqlite3FindTable(db, zName, zDb);
101617 if( pTable ){
101618 if( !noErr ){
101619 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
101620 }else{
101621 assert( !db->init.busy || CORRUPT_DB );
101622 sqlite3CodeVerifySchema(pParse, iDb);
101624 goto begin_table_error;
101626 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
101627 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
101628 goto begin_table_error;
101632 pTable = sqlite3DbMallocZero(db, sizeof(Table));
101633 if( pTable==0 ){
101634 assert( db->mallocFailed );
101635 pParse->rc = SQLITE_NOMEM_BKPT;
101636 pParse->nErr++;
101637 goto begin_table_error;
101639 pTable->zName = zName;
101640 pTable->iPKey = -1;
101641 pTable->pSchema = db->aDb[iDb].pSchema;
101642 pTable->nTabRef = 1;
101643 #ifdef SQLITE_DEFAULT_ROWEST
101644 pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
101645 #else
101646 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
101647 #endif
101648 assert( pParse->pNewTable==0 );
101649 pParse->pNewTable = pTable;
101651 /* If this is the magic sqlite_sequence table used by autoincrement,
101652 ** then record a pointer to this table in the main database structure
101653 ** so that INSERT can find the table easily.
101655 #ifndef SQLITE_OMIT_AUTOINCREMENT
101656 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
101657 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101658 pTable->pSchema->pSeqTab = pTable;
101660 #endif
101662 /* Begin generating the code that will insert the table record into
101663 ** the SQLITE_MASTER table. Note in particular that we must go ahead
101664 ** and allocate the record number for the table entry now. Before any
101665 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
101666 ** indices to be created and the table record must come before the
101667 ** indices. Hence, the record number for the table must be allocated
101668 ** now.
101670 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
101671 int addr1;
101672 int fileFormat;
101673 int reg1, reg2, reg3;
101674 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
101675 static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
101676 sqlite3BeginWriteOperation(pParse, 1, iDb);
101678 #ifndef SQLITE_OMIT_VIRTUALTABLE
101679 if( isVirtual ){
101680 sqlite3VdbeAddOp0(v, OP_VBegin);
101682 #endif
101684 /* If the file format and encoding in the database have not been set,
101685 ** set them now.
101687 reg1 = pParse->regRowid = ++pParse->nMem;
101688 reg2 = pParse->regRoot = ++pParse->nMem;
101689 reg3 = ++pParse->nMem;
101690 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
101691 sqlite3VdbeUsesBtree(v, iDb);
101692 addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
101693 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
101694 1 : SQLITE_MAX_FILE_FORMAT;
101695 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
101696 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
101697 sqlite3VdbeJumpHere(v, addr1);
101699 /* This just creates a place-holder record in the sqlite_master table.
101700 ** The record created does not contain anything yet. It will be replaced
101701 ** by the real entry in code generated at sqlite3EndTable().
101703 ** The rowid for the new entry is left in register pParse->regRowid.
101704 ** The root page number of the new table is left in reg pParse->regRoot.
101705 ** The rowid and root page number values are needed by the code that
101706 ** sqlite3EndTable will generate.
101708 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
101709 if( isView || isVirtual ){
101710 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
101711 }else
101712 #endif
101714 pParse->addrCrTab =
101715 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
101717 sqlite3OpenMasterTable(pParse, iDb);
101718 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
101719 sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
101720 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
101721 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
101722 sqlite3VdbeAddOp0(v, OP_Close);
101725 /* Normal (non-error) return. */
101726 return;
101728 /* If an error occurs, we jump here */
101729 begin_table_error:
101730 sqlite3DbFree(db, zName);
101731 return;
101734 /* Set properties of a table column based on the (magical)
101735 ** name of the column.
101737 #if SQLITE_ENABLE_HIDDEN_COLUMNS
101738 SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
101739 if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
101740 pCol->colFlags |= COLFLAG_HIDDEN;
101741 }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
101742 pTab->tabFlags |= TF_OOOHidden;
101745 #endif
101749 ** Add a new column to the table currently being constructed.
101751 ** The parser calls this routine once for each column declaration
101752 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
101753 ** first to get things going. Then this routine is called for each
101754 ** column.
101756 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
101757 Table *p;
101758 int i;
101759 char *z;
101760 char *zType;
101761 Column *pCol;
101762 sqlite3 *db = pParse->db;
101763 if( (p = pParse->pNewTable)==0 ) return;
101764 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
101765 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
101766 return;
101768 z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
101769 if( z==0 ) return;
101770 memcpy(z, pName->z, pName->n);
101771 z[pName->n] = 0;
101772 sqlite3Dequote(z);
101773 for(i=0; i<p->nCol; i++){
101774 if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
101775 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
101776 sqlite3DbFree(db, z);
101777 return;
101780 if( (p->nCol & 0x7)==0 ){
101781 Column *aNew;
101782 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
101783 if( aNew==0 ){
101784 sqlite3DbFree(db, z);
101785 return;
101787 p->aCol = aNew;
101789 pCol = &p->aCol[p->nCol];
101790 memset(pCol, 0, sizeof(p->aCol[0]));
101791 pCol->zName = z;
101792 sqlite3ColumnPropertiesFromName(p, pCol);
101794 if( pType->n==0 ){
101795 /* If there is no type specified, columns have the default affinity
101796 ** 'BLOB'. */
101797 pCol->affinity = SQLITE_AFF_BLOB;
101798 pCol->szEst = 1;
101799 }else{
101800 zType = z + sqlite3Strlen30(z) + 1;
101801 memcpy(zType, pType->z, pType->n);
101802 zType[pType->n] = 0;
101803 sqlite3Dequote(zType);
101804 pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
101805 pCol->colFlags |= COLFLAG_HASTYPE;
101807 p->nCol++;
101808 pParse->constraintName.n = 0;
101812 ** This routine is called by the parser while in the middle of
101813 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
101814 ** been seen on a column. This routine sets the notNull flag on
101815 ** the column currently under construction.
101817 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
101818 Table *p;
101819 p = pParse->pNewTable;
101820 if( p==0 || NEVER(p->nCol<1) ) return;
101821 p->aCol[p->nCol-1].notNull = (u8)onError;
101822 p->tabFlags |= TF_HasNotNull;
101826 ** Scan the column type name zType (length nType) and return the
101827 ** associated affinity type.
101829 ** This routine does a case-independent search of zType for the
101830 ** substrings in the following table. If one of the substrings is
101831 ** found, the corresponding affinity is returned. If zType contains
101832 ** more than one of the substrings, entries toward the top of
101833 ** the table take priority. For example, if zType is 'BLOBINT',
101834 ** SQLITE_AFF_INTEGER is returned.
101836 ** Substring | Affinity
101837 ** --------------------------------
101838 ** 'INT' | SQLITE_AFF_INTEGER
101839 ** 'CHAR' | SQLITE_AFF_TEXT
101840 ** 'CLOB' | SQLITE_AFF_TEXT
101841 ** 'TEXT' | SQLITE_AFF_TEXT
101842 ** 'BLOB' | SQLITE_AFF_BLOB
101843 ** 'REAL' | SQLITE_AFF_REAL
101844 ** 'FLOA' | SQLITE_AFF_REAL
101845 ** 'DOUB' | SQLITE_AFF_REAL
101847 ** If none of the substrings in the above table are found,
101848 ** SQLITE_AFF_NUMERIC is returned.
101850 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
101851 u32 h = 0;
101852 char aff = SQLITE_AFF_NUMERIC;
101853 const char *zChar = 0;
101855 assert( zIn!=0 );
101856 while( zIn[0] ){
101857 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
101858 zIn++;
101859 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
101860 aff = SQLITE_AFF_TEXT;
101861 zChar = zIn;
101862 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
101863 aff = SQLITE_AFF_TEXT;
101864 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
101865 aff = SQLITE_AFF_TEXT;
101866 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
101867 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
101868 aff = SQLITE_AFF_BLOB;
101869 if( zIn[0]=='(' ) zChar = zIn;
101870 #ifndef SQLITE_OMIT_FLOATING_POINT
101871 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
101872 && aff==SQLITE_AFF_NUMERIC ){
101873 aff = SQLITE_AFF_REAL;
101874 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
101875 && aff==SQLITE_AFF_NUMERIC ){
101876 aff = SQLITE_AFF_REAL;
101877 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
101878 && aff==SQLITE_AFF_NUMERIC ){
101879 aff = SQLITE_AFF_REAL;
101880 #endif
101881 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
101882 aff = SQLITE_AFF_INTEGER;
101883 break;
101887 /* If pszEst is not NULL, store an estimate of the field size. The
101888 ** estimate is scaled so that the size of an integer is 1. */
101889 if( pszEst ){
101890 *pszEst = 1; /* default size is approx 4 bytes */
101891 if( aff<SQLITE_AFF_NUMERIC ){
101892 if( zChar ){
101893 while( zChar[0] ){
101894 if( sqlite3Isdigit(zChar[0]) ){
101895 int v = 0;
101896 sqlite3GetInt32(zChar, &v);
101897 v = v/4 + 1;
101898 if( v>255 ) v = 255;
101899 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
101900 break;
101902 zChar++;
101904 }else{
101905 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
101909 return aff;
101913 ** The expression is the default value for the most recently added column
101914 ** of the table currently under construction.
101916 ** Default value expressions must be constant. Raise an exception if this
101917 ** is not the case.
101919 ** This routine is called by the parser while in the middle of
101920 ** parsing a CREATE TABLE statement.
101922 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
101923 Table *p;
101924 Column *pCol;
101925 sqlite3 *db = pParse->db;
101926 p = pParse->pNewTable;
101927 if( p!=0 ){
101928 pCol = &(p->aCol[p->nCol-1]);
101929 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
101930 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
101931 pCol->zName);
101932 }else{
101933 /* A copy of pExpr is used instead of the original, as pExpr contains
101934 ** tokens that point to volatile memory. The 'span' of the expression
101935 ** is required by pragma table_info.
101937 Expr x;
101938 sqlite3ExprDelete(db, pCol->pDflt);
101939 memset(&x, 0, sizeof(x));
101940 x.op = TK_SPAN;
101941 x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
101942 (int)(pSpan->zEnd - pSpan->zStart));
101943 x.pLeft = pSpan->pExpr;
101944 x.flags = EP_Skip;
101945 pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
101946 sqlite3DbFree(db, x.u.zToken);
101949 sqlite3ExprDelete(db, pSpan->pExpr);
101953 ** Backwards Compatibility Hack:
101955 ** Historical versions of SQLite accepted strings as column names in
101956 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
101958 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
101959 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
101961 ** This is goofy. But to preserve backwards compatibility we continue to
101962 ** accept it. This routine does the necessary conversion. It converts
101963 ** the expression given in its argument from a TK_STRING into a TK_ID
101964 ** if the expression is just a TK_STRING with an optional COLLATE clause.
101965 ** If the epxression is anything other than TK_STRING, the expression is
101966 ** unchanged.
101968 static void sqlite3StringToId(Expr *p){
101969 if( p->op==TK_STRING ){
101970 p->op = TK_ID;
101971 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
101972 p->pLeft->op = TK_ID;
101977 ** Designate the PRIMARY KEY for the table. pList is a list of names
101978 ** of columns that form the primary key. If pList is NULL, then the
101979 ** most recently added column of the table is the primary key.
101981 ** A table can have at most one primary key. If the table already has
101982 ** a primary key (and this is the second primary key) then create an
101983 ** error.
101985 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
101986 ** then we will try to use that column as the rowid. Set the Table.iPKey
101987 ** field of the table under construction to be the index of the
101988 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
101989 ** no INTEGER PRIMARY KEY.
101991 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
101992 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
101994 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
101995 Parse *pParse, /* Parsing context */
101996 ExprList *pList, /* List of field names to be indexed */
101997 int onError, /* What to do with a uniqueness conflict */
101998 int autoInc, /* True if the AUTOINCREMENT keyword is present */
101999 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
102001 Table *pTab = pParse->pNewTable;
102002 Column *pCol = 0;
102003 int iCol = -1, i;
102004 int nTerm;
102005 if( pTab==0 ) goto primary_key_exit;
102006 if( pTab->tabFlags & TF_HasPrimaryKey ){
102007 sqlite3ErrorMsg(pParse,
102008 "table \"%s\" has more than one primary key", pTab->zName);
102009 goto primary_key_exit;
102011 pTab->tabFlags |= TF_HasPrimaryKey;
102012 if( pList==0 ){
102013 iCol = pTab->nCol - 1;
102014 pCol = &pTab->aCol[iCol];
102015 pCol->colFlags |= COLFLAG_PRIMKEY;
102016 nTerm = 1;
102017 }else{
102018 nTerm = pList->nExpr;
102019 for(i=0; i<nTerm; i++){
102020 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
102021 assert( pCExpr!=0 );
102022 sqlite3StringToId(pCExpr);
102023 if( pCExpr->op==TK_ID ){
102024 const char *zCName = pCExpr->u.zToken;
102025 for(iCol=0; iCol<pTab->nCol; iCol++){
102026 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
102027 pCol = &pTab->aCol[iCol];
102028 pCol->colFlags |= COLFLAG_PRIMKEY;
102029 break;
102035 if( nTerm==1
102036 && pCol
102037 && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
102038 && sortOrder!=SQLITE_SO_DESC
102040 pTab->iPKey = iCol;
102041 pTab->keyConf = (u8)onError;
102042 assert( autoInc==0 || autoInc==1 );
102043 pTab->tabFlags |= autoInc*TF_Autoincrement;
102044 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
102045 }else if( autoInc ){
102046 #ifndef SQLITE_OMIT_AUTOINCREMENT
102047 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
102048 "INTEGER PRIMARY KEY");
102049 #endif
102050 }else{
102051 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
102052 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
102053 pList = 0;
102056 primary_key_exit:
102057 sqlite3ExprListDelete(pParse->db, pList);
102058 return;
102062 ** Add a new CHECK constraint to the table currently under construction.
102064 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
102065 Parse *pParse, /* Parsing context */
102066 Expr *pCheckExpr /* The check expression */
102068 #ifndef SQLITE_OMIT_CHECK
102069 Table *pTab = pParse->pNewTable;
102070 sqlite3 *db = pParse->db;
102071 if( pTab && !IN_DECLARE_VTAB
102072 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
102074 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
102075 if( pParse->constraintName.n ){
102076 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
102078 }else
102079 #endif
102081 sqlite3ExprDelete(pParse->db, pCheckExpr);
102086 ** Set the collation function of the most recently parsed table column
102087 ** to the CollSeq given.
102089 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
102090 Table *p;
102091 int i;
102092 char *zColl; /* Dequoted name of collation sequence */
102093 sqlite3 *db;
102095 if( (p = pParse->pNewTable)==0 ) return;
102096 i = p->nCol-1;
102097 db = pParse->db;
102098 zColl = sqlite3NameFromToken(db, pToken);
102099 if( !zColl ) return;
102101 if( sqlite3LocateCollSeq(pParse, zColl) ){
102102 Index *pIdx;
102103 sqlite3DbFree(db, p->aCol[i].zColl);
102104 p->aCol[i].zColl = zColl;
102106 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
102107 ** then an index may have been created on this column before the
102108 ** collation type was added. Correct this if it is the case.
102110 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
102111 assert( pIdx->nKeyCol==1 );
102112 if( pIdx->aiColumn[0]==i ){
102113 pIdx->azColl[0] = p->aCol[i].zColl;
102116 }else{
102117 sqlite3DbFree(db, zColl);
102122 ** This function returns the collation sequence for database native text
102123 ** encoding identified by the string zName, length nName.
102125 ** If the requested collation sequence is not available, or not available
102126 ** in the database native encoding, the collation factory is invoked to
102127 ** request it. If the collation factory does not supply such a sequence,
102128 ** and the sequence is available in another text encoding, then that is
102129 ** returned instead.
102131 ** If no versions of the requested collations sequence are available, or
102132 ** another error occurs, NULL is returned and an error message written into
102133 ** pParse.
102135 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
102136 ** invokes the collation factory if the named collation cannot be found
102137 ** and generates an error message.
102139 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
102141 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
102142 sqlite3 *db = pParse->db;
102143 u8 enc = ENC(db);
102144 u8 initbusy = db->init.busy;
102145 CollSeq *pColl;
102147 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
102148 if( !initbusy && (!pColl || !pColl->xCmp) ){
102149 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
102152 return pColl;
102157 ** Generate code that will increment the schema cookie.
102159 ** The schema cookie is used to determine when the schema for the
102160 ** database changes. After each schema change, the cookie value
102161 ** changes. When a process first reads the schema it records the
102162 ** cookie. Thereafter, whenever it goes to access the database,
102163 ** it checks the cookie to make sure the schema has not changed
102164 ** since it was last read.
102166 ** This plan is not completely bullet-proof. It is possible for
102167 ** the schema to change multiple times and for the cookie to be
102168 ** set back to prior value. But schema changes are infrequent
102169 ** and the probability of hitting the same cookie value is only
102170 ** 1 chance in 2^32. So we're safe enough.
102172 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
102173 ** the schema-version whenever the schema changes.
102175 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
102176 sqlite3 *db = pParse->db;
102177 Vdbe *v = pParse->pVdbe;
102178 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102179 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
102180 db->aDb[iDb].pSchema->schema_cookie+1);
102184 ** Measure the number of characters needed to output the given
102185 ** identifier. The number returned includes any quotes used
102186 ** but does not include the null terminator.
102188 ** The estimate is conservative. It might be larger that what is
102189 ** really needed.
102191 static int identLength(const char *z){
102192 int n;
102193 for(n=0; *z; n++, z++){
102194 if( *z=='"' ){ n++; }
102196 return n + 2;
102200 ** The first parameter is a pointer to an output buffer. The second
102201 ** parameter is a pointer to an integer that contains the offset at
102202 ** which to write into the output buffer. This function copies the
102203 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
102204 ** to the specified offset in the buffer and updates *pIdx to refer
102205 ** to the first byte after the last byte written before returning.
102207 ** If the string zSignedIdent consists entirely of alpha-numeric
102208 ** characters, does not begin with a digit and is not an SQL keyword,
102209 ** then it is copied to the output buffer exactly as it is. Otherwise,
102210 ** it is quoted using double-quotes.
102212 static void identPut(char *z, int *pIdx, char *zSignedIdent){
102213 unsigned char *zIdent = (unsigned char*)zSignedIdent;
102214 int i, j, needQuote;
102215 i = *pIdx;
102217 for(j=0; zIdent[j]; j++){
102218 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
102220 needQuote = sqlite3Isdigit(zIdent[0])
102221 || sqlite3KeywordCode(zIdent, j)!=TK_ID
102222 || zIdent[j]!=0
102223 || j==0;
102225 if( needQuote ) z[i++] = '"';
102226 for(j=0; zIdent[j]; j++){
102227 z[i++] = zIdent[j];
102228 if( zIdent[j]=='"' ) z[i++] = '"';
102230 if( needQuote ) z[i++] = '"';
102231 z[i] = 0;
102232 *pIdx = i;
102236 ** Generate a CREATE TABLE statement appropriate for the given
102237 ** table. Memory to hold the text of the statement is obtained
102238 ** from sqliteMalloc() and must be freed by the calling function.
102240 static char *createTableStmt(sqlite3 *db, Table *p){
102241 int i, k, n;
102242 char *zStmt;
102243 char *zSep, *zSep2, *zEnd;
102244 Column *pCol;
102245 n = 0;
102246 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
102247 n += identLength(pCol->zName) + 5;
102249 n += identLength(p->zName);
102250 if( n<50 ){
102251 zSep = "";
102252 zSep2 = ",";
102253 zEnd = ")";
102254 }else{
102255 zSep = "\n ";
102256 zSep2 = ",\n ";
102257 zEnd = "\n)";
102259 n += 35 + 6*p->nCol;
102260 zStmt = sqlite3DbMallocRaw(0, n);
102261 if( zStmt==0 ){
102262 sqlite3OomFault(db);
102263 return 0;
102265 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
102266 k = sqlite3Strlen30(zStmt);
102267 identPut(zStmt, &k, p->zName);
102268 zStmt[k++] = '(';
102269 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
102270 static const char * const azType[] = {
102271 /* SQLITE_AFF_BLOB */ "",
102272 /* SQLITE_AFF_TEXT */ " TEXT",
102273 /* SQLITE_AFF_NUMERIC */ " NUM",
102274 /* SQLITE_AFF_INTEGER */ " INT",
102275 /* SQLITE_AFF_REAL */ " REAL"
102277 int len;
102278 const char *zType;
102280 sqlite3_snprintf(n-k, &zStmt[k], zSep);
102281 k += sqlite3Strlen30(&zStmt[k]);
102282 zSep = zSep2;
102283 identPut(zStmt, &k, pCol->zName);
102284 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
102285 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
102286 testcase( pCol->affinity==SQLITE_AFF_BLOB );
102287 testcase( pCol->affinity==SQLITE_AFF_TEXT );
102288 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
102289 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
102290 testcase( pCol->affinity==SQLITE_AFF_REAL );
102292 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
102293 len = sqlite3Strlen30(zType);
102294 assert( pCol->affinity==SQLITE_AFF_BLOB
102295 || pCol->affinity==sqlite3AffinityType(zType, 0) );
102296 memcpy(&zStmt[k], zType, len);
102297 k += len;
102298 assert( k<=n );
102300 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
102301 return zStmt;
102305 ** Resize an Index object to hold N columns total. Return SQLITE_OK
102306 ** on success and SQLITE_NOMEM on an OOM error.
102308 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
102309 char *zExtra;
102310 int nByte;
102311 if( pIdx->nColumn>=N ) return SQLITE_OK;
102312 assert( pIdx->isResized==0 );
102313 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
102314 zExtra = sqlite3DbMallocZero(db, nByte);
102315 if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
102316 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
102317 pIdx->azColl = (const char**)zExtra;
102318 zExtra += sizeof(char*)*N;
102319 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
102320 pIdx->aiColumn = (i16*)zExtra;
102321 zExtra += sizeof(i16)*N;
102322 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
102323 pIdx->aSortOrder = (u8*)zExtra;
102324 pIdx->nColumn = N;
102325 pIdx->isResized = 1;
102326 return SQLITE_OK;
102330 ** Estimate the total row width for a table.
102332 static void estimateTableWidth(Table *pTab){
102333 unsigned wTable = 0;
102334 const Column *pTabCol;
102335 int i;
102336 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
102337 wTable += pTabCol->szEst;
102339 if( pTab->iPKey<0 ) wTable++;
102340 pTab->szTabRow = sqlite3LogEst(wTable*4);
102344 ** Estimate the average size of a row for an index.
102346 static void estimateIndexWidth(Index *pIdx){
102347 unsigned wIndex = 0;
102348 int i;
102349 const Column *aCol = pIdx->pTable->aCol;
102350 for(i=0; i<pIdx->nColumn; i++){
102351 i16 x = pIdx->aiColumn[i];
102352 assert( x<pIdx->pTable->nCol );
102353 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
102355 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
102358 /* Return true if value x is found any of the first nCol entries of aiCol[]
102360 static int hasColumn(const i16 *aiCol, int nCol, int x){
102361 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
102362 return 0;
102366 ** This routine runs at the end of parsing a CREATE TABLE statement that
102367 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
102368 ** internal schema data structures and the generated VDBE code so that they
102369 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
102370 ** Changes include:
102372 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
102373 ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
102374 ** into BTREE_BLOBKEY.
102375 ** (3) Bypass the creation of the sqlite_master table entry
102376 ** for the PRIMARY KEY as the primary key index is now
102377 ** identified by the sqlite_master table entry of the table itself.
102378 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
102379 ** schema to the rootpage from the main table.
102380 ** (5) Add all table columns to the PRIMARY KEY Index object
102381 ** so that the PRIMARY KEY is a covering index. The surplus
102382 ** columns are part of KeyInfo.nAllField and are not used for
102383 ** sorting or lookup or uniqueness checks.
102384 ** (6) Replace the rowid tail on all automatically generated UNIQUE
102385 ** indices with the PRIMARY KEY columns.
102387 ** For virtual tables, only (1) is performed.
102389 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
102390 Index *pIdx;
102391 Index *pPk;
102392 int nPk;
102393 int i, j;
102394 sqlite3 *db = pParse->db;
102395 Vdbe *v = pParse->pVdbe;
102397 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
102399 if( !db->init.imposterTable ){
102400 for(i=0; i<pTab->nCol; i++){
102401 if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
102402 pTab->aCol[i].notNull = OE_Abort;
102407 /* The remaining transformations only apply to b-tree tables, not to
102408 ** virtual tables */
102409 if( IN_DECLARE_VTAB ) return;
102411 /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
102412 ** into BTREE_BLOBKEY.
102414 if( pParse->addrCrTab ){
102415 assert( v );
102416 sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
102419 /* Locate the PRIMARY KEY index. Or, if this table was originally
102420 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
102422 if( pTab->iPKey>=0 ){
102423 ExprList *pList;
102424 Token ipkToken;
102425 sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
102426 pList = sqlite3ExprListAppend(pParse, 0,
102427 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
102428 if( pList==0 ) return;
102429 pList->a[0].sortOrder = pParse->iPkSortOrder;
102430 assert( pParse->pNewTable==pTab );
102431 sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
102432 SQLITE_IDXTYPE_PRIMARYKEY);
102433 if( db->mallocFailed ) return;
102434 pPk = sqlite3PrimaryKeyIndex(pTab);
102435 pTab->iPKey = -1;
102436 }else{
102437 pPk = sqlite3PrimaryKeyIndex(pTab);
102440 ** Remove all redundant columns from the PRIMARY KEY. For example, change
102441 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
102442 ** code assumes the PRIMARY KEY contains no repeated columns.
102444 for(i=j=1; i<pPk->nKeyCol; i++){
102445 if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
102446 pPk->nColumn--;
102447 }else{
102448 pPk->aiColumn[j++] = pPk->aiColumn[i];
102451 pPk->nKeyCol = j;
102453 assert( pPk!=0 );
102454 pPk->isCovering = 1;
102455 if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
102456 nPk = pPk->nKeyCol;
102458 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
102459 ** table entry. This is only required if currently generating VDBE
102460 ** code for a CREATE TABLE (not when parsing one as part of reading
102461 ** a database schema). */
102462 if( v && pPk->tnum>0 ){
102463 assert( db->init.busy==0 );
102464 sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
102467 /* The root page of the PRIMARY KEY is the table root page */
102468 pPk->tnum = pTab->tnum;
102470 /* Update the in-memory representation of all UNIQUE indices by converting
102471 ** the final rowid column into one or more columns of the PRIMARY KEY.
102473 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102474 int n;
102475 if( IsPrimaryKeyIndex(pIdx) ) continue;
102476 for(i=n=0; i<nPk; i++){
102477 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
102479 if( n==0 ){
102480 /* This index is a superset of the primary key */
102481 pIdx->nColumn = pIdx->nKeyCol;
102482 continue;
102484 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
102485 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
102486 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
102487 pIdx->aiColumn[j] = pPk->aiColumn[i];
102488 pIdx->azColl[j] = pPk->azColl[i];
102492 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
102493 assert( pIdx->nColumn>=j );
102496 /* Add all table columns to the PRIMARY KEY index
102498 if( nPk<pTab->nCol ){
102499 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
102500 for(i=0, j=nPk; i<pTab->nCol; i++){
102501 if( !hasColumn(pPk->aiColumn, j, i) ){
102502 assert( j<pPk->nColumn );
102503 pPk->aiColumn[j] = i;
102504 pPk->azColl[j] = sqlite3StrBINARY;
102508 assert( pPk->nColumn==j );
102509 assert( pTab->nCol==j );
102510 }else{
102511 pPk->nColumn = pTab->nCol;
102516 ** This routine is called to report the final ")" that terminates
102517 ** a CREATE TABLE statement.
102519 ** The table structure that other action routines have been building
102520 ** is added to the internal hash tables, assuming no errors have
102521 ** occurred.
102523 ** An entry for the table is made in the master table on disk, unless
102524 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
102525 ** it means we are reading the sqlite_master table because we just
102526 ** connected to the database or because the sqlite_master table has
102527 ** recently changed, so the entry for this table already exists in
102528 ** the sqlite_master table. We do not want to create it again.
102530 ** If the pSelect argument is not NULL, it means that this routine
102531 ** was called to create a table generated from a
102532 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
102533 ** the new table will match the result set of the SELECT.
102535 SQLITE_PRIVATE void sqlite3EndTable(
102536 Parse *pParse, /* Parse context */
102537 Token *pCons, /* The ',' token after the last column defn. */
102538 Token *pEnd, /* The ')' before options in the CREATE TABLE */
102539 u8 tabOpts, /* Extra table options. Usually 0. */
102540 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
102542 Table *p; /* The new table */
102543 sqlite3 *db = pParse->db; /* The database connection */
102544 int iDb; /* Database in which the table lives */
102545 Index *pIdx; /* An implied index of the table */
102547 if( pEnd==0 && pSelect==0 ){
102548 return;
102550 assert( !db->mallocFailed );
102551 p = pParse->pNewTable;
102552 if( p==0 ) return;
102554 assert( !db->init.busy || !pSelect );
102556 /* If the db->init.busy is 1 it means we are reading the SQL off the
102557 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
102558 ** So do not write to the disk again. Extract the root page number
102559 ** for the table from the db->init.newTnum field. (The page number
102560 ** should have been put there by the sqliteOpenCb routine.)
102562 ** If the root page number is 1, that means this is the sqlite_master
102563 ** table itself. So mark it read-only.
102565 if( db->init.busy ){
102566 p->tnum = db->init.newTnum;
102567 if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
102570 /* Special processing for WITHOUT ROWID Tables */
102571 if( tabOpts & TF_WithoutRowid ){
102572 if( (p->tabFlags & TF_Autoincrement) ){
102573 sqlite3ErrorMsg(pParse,
102574 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
102575 return;
102577 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
102578 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
102579 }else{
102580 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
102581 convertToWithoutRowidTable(pParse, p);
102585 iDb = sqlite3SchemaToIndex(db, p->pSchema);
102587 #ifndef SQLITE_OMIT_CHECK
102588 /* Resolve names in all CHECK constraint expressions.
102590 if( p->pCheck ){
102591 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
102593 #endif /* !defined(SQLITE_OMIT_CHECK) */
102595 /* Estimate the average row size for the table and for all implied indices */
102596 estimateTableWidth(p);
102597 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
102598 estimateIndexWidth(pIdx);
102601 /* If not initializing, then create a record for the new table
102602 ** in the SQLITE_MASTER table of the database.
102604 ** If this is a TEMPORARY table, write the entry into the auxiliary
102605 ** file instead of into the main database file.
102607 if( !db->init.busy ){
102608 int n;
102609 Vdbe *v;
102610 char *zType; /* "view" or "table" */
102611 char *zType2; /* "VIEW" or "TABLE" */
102612 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
102614 v = sqlite3GetVdbe(pParse);
102615 if( NEVER(v==0) ) return;
102617 sqlite3VdbeAddOp1(v, OP_Close, 0);
102620 ** Initialize zType for the new view or table.
102622 if( p->pSelect==0 ){
102623 /* A regular table */
102624 zType = "table";
102625 zType2 = "TABLE";
102626 #ifndef SQLITE_OMIT_VIEW
102627 }else{
102628 /* A view */
102629 zType = "view";
102630 zType2 = "VIEW";
102631 #endif
102634 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
102635 ** statement to populate the new table. The root-page number for the
102636 ** new table is in register pParse->regRoot.
102638 ** Once the SELECT has been coded by sqlite3Select(), it is in a
102639 ** suitable state to query for the column names and types to be used
102640 ** by the new table.
102642 ** A shared-cache write-lock is not required to write to the new table,
102643 ** as a schema-lock must have already been obtained to create it. Since
102644 ** a schema-lock excludes all other database users, the write-lock would
102645 ** be redundant.
102647 if( pSelect ){
102648 SelectDest dest; /* Where the SELECT should store results */
102649 int regYield; /* Register holding co-routine entry-point */
102650 int addrTop; /* Top of the co-routine */
102651 int regRec; /* A record to be insert into the new table */
102652 int regRowid; /* Rowid of the next row to insert */
102653 int addrInsLoop; /* Top of the loop for inserting rows */
102654 Table *pSelTab; /* A table that describes the SELECT results */
102656 regYield = ++pParse->nMem;
102657 regRec = ++pParse->nMem;
102658 regRowid = ++pParse->nMem;
102659 assert(pParse->nTab==1);
102660 sqlite3MayAbort(pParse);
102661 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
102662 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
102663 pParse->nTab = 2;
102664 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
102665 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
102666 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
102667 sqlite3Select(pParse, pSelect, &dest);
102668 sqlite3VdbeEndCoroutine(v, regYield);
102669 sqlite3VdbeJumpHere(v, addrTop - 1);
102670 if( pParse->nErr ) return;
102671 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
102672 if( pSelTab==0 ) return;
102673 assert( p->aCol==0 );
102674 p->nCol = pSelTab->nCol;
102675 p->aCol = pSelTab->aCol;
102676 pSelTab->nCol = 0;
102677 pSelTab->aCol = 0;
102678 sqlite3DeleteTable(db, pSelTab);
102679 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
102680 VdbeCoverage(v);
102681 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
102682 sqlite3TableAffinity(v, p, 0);
102683 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
102684 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
102685 sqlite3VdbeGoto(v, addrInsLoop);
102686 sqlite3VdbeJumpHere(v, addrInsLoop);
102687 sqlite3VdbeAddOp1(v, OP_Close, 1);
102690 /* Compute the complete text of the CREATE statement */
102691 if( pSelect ){
102692 zStmt = createTableStmt(db, p);
102693 }else{
102694 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
102695 n = (int)(pEnd2->z - pParse->sNameToken.z);
102696 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
102697 zStmt = sqlite3MPrintf(db,
102698 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
102702 /* A slot for the record has already been allocated in the
102703 ** SQLITE_MASTER table. We just need to update that slot with all
102704 ** the information we've collected.
102706 sqlite3NestedParse(pParse,
102707 "UPDATE %Q.%s "
102708 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
102709 "WHERE rowid=#%d",
102710 db->aDb[iDb].zDbSName, MASTER_NAME,
102711 zType,
102712 p->zName,
102713 p->zName,
102714 pParse->regRoot,
102715 zStmt,
102716 pParse->regRowid
102718 sqlite3DbFree(db, zStmt);
102719 sqlite3ChangeCookie(pParse, iDb);
102721 #ifndef SQLITE_OMIT_AUTOINCREMENT
102722 /* Check to see if we need to create an sqlite_sequence table for
102723 ** keeping track of autoincrement keys.
102725 if( (p->tabFlags & TF_Autoincrement)!=0 ){
102726 Db *pDb = &db->aDb[iDb];
102727 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102728 if( pDb->pSchema->pSeqTab==0 ){
102729 sqlite3NestedParse(pParse,
102730 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
102731 pDb->zDbSName
102735 #endif
102737 /* Reparse everything to update our internal data structures */
102738 sqlite3VdbeAddParseSchemaOp(v, iDb,
102739 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
102743 /* Add the table to the in-memory representation of the database.
102745 if( db->init.busy ){
102746 Table *pOld;
102747 Schema *pSchema = p->pSchema;
102748 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102749 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
102750 if( pOld ){
102751 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
102752 sqlite3OomFault(db);
102753 return;
102755 pParse->pNewTable = 0;
102756 db->mDbFlags |= DBFLAG_SchemaChange;
102758 #ifndef SQLITE_OMIT_ALTERTABLE
102759 if( !p->pSelect ){
102760 const char *zName = (const char *)pParse->sNameToken.z;
102761 int nName;
102762 assert( !pSelect && pCons && pEnd );
102763 if( pCons->z==0 ){
102764 pCons = pEnd;
102766 nName = (int)((const char *)pCons->z - zName);
102767 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
102769 #endif
102773 #ifndef SQLITE_OMIT_VIEW
102775 ** The parser calls this routine in order to create a new VIEW
102777 SQLITE_PRIVATE void sqlite3CreateView(
102778 Parse *pParse, /* The parsing context */
102779 Token *pBegin, /* The CREATE token that begins the statement */
102780 Token *pName1, /* The token that holds the name of the view */
102781 Token *pName2, /* The token that holds the name of the view */
102782 ExprList *pCNames, /* Optional list of view column names */
102783 Select *pSelect, /* A SELECT statement that will become the new view */
102784 int isTemp, /* TRUE for a TEMPORARY view */
102785 int noErr /* Suppress error messages if VIEW already exists */
102787 Table *p;
102788 int n;
102789 const char *z;
102790 Token sEnd;
102791 DbFixer sFix;
102792 Token *pName = 0;
102793 int iDb;
102794 sqlite3 *db = pParse->db;
102796 if( pParse->nVar>0 ){
102797 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
102798 goto create_view_fail;
102800 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
102801 p = pParse->pNewTable;
102802 if( p==0 || pParse->nErr ) goto create_view_fail;
102803 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
102804 iDb = sqlite3SchemaToIndex(db, p->pSchema);
102805 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
102806 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
102808 /* Make a copy of the entire SELECT statement that defines the view.
102809 ** This will force all the Expr.token.z values to be dynamically
102810 ** allocated rather than point to the input string - which means that
102811 ** they will persist after the current sqlite3_exec() call returns.
102813 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
102814 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
102815 if( db->mallocFailed ) goto create_view_fail;
102817 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
102818 ** the end.
102820 sEnd = pParse->sLastToken;
102821 assert( sEnd.z[0]!=0 );
102822 if( sEnd.z[0]!=';' ){
102823 sEnd.z += sEnd.n;
102825 sEnd.n = 0;
102826 n = (int)(sEnd.z - pBegin->z);
102827 assert( n>0 );
102828 z = pBegin->z;
102829 while( sqlite3Isspace(z[n-1]) ){ n--; }
102830 sEnd.z = &z[n-1];
102831 sEnd.n = 1;
102833 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
102834 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
102836 create_view_fail:
102837 sqlite3SelectDelete(db, pSelect);
102838 sqlite3ExprListDelete(db, pCNames);
102839 return;
102841 #endif /* SQLITE_OMIT_VIEW */
102843 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
102845 ** The Table structure pTable is really a VIEW. Fill in the names of
102846 ** the columns of the view in the pTable structure. Return the number
102847 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
102849 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
102850 Table *pSelTab; /* A fake table from which we get the result set */
102851 Select *pSel; /* Copy of the SELECT that implements the view */
102852 int nErr = 0; /* Number of errors encountered */
102853 int n; /* Temporarily holds the number of cursors assigned */
102854 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
102855 #ifndef SQLITE_OMIT_VIRTUALTABLE
102856 int rc;
102857 #endif
102858 #ifndef SQLITE_OMIT_AUTHORIZATION
102859 sqlite3_xauth xAuth; /* Saved xAuth pointer */
102860 #endif
102862 assert( pTable );
102864 #ifndef SQLITE_OMIT_VIRTUALTABLE
102865 db->nSchemaLock++;
102866 rc = sqlite3VtabCallConnect(pParse, pTable);
102867 db->nSchemaLock--;
102868 if( rc ){
102869 return 1;
102871 if( IsVirtual(pTable) ) return 0;
102872 #endif
102874 #ifndef SQLITE_OMIT_VIEW
102875 /* A positive nCol means the columns names for this view are
102876 ** already known.
102878 if( pTable->nCol>0 ) return 0;
102880 /* A negative nCol is a special marker meaning that we are currently
102881 ** trying to compute the column names. If we enter this routine with
102882 ** a negative nCol, it means two or more views form a loop, like this:
102884 ** CREATE VIEW one AS SELECT * FROM two;
102885 ** CREATE VIEW two AS SELECT * FROM one;
102887 ** Actually, the error above is now caught prior to reaching this point.
102888 ** But the following test is still important as it does come up
102889 ** in the following:
102891 ** CREATE TABLE main.ex1(a);
102892 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
102893 ** SELECT * FROM temp.ex1;
102895 if( pTable->nCol<0 ){
102896 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
102897 return 1;
102899 assert( pTable->nCol>=0 );
102901 /* If we get this far, it means we need to compute the table names.
102902 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
102903 ** "*" elements in the results set of the view and will assign cursors
102904 ** to the elements of the FROM clause. But we do not want these changes
102905 ** to be permanent. So the computation is done on a copy of the SELECT
102906 ** statement that defines the view.
102908 assert( pTable->pSelect );
102909 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
102910 if( pSel ){
102911 n = pParse->nTab;
102912 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
102913 pTable->nCol = -1;
102914 db->lookaside.bDisable++;
102915 #ifndef SQLITE_OMIT_AUTHORIZATION
102916 xAuth = db->xAuth;
102917 db->xAuth = 0;
102918 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
102919 db->xAuth = xAuth;
102920 #else
102921 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
102922 #endif
102923 pParse->nTab = n;
102924 if( pTable->pCheck ){
102925 /* CREATE VIEW name(arglist) AS ...
102926 ** The names of the columns in the table are taken from
102927 ** arglist which is stored in pTable->pCheck. The pCheck field
102928 ** normally holds CHECK constraints on an ordinary table, but for
102929 ** a VIEW it holds the list of column names.
102931 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
102932 &pTable->nCol, &pTable->aCol);
102933 if( db->mallocFailed==0
102934 && pParse->nErr==0
102935 && pTable->nCol==pSel->pEList->nExpr
102937 sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
102939 }else if( pSelTab ){
102940 /* CREATE VIEW name AS... without an argument list. Construct
102941 ** the column names from the SELECT statement that defines the view.
102943 assert( pTable->aCol==0 );
102944 pTable->nCol = pSelTab->nCol;
102945 pTable->aCol = pSelTab->aCol;
102946 pSelTab->nCol = 0;
102947 pSelTab->aCol = 0;
102948 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
102949 }else{
102950 pTable->nCol = 0;
102951 nErr++;
102953 sqlite3DeleteTable(db, pSelTab);
102954 sqlite3SelectDelete(db, pSel);
102955 db->lookaside.bDisable--;
102956 } else {
102957 nErr++;
102959 pTable->pSchema->schemaFlags |= DB_UnresetViews;
102960 #endif /* SQLITE_OMIT_VIEW */
102961 return nErr;
102963 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
102965 #ifndef SQLITE_OMIT_VIEW
102967 ** Clear the column names from every VIEW in database idx.
102969 static void sqliteViewResetAll(sqlite3 *db, int idx){
102970 HashElem *i;
102971 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
102972 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
102973 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
102974 Table *pTab = sqliteHashData(i);
102975 if( pTab->pSelect ){
102976 sqlite3DeleteColumnNames(db, pTab);
102977 pTab->aCol = 0;
102978 pTab->nCol = 0;
102981 DbClearProperty(db, idx, DB_UnresetViews);
102983 #else
102984 # define sqliteViewResetAll(A,B)
102985 #endif /* SQLITE_OMIT_VIEW */
102988 ** This function is called by the VDBE to adjust the internal schema
102989 ** used by SQLite when the btree layer moves a table root page. The
102990 ** root-page of a table or index in database iDb has changed from iFrom
102991 ** to iTo.
102993 ** Ticket #1728: The symbol table might still contain information
102994 ** on tables and/or indices that are the process of being deleted.
102995 ** If you are unlucky, one of those deleted indices or tables might
102996 ** have the same rootpage number as the real table or index that is
102997 ** being moved. So we cannot stop searching after the first match
102998 ** because the first match might be for one of the deleted indices
102999 ** or tables and not the table/index that is actually being moved.
103000 ** We must continue looping until all tables and indices with
103001 ** rootpage==iFrom have been converted to have a rootpage of iTo
103002 ** in order to be certain that we got the right one.
103004 #ifndef SQLITE_OMIT_AUTOVACUUM
103005 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
103006 HashElem *pElem;
103007 Hash *pHash;
103008 Db *pDb;
103010 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
103011 pDb = &db->aDb[iDb];
103012 pHash = &pDb->pSchema->tblHash;
103013 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
103014 Table *pTab = sqliteHashData(pElem);
103015 if( pTab->tnum==iFrom ){
103016 pTab->tnum = iTo;
103019 pHash = &pDb->pSchema->idxHash;
103020 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
103021 Index *pIdx = sqliteHashData(pElem);
103022 if( pIdx->tnum==iFrom ){
103023 pIdx->tnum = iTo;
103027 #endif
103030 ** Write code to erase the table with root-page iTable from database iDb.
103031 ** Also write code to modify the sqlite_master table and internal schema
103032 ** if a root-page of another table is moved by the btree-layer whilst
103033 ** erasing iTable (this can happen with an auto-vacuum database).
103035 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
103036 Vdbe *v = sqlite3GetVdbe(pParse);
103037 int r1 = sqlite3GetTempReg(pParse);
103038 assert( iTable>1 );
103039 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
103040 sqlite3MayAbort(pParse);
103041 #ifndef SQLITE_OMIT_AUTOVACUUM
103042 /* OP_Destroy stores an in integer r1. If this integer
103043 ** is non-zero, then it is the root page number of a table moved to
103044 ** location iTable. The following code modifies the sqlite_master table to
103045 ** reflect this.
103047 ** The "#NNN" in the SQL is a special constant that means whatever value
103048 ** is in register NNN. See grammar rules associated with the TK_REGISTER
103049 ** token for additional information.
103051 sqlite3NestedParse(pParse,
103052 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
103053 pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
103054 #endif
103055 sqlite3ReleaseTempReg(pParse, r1);
103059 ** Write VDBE code to erase table pTab and all associated indices on disk.
103060 ** Code to update the sqlite_master tables and internal schema definitions
103061 ** in case a root-page belonging to another table is moved by the btree layer
103062 ** is also added (this can happen with an auto-vacuum database).
103064 static void destroyTable(Parse *pParse, Table *pTab){
103065 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
103066 ** is not defined), then it is important to call OP_Destroy on the
103067 ** table and index root-pages in order, starting with the numerically
103068 ** largest root-page number. This guarantees that none of the root-pages
103069 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
103070 ** following were coded:
103072 ** OP_Destroy 4 0
103073 ** ...
103074 ** OP_Destroy 5 0
103076 ** and root page 5 happened to be the largest root-page number in the
103077 ** database, then root page 5 would be moved to page 4 by the
103078 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
103079 ** a free-list page.
103081 int iTab = pTab->tnum;
103082 int iDestroyed = 0;
103084 while( 1 ){
103085 Index *pIdx;
103086 int iLargest = 0;
103088 if( iDestroyed==0 || iTab<iDestroyed ){
103089 iLargest = iTab;
103091 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103092 int iIdx = pIdx->tnum;
103093 assert( pIdx->pSchema==pTab->pSchema );
103094 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
103095 iLargest = iIdx;
103098 if( iLargest==0 ){
103099 return;
103100 }else{
103101 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
103102 assert( iDb>=0 && iDb<pParse->db->nDb );
103103 destroyRootPage(pParse, iLargest, iDb);
103104 iDestroyed = iLargest;
103110 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
103111 ** after a DROP INDEX or DROP TABLE command.
103113 static void sqlite3ClearStatTables(
103114 Parse *pParse, /* The parsing context */
103115 int iDb, /* The database number */
103116 const char *zType, /* "idx" or "tbl" */
103117 const char *zName /* Name of index or table */
103119 int i;
103120 const char *zDbName = pParse->db->aDb[iDb].zDbSName;
103121 for(i=1; i<=4; i++){
103122 char zTab[24];
103123 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
103124 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
103125 sqlite3NestedParse(pParse,
103126 "DELETE FROM %Q.%s WHERE %s=%Q",
103127 zDbName, zTab, zType, zName
103134 ** Generate code to drop a table.
103136 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
103137 Vdbe *v;
103138 sqlite3 *db = pParse->db;
103139 Trigger *pTrigger;
103140 Db *pDb = &db->aDb[iDb];
103142 v = sqlite3GetVdbe(pParse);
103143 assert( v!=0 );
103144 sqlite3BeginWriteOperation(pParse, 1, iDb);
103146 #ifndef SQLITE_OMIT_VIRTUALTABLE
103147 if( IsVirtual(pTab) ){
103148 sqlite3VdbeAddOp0(v, OP_VBegin);
103150 #endif
103152 /* Drop all triggers associated with the table being dropped. Code
103153 ** is generated to remove entries from sqlite_master and/or
103154 ** sqlite_temp_master if required.
103156 pTrigger = sqlite3TriggerList(pParse, pTab);
103157 while( pTrigger ){
103158 assert( pTrigger->pSchema==pTab->pSchema ||
103159 pTrigger->pSchema==db->aDb[1].pSchema );
103160 sqlite3DropTriggerPtr(pParse, pTrigger);
103161 pTrigger = pTrigger->pNext;
103164 #ifndef SQLITE_OMIT_AUTOINCREMENT
103165 /* Remove any entries of the sqlite_sequence table associated with
103166 ** the table being dropped. This is done before the table is dropped
103167 ** at the btree level, in case the sqlite_sequence table needs to
103168 ** move as a result of the drop (can happen in auto-vacuum mode).
103170 if( pTab->tabFlags & TF_Autoincrement ){
103171 sqlite3NestedParse(pParse,
103172 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
103173 pDb->zDbSName, pTab->zName
103176 #endif
103178 /* Drop all SQLITE_MASTER table and index entries that refer to the
103179 ** table. The program name loops through the master table and deletes
103180 ** every row that refers to a table of the same name as the one being
103181 ** dropped. Triggers are handled separately because a trigger can be
103182 ** created in the temp database that refers to a table in another
103183 ** database.
103185 sqlite3NestedParse(pParse,
103186 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
103187 pDb->zDbSName, MASTER_NAME, pTab->zName);
103188 if( !isView && !IsVirtual(pTab) ){
103189 destroyTable(pParse, pTab);
103192 /* Remove the table entry from SQLite's internal schema and modify
103193 ** the schema cookie.
103195 if( IsVirtual(pTab) ){
103196 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
103198 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
103199 sqlite3ChangeCookie(pParse, iDb);
103200 sqliteViewResetAll(db, iDb);
103204 ** This routine is called to do the work of a DROP TABLE statement.
103205 ** pName is the name of the table to be dropped.
103207 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
103208 Table *pTab;
103209 Vdbe *v;
103210 sqlite3 *db = pParse->db;
103211 int iDb;
103213 if( db->mallocFailed ){
103214 goto exit_drop_table;
103216 assert( pParse->nErr==0 );
103217 assert( pName->nSrc==1 );
103218 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
103219 if( noErr ) db->suppressErr++;
103220 assert( isView==0 || isView==LOCATE_VIEW );
103221 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
103222 if( noErr ) db->suppressErr--;
103224 if( pTab==0 ){
103225 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
103226 goto exit_drop_table;
103228 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103229 assert( iDb>=0 && iDb<db->nDb );
103231 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
103232 ** it is initialized.
103234 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
103235 goto exit_drop_table;
103237 #ifndef SQLITE_OMIT_AUTHORIZATION
103239 int code;
103240 const char *zTab = SCHEMA_TABLE(iDb);
103241 const char *zDb = db->aDb[iDb].zDbSName;
103242 const char *zArg2 = 0;
103243 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
103244 goto exit_drop_table;
103246 if( isView ){
103247 if( !OMIT_TEMPDB && iDb==1 ){
103248 code = SQLITE_DROP_TEMP_VIEW;
103249 }else{
103250 code = SQLITE_DROP_VIEW;
103252 #ifndef SQLITE_OMIT_VIRTUALTABLE
103253 }else if( IsVirtual(pTab) ){
103254 code = SQLITE_DROP_VTABLE;
103255 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
103256 #endif
103257 }else{
103258 if( !OMIT_TEMPDB && iDb==1 ){
103259 code = SQLITE_DROP_TEMP_TABLE;
103260 }else{
103261 code = SQLITE_DROP_TABLE;
103264 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
103265 goto exit_drop_table;
103267 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
103268 goto exit_drop_table;
103271 #endif
103272 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
103273 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
103274 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
103275 goto exit_drop_table;
103278 #ifndef SQLITE_OMIT_VIEW
103279 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
103280 ** on a table.
103282 if( isView && pTab->pSelect==0 ){
103283 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
103284 goto exit_drop_table;
103286 if( !isView && pTab->pSelect ){
103287 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
103288 goto exit_drop_table;
103290 #endif
103292 /* Generate code to remove the table from the master table
103293 ** on disk.
103295 v = sqlite3GetVdbe(pParse);
103296 if( v ){
103297 sqlite3BeginWriteOperation(pParse, 1, iDb);
103298 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
103299 sqlite3FkDropTable(pParse, pName, pTab);
103300 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
103303 exit_drop_table:
103304 sqlite3SrcListDelete(db, pName);
103308 ** This routine is called to create a new foreign key on the table
103309 ** currently under construction. pFromCol determines which columns
103310 ** in the current table point to the foreign key. If pFromCol==0 then
103311 ** connect the key to the last column inserted. pTo is the name of
103312 ** the table referred to (a.k.a the "parent" table). pToCol is a list
103313 ** of tables in the parent pTo table. flags contains all
103314 ** information about the conflict resolution algorithms specified
103315 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
103317 ** An FKey structure is created and added to the table currently
103318 ** under construction in the pParse->pNewTable field.
103320 ** The foreign key is set for IMMEDIATE processing. A subsequent call
103321 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
103323 SQLITE_PRIVATE void sqlite3CreateForeignKey(
103324 Parse *pParse, /* Parsing context */
103325 ExprList *pFromCol, /* Columns in this table that point to other table */
103326 Token *pTo, /* Name of the other table */
103327 ExprList *pToCol, /* Columns in the other table */
103328 int flags /* Conflict resolution algorithms. */
103330 sqlite3 *db = pParse->db;
103331 #ifndef SQLITE_OMIT_FOREIGN_KEY
103332 FKey *pFKey = 0;
103333 FKey *pNextTo;
103334 Table *p = pParse->pNewTable;
103335 int nByte;
103336 int i;
103337 int nCol;
103338 char *z;
103340 assert( pTo!=0 );
103341 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
103342 if( pFromCol==0 ){
103343 int iCol = p->nCol-1;
103344 if( NEVER(iCol<0) ) goto fk_end;
103345 if( pToCol && pToCol->nExpr!=1 ){
103346 sqlite3ErrorMsg(pParse, "foreign key on %s"
103347 " should reference only one column of table %T",
103348 p->aCol[iCol].zName, pTo);
103349 goto fk_end;
103351 nCol = 1;
103352 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
103353 sqlite3ErrorMsg(pParse,
103354 "number of columns in foreign key does not match the number of "
103355 "columns in the referenced table");
103356 goto fk_end;
103357 }else{
103358 nCol = pFromCol->nExpr;
103360 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
103361 if( pToCol ){
103362 for(i=0; i<pToCol->nExpr; i++){
103363 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
103366 pFKey = sqlite3DbMallocZero(db, nByte );
103367 if( pFKey==0 ){
103368 goto fk_end;
103370 pFKey->pFrom = p;
103371 pFKey->pNextFrom = p->pFKey;
103372 z = (char*)&pFKey->aCol[nCol];
103373 pFKey->zTo = z;
103374 memcpy(z, pTo->z, pTo->n);
103375 z[pTo->n] = 0;
103376 sqlite3Dequote(z);
103377 z += pTo->n+1;
103378 pFKey->nCol = nCol;
103379 if( pFromCol==0 ){
103380 pFKey->aCol[0].iFrom = p->nCol-1;
103381 }else{
103382 for(i=0; i<nCol; i++){
103383 int j;
103384 for(j=0; j<p->nCol; j++){
103385 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
103386 pFKey->aCol[i].iFrom = j;
103387 break;
103390 if( j>=p->nCol ){
103391 sqlite3ErrorMsg(pParse,
103392 "unknown column \"%s\" in foreign key definition",
103393 pFromCol->a[i].zName);
103394 goto fk_end;
103398 if( pToCol ){
103399 for(i=0; i<nCol; i++){
103400 int n = sqlite3Strlen30(pToCol->a[i].zName);
103401 pFKey->aCol[i].zCol = z;
103402 memcpy(z, pToCol->a[i].zName, n);
103403 z[n] = 0;
103404 z += n+1;
103407 pFKey->isDeferred = 0;
103408 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
103409 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
103411 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
103412 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
103413 pFKey->zTo, (void *)pFKey
103415 if( pNextTo==pFKey ){
103416 sqlite3OomFault(db);
103417 goto fk_end;
103419 if( pNextTo ){
103420 assert( pNextTo->pPrevTo==0 );
103421 pFKey->pNextTo = pNextTo;
103422 pNextTo->pPrevTo = pFKey;
103425 /* Link the foreign key to the table as the last step.
103427 p->pFKey = pFKey;
103428 pFKey = 0;
103430 fk_end:
103431 sqlite3DbFree(db, pFKey);
103432 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
103433 sqlite3ExprListDelete(db, pFromCol);
103434 sqlite3ExprListDelete(db, pToCol);
103438 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
103439 ** clause is seen as part of a foreign key definition. The isDeferred
103440 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
103441 ** The behavior of the most recently created foreign key is adjusted
103442 ** accordingly.
103444 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
103445 #ifndef SQLITE_OMIT_FOREIGN_KEY
103446 Table *pTab;
103447 FKey *pFKey;
103448 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
103449 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
103450 pFKey->isDeferred = (u8)isDeferred;
103451 #endif
103455 ** Generate code that will erase and refill index *pIdx. This is
103456 ** used to initialize a newly created index or to recompute the
103457 ** content of an index in response to a REINDEX command.
103459 ** if memRootPage is not negative, it means that the index is newly
103460 ** created. The register specified by memRootPage contains the
103461 ** root page number of the index. If memRootPage is negative, then
103462 ** the index already exists and must be cleared before being refilled and
103463 ** the root page number of the index is taken from pIndex->tnum.
103465 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
103466 Table *pTab = pIndex->pTable; /* The table that is indexed */
103467 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
103468 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
103469 int iSorter; /* Cursor opened by OpenSorter (if in use) */
103470 int addr1; /* Address of top of loop */
103471 int addr2; /* Address to jump to for next iteration */
103472 int tnum; /* Root page of index */
103473 int iPartIdxLabel; /* Jump to this label to skip a row */
103474 Vdbe *v; /* Generate code into this virtual machine */
103475 KeyInfo *pKey; /* KeyInfo for index */
103476 int regRecord; /* Register holding assembled index record */
103477 sqlite3 *db = pParse->db; /* The database connection */
103478 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
103480 #ifndef SQLITE_OMIT_AUTHORIZATION
103481 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
103482 db->aDb[iDb].zDbSName ) ){
103483 return;
103485 #endif
103487 /* Require a write-lock on the table to perform this operation */
103488 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
103490 v = sqlite3GetVdbe(pParse);
103491 if( v==0 ) return;
103492 if( memRootPage>=0 ){
103493 tnum = memRootPage;
103494 }else{
103495 tnum = pIndex->tnum;
103497 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
103498 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
103500 /* Open the sorter cursor if we are to use one. */
103501 iSorter = pParse->nTab++;
103502 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
103503 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
103505 /* Open the table. Loop through all rows of the table, inserting index
103506 ** records into the sorter. */
103507 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
103508 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
103509 regRecord = sqlite3GetTempReg(pParse);
103511 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
103512 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
103513 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
103514 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
103515 sqlite3VdbeJumpHere(v, addr1);
103516 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
103517 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
103518 (char *)pKey, P4_KEYINFO);
103519 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
103521 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
103522 if( IsUniqueIndex(pIndex) ){
103523 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
103524 sqlite3VdbeGoto(v, j2);
103525 addr2 = sqlite3VdbeCurrentAddr(v);
103526 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
103527 pIndex->nKeyCol); VdbeCoverage(v);
103528 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
103529 }else{
103530 addr2 = sqlite3VdbeCurrentAddr(v);
103532 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
103533 sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
103534 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
103535 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
103536 sqlite3ReleaseTempReg(pParse, regRecord);
103537 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
103538 sqlite3VdbeJumpHere(v, addr1);
103540 sqlite3VdbeAddOp1(v, OP_Close, iTab);
103541 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
103542 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
103546 ** Allocate heap space to hold an Index object with nCol columns.
103548 ** Increase the allocation size to provide an extra nExtra bytes
103549 ** of 8-byte aligned space after the Index object and return a
103550 ** pointer to this extra space in *ppExtra.
103552 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
103553 sqlite3 *db, /* Database connection */
103554 i16 nCol, /* Total number of columns in the index */
103555 int nExtra, /* Number of bytes of extra space to alloc */
103556 char **ppExtra /* Pointer to the "extra" space */
103558 Index *p; /* Allocated index object */
103559 int nByte; /* Bytes of space for Index object + arrays */
103561 nByte = ROUND8(sizeof(Index)) + /* Index structure */
103562 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
103563 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
103564 sizeof(i16)*nCol + /* Index.aiColumn */
103565 sizeof(u8)*nCol); /* Index.aSortOrder */
103566 p = sqlite3DbMallocZero(db, nByte + nExtra);
103567 if( p ){
103568 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
103569 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
103570 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
103571 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
103572 p->aSortOrder = (u8*)pExtra;
103573 p->nColumn = nCol;
103574 p->nKeyCol = nCol - 1;
103575 *ppExtra = ((char*)p) + nByte;
103577 return p;
103581 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
103582 ** and pTblList is the name of the table that is to be indexed. Both will
103583 ** be NULL for a primary key or an index that is created to satisfy a
103584 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
103585 ** as the table to be indexed. pParse->pNewTable is a table that is
103586 ** currently being constructed by a CREATE TABLE statement.
103588 ** pList is a list of columns to be indexed. pList will be NULL if this
103589 ** is a primary key or unique-constraint on the most recent column added
103590 ** to the table currently under construction.
103592 SQLITE_PRIVATE void sqlite3CreateIndex(
103593 Parse *pParse, /* All information about this parse */
103594 Token *pName1, /* First part of index name. May be NULL */
103595 Token *pName2, /* Second part of index name. May be NULL */
103596 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
103597 ExprList *pList, /* A list of columns to be indexed */
103598 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
103599 Token *pStart, /* The CREATE token that begins this statement */
103600 Expr *pPIWhere, /* WHERE clause for partial indices */
103601 int sortOrder, /* Sort order of primary key when pList==NULL */
103602 int ifNotExist, /* Omit error if index already exists */
103603 u8 idxType /* The index type */
103605 Table *pTab = 0; /* Table to be indexed */
103606 Index *pIndex = 0; /* The index to be created */
103607 char *zName = 0; /* Name of the index */
103608 int nName; /* Number of characters in zName */
103609 int i, j;
103610 DbFixer sFix; /* For assigning database names to pTable */
103611 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
103612 sqlite3 *db = pParse->db;
103613 Db *pDb; /* The specific table containing the indexed database */
103614 int iDb; /* Index of the database that is being written */
103615 Token *pName = 0; /* Unqualified name of the index to create */
103616 struct ExprList_item *pListItem; /* For looping over pList */
103617 int nExtra = 0; /* Space allocated for zExtra[] */
103618 int nExtraCol; /* Number of extra columns needed */
103619 char *zExtra = 0; /* Extra space after the Index object */
103620 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
103622 if( db->mallocFailed || pParse->nErr>0 ){
103623 goto exit_create_index;
103625 if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
103626 goto exit_create_index;
103628 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
103629 goto exit_create_index;
103633 ** Find the table that is to be indexed. Return early if not found.
103635 if( pTblName!=0 ){
103637 /* Use the two-part index name to determine the database
103638 ** to search for the table. 'Fix' the table name to this db
103639 ** before looking up the table.
103641 assert( pName1 && pName2 );
103642 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
103643 if( iDb<0 ) goto exit_create_index;
103644 assert( pName && pName->z );
103646 #ifndef SQLITE_OMIT_TEMPDB
103647 /* If the index name was unqualified, check if the table
103648 ** is a temp table. If so, set the database to 1. Do not do this
103649 ** if initialising a database schema.
103651 if( !db->init.busy ){
103652 pTab = sqlite3SrcListLookup(pParse, pTblName);
103653 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
103654 iDb = 1;
103657 #endif
103659 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
103660 if( sqlite3FixSrcList(&sFix, pTblName) ){
103661 /* Because the parser constructs pTblName from a single identifier,
103662 ** sqlite3FixSrcList can never fail. */
103663 assert(0);
103665 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
103666 assert( db->mallocFailed==0 || pTab==0 );
103667 if( pTab==0 ) goto exit_create_index;
103668 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
103669 sqlite3ErrorMsg(pParse,
103670 "cannot create a TEMP index on non-TEMP table \"%s\"",
103671 pTab->zName);
103672 goto exit_create_index;
103674 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
103675 }else{
103676 assert( pName==0 );
103677 assert( pStart==0 );
103678 pTab = pParse->pNewTable;
103679 if( !pTab ) goto exit_create_index;
103680 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103682 pDb = &db->aDb[iDb];
103684 assert( pTab!=0 );
103685 assert( pParse->nErr==0 );
103686 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
103687 && db->init.busy==0
103688 #if SQLITE_USER_AUTHENTICATION
103689 && sqlite3UserAuthTable(pTab->zName)==0
103690 #endif
103691 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
103692 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
103693 goto exit_create_index;
103695 #ifndef SQLITE_OMIT_VIEW
103696 if( pTab->pSelect ){
103697 sqlite3ErrorMsg(pParse, "views may not be indexed");
103698 goto exit_create_index;
103700 #endif
103701 #ifndef SQLITE_OMIT_VIRTUALTABLE
103702 if( IsVirtual(pTab) ){
103703 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
103704 goto exit_create_index;
103706 #endif
103709 ** Find the name of the index. Make sure there is not already another
103710 ** index or table with the same name.
103712 ** Exception: If we are reading the names of permanent indices from the
103713 ** sqlite_master table (because some other process changed the schema) and
103714 ** one of the index names collides with the name of a temporary table or
103715 ** index, then we will continue to process this index.
103717 ** If pName==0 it means that we are
103718 ** dealing with a primary key or UNIQUE constraint. We have to invent our
103719 ** own name.
103721 if( pName ){
103722 zName = sqlite3NameFromToken(db, pName);
103723 if( zName==0 ) goto exit_create_index;
103724 assert( pName->z!=0 );
103725 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
103726 goto exit_create_index;
103728 if( !db->init.busy ){
103729 if( sqlite3FindTable(db, zName, 0)!=0 ){
103730 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
103731 goto exit_create_index;
103734 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
103735 if( !ifNotExist ){
103736 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
103737 }else{
103738 assert( !db->init.busy );
103739 sqlite3CodeVerifySchema(pParse, iDb);
103741 goto exit_create_index;
103743 }else{
103744 int n;
103745 Index *pLoop;
103746 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
103747 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
103748 if( zName==0 ){
103749 goto exit_create_index;
103752 /* Automatic index names generated from within sqlite3_declare_vtab()
103753 ** must have names that are distinct from normal automatic index names.
103754 ** The following statement converts "sqlite3_autoindex..." into
103755 ** "sqlite3_butoindex..." in order to make the names distinct.
103756 ** The "vtab_err.test" test demonstrates the need of this statement. */
103757 if( IN_DECLARE_VTAB ) zName[7]++;
103760 /* Check for authorization to create an index.
103762 #ifndef SQLITE_OMIT_AUTHORIZATION
103764 const char *zDb = pDb->zDbSName;
103765 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
103766 goto exit_create_index;
103768 i = SQLITE_CREATE_INDEX;
103769 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
103770 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
103771 goto exit_create_index;
103774 #endif
103776 /* If pList==0, it means this routine was called to make a primary
103777 ** key out of the last column added to the table under construction.
103778 ** So create a fake list to simulate this.
103780 if( pList==0 ){
103781 Token prevCol;
103782 sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
103783 pList = sqlite3ExprListAppend(pParse, 0,
103784 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
103785 if( pList==0 ) goto exit_create_index;
103786 assert( pList->nExpr==1 );
103787 sqlite3ExprListSetSortOrder(pList, sortOrder);
103788 }else{
103789 sqlite3ExprListCheckLength(pParse, pList, "index");
103792 /* Figure out how many bytes of space are required to store explicitly
103793 ** specified collation sequence names.
103795 for(i=0; i<pList->nExpr; i++){
103796 Expr *pExpr = pList->a[i].pExpr;
103797 assert( pExpr!=0 );
103798 if( pExpr->op==TK_COLLATE ){
103799 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
103804 ** Allocate the index structure.
103806 nName = sqlite3Strlen30(zName);
103807 nExtraCol = pPk ? pPk->nKeyCol : 1;
103808 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
103809 nName + nExtra + 1, &zExtra);
103810 if( db->mallocFailed ){
103811 goto exit_create_index;
103813 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
103814 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
103815 pIndex->zName = zExtra;
103816 zExtra += nName + 1;
103817 memcpy(pIndex->zName, zName, nName+1);
103818 pIndex->pTable = pTab;
103819 pIndex->onError = (u8)onError;
103820 pIndex->uniqNotNull = onError!=OE_None;
103821 pIndex->idxType = idxType;
103822 pIndex->pSchema = db->aDb[iDb].pSchema;
103823 pIndex->nKeyCol = pList->nExpr;
103824 if( pPIWhere ){
103825 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
103826 pIndex->pPartIdxWhere = pPIWhere;
103827 pPIWhere = 0;
103829 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
103831 /* Check to see if we should honor DESC requests on index columns
103833 if( pDb->pSchema->file_format>=4 ){
103834 sortOrderMask = -1; /* Honor DESC */
103835 }else{
103836 sortOrderMask = 0; /* Ignore DESC */
103839 /* Analyze the list of expressions that form the terms of the index and
103840 ** report any errors. In the common case where the expression is exactly
103841 ** a table column, store that column in aiColumn[]. For general expressions,
103842 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
103844 ** TODO: Issue a warning if two or more columns of the index are identical.
103845 ** TODO: Issue a warning if the table primary key is used as part of the
103846 ** index key.
103848 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
103849 Expr *pCExpr; /* The i-th index expression */
103850 int requestedSortOrder; /* ASC or DESC on the i-th expression */
103851 const char *zColl; /* Collation sequence name */
103853 sqlite3StringToId(pListItem->pExpr);
103854 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
103855 if( pParse->nErr ) goto exit_create_index;
103856 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
103857 if( pCExpr->op!=TK_COLUMN ){
103858 if( pTab==pParse->pNewTable ){
103859 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
103860 "UNIQUE constraints");
103861 goto exit_create_index;
103863 if( pIndex->aColExpr==0 ){
103864 ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
103865 pIndex->aColExpr = pCopy;
103866 if( !db->mallocFailed ){
103867 assert( pCopy!=0 );
103868 pListItem = &pCopy->a[i];
103871 j = XN_EXPR;
103872 pIndex->aiColumn[i] = XN_EXPR;
103873 pIndex->uniqNotNull = 0;
103874 }else{
103875 j = pCExpr->iColumn;
103876 assert( j<=0x7fff );
103877 if( j<0 ){
103878 j = pTab->iPKey;
103879 }else if( pTab->aCol[j].notNull==0 ){
103880 pIndex->uniqNotNull = 0;
103882 pIndex->aiColumn[i] = (i16)j;
103884 zColl = 0;
103885 if( pListItem->pExpr->op==TK_COLLATE ){
103886 int nColl;
103887 zColl = pListItem->pExpr->u.zToken;
103888 nColl = sqlite3Strlen30(zColl) + 1;
103889 assert( nExtra>=nColl );
103890 memcpy(zExtra, zColl, nColl);
103891 zColl = zExtra;
103892 zExtra += nColl;
103893 nExtra -= nColl;
103894 }else if( j>=0 ){
103895 zColl = pTab->aCol[j].zColl;
103897 if( !zColl ) zColl = sqlite3StrBINARY;
103898 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
103899 goto exit_create_index;
103901 pIndex->azColl[i] = zColl;
103902 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
103903 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
103906 /* Append the table key to the end of the index. For WITHOUT ROWID
103907 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
103908 ** normal tables (when pPk==0) this will be the rowid.
103910 if( pPk ){
103911 for(j=0; j<pPk->nKeyCol; j++){
103912 int x = pPk->aiColumn[j];
103913 assert( x>=0 );
103914 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
103915 pIndex->nColumn--;
103916 }else{
103917 pIndex->aiColumn[i] = x;
103918 pIndex->azColl[i] = pPk->azColl[j];
103919 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
103923 assert( i==pIndex->nColumn );
103924 }else{
103925 pIndex->aiColumn[i] = XN_ROWID;
103926 pIndex->azColl[i] = sqlite3StrBINARY;
103928 sqlite3DefaultRowEst(pIndex);
103929 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
103931 /* If this index contains every column of its table, then mark
103932 ** it as a covering index */
103933 assert( HasRowid(pTab)
103934 || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
103935 if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
103936 pIndex->isCovering = 1;
103937 for(j=0; j<pTab->nCol; j++){
103938 if( j==pTab->iPKey ) continue;
103939 if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
103940 pIndex->isCovering = 0;
103941 break;
103945 if( pTab==pParse->pNewTable ){
103946 /* This routine has been called to create an automatic index as a
103947 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
103948 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
103949 ** i.e. one of:
103951 ** CREATE TABLE t(x PRIMARY KEY, y);
103952 ** CREATE TABLE t(x, y, UNIQUE(x, y));
103954 ** Either way, check to see if the table already has such an index. If
103955 ** so, don't bother creating this one. This only applies to
103956 ** automatically created indices. Users can do as they wish with
103957 ** explicit indices.
103959 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
103960 ** (and thus suppressing the second one) even if they have different
103961 ** sort orders.
103963 ** If there are different collating sequences or if the columns of
103964 ** the constraint occur in different orders, then the constraints are
103965 ** considered distinct and both result in separate indices.
103967 Index *pIdx;
103968 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103969 int k;
103970 assert( IsUniqueIndex(pIdx) );
103971 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
103972 assert( IsUniqueIndex(pIndex) );
103974 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
103975 for(k=0; k<pIdx->nKeyCol; k++){
103976 const char *z1;
103977 const char *z2;
103978 assert( pIdx->aiColumn[k]>=0 );
103979 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
103980 z1 = pIdx->azColl[k];
103981 z2 = pIndex->azColl[k];
103982 if( sqlite3StrICmp(z1, z2) ) break;
103984 if( k==pIdx->nKeyCol ){
103985 if( pIdx->onError!=pIndex->onError ){
103986 /* This constraint creates the same index as a previous
103987 ** constraint specified somewhere in the CREATE TABLE statement.
103988 ** However the ON CONFLICT clauses are different. If both this
103989 ** constraint and the previous equivalent constraint have explicit
103990 ** ON CONFLICT clauses this is an error. Otherwise, use the
103991 ** explicitly specified behavior for the index.
103993 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
103994 sqlite3ErrorMsg(pParse,
103995 "conflicting ON CONFLICT clauses specified", 0);
103997 if( pIdx->onError==OE_Default ){
103998 pIdx->onError = pIndex->onError;
104001 if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
104002 goto exit_create_index;
104007 /* Link the new Index structure to its table and to the other
104008 ** in-memory database structures.
104010 assert( pParse->nErr==0 );
104011 if( db->init.busy ){
104012 Index *p;
104013 assert( !IN_DECLARE_VTAB );
104014 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
104015 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
104016 pIndex->zName, pIndex);
104017 if( p ){
104018 assert( p==pIndex ); /* Malloc must have failed */
104019 sqlite3OomFault(db);
104020 goto exit_create_index;
104022 db->mDbFlags |= DBFLAG_SchemaChange;
104023 if( pTblName!=0 ){
104024 pIndex->tnum = db->init.newTnum;
104028 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
104029 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
104030 ** emit code to allocate the index rootpage on disk and make an entry for
104031 ** the index in the sqlite_master table and populate the index with
104032 ** content. But, do not do this if we are simply reading the sqlite_master
104033 ** table to parse the schema, or if this index is the PRIMARY KEY index
104034 ** of a WITHOUT ROWID table.
104036 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
104037 ** or UNIQUE index in a CREATE TABLE statement. Since the table
104038 ** has just been created, it contains no data and the index initialization
104039 ** step can be skipped.
104041 else if( HasRowid(pTab) || pTblName!=0 ){
104042 Vdbe *v;
104043 char *zStmt;
104044 int iMem = ++pParse->nMem;
104046 v = sqlite3GetVdbe(pParse);
104047 if( v==0 ) goto exit_create_index;
104049 sqlite3BeginWriteOperation(pParse, 1, iDb);
104051 /* Create the rootpage for the index using CreateIndex. But before
104052 ** doing so, code a Noop instruction and store its address in
104053 ** Index.tnum. This is required in case this index is actually a
104054 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
104055 ** that case the convertToWithoutRowidTable() routine will replace
104056 ** the Noop with a Goto to jump over the VDBE code generated below. */
104057 pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
104058 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
104060 /* Gather the complete text of the CREATE INDEX statement into
104061 ** the zStmt variable
104063 if( pStart ){
104064 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
104065 if( pName->z[n-1]==';' ) n--;
104066 /* A named index with an explicit CREATE INDEX statement */
104067 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
104068 onError==OE_None ? "" : " UNIQUE", n, pName->z);
104069 }else{
104070 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
104071 /* zStmt = sqlite3MPrintf(""); */
104072 zStmt = 0;
104075 /* Add an entry in sqlite_master for this index
104077 sqlite3NestedParse(pParse,
104078 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
104079 db->aDb[iDb].zDbSName, MASTER_NAME,
104080 pIndex->zName,
104081 pTab->zName,
104082 iMem,
104083 zStmt
104085 sqlite3DbFree(db, zStmt);
104087 /* Fill the index with data and reparse the schema. Code an OP_Expire
104088 ** to invalidate all pre-compiled statements.
104090 if( pTblName ){
104091 sqlite3RefillIndex(pParse, pIndex, iMem);
104092 sqlite3ChangeCookie(pParse, iDb);
104093 sqlite3VdbeAddParseSchemaOp(v, iDb,
104094 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
104095 sqlite3VdbeAddOp0(v, OP_Expire);
104098 sqlite3VdbeJumpHere(v, pIndex->tnum);
104101 /* When adding an index to the list of indices for a table, make
104102 ** sure all indices labeled OE_Replace come after all those labeled
104103 ** OE_Ignore. This is necessary for the correct constraint check
104104 ** processing (in sqlite3GenerateConstraintChecks()) as part of
104105 ** UPDATE and INSERT statements.
104107 if( db->init.busy || pTblName==0 ){
104108 if( onError!=OE_Replace || pTab->pIndex==0
104109 || pTab->pIndex->onError==OE_Replace){
104110 pIndex->pNext = pTab->pIndex;
104111 pTab->pIndex = pIndex;
104112 }else{
104113 Index *pOther = pTab->pIndex;
104114 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
104115 pOther = pOther->pNext;
104117 pIndex->pNext = pOther->pNext;
104118 pOther->pNext = pIndex;
104120 pIndex = 0;
104123 /* Clean up before exiting */
104124 exit_create_index:
104125 if( pIndex ) freeIndex(db, pIndex);
104126 sqlite3ExprDelete(db, pPIWhere);
104127 sqlite3ExprListDelete(db, pList);
104128 sqlite3SrcListDelete(db, pTblName);
104129 sqlite3DbFree(db, zName);
104133 ** Fill the Index.aiRowEst[] array with default information - information
104134 ** to be used when we have not run the ANALYZE command.
104136 ** aiRowEst[0] is supposed to contain the number of elements in the index.
104137 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
104138 ** number of rows in the table that match any particular value of the
104139 ** first column of the index. aiRowEst[2] is an estimate of the number
104140 ** of rows that match any particular combination of the first 2 columns
104141 ** of the index. And so forth. It must always be the case that
104143 ** aiRowEst[N]<=aiRowEst[N-1]
104144 ** aiRowEst[N]>=1
104146 ** Apart from that, we have little to go on besides intuition as to
104147 ** how aiRowEst[] should be initialized. The numbers generated here
104148 ** are based on typical values found in actual indices.
104150 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
104151 /* 10, 9, 8, 7, 6 */
104152 LogEst aVal[] = { 33, 32, 30, 28, 26 };
104153 LogEst *a = pIdx->aiRowLogEst;
104154 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
104155 int i;
104157 /* Indexes with default row estimates should not have stat1 data */
104158 assert( !pIdx->hasStat1 );
104160 /* Set the first entry (number of rows in the index) to the estimated
104161 ** number of rows in the table, or half the number of rows in the table
104162 ** for a partial index. But do not let the estimate drop below 10. */
104163 a[0] = pIdx->pTable->nRowLogEst;
104164 if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
104165 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
104167 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
104168 ** 6 and each subsequent value (if any) is 5. */
104169 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
104170 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
104171 a[i] = 23; assert( 23==sqlite3LogEst(5) );
104174 assert( 0==sqlite3LogEst(1) );
104175 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
104179 ** This routine will drop an existing named index. This routine
104180 ** implements the DROP INDEX statement.
104182 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
104183 Index *pIndex;
104184 Vdbe *v;
104185 sqlite3 *db = pParse->db;
104186 int iDb;
104188 assert( pParse->nErr==0 ); /* Never called with prior errors */
104189 if( db->mallocFailed ){
104190 goto exit_drop_index;
104192 assert( pName->nSrc==1 );
104193 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
104194 goto exit_drop_index;
104196 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
104197 if( pIndex==0 ){
104198 if( !ifExists ){
104199 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
104200 }else{
104201 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
104203 pParse->checkSchema = 1;
104204 goto exit_drop_index;
104206 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
104207 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
104208 "or PRIMARY KEY constraint cannot be dropped", 0);
104209 goto exit_drop_index;
104211 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
104212 #ifndef SQLITE_OMIT_AUTHORIZATION
104214 int code = SQLITE_DROP_INDEX;
104215 Table *pTab = pIndex->pTable;
104216 const char *zDb = db->aDb[iDb].zDbSName;
104217 const char *zTab = SCHEMA_TABLE(iDb);
104218 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
104219 goto exit_drop_index;
104221 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
104222 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
104223 goto exit_drop_index;
104226 #endif
104228 /* Generate code to remove the index and from the master table */
104229 v = sqlite3GetVdbe(pParse);
104230 if( v ){
104231 sqlite3BeginWriteOperation(pParse, 1, iDb);
104232 sqlite3NestedParse(pParse,
104233 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
104234 db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
104236 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
104237 sqlite3ChangeCookie(pParse, iDb);
104238 destroyRootPage(pParse, pIndex->tnum, iDb);
104239 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
104242 exit_drop_index:
104243 sqlite3SrcListDelete(db, pName);
104247 ** pArray is a pointer to an array of objects. Each object in the
104248 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
104249 ** to extend the array so that there is space for a new object at the end.
104251 ** When this function is called, *pnEntry contains the current size of
104252 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
104253 ** in total).
104255 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
104256 ** space allocated for the new object is zeroed, *pnEntry updated to
104257 ** reflect the new size of the array and a pointer to the new allocation
104258 ** returned. *pIdx is set to the index of the new array entry in this case.
104260 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
104261 ** unchanged and a copy of pArray returned.
104263 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
104264 sqlite3 *db, /* Connection to notify of malloc failures */
104265 void *pArray, /* Array of objects. Might be reallocated */
104266 int szEntry, /* Size of each object in the array */
104267 int *pnEntry, /* Number of objects currently in use */
104268 int *pIdx /* Write the index of a new slot here */
104270 char *z;
104271 int n = *pnEntry;
104272 if( (n & (n-1))==0 ){
104273 int sz = (n==0) ? 1 : 2*n;
104274 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
104275 if( pNew==0 ){
104276 *pIdx = -1;
104277 return pArray;
104279 pArray = pNew;
104281 z = (char*)pArray;
104282 memset(&z[n * szEntry], 0, szEntry);
104283 *pIdx = n;
104284 ++*pnEntry;
104285 return pArray;
104289 ** Append a new element to the given IdList. Create a new IdList if
104290 ** need be.
104292 ** A new IdList is returned, or NULL if malloc() fails.
104294 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
104295 int i;
104296 if( pList==0 ){
104297 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
104298 if( pList==0 ) return 0;
104300 pList->a = sqlite3ArrayAllocate(
104302 pList->a,
104303 sizeof(pList->a[0]),
104304 &pList->nId,
104307 if( i<0 ){
104308 sqlite3IdListDelete(db, pList);
104309 return 0;
104311 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
104312 return pList;
104316 ** Delete an IdList.
104318 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
104319 int i;
104320 if( pList==0 ) return;
104321 for(i=0; i<pList->nId; i++){
104322 sqlite3DbFree(db, pList->a[i].zName);
104324 sqlite3DbFree(db, pList->a);
104325 sqlite3DbFreeNN(db, pList);
104329 ** Return the index in pList of the identifier named zId. Return -1
104330 ** if not found.
104332 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
104333 int i;
104334 if( pList==0 ) return -1;
104335 for(i=0; i<pList->nId; i++){
104336 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
104338 return -1;
104342 ** Expand the space allocated for the given SrcList object by
104343 ** creating nExtra new slots beginning at iStart. iStart is zero based.
104344 ** New slots are zeroed.
104346 ** For example, suppose a SrcList initially contains two entries: A,B.
104347 ** To append 3 new entries onto the end, do this:
104349 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
104351 ** After the call above it would contain: A, B, nil, nil, nil.
104352 ** If the iStart argument had been 1 instead of 2, then the result
104353 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
104354 ** the iStart value would be 0. The result then would
104355 ** be: nil, nil, nil, A, B.
104357 ** If a memory allocation fails the SrcList is unchanged. The
104358 ** db->mallocFailed flag will be set to true.
104360 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
104361 sqlite3 *db, /* Database connection to notify of OOM errors */
104362 SrcList *pSrc, /* The SrcList to be enlarged */
104363 int nExtra, /* Number of new slots to add to pSrc->a[] */
104364 int iStart /* Index in pSrc->a[] of first new slot */
104366 int i;
104368 /* Sanity checking on calling parameters */
104369 assert( iStart>=0 );
104370 assert( nExtra>=1 );
104371 assert( pSrc!=0 );
104372 assert( iStart<=pSrc->nSrc );
104374 /* Allocate additional space if needed */
104375 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
104376 SrcList *pNew;
104377 int nAlloc = pSrc->nSrc*2+nExtra;
104378 int nGot;
104379 pNew = sqlite3DbRealloc(db, pSrc,
104380 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
104381 if( pNew==0 ){
104382 assert( db->mallocFailed );
104383 return pSrc;
104385 pSrc = pNew;
104386 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
104387 pSrc->nAlloc = nGot;
104390 /* Move existing slots that come after the newly inserted slots
104391 ** out of the way */
104392 for(i=pSrc->nSrc-1; i>=iStart; i--){
104393 pSrc->a[i+nExtra] = pSrc->a[i];
104395 pSrc->nSrc += nExtra;
104397 /* Zero the newly allocated slots */
104398 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
104399 for(i=iStart; i<iStart+nExtra; i++){
104400 pSrc->a[i].iCursor = -1;
104403 /* Return a pointer to the enlarged SrcList */
104404 return pSrc;
104409 ** Append a new table name to the given SrcList. Create a new SrcList if
104410 ** need be. A new entry is created in the SrcList even if pTable is NULL.
104412 ** A SrcList is returned, or NULL if there is an OOM error. The returned
104413 ** SrcList might be the same as the SrcList that was input or it might be
104414 ** a new one. If an OOM error does occurs, then the prior value of pList
104415 ** that is input to this routine is automatically freed.
104417 ** If pDatabase is not null, it means that the table has an optional
104418 ** database name prefix. Like this: "database.table". The pDatabase
104419 ** points to the table name and the pTable points to the database name.
104420 ** The SrcList.a[].zName field is filled with the table name which might
104421 ** come from pTable (if pDatabase is NULL) or from pDatabase.
104422 ** SrcList.a[].zDatabase is filled with the database name from pTable,
104423 ** or with NULL if no database is specified.
104425 ** In other words, if call like this:
104427 ** sqlite3SrcListAppend(D,A,B,0);
104429 ** Then B is a table name and the database name is unspecified. If called
104430 ** like this:
104432 ** sqlite3SrcListAppend(D,A,B,C);
104434 ** Then C is the table name and B is the database name. If C is defined
104435 ** then so is B. In other words, we never have a case where:
104437 ** sqlite3SrcListAppend(D,A,0,C);
104439 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
104440 ** before being added to the SrcList.
104442 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
104443 sqlite3 *db, /* Connection to notify of malloc failures */
104444 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
104445 Token *pTable, /* Table to append */
104446 Token *pDatabase /* Database of the table */
104448 struct SrcList_item *pItem;
104449 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
104450 assert( db!=0 );
104451 if( pList==0 ){
104452 pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
104453 if( pList==0 ) return 0;
104454 pList->nAlloc = 1;
104455 pList->nSrc = 1;
104456 memset(&pList->a[0], 0, sizeof(pList->a[0]));
104457 pList->a[0].iCursor = -1;
104458 }else{
104459 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
104461 if( db->mallocFailed ){
104462 sqlite3SrcListDelete(db, pList);
104463 return 0;
104465 pItem = &pList->a[pList->nSrc-1];
104466 if( pDatabase && pDatabase->z==0 ){
104467 pDatabase = 0;
104469 if( pDatabase ){
104470 pItem->zName = sqlite3NameFromToken(db, pDatabase);
104471 pItem->zDatabase = sqlite3NameFromToken(db, pTable);
104472 }else{
104473 pItem->zName = sqlite3NameFromToken(db, pTable);
104474 pItem->zDatabase = 0;
104476 return pList;
104480 ** Assign VdbeCursor index numbers to all tables in a SrcList
104482 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
104483 int i;
104484 struct SrcList_item *pItem;
104485 assert(pList || pParse->db->mallocFailed );
104486 if( pList ){
104487 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
104488 if( pItem->iCursor>=0 ) break;
104489 pItem->iCursor = pParse->nTab++;
104490 if( pItem->pSelect ){
104491 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
104498 ** Delete an entire SrcList including all its substructure.
104500 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
104501 int i;
104502 struct SrcList_item *pItem;
104503 if( pList==0 ) return;
104504 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
104505 sqlite3DbFree(db, pItem->zDatabase);
104506 sqlite3DbFree(db, pItem->zName);
104507 sqlite3DbFree(db, pItem->zAlias);
104508 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
104509 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
104510 sqlite3DeleteTable(db, pItem->pTab);
104511 sqlite3SelectDelete(db, pItem->pSelect);
104512 sqlite3ExprDelete(db, pItem->pOn);
104513 sqlite3IdListDelete(db, pItem->pUsing);
104515 sqlite3DbFreeNN(db, pList);
104519 ** This routine is called by the parser to add a new term to the
104520 ** end of a growing FROM clause. The "p" parameter is the part of
104521 ** the FROM clause that has already been constructed. "p" is NULL
104522 ** if this is the first term of the FROM clause. pTable and pDatabase
104523 ** are the name of the table and database named in the FROM clause term.
104524 ** pDatabase is NULL if the database name qualifier is missing - the
104525 ** usual case. If the term has an alias, then pAlias points to the
104526 ** alias token. If the term is a subquery, then pSubquery is the
104527 ** SELECT statement that the subquery encodes. The pTable and
104528 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
104529 ** parameters are the content of the ON and USING clauses.
104531 ** Return a new SrcList which encodes is the FROM with the new
104532 ** term added.
104534 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
104535 Parse *pParse, /* Parsing context */
104536 SrcList *p, /* The left part of the FROM clause already seen */
104537 Token *pTable, /* Name of the table to add to the FROM clause */
104538 Token *pDatabase, /* Name of the database containing pTable */
104539 Token *pAlias, /* The right-hand side of the AS subexpression */
104540 Select *pSubquery, /* A subquery used in place of a table name */
104541 Expr *pOn, /* The ON clause of a join */
104542 IdList *pUsing /* The USING clause of a join */
104544 struct SrcList_item *pItem;
104545 sqlite3 *db = pParse->db;
104546 if( !p && (pOn || pUsing) ){
104547 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
104548 (pOn ? "ON" : "USING")
104550 goto append_from_error;
104552 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
104553 if( p==0 || NEVER(p->nSrc==0) ){
104554 goto append_from_error;
104556 pItem = &p->a[p->nSrc-1];
104557 assert( pAlias!=0 );
104558 if( pAlias->n ){
104559 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
104561 pItem->pSelect = pSubquery;
104562 pItem->pOn = pOn;
104563 pItem->pUsing = pUsing;
104564 return p;
104566 append_from_error:
104567 assert( p==0 );
104568 sqlite3ExprDelete(db, pOn);
104569 sqlite3IdListDelete(db, pUsing);
104570 sqlite3SelectDelete(db, pSubquery);
104571 return 0;
104575 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
104576 ** element of the source-list passed as the second argument.
104578 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
104579 assert( pIndexedBy!=0 );
104580 if( p && pIndexedBy->n>0 ){
104581 struct SrcList_item *pItem;
104582 assert( p->nSrc>0 );
104583 pItem = &p->a[p->nSrc-1];
104584 assert( pItem->fg.notIndexed==0 );
104585 assert( pItem->fg.isIndexedBy==0 );
104586 assert( pItem->fg.isTabFunc==0 );
104587 if( pIndexedBy->n==1 && !pIndexedBy->z ){
104588 /* A "NOT INDEXED" clause was supplied. See parse.y
104589 ** construct "indexed_opt" for details. */
104590 pItem->fg.notIndexed = 1;
104591 }else{
104592 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
104593 pItem->fg.isIndexedBy = 1;
104599 ** Add the list of function arguments to the SrcList entry for a
104600 ** table-valued-function.
104602 SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
104603 if( p ){
104604 struct SrcList_item *pItem = &p->a[p->nSrc-1];
104605 assert( pItem->fg.notIndexed==0 );
104606 assert( pItem->fg.isIndexedBy==0 );
104607 assert( pItem->fg.isTabFunc==0 );
104608 pItem->u1.pFuncArg = pList;
104609 pItem->fg.isTabFunc = 1;
104610 }else{
104611 sqlite3ExprListDelete(pParse->db, pList);
104616 ** When building up a FROM clause in the parser, the join operator
104617 ** is initially attached to the left operand. But the code generator
104618 ** expects the join operator to be on the right operand. This routine
104619 ** Shifts all join operators from left to right for an entire FROM
104620 ** clause.
104622 ** Example: Suppose the join is like this:
104624 ** A natural cross join B
104626 ** The operator is "natural cross join". The A and B operands are stored
104627 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
104628 ** operator with A. This routine shifts that operator over to B.
104630 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
104631 if( p ){
104632 int i;
104633 for(i=p->nSrc-1; i>0; i--){
104634 p->a[i].fg.jointype = p->a[i-1].fg.jointype;
104636 p->a[0].fg.jointype = 0;
104641 ** Generate VDBE code for a BEGIN statement.
104643 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
104644 sqlite3 *db;
104645 Vdbe *v;
104646 int i;
104648 assert( pParse!=0 );
104649 db = pParse->db;
104650 assert( db!=0 );
104651 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
104652 return;
104654 v = sqlite3GetVdbe(pParse);
104655 if( !v ) return;
104656 if( type!=TK_DEFERRED ){
104657 for(i=0; i<db->nDb; i++){
104658 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
104659 sqlite3VdbeUsesBtree(v, i);
104662 sqlite3VdbeAddOp0(v, OP_AutoCommit);
104666 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
104667 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
104668 ** code is generated for a COMMIT.
104670 SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
104671 Vdbe *v;
104672 int isRollback;
104674 assert( pParse!=0 );
104675 assert( pParse->db!=0 );
104676 assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
104677 isRollback = eType==TK_ROLLBACK;
104678 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
104679 isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
104680 return;
104682 v = sqlite3GetVdbe(pParse);
104683 if( v ){
104684 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
104689 ** This function is called by the parser when it parses a command to create,
104690 ** release or rollback an SQL savepoint.
104692 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
104693 char *zName = sqlite3NameFromToken(pParse->db, pName);
104694 if( zName ){
104695 Vdbe *v = sqlite3GetVdbe(pParse);
104696 #ifndef SQLITE_OMIT_AUTHORIZATION
104697 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
104698 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
104699 #endif
104700 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
104701 sqlite3DbFree(pParse->db, zName);
104702 return;
104704 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
104709 ** Make sure the TEMP database is open and available for use. Return
104710 ** the number of errors. Leave any error messages in the pParse structure.
104712 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
104713 sqlite3 *db = pParse->db;
104714 if( db->aDb[1].pBt==0 && !pParse->explain ){
104715 int rc;
104716 Btree *pBt;
104717 static const int flags =
104718 SQLITE_OPEN_READWRITE |
104719 SQLITE_OPEN_CREATE |
104720 SQLITE_OPEN_EXCLUSIVE |
104721 SQLITE_OPEN_DELETEONCLOSE |
104722 SQLITE_OPEN_TEMP_DB;
104724 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
104725 if( rc!=SQLITE_OK ){
104726 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
104727 "file for storing temporary tables");
104728 pParse->rc = rc;
104729 return 1;
104731 db->aDb[1].pBt = pBt;
104732 assert( db->aDb[1].pSchema );
104733 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
104734 sqlite3OomFault(db);
104735 return 1;
104738 return 0;
104742 ** Record the fact that the schema cookie will need to be verified
104743 ** for database iDb. The code to actually verify the schema cookie
104744 ** will occur at the end of the top-level VDBE and will be generated
104745 ** later, by sqlite3FinishCoding().
104747 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
104748 Parse *pToplevel = sqlite3ParseToplevel(pParse);
104750 assert( iDb>=0 && iDb<pParse->db->nDb );
104751 assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
104752 assert( iDb<SQLITE_MAX_ATTACHED+2 );
104753 assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
104754 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
104755 DbMaskSet(pToplevel->cookieMask, iDb);
104756 if( !OMIT_TEMPDB && iDb==1 ){
104757 sqlite3OpenTempDatabase(pToplevel);
104763 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
104764 ** attached database. Otherwise, invoke it for the database named zDb only.
104766 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
104767 sqlite3 *db = pParse->db;
104768 int i;
104769 for(i=0; i<db->nDb; i++){
104770 Db *pDb = &db->aDb[i];
104771 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
104772 sqlite3CodeVerifySchema(pParse, i);
104778 ** Generate VDBE code that prepares for doing an operation that
104779 ** might change the database.
104781 ** This routine starts a new transaction if we are not already within
104782 ** a transaction. If we are already within a transaction, then a checkpoint
104783 ** is set if the setStatement parameter is true. A checkpoint should
104784 ** be set for operations that might fail (due to a constraint) part of
104785 ** the way through and which will need to undo some writes without having to
104786 ** rollback the whole transaction. For operations where all constraints
104787 ** can be checked before any changes are made to the database, it is never
104788 ** necessary to undo a write and the checkpoint should not be set.
104790 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
104791 Parse *pToplevel = sqlite3ParseToplevel(pParse);
104792 sqlite3CodeVerifySchema(pParse, iDb);
104793 DbMaskSet(pToplevel->writeMask, iDb);
104794 pToplevel->isMultiWrite |= setStatement;
104798 ** Indicate that the statement currently under construction might write
104799 ** more than one entry (example: deleting one row then inserting another,
104800 ** inserting multiple rows in a table, or inserting a row and index entries.)
104801 ** If an abort occurs after some of these writes have completed, then it will
104802 ** be necessary to undo the completed writes.
104804 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
104805 Parse *pToplevel = sqlite3ParseToplevel(pParse);
104806 pToplevel->isMultiWrite = 1;
104810 ** The code generator calls this routine if is discovers that it is
104811 ** possible to abort a statement prior to completion. In order to
104812 ** perform this abort without corrupting the database, we need to make
104813 ** sure that the statement is protected by a statement transaction.
104815 ** Technically, we only need to set the mayAbort flag if the
104816 ** isMultiWrite flag was previously set. There is a time dependency
104817 ** such that the abort must occur after the multiwrite. This makes
104818 ** some statements involving the REPLACE conflict resolution algorithm
104819 ** go a little faster. But taking advantage of this time dependency
104820 ** makes it more difficult to prove that the code is correct (in
104821 ** particular, it prevents us from writing an effective
104822 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
104823 ** to take the safe route and skip the optimization.
104825 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
104826 Parse *pToplevel = sqlite3ParseToplevel(pParse);
104827 pToplevel->mayAbort = 1;
104831 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
104832 ** error. The onError parameter determines which (if any) of the statement
104833 ** and/or current transaction is rolled back.
104835 SQLITE_PRIVATE void sqlite3HaltConstraint(
104836 Parse *pParse, /* Parsing context */
104837 int errCode, /* extended error code */
104838 int onError, /* Constraint type */
104839 char *p4, /* Error message */
104840 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
104841 u8 p5Errmsg /* P5_ErrMsg type */
104843 Vdbe *v = sqlite3GetVdbe(pParse);
104844 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
104845 if( onError==OE_Abort ){
104846 sqlite3MayAbort(pParse);
104848 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
104849 sqlite3VdbeChangeP5(v, p5Errmsg);
104853 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
104855 SQLITE_PRIVATE void sqlite3UniqueConstraint(
104856 Parse *pParse, /* Parsing context */
104857 int onError, /* Constraint type */
104858 Index *pIdx /* The index that triggers the constraint */
104860 char *zErr;
104861 int j;
104862 StrAccum errMsg;
104863 Table *pTab = pIdx->pTable;
104865 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
104866 if( pIdx->aColExpr ){
104867 sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
104868 }else{
104869 for(j=0; j<pIdx->nKeyCol; j++){
104870 char *zCol;
104871 assert( pIdx->aiColumn[j]>=0 );
104872 zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
104873 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
104874 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
104875 sqlite3StrAccumAppend(&errMsg, ".", 1);
104876 sqlite3StrAccumAppendAll(&errMsg, zCol);
104879 zErr = sqlite3StrAccumFinish(&errMsg);
104880 sqlite3HaltConstraint(pParse,
104881 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
104882 : SQLITE_CONSTRAINT_UNIQUE,
104883 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
104888 ** Code an OP_Halt due to non-unique rowid.
104890 SQLITE_PRIVATE void sqlite3RowidConstraint(
104891 Parse *pParse, /* Parsing context */
104892 int onError, /* Conflict resolution algorithm */
104893 Table *pTab /* The table with the non-unique rowid */
104895 char *zMsg;
104896 int rc;
104897 if( pTab->iPKey>=0 ){
104898 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
104899 pTab->aCol[pTab->iPKey].zName);
104900 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
104901 }else{
104902 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
104903 rc = SQLITE_CONSTRAINT_ROWID;
104905 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
104906 P5_ConstraintUnique);
104910 ** Check to see if pIndex uses the collating sequence pColl. Return
104911 ** true if it does and false if it does not.
104913 #ifndef SQLITE_OMIT_REINDEX
104914 static int collationMatch(const char *zColl, Index *pIndex){
104915 int i;
104916 assert( zColl!=0 );
104917 for(i=0; i<pIndex->nColumn; i++){
104918 const char *z = pIndex->azColl[i];
104919 assert( z!=0 || pIndex->aiColumn[i]<0 );
104920 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
104921 return 1;
104924 return 0;
104926 #endif
104929 ** Recompute all indices of pTab that use the collating sequence pColl.
104930 ** If pColl==0 then recompute all indices of pTab.
104932 #ifndef SQLITE_OMIT_REINDEX
104933 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
104934 Index *pIndex; /* An index associated with pTab */
104936 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
104937 if( zColl==0 || collationMatch(zColl, pIndex) ){
104938 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
104939 sqlite3BeginWriteOperation(pParse, 0, iDb);
104940 sqlite3RefillIndex(pParse, pIndex, -1);
104944 #endif
104947 ** Recompute all indices of all tables in all databases where the
104948 ** indices use the collating sequence pColl. If pColl==0 then recompute
104949 ** all indices everywhere.
104951 #ifndef SQLITE_OMIT_REINDEX
104952 static void reindexDatabases(Parse *pParse, char const *zColl){
104953 Db *pDb; /* A single database */
104954 int iDb; /* The database index number */
104955 sqlite3 *db = pParse->db; /* The database connection */
104956 HashElem *k; /* For looping over tables in pDb */
104957 Table *pTab; /* A table in the database */
104959 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
104960 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
104961 assert( pDb!=0 );
104962 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
104963 pTab = (Table*)sqliteHashData(k);
104964 reindexTable(pParse, pTab, zColl);
104968 #endif
104971 ** Generate code for the REINDEX command.
104973 ** REINDEX -- 1
104974 ** REINDEX <collation> -- 2
104975 ** REINDEX ?<database>.?<tablename> -- 3
104976 ** REINDEX ?<database>.?<indexname> -- 4
104978 ** Form 1 causes all indices in all attached databases to be rebuilt.
104979 ** Form 2 rebuilds all indices in all databases that use the named
104980 ** collating function. Forms 3 and 4 rebuild the named index or all
104981 ** indices associated with the named table.
104983 #ifndef SQLITE_OMIT_REINDEX
104984 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
104985 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
104986 char *z; /* Name of a table or index */
104987 const char *zDb; /* Name of the database */
104988 Table *pTab; /* A table in the database */
104989 Index *pIndex; /* An index associated with pTab */
104990 int iDb; /* The database index number */
104991 sqlite3 *db = pParse->db; /* The database connection */
104992 Token *pObjName; /* Name of the table or index to be reindexed */
104994 /* Read the database schema. If an error occurs, leave an error message
104995 ** and code in pParse and return NULL. */
104996 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
104997 return;
105000 if( pName1==0 ){
105001 reindexDatabases(pParse, 0);
105002 return;
105003 }else if( NEVER(pName2==0) || pName2->z==0 ){
105004 char *zColl;
105005 assert( pName1->z );
105006 zColl = sqlite3NameFromToken(pParse->db, pName1);
105007 if( !zColl ) return;
105008 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
105009 if( pColl ){
105010 reindexDatabases(pParse, zColl);
105011 sqlite3DbFree(db, zColl);
105012 return;
105014 sqlite3DbFree(db, zColl);
105016 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
105017 if( iDb<0 ) return;
105018 z = sqlite3NameFromToken(db, pObjName);
105019 if( z==0 ) return;
105020 zDb = db->aDb[iDb].zDbSName;
105021 pTab = sqlite3FindTable(db, z, zDb);
105022 if( pTab ){
105023 reindexTable(pParse, pTab, 0);
105024 sqlite3DbFree(db, z);
105025 return;
105027 pIndex = sqlite3FindIndex(db, z, zDb);
105028 sqlite3DbFree(db, z);
105029 if( pIndex ){
105030 sqlite3BeginWriteOperation(pParse, 0, iDb);
105031 sqlite3RefillIndex(pParse, pIndex, -1);
105032 return;
105034 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
105036 #endif
105039 ** Return a KeyInfo structure that is appropriate for the given Index.
105041 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
105042 ** when it has finished using it.
105044 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
105045 int i;
105046 int nCol = pIdx->nColumn;
105047 int nKey = pIdx->nKeyCol;
105048 KeyInfo *pKey;
105049 if( pParse->nErr ) return 0;
105050 if( pIdx->uniqNotNull ){
105051 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
105052 }else{
105053 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
105055 if( pKey ){
105056 assert( sqlite3KeyInfoIsWriteable(pKey) );
105057 for(i=0; i<nCol; i++){
105058 const char *zColl = pIdx->azColl[i];
105059 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
105060 sqlite3LocateCollSeq(pParse, zColl);
105061 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
105063 if( pParse->nErr ){
105064 sqlite3KeyInfoUnref(pKey);
105065 pKey = 0;
105068 return pKey;
105071 #ifndef SQLITE_OMIT_CTE
105073 ** This routine is invoked once per CTE by the parser while parsing a
105074 ** WITH clause.
105076 SQLITE_PRIVATE With *sqlite3WithAdd(
105077 Parse *pParse, /* Parsing context */
105078 With *pWith, /* Existing WITH clause, or NULL */
105079 Token *pName, /* Name of the common-table */
105080 ExprList *pArglist, /* Optional column name list for the table */
105081 Select *pQuery /* Query used to initialize the table */
105083 sqlite3 *db = pParse->db;
105084 With *pNew;
105085 char *zName;
105087 /* Check that the CTE name is unique within this WITH clause. If
105088 ** not, store an error in the Parse structure. */
105089 zName = sqlite3NameFromToken(pParse->db, pName);
105090 if( zName && pWith ){
105091 int i;
105092 for(i=0; i<pWith->nCte; i++){
105093 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
105094 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
105099 if( pWith ){
105100 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
105101 pNew = sqlite3DbRealloc(db, pWith, nByte);
105102 }else{
105103 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
105105 assert( (pNew!=0 && zName!=0) || db->mallocFailed );
105107 if( db->mallocFailed ){
105108 sqlite3ExprListDelete(db, pArglist);
105109 sqlite3SelectDelete(db, pQuery);
105110 sqlite3DbFree(db, zName);
105111 pNew = pWith;
105112 }else{
105113 pNew->a[pNew->nCte].pSelect = pQuery;
105114 pNew->a[pNew->nCte].pCols = pArglist;
105115 pNew->a[pNew->nCte].zName = zName;
105116 pNew->a[pNew->nCte].zCteErr = 0;
105117 pNew->nCte++;
105120 return pNew;
105124 ** Free the contents of the With object passed as the second argument.
105126 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
105127 if( pWith ){
105128 int i;
105129 for(i=0; i<pWith->nCte; i++){
105130 struct Cte *pCte = &pWith->a[i];
105131 sqlite3ExprListDelete(db, pCte->pCols);
105132 sqlite3SelectDelete(db, pCte->pSelect);
105133 sqlite3DbFree(db, pCte->zName);
105135 sqlite3DbFree(db, pWith);
105138 #endif /* !defined(SQLITE_OMIT_CTE) */
105140 /************** End of build.c ***********************************************/
105141 /************** Begin file callback.c ****************************************/
105143 ** 2005 May 23
105145 ** The author disclaims copyright to this source code. In place of
105146 ** a legal notice, here is a blessing:
105148 ** May you do good and not evil.
105149 ** May you find forgiveness for yourself and forgive others.
105150 ** May you share freely, never taking more than you give.
105152 *************************************************************************
105154 ** This file contains functions used to access the internal hash tables
105155 ** of user defined functions and collation sequences.
105158 /* #include "sqliteInt.h" */
105161 ** Invoke the 'collation needed' callback to request a collation sequence
105162 ** in the encoding enc of name zName, length nName.
105164 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
105165 assert( !db->xCollNeeded || !db->xCollNeeded16 );
105166 if( db->xCollNeeded ){
105167 char *zExternal = sqlite3DbStrDup(db, zName);
105168 if( !zExternal ) return;
105169 db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
105170 sqlite3DbFree(db, zExternal);
105172 #ifndef SQLITE_OMIT_UTF16
105173 if( db->xCollNeeded16 ){
105174 char const *zExternal;
105175 sqlite3_value *pTmp = sqlite3ValueNew(db);
105176 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
105177 zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
105178 if( zExternal ){
105179 db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
105181 sqlite3ValueFree(pTmp);
105183 #endif
105187 ** This routine is called if the collation factory fails to deliver a
105188 ** collation function in the best encoding but there may be other versions
105189 ** of this collation function (for other text encodings) available. Use one
105190 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
105191 ** possible.
105193 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
105194 CollSeq *pColl2;
105195 char *z = pColl->zName;
105196 int i;
105197 static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
105198 for(i=0; i<3; i++){
105199 pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
105200 if( pColl2->xCmp!=0 ){
105201 memcpy(pColl, pColl2, sizeof(CollSeq));
105202 pColl->xDel = 0; /* Do not copy the destructor */
105203 return SQLITE_OK;
105206 return SQLITE_ERROR;
105210 ** This function is responsible for invoking the collation factory callback
105211 ** or substituting a collation sequence of a different encoding when the
105212 ** requested collation sequence is not available in the desired encoding.
105214 ** If it is not NULL, then pColl must point to the database native encoding
105215 ** collation sequence with name zName, length nName.
105217 ** The return value is either the collation sequence to be used in database
105218 ** db for collation type name zName, length nName, or NULL, if no collation
105219 ** sequence can be found. If no collation is found, leave an error message.
105221 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
105223 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
105224 Parse *pParse, /* Parsing context */
105225 u8 enc, /* The desired encoding for the collating sequence */
105226 CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
105227 const char *zName /* Collating sequence name */
105229 CollSeq *p;
105230 sqlite3 *db = pParse->db;
105232 p = pColl;
105233 if( !p ){
105234 p = sqlite3FindCollSeq(db, enc, zName, 0);
105236 if( !p || !p->xCmp ){
105237 /* No collation sequence of this type for this encoding is registered.
105238 ** Call the collation factory to see if it can supply us with one.
105240 callCollNeeded(db, enc, zName);
105241 p = sqlite3FindCollSeq(db, enc, zName, 0);
105243 if( p && !p->xCmp && synthCollSeq(db, p) ){
105244 p = 0;
105246 assert( !p || p->xCmp );
105247 if( p==0 ){
105248 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
105250 return p;
105254 ** This routine is called on a collation sequence before it is used to
105255 ** check that it is defined. An undefined collation sequence exists when
105256 ** a database is loaded that contains references to collation sequences
105257 ** that have not been defined by sqlite3_create_collation() etc.
105259 ** If required, this routine calls the 'collation needed' callback to
105260 ** request a definition of the collating sequence. If this doesn't work,
105261 ** an equivalent collating sequence that uses a text encoding different
105262 ** from the main database is substituted, if one is available.
105264 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
105265 if( pColl && pColl->xCmp==0 ){
105266 const char *zName = pColl->zName;
105267 sqlite3 *db = pParse->db;
105268 CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
105269 if( !p ){
105270 return SQLITE_ERROR;
105272 assert( p==pColl );
105274 return SQLITE_OK;
105280 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
105281 ** specified by zName and nName is not found and parameter 'create' is
105282 ** true, then create a new entry. Otherwise return NULL.
105284 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
105285 ** array of three CollSeq structures. The first is the collation sequence
105286 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
105288 ** Stored immediately after the three collation sequences is a copy of
105289 ** the collation sequence name. A pointer to this string is stored in
105290 ** each collation sequence structure.
105292 static CollSeq *findCollSeqEntry(
105293 sqlite3 *db, /* Database connection */
105294 const char *zName, /* Name of the collating sequence */
105295 int create /* Create a new entry if true */
105297 CollSeq *pColl;
105298 pColl = sqlite3HashFind(&db->aCollSeq, zName);
105300 if( 0==pColl && create ){
105301 int nName = sqlite3Strlen30(zName) + 1;
105302 pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
105303 if( pColl ){
105304 CollSeq *pDel = 0;
105305 pColl[0].zName = (char*)&pColl[3];
105306 pColl[0].enc = SQLITE_UTF8;
105307 pColl[1].zName = (char*)&pColl[3];
105308 pColl[1].enc = SQLITE_UTF16LE;
105309 pColl[2].zName = (char*)&pColl[3];
105310 pColl[2].enc = SQLITE_UTF16BE;
105311 memcpy(pColl[0].zName, zName, nName);
105312 pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
105314 /* If a malloc() failure occurred in sqlite3HashInsert(), it will
105315 ** return the pColl pointer to be deleted (because it wasn't added
105316 ** to the hash table).
105318 assert( pDel==0 || pDel==pColl );
105319 if( pDel!=0 ){
105320 sqlite3OomFault(db);
105321 sqlite3DbFree(db, pDel);
105322 pColl = 0;
105326 return pColl;
105330 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
105331 ** Return the CollSeq* pointer for the collation sequence named zName
105332 ** for the encoding 'enc' from the database 'db'.
105334 ** If the entry specified is not found and 'create' is true, then create a
105335 ** new entry. Otherwise return NULL.
105337 ** A separate function sqlite3LocateCollSeq() is a wrapper around
105338 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
105339 ** if necessary and generates an error message if the collating sequence
105340 ** cannot be found.
105342 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
105344 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
105345 sqlite3 *db,
105346 u8 enc,
105347 const char *zName,
105348 int create
105350 CollSeq *pColl;
105351 if( zName ){
105352 pColl = findCollSeqEntry(db, zName, create);
105353 }else{
105354 pColl = db->pDfltColl;
105356 assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
105357 assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
105358 if( pColl ) pColl += enc-1;
105359 return pColl;
105362 /* During the search for the best function definition, this procedure
105363 ** is called to test how well the function passed as the first argument
105364 ** matches the request for a function with nArg arguments in a system
105365 ** that uses encoding enc. The value returned indicates how well the
105366 ** request is matched. A higher value indicates a better match.
105368 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
105369 ** is also -1. In other words, we are searching for a function that
105370 ** takes a variable number of arguments.
105372 ** If nArg is -2 that means that we are searching for any function
105373 ** regardless of the number of arguments it uses, so return a positive
105374 ** match score for any
105376 ** The returned value is always between 0 and 6, as follows:
105378 ** 0: Not a match.
105379 ** 1: UTF8/16 conversion required and function takes any number of arguments.
105380 ** 2: UTF16 byte order change required and function takes any number of args.
105381 ** 3: encoding matches and function takes any number of arguments
105382 ** 4: UTF8/16 conversion required - argument count matches exactly
105383 ** 5: UTF16 byte order conversion required - argument count matches exactly
105384 ** 6: Perfect match: encoding and argument count match exactly.
105386 ** If nArg==(-2) then any function with a non-null xSFunc is
105387 ** a perfect match and any function with xSFunc NULL is
105388 ** a non-match.
105390 #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
105391 static int matchQuality(
105392 FuncDef *p, /* The function we are evaluating for match quality */
105393 int nArg, /* Desired number of arguments. (-1)==any */
105394 u8 enc /* Desired text encoding */
105396 int match;
105398 /* nArg of -2 is a special case */
105399 if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
105401 /* Wrong number of arguments means "no match" */
105402 if( p->nArg!=nArg && p->nArg>=0 ) return 0;
105404 /* Give a better score to a function with a specific number of arguments
105405 ** than to function that accepts any number of arguments. */
105406 if( p->nArg==nArg ){
105407 match = 4;
105408 }else{
105409 match = 1;
105412 /* Bonus points if the text encoding matches */
105413 if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
105414 match += 2; /* Exact encoding match */
105415 }else if( (enc & p->funcFlags & 2)!=0 ){
105416 match += 1; /* Both are UTF16, but with different byte orders */
105419 return match;
105423 ** Search a FuncDefHash for a function with the given name. Return
105424 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
105426 static FuncDef *functionSearch(
105427 int h, /* Hash of the name */
105428 const char *zFunc /* Name of function */
105430 FuncDef *p;
105431 for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
105432 if( sqlite3StrICmp(p->zName, zFunc)==0 ){
105433 return p;
105436 return 0;
105440 ** Insert a new FuncDef into a FuncDefHash hash table.
105442 SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
105443 FuncDef *aDef, /* List of global functions to be inserted */
105444 int nDef /* Length of the apDef[] list */
105446 int i;
105447 for(i=0; i<nDef; i++){
105448 FuncDef *pOther;
105449 const char *zName = aDef[i].zName;
105450 int nName = sqlite3Strlen30(zName);
105451 int h = (zName[0] + nName) % SQLITE_FUNC_HASH_SZ;
105452 assert( zName[0]>='a' && zName[0]<='z' );
105453 pOther = functionSearch(h, zName);
105454 if( pOther ){
105455 assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
105456 aDef[i].pNext = pOther->pNext;
105457 pOther->pNext = &aDef[i];
105458 }else{
105459 aDef[i].pNext = 0;
105460 aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
105461 sqlite3BuiltinFunctions.a[h] = &aDef[i];
105469 ** Locate a user function given a name, a number of arguments and a flag
105470 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
105471 ** pointer to the FuncDef structure that defines that function, or return
105472 ** NULL if the function does not exist.
105474 ** If the createFlag argument is true, then a new (blank) FuncDef
105475 ** structure is created and liked into the "db" structure if a
105476 ** no matching function previously existed.
105478 ** If nArg is -2, then the first valid function found is returned. A
105479 ** function is valid if xSFunc is non-zero. The nArg==(-2)
105480 ** case is used to see if zName is a valid function name for some number
105481 ** of arguments. If nArg is -2, then createFlag must be 0.
105483 ** If createFlag is false, then a function with the required name and
105484 ** number of arguments may be returned even if the eTextRep flag does not
105485 ** match that requested.
105487 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
105488 sqlite3 *db, /* An open database */
105489 const char *zName, /* Name of the function. zero-terminated */
105490 int nArg, /* Number of arguments. -1 means any number */
105491 u8 enc, /* Preferred text encoding */
105492 u8 createFlag /* Create new entry if true and does not otherwise exist */
105494 FuncDef *p; /* Iterator variable */
105495 FuncDef *pBest = 0; /* Best match found so far */
105496 int bestScore = 0; /* Score of best match */
105497 int h; /* Hash value */
105498 int nName; /* Length of the name */
105500 assert( nArg>=(-2) );
105501 assert( nArg>=(-1) || createFlag==0 );
105502 nName = sqlite3Strlen30(zName);
105504 /* First search for a match amongst the application-defined functions.
105506 p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
105507 while( p ){
105508 int score = matchQuality(p, nArg, enc);
105509 if( score>bestScore ){
105510 pBest = p;
105511 bestScore = score;
105513 p = p->pNext;
105516 /* If no match is found, search the built-in functions.
105518 ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
105519 ** functions even if a prior app-defined function was found. And give
105520 ** priority to built-in functions.
105522 ** Except, if createFlag is true, that means that we are trying to
105523 ** install a new function. Whatever FuncDef structure is returned it will
105524 ** have fields overwritten with new information appropriate for the
105525 ** new function. But the FuncDefs for built-in functions are read-only.
105526 ** So we must not search for built-ins when creating a new function.
105528 if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
105529 bestScore = 0;
105530 h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
105531 p = functionSearch(h, zName);
105532 while( p ){
105533 int score = matchQuality(p, nArg, enc);
105534 if( score>bestScore ){
105535 pBest = p;
105536 bestScore = score;
105538 p = p->pNext;
105542 /* If the createFlag parameter is true and the search did not reveal an
105543 ** exact match for the name, number of arguments and encoding, then add a
105544 ** new entry to the hash table and return it.
105546 if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
105547 (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
105548 FuncDef *pOther;
105549 pBest->zName = (const char*)&pBest[1];
105550 pBest->nArg = (u16)nArg;
105551 pBest->funcFlags = enc;
105552 memcpy((char*)&pBest[1], zName, nName+1);
105553 pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
105554 if( pOther==pBest ){
105555 sqlite3DbFree(db, pBest);
105556 sqlite3OomFault(db);
105557 return 0;
105558 }else{
105559 pBest->pNext = pOther;
105563 if( pBest && (pBest->xSFunc || createFlag) ){
105564 return pBest;
105566 return 0;
105570 ** Free all resources held by the schema structure. The void* argument points
105571 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
105572 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
105573 ** of the schema hash tables).
105575 ** The Schema.cache_size variable is not cleared.
105577 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
105578 Hash temp1;
105579 Hash temp2;
105580 HashElem *pElem;
105581 Schema *pSchema = (Schema *)p;
105583 temp1 = pSchema->tblHash;
105584 temp2 = pSchema->trigHash;
105585 sqlite3HashInit(&pSchema->trigHash);
105586 sqlite3HashClear(&pSchema->idxHash);
105587 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
105588 sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
105590 sqlite3HashClear(&temp2);
105591 sqlite3HashInit(&pSchema->tblHash);
105592 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
105593 Table *pTab = sqliteHashData(pElem);
105594 sqlite3DeleteTable(0, pTab);
105596 sqlite3HashClear(&temp1);
105597 sqlite3HashClear(&pSchema->fkeyHash);
105598 pSchema->pSeqTab = 0;
105599 if( pSchema->schemaFlags & DB_SchemaLoaded ){
105600 pSchema->iGeneration++;
105602 pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
105606 ** Find and return the schema associated with a BTree. Create
105607 ** a new one if necessary.
105609 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
105610 Schema * p;
105611 if( pBt ){
105612 p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
105613 }else{
105614 p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
105616 if( !p ){
105617 sqlite3OomFault(db);
105618 }else if ( 0==p->file_format ){
105619 sqlite3HashInit(&p->tblHash);
105620 sqlite3HashInit(&p->idxHash);
105621 sqlite3HashInit(&p->trigHash);
105622 sqlite3HashInit(&p->fkeyHash);
105623 p->enc = SQLITE_UTF8;
105625 return p;
105628 /************** End of callback.c ********************************************/
105629 /************** Begin file delete.c ******************************************/
105631 ** 2001 September 15
105633 ** The author disclaims copyright to this source code. In place of
105634 ** a legal notice, here is a blessing:
105636 ** May you do good and not evil.
105637 ** May you find forgiveness for yourself and forgive others.
105638 ** May you share freely, never taking more than you give.
105640 *************************************************************************
105641 ** This file contains C code routines that are called by the parser
105642 ** in order to generate code for DELETE FROM statements.
105644 /* #include "sqliteInt.h" */
105647 ** While a SrcList can in general represent multiple tables and subqueries
105648 ** (as in the FROM clause of a SELECT statement) in this case it contains
105649 ** the name of a single table, as one might find in an INSERT, DELETE,
105650 ** or UPDATE statement. Look up that table in the symbol table and
105651 ** return a pointer. Set an error message and return NULL if the table
105652 ** name is not found or if any other error occurs.
105654 ** The following fields are initialized appropriate in pSrc:
105656 ** pSrc->a[0].pTab Pointer to the Table object
105657 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
105660 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
105661 struct SrcList_item *pItem = pSrc->a;
105662 Table *pTab;
105663 assert( pItem && pSrc->nSrc==1 );
105664 pTab = sqlite3LocateTableItem(pParse, 0, pItem);
105665 sqlite3DeleteTable(pParse->db, pItem->pTab);
105666 pItem->pTab = pTab;
105667 if( pTab ){
105668 pTab->nTabRef++;
105670 if( sqlite3IndexedByLookup(pParse, pItem) ){
105671 pTab = 0;
105673 return pTab;
105677 ** Check to make sure the given table is writable. If it is not
105678 ** writable, generate an error message and return 1. If it is
105679 ** writable return 0;
105681 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
105682 /* A table is not writable under the following circumstances:
105684 ** 1) It is a virtual table and no implementation of the xUpdate method
105685 ** has been provided, or
105686 ** 2) It is a system table (i.e. sqlite_master), this call is not
105687 ** part of a nested parse and writable_schema pragma has not
105688 ** been specified.
105690 ** In either case leave an error message in pParse and return non-zero.
105692 if( ( IsVirtual(pTab)
105693 && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
105694 || ( (pTab->tabFlags & TF_Readonly)!=0
105695 && (pParse->db->flags & SQLITE_WriteSchema)==0
105696 && pParse->nested==0 )
105698 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
105699 return 1;
105702 #ifndef SQLITE_OMIT_VIEW
105703 if( !viewOk && pTab->pSelect ){
105704 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
105705 return 1;
105707 #endif
105708 return 0;
105712 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
105714 ** Evaluate a view and store its result in an ephemeral table. The
105715 ** pWhere argument is an optional WHERE clause that restricts the
105716 ** set of rows in the view that are to be added to the ephemeral table.
105718 SQLITE_PRIVATE void sqlite3MaterializeView(
105719 Parse *pParse, /* Parsing context */
105720 Table *pView, /* View definition */
105721 Expr *pWhere, /* Optional WHERE clause to be added */
105722 int iCur /* Cursor number for ephemeral table */
105724 SelectDest dest;
105725 Select *pSel;
105726 SrcList *pFrom;
105727 sqlite3 *db = pParse->db;
105728 int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
105729 pWhere = sqlite3ExprDup(db, pWhere, 0);
105730 pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
105731 if( pFrom ){
105732 assert( pFrom->nSrc==1 );
105733 pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
105734 pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
105735 assert( pFrom->a[0].pOn==0 );
105736 assert( pFrom->a[0].pUsing==0 );
105738 pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
105739 SF_IncludeHidden, 0, 0);
105740 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
105741 sqlite3Select(pParse, pSel, &dest);
105742 sqlite3SelectDelete(db, pSel);
105744 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
105746 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
105748 ** Generate an expression tree to implement the WHERE, ORDER BY,
105749 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
105751 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
105752 ** \__________________________/
105753 ** pLimitWhere (pInClause)
105755 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
105756 Parse *pParse, /* The parser context */
105757 SrcList *pSrc, /* the FROM clause -- which tables to scan */
105758 Expr *pWhere, /* The WHERE clause. May be null */
105759 ExprList *pOrderBy, /* The ORDER BY clause. May be null */
105760 Expr *pLimit, /* The LIMIT clause. May be null */
105761 Expr *pOffset, /* The OFFSET clause. May be null */
105762 char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
105764 Expr *pWhereRowid = NULL; /* WHERE rowid .. */
105765 Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
105766 Expr *pSelectRowid = NULL; /* SELECT rowid ... */
105767 ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
105768 SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
105769 Select *pSelect = NULL; /* Complete SELECT tree */
105771 /* Check that there isn't an ORDER BY without a LIMIT clause.
105773 if( pOrderBy && (pLimit == 0) ) {
105774 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
105775 goto limit_where_cleanup;
105778 /* We only need to generate a select expression if there
105779 ** is a limit/offset term to enforce.
105781 if( pLimit == 0 ) {
105782 /* if pLimit is null, pOffset will always be null as well. */
105783 assert( pOffset == 0 );
105784 return pWhere;
105787 /* Generate a select expression tree to enforce the limit/offset
105788 ** term for the DELETE or UPDATE statement. For example:
105789 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
105790 ** becomes:
105791 ** DELETE FROM table_a WHERE rowid IN (
105792 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
105793 ** );
105796 pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
105797 if( pSelectRowid == 0 ) goto limit_where_cleanup;
105798 pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
105799 if( pEList == 0 ) goto limit_where_cleanup;
105801 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
105802 ** and the SELECT subtree. */
105803 pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
105804 if( pSelectSrc == 0 ) {
105805 sqlite3ExprListDelete(pParse->db, pEList);
105806 goto limit_where_cleanup;
105809 /* generate the SELECT expression tree. */
105810 pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
105811 pOrderBy,0,pLimit,pOffset);
105812 if( pSelect == 0 ) return 0;
105814 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
105815 pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
105816 pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0) : 0;
105817 sqlite3PExprAddSelect(pParse, pInClause, pSelect);
105818 return pInClause;
105820 limit_where_cleanup:
105821 sqlite3ExprDelete(pParse->db, pWhere);
105822 sqlite3ExprListDelete(pParse->db, pOrderBy);
105823 sqlite3ExprDelete(pParse->db, pLimit);
105824 sqlite3ExprDelete(pParse->db, pOffset);
105825 return 0;
105827 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
105828 /* && !defined(SQLITE_OMIT_SUBQUERY) */
105831 ** Generate code for a DELETE FROM statement.
105833 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
105834 ** \________/ \________________/
105835 ** pTabList pWhere
105837 SQLITE_PRIVATE void sqlite3DeleteFrom(
105838 Parse *pParse, /* The parser context */
105839 SrcList *pTabList, /* The table from which we should delete things */
105840 Expr *pWhere /* The WHERE clause. May be null */
105842 Vdbe *v; /* The virtual database engine */
105843 Table *pTab; /* The table from which records will be deleted */
105844 int i; /* Loop counter */
105845 WhereInfo *pWInfo; /* Information about the WHERE clause */
105846 Index *pIdx; /* For looping over indices of the table */
105847 int iTabCur; /* Cursor number for the table */
105848 int iDataCur = 0; /* VDBE cursor for the canonical data source */
105849 int iIdxCur = 0; /* Cursor number of the first index */
105850 int nIdx; /* Number of indices */
105851 sqlite3 *db; /* Main database structure */
105852 AuthContext sContext; /* Authorization context */
105853 NameContext sNC; /* Name context to resolve expressions in */
105854 int iDb; /* Database number */
105855 int memCnt = -1; /* Memory cell used for change counting */
105856 int rcauth; /* Value returned by authorization callback */
105857 int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
105858 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
105859 u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
105860 Index *pPk; /* The PRIMARY KEY index on the table */
105861 int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
105862 i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
105863 int iKey; /* Memory cell holding key of row to be deleted */
105864 i16 nKey; /* Number of memory cells in the row key */
105865 int iEphCur = 0; /* Ephemeral table holding all primary key values */
105866 int iRowSet = 0; /* Register for rowset of rows to delete */
105867 int addrBypass = 0; /* Address of jump over the delete logic */
105868 int addrLoop = 0; /* Top of the delete loop */
105869 int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
105870 int bComplex; /* True if there are triggers or FKs or
105871 ** subqueries in the WHERE clause */
105873 #ifndef SQLITE_OMIT_TRIGGER
105874 int isView; /* True if attempting to delete from a view */
105875 Trigger *pTrigger; /* List of table triggers, if required */
105876 #endif
105878 memset(&sContext, 0, sizeof(sContext));
105879 db = pParse->db;
105880 if( pParse->nErr || db->mallocFailed ){
105881 goto delete_from_cleanup;
105883 assert( pTabList->nSrc==1 );
105885 /* Locate the table which we want to delete. This table has to be
105886 ** put in an SrcList structure because some of the subroutines we
105887 ** will be calling are designed to work with multiple tables and expect
105888 ** an SrcList* parameter instead of just a Table* parameter.
105890 pTab = sqlite3SrcListLookup(pParse, pTabList);
105891 if( pTab==0 ) goto delete_from_cleanup;
105893 /* Figure out if we have any triggers and if the table being
105894 ** deleted from is a view
105896 #ifndef SQLITE_OMIT_TRIGGER
105897 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
105898 isView = pTab->pSelect!=0;
105899 bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
105900 #else
105901 # define pTrigger 0
105902 # define isView 0
105903 #endif
105904 #ifdef SQLITE_OMIT_VIEW
105905 # undef isView
105906 # define isView 0
105907 #endif
105909 /* If pTab is really a view, make sure it has been initialized.
105911 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
105912 goto delete_from_cleanup;
105915 if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
105916 goto delete_from_cleanup;
105918 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
105919 assert( iDb<db->nDb );
105920 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
105921 db->aDb[iDb].zDbSName);
105922 assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
105923 if( rcauth==SQLITE_DENY ){
105924 goto delete_from_cleanup;
105926 assert(!isView || pTrigger);
105928 /* Assign cursor numbers to the table and all its indices.
105930 assert( pTabList->nSrc==1 );
105931 iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
105932 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
105933 pParse->nTab++;
105936 /* Start the view context
105938 if( isView ){
105939 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
105942 /* Begin generating code.
105944 v = sqlite3GetVdbe(pParse);
105945 if( v==0 ){
105946 goto delete_from_cleanup;
105948 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
105949 sqlite3BeginWriteOperation(pParse, 1, iDb);
105951 /* If we are trying to delete from a view, realize that view into
105952 ** an ephemeral table.
105954 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
105955 if( isView ){
105956 sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
105957 iDataCur = iIdxCur = iTabCur;
105959 #endif
105961 /* Resolve the column names in the WHERE clause.
105963 memset(&sNC, 0, sizeof(sNC));
105964 sNC.pParse = pParse;
105965 sNC.pSrcList = pTabList;
105966 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
105967 goto delete_from_cleanup;
105970 /* Initialize the counter of the number of rows deleted, if
105971 ** we are counting rows.
105973 if( db->flags & SQLITE_CountRows ){
105974 memCnt = ++pParse->nMem;
105975 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
105978 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
105979 /* Special case: A DELETE without a WHERE clause deletes everything.
105980 ** It is easier just to erase the whole table. Prior to version 3.6.5,
105981 ** this optimization caused the row change count (the value returned by
105982 ** API function sqlite3_count_changes) to be set incorrectly.
105984 ** The "rcauth==SQLITE_OK" terms is the
105985 ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
105986 ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
105987 ** the truncate optimization is disabled and all rows are deleted
105988 ** individually.
105990 if( rcauth==SQLITE_OK
105991 && pWhere==0
105992 && !bComplex
105993 && !IsVirtual(pTab)
105994 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
105995 && db->xPreUpdateCallback==0
105996 #endif
105998 assert( !isView );
105999 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
106000 if( HasRowid(pTab) ){
106001 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
106002 pTab->zName, P4_STATIC);
106004 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
106005 assert( pIdx->pSchema==pTab->pSchema );
106006 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
106008 }else
106009 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
106011 u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
106012 if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
106013 wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
106014 if( HasRowid(pTab) ){
106015 /* For a rowid table, initialize the RowSet to an empty set */
106016 pPk = 0;
106017 nPk = 1;
106018 iRowSet = ++pParse->nMem;
106019 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
106020 }else{
106021 /* For a WITHOUT ROWID table, create an ephemeral table used to
106022 ** hold all primary keys for rows to be deleted. */
106023 pPk = sqlite3PrimaryKeyIndex(pTab);
106024 assert( pPk!=0 );
106025 nPk = pPk->nKeyCol;
106026 iPk = pParse->nMem+1;
106027 pParse->nMem += nPk;
106028 iEphCur = pParse->nTab++;
106029 addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
106030 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
106033 /* Construct a query to find the rowid or primary key for every row
106034 ** to be deleted, based on the WHERE clause. Set variable eOnePass
106035 ** to indicate the strategy used to implement this delete:
106037 ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
106038 ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
106039 ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
106041 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
106042 if( pWInfo==0 ) goto delete_from_cleanup;
106043 eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
106044 assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
106045 assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
106047 /* Keep track of the number of rows to be deleted */
106048 if( db->flags & SQLITE_CountRows ){
106049 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
106052 /* Extract the rowid or primary key for the current row */
106053 if( pPk ){
106054 for(i=0; i<nPk; i++){
106055 assert( pPk->aiColumn[i]>=0 );
106056 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
106057 pPk->aiColumn[i], iPk+i);
106059 iKey = iPk;
106060 }else{
106061 iKey = pParse->nMem + 1;
106062 iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
106063 if( iKey>pParse->nMem ) pParse->nMem = iKey;
106066 if( eOnePass!=ONEPASS_OFF ){
106067 /* For ONEPASS, no need to store the rowid/primary-key. There is only
106068 ** one, so just keep it in its register(s) and fall through to the
106069 ** delete code. */
106070 nKey = nPk; /* OP_Found will use an unpacked key */
106071 aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
106072 if( aToOpen==0 ){
106073 sqlite3WhereEnd(pWInfo);
106074 goto delete_from_cleanup;
106076 memset(aToOpen, 1, nIdx+1);
106077 aToOpen[nIdx+1] = 0;
106078 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
106079 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
106080 if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
106081 }else{
106082 if( pPk ){
106083 /* Add the PK key for this row to the temporary table */
106084 iKey = ++pParse->nMem;
106085 nKey = 0; /* Zero tells OP_Found to use a composite key */
106086 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
106087 sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
106088 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
106089 }else{
106090 /* Add the rowid of the row to be deleted to the RowSet */
106091 nKey = 1; /* OP_DeferredSeek always uses a single rowid */
106092 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
106096 /* If this DELETE cannot use the ONEPASS strategy, this is the
106097 ** end of the WHERE loop */
106098 if( eOnePass!=ONEPASS_OFF ){
106099 addrBypass = sqlite3VdbeMakeLabel(v);
106100 }else{
106101 sqlite3WhereEnd(pWInfo);
106104 /* Unless this is a view, open cursors for the table we are
106105 ** deleting from and all its indices. If this is a view, then the
106106 ** only effect this statement has is to fire the INSTEAD OF
106107 ** triggers.
106109 if( !isView ){
106110 int iAddrOnce = 0;
106111 if( eOnePass==ONEPASS_MULTI ){
106112 iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
106114 testcase( IsVirtual(pTab) );
106115 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
106116 iTabCur, aToOpen, &iDataCur, &iIdxCur);
106117 assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
106118 assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
106119 if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
106122 /* Set up a loop over the rowids/primary-keys that were found in the
106123 ** where-clause loop above.
106125 if( eOnePass!=ONEPASS_OFF ){
106126 assert( nKey==nPk ); /* OP_Found will use an unpacked key */
106127 if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
106128 assert( pPk!=0 || pTab->pSelect!=0 );
106129 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
106130 VdbeCoverage(v);
106132 }else if( pPk ){
106133 addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
106134 if( IsVirtual(pTab) ){
106135 sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
106136 }else{
106137 sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
106139 assert( nKey==0 ); /* OP_Found will use a composite key */
106140 }else{
106141 addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
106142 VdbeCoverage(v);
106143 assert( nKey==1 );
106146 /* Delete the row */
106147 #ifndef SQLITE_OMIT_VIRTUALTABLE
106148 if( IsVirtual(pTab) ){
106149 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
106150 sqlite3VtabMakeWritable(pParse, pTab);
106151 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
106152 sqlite3VdbeChangeP5(v, OE_Abort);
106153 assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
106154 sqlite3MayAbort(pParse);
106155 if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
106156 pParse->isMultiWrite = 0;
106158 }else
106159 #endif
106161 int count = (pParse->nested==0); /* True to count changes */
106162 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
106163 iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
106166 /* End of the loop over all rowids/primary-keys. */
106167 if( eOnePass!=ONEPASS_OFF ){
106168 sqlite3VdbeResolveLabel(v, addrBypass);
106169 sqlite3WhereEnd(pWInfo);
106170 }else if( pPk ){
106171 sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
106172 sqlite3VdbeJumpHere(v, addrLoop);
106173 }else{
106174 sqlite3VdbeGoto(v, addrLoop);
106175 sqlite3VdbeJumpHere(v, addrLoop);
106177 } /* End non-truncate path */
106179 /* Update the sqlite_sequence table by storing the content of the
106180 ** maximum rowid counter values recorded while inserting into
106181 ** autoincrement tables.
106183 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
106184 sqlite3AutoincrementEnd(pParse);
106187 /* Return the number of rows that were deleted. If this routine is
106188 ** generating code because of a call to sqlite3NestedParse(), do not
106189 ** invoke the callback function.
106191 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
106192 sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
106193 sqlite3VdbeSetNumCols(v, 1);
106194 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
106197 delete_from_cleanup:
106198 sqlite3AuthContextPop(&sContext);
106199 sqlite3SrcListDelete(db, pTabList);
106200 sqlite3ExprDelete(db, pWhere);
106201 sqlite3DbFree(db, aToOpen);
106202 return;
106204 /* Make sure "isView" and other macros defined above are undefined. Otherwise
106205 ** they may interfere with compilation of other functions in this file
106206 ** (or in another file, if this file becomes part of the amalgamation). */
106207 #ifdef isView
106208 #undef isView
106209 #endif
106210 #ifdef pTrigger
106211 #undef pTrigger
106212 #endif
106215 ** This routine generates VDBE code that causes a single row of a
106216 ** single table to be deleted. Both the original table entry and
106217 ** all indices are removed.
106219 ** Preconditions:
106221 ** 1. iDataCur is an open cursor on the btree that is the canonical data
106222 ** store for the table. (This will be either the table itself,
106223 ** in the case of a rowid table, or the PRIMARY KEY index in the case
106224 ** of a WITHOUT ROWID table.)
106226 ** 2. Read/write cursors for all indices of pTab must be open as
106227 ** cursor number iIdxCur+i for the i-th index.
106229 ** 3. The primary key for the row to be deleted must be stored in a
106230 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
106231 ** that a search record formed from OP_MakeRecord is contained in the
106232 ** single memory location iPk.
106234 ** eMode:
106235 ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
106236 ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
106237 ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
106238 ** then this function must seek iDataCur to the entry identified by iPk
106239 ** and nPk before reading from it.
106241 ** If eMode is ONEPASS_MULTI, then this call is being made as part
106242 ** of a ONEPASS delete that affects multiple rows. In this case, if
106243 ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
106244 ** iDataCur, then its position should be preserved following the delete
106245 ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
106246 ** position of iDataCur should be preserved instead.
106248 ** iIdxNoSeek:
106249 ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
106250 ** then it identifies an index cursor (from within array of cursors
106251 ** starting at iIdxCur) that already points to the index entry to be deleted.
106252 ** Except, this optimization is disabled if there are BEFORE triggers since
106253 ** the trigger body might have moved the cursor.
106255 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
106256 Parse *pParse, /* Parsing context */
106257 Table *pTab, /* Table containing the row to be deleted */
106258 Trigger *pTrigger, /* List of triggers to (potentially) fire */
106259 int iDataCur, /* Cursor from which column data is extracted */
106260 int iIdxCur, /* First index cursor */
106261 int iPk, /* First memory cell containing the PRIMARY KEY */
106262 i16 nPk, /* Number of PRIMARY KEY memory cells */
106263 u8 count, /* If non-zero, increment the row change counter */
106264 u8 onconf, /* Default ON CONFLICT policy for triggers */
106265 u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
106266 int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
106268 Vdbe *v = pParse->pVdbe; /* Vdbe */
106269 int iOld = 0; /* First register in OLD.* array */
106270 int iLabel; /* Label resolved to end of generated code */
106271 u8 opSeek; /* Seek opcode */
106273 /* Vdbe is guaranteed to have been allocated by this stage. */
106274 assert( v );
106275 VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
106276 iDataCur, iIdxCur, iPk, (int)nPk));
106278 /* Seek cursor iCur to the row to delete. If this row no longer exists
106279 ** (this can happen if a trigger program has already deleted it), do
106280 ** not attempt to delete it or fire any DELETE triggers. */
106281 iLabel = sqlite3VdbeMakeLabel(v);
106282 opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
106283 if( eMode==ONEPASS_OFF ){
106284 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
106285 VdbeCoverageIf(v, opSeek==OP_NotExists);
106286 VdbeCoverageIf(v, opSeek==OP_NotFound);
106289 /* If there are any triggers to fire, allocate a range of registers to
106290 ** use for the old.* references in the triggers. */
106291 if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
106292 u32 mask; /* Mask of OLD.* columns in use */
106293 int iCol; /* Iterator used while populating OLD.* */
106294 int addrStart; /* Start of BEFORE trigger programs */
106296 /* TODO: Could use temporary registers here. Also could attempt to
106297 ** avoid copying the contents of the rowid register. */
106298 mask = sqlite3TriggerColmask(
106299 pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
106301 mask |= sqlite3FkOldmask(pParse, pTab);
106302 iOld = pParse->nMem+1;
106303 pParse->nMem += (1 + pTab->nCol);
106305 /* Populate the OLD.* pseudo-table register array. These values will be
106306 ** used by any BEFORE and AFTER triggers that exist. */
106307 sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
106308 for(iCol=0; iCol<pTab->nCol; iCol++){
106309 testcase( mask!=0xffffffff && iCol==31 );
106310 testcase( mask!=0xffffffff && iCol==32 );
106311 if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
106312 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
106316 /* Invoke BEFORE DELETE trigger programs. */
106317 addrStart = sqlite3VdbeCurrentAddr(v);
106318 sqlite3CodeRowTrigger(pParse, pTrigger,
106319 TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
106322 /* If any BEFORE triggers were coded, then seek the cursor to the
106323 ** row to be deleted again. It may be that the BEFORE triggers moved
106324 ** the cursor or already deleted the row that the cursor was
106325 ** pointing to.
106327 ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
106328 ** may have moved that cursor.
106330 if( addrStart<sqlite3VdbeCurrentAddr(v) ){
106331 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
106332 VdbeCoverageIf(v, opSeek==OP_NotExists);
106333 VdbeCoverageIf(v, opSeek==OP_NotFound);
106334 testcase( iIdxNoSeek>=0 );
106335 iIdxNoSeek = -1;
106338 /* Do FK processing. This call checks that any FK constraints that
106339 ** refer to this table (i.e. constraints attached to other tables)
106340 ** are not violated by deleting this row. */
106341 sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
106344 /* Delete the index and table entries. Skip this step if pTab is really
106345 ** a view (in which case the only effect of the DELETE statement is to
106346 ** fire the INSTEAD OF triggers).
106348 ** If variable 'count' is non-zero, then this OP_Delete instruction should
106349 ** invoke the update-hook. The pre-update-hook, on the other hand should
106350 ** be invoked unless table pTab is a system table. The difference is that
106351 ** the update-hook is not invoked for rows removed by REPLACE, but the
106352 ** pre-update-hook is.
106354 if( pTab->pSelect==0 ){
106355 u8 p5 = 0;
106356 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
106357 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
106358 if( pParse->nested==0 ){
106359 sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
106361 if( eMode!=ONEPASS_OFF ){
106362 sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
106364 if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
106365 sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
106367 if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
106368 sqlite3VdbeChangeP5(v, p5);
106371 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
106372 ** handle rows (possibly in other tables) that refer via a foreign key
106373 ** to the row just deleted. */
106374 sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
106376 /* Invoke AFTER DELETE trigger programs. */
106377 sqlite3CodeRowTrigger(pParse, pTrigger,
106378 TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
106381 /* Jump here if the row had already been deleted before any BEFORE
106382 ** trigger programs were invoked. Or if a trigger program throws a
106383 ** RAISE(IGNORE) exception. */
106384 sqlite3VdbeResolveLabel(v, iLabel);
106385 VdbeModuleComment((v, "END: GenRowDel()"));
106389 ** This routine generates VDBE code that causes the deletion of all
106390 ** index entries associated with a single row of a single table, pTab
106392 ** Preconditions:
106394 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
106395 ** btree for the table pTab. (This will be either the table itself
106396 ** for rowid tables or to the primary key index for WITHOUT ROWID
106397 ** tables.)
106399 ** 2. Read/write cursors for all indices of pTab must be open as
106400 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
106401 ** index is the 0-th index.)
106403 ** 3. The "iDataCur" cursor must be already be positioned on the row
106404 ** that is to be deleted.
106406 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
106407 Parse *pParse, /* Parsing and code generating context */
106408 Table *pTab, /* Table containing the row to be deleted */
106409 int iDataCur, /* Cursor of table holding data. */
106410 int iIdxCur, /* First index cursor */
106411 int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
106412 int iIdxNoSeek /* Do not delete from this cursor */
106414 int i; /* Index loop counter */
106415 int r1 = -1; /* Register holding an index key */
106416 int iPartIdxLabel; /* Jump destination for skipping partial index entries */
106417 Index *pIdx; /* Current index */
106418 Index *pPrior = 0; /* Prior index */
106419 Vdbe *v; /* The prepared statement under construction */
106420 Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
106422 v = pParse->pVdbe;
106423 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
106424 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
106425 assert( iIdxCur+i!=iDataCur || pPk==pIdx );
106426 if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
106427 if( pIdx==pPk ) continue;
106428 if( iIdxCur+i==iIdxNoSeek ) continue;
106429 VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
106430 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
106431 &iPartIdxLabel, pPrior, r1);
106432 sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
106433 pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
106434 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
106435 pPrior = pIdx;
106440 ** Generate code that will assemble an index key and stores it in register
106441 ** regOut. The key with be for index pIdx which is an index on pTab.
106442 ** iCur is the index of a cursor open on the pTab table and pointing to
106443 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
106444 ** iCur must be the cursor of the PRIMARY KEY index.
106446 ** Return a register number which is the first in a block of
106447 ** registers that holds the elements of the index key. The
106448 ** block of registers has already been deallocated by the time
106449 ** this routine returns.
106451 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
106452 ** to that label if pIdx is a partial index that should be skipped.
106453 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
106454 ** A partial index should be skipped if its WHERE clause evaluates
106455 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
106456 ** will be set to zero which is an empty label that is ignored by
106457 ** sqlite3ResolvePartIdxLabel().
106459 ** The pPrior and regPrior parameters are used to implement a cache to
106460 ** avoid unnecessary register loads. If pPrior is not NULL, then it is
106461 ** a pointer to a different index for which an index key has just been
106462 ** computed into register regPrior. If the current pIdx index is generating
106463 ** its key into the same sequence of registers and if pPrior and pIdx share
106464 ** a column in common, then the register corresponding to that column already
106465 ** holds the correct value and the loading of that register is skipped.
106466 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
106467 ** on a table with multiple indices, and especially with the ROWID or
106468 ** PRIMARY KEY columns of the index.
106470 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
106471 Parse *pParse, /* Parsing context */
106472 Index *pIdx, /* The index for which to generate a key */
106473 int iDataCur, /* Cursor number from which to take column data */
106474 int regOut, /* Put the new key into this register if not 0 */
106475 int prefixOnly, /* Compute only a unique prefix of the key */
106476 int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
106477 Index *pPrior, /* Previously generated index key */
106478 int regPrior /* Register holding previous generated key */
106480 Vdbe *v = pParse->pVdbe;
106481 int j;
106482 int regBase;
106483 int nCol;
106485 if( piPartIdxLabel ){
106486 if( pIdx->pPartIdxWhere ){
106487 *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
106488 pParse->iSelfTab = iDataCur + 1;
106489 sqlite3ExprCachePush(pParse);
106490 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
106491 SQLITE_JUMPIFNULL);
106492 pParse->iSelfTab = 0;
106493 }else{
106494 *piPartIdxLabel = 0;
106497 nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
106498 regBase = sqlite3GetTempRange(pParse, nCol);
106499 if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
106500 for(j=0; j<nCol; j++){
106501 if( pPrior
106502 && pPrior->aiColumn[j]==pIdx->aiColumn[j]
106503 && pPrior->aiColumn[j]!=XN_EXPR
106505 /* This column was already computed by the previous index */
106506 continue;
106508 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
106509 /* If the column affinity is REAL but the number is an integer, then it
106510 ** might be stored in the table as an integer (using a compact
106511 ** representation) then converted to REAL by an OP_RealAffinity opcode.
106512 ** But we are getting ready to store this value back into an index, where
106513 ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
106514 ** opcode if it is present */
106515 sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
106517 if( regOut ){
106518 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
106519 if( pIdx->pTable->pSelect ){
106520 const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
106521 sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
106524 sqlite3ReleaseTempRange(pParse, regBase, nCol);
106525 return regBase;
106529 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
106530 ** because it was a partial index, then this routine should be called to
106531 ** resolve that label.
106533 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
106534 if( iLabel ){
106535 sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
106536 sqlite3ExprCachePop(pParse);
106540 /************** End of delete.c **********************************************/
106541 /************** Begin file func.c ********************************************/
106543 ** 2002 February 23
106545 ** The author disclaims copyright to this source code. In place of
106546 ** a legal notice, here is a blessing:
106548 ** May you do good and not evil.
106549 ** May you find forgiveness for yourself and forgive others.
106550 ** May you share freely, never taking more than you give.
106552 *************************************************************************
106553 ** This file contains the C-language implementations for many of the SQL
106554 ** functions of SQLite. (Some function, and in particular the date and
106555 ** time functions, are implemented separately.)
106557 /* #include "sqliteInt.h" */
106558 /* #include <stdlib.h> */
106559 /* #include <assert.h> */
106560 /* #include "vdbeInt.h" */
106563 ** Return the collating function associated with a function.
106565 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
106566 VdbeOp *pOp;
106567 assert( context->pVdbe!=0 );
106568 pOp = &context->pVdbe->aOp[context->iOp-1];
106569 assert( pOp->opcode==OP_CollSeq );
106570 assert( pOp->p4type==P4_COLLSEQ );
106571 return pOp->p4.pColl;
106575 ** Indicate that the accumulator load should be skipped on this
106576 ** iteration of the aggregate loop.
106578 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
106579 context->skipFlag = 1;
106583 ** Implementation of the non-aggregate min() and max() functions
106585 static void minmaxFunc(
106586 sqlite3_context *context,
106587 int argc,
106588 sqlite3_value **argv
106590 int i;
106591 int mask; /* 0 for min() or 0xffffffff for max() */
106592 int iBest;
106593 CollSeq *pColl;
106595 assert( argc>1 );
106596 mask = sqlite3_user_data(context)==0 ? 0 : -1;
106597 pColl = sqlite3GetFuncCollSeq(context);
106598 assert( pColl );
106599 assert( mask==-1 || mask==0 );
106600 iBest = 0;
106601 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
106602 for(i=1; i<argc; i++){
106603 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
106604 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
106605 testcase( mask==0 );
106606 iBest = i;
106609 sqlite3_result_value(context, argv[iBest]);
106613 ** Return the type of the argument.
106615 static void typeofFunc(
106616 sqlite3_context *context,
106617 int NotUsed,
106618 sqlite3_value **argv
106620 static const char *azType[] = { "integer", "real", "text", "blob", "null" };
106621 int i = sqlite3_value_type(argv[0]) - 1;
106622 UNUSED_PARAMETER(NotUsed);
106623 assert( i>=0 && i<ArraySize(azType) );
106624 assert( SQLITE_INTEGER==1 );
106625 assert( SQLITE_FLOAT==2 );
106626 assert( SQLITE_TEXT==3 );
106627 assert( SQLITE_BLOB==4 );
106628 assert( SQLITE_NULL==5 );
106629 /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
106630 ** the datatype code for the initial datatype of the sqlite3_value object
106631 ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
106632 ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
106633 sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
106638 ** Implementation of the length() function
106640 static void lengthFunc(
106641 sqlite3_context *context,
106642 int argc,
106643 sqlite3_value **argv
106645 int len;
106647 assert( argc==1 );
106648 UNUSED_PARAMETER(argc);
106649 switch( sqlite3_value_type(argv[0]) ){
106650 case SQLITE_BLOB:
106651 case SQLITE_INTEGER:
106652 case SQLITE_FLOAT: {
106653 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
106654 break;
106656 case SQLITE_TEXT: {
106657 const unsigned char *z = sqlite3_value_text(argv[0]);
106658 if( z==0 ) return;
106659 len = 0;
106660 while( *z ){
106661 len++;
106662 SQLITE_SKIP_UTF8(z);
106664 sqlite3_result_int(context, len);
106665 break;
106667 default: {
106668 sqlite3_result_null(context);
106669 break;
106675 ** Implementation of the abs() function.
106677 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
106678 ** the numeric argument X.
106680 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106681 assert( argc==1 );
106682 UNUSED_PARAMETER(argc);
106683 switch( sqlite3_value_type(argv[0]) ){
106684 case SQLITE_INTEGER: {
106685 i64 iVal = sqlite3_value_int64(argv[0]);
106686 if( iVal<0 ){
106687 if( iVal==SMALLEST_INT64 ){
106688 /* IMP: R-31676-45509 If X is the integer -9223372036854775808
106689 ** then abs(X) throws an integer overflow error since there is no
106690 ** equivalent positive 64-bit two complement value. */
106691 sqlite3_result_error(context, "integer overflow", -1);
106692 return;
106694 iVal = -iVal;
106696 sqlite3_result_int64(context, iVal);
106697 break;
106699 case SQLITE_NULL: {
106700 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
106701 sqlite3_result_null(context);
106702 break;
106704 default: {
106705 /* Because sqlite3_value_double() returns 0.0 if the argument is not
106706 ** something that can be converted into a number, we have:
106707 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
106708 ** that cannot be converted to a numeric value.
106710 double rVal = sqlite3_value_double(argv[0]);
106711 if( rVal<0 ) rVal = -rVal;
106712 sqlite3_result_double(context, rVal);
106713 break;
106719 ** Implementation of the instr() function.
106721 ** instr(haystack,needle) finds the first occurrence of needle
106722 ** in haystack and returns the number of previous characters plus 1,
106723 ** or 0 if needle does not occur within haystack.
106725 ** If both haystack and needle are BLOBs, then the result is one more than
106726 ** the number of bytes in haystack prior to the first occurrence of needle,
106727 ** or 0 if needle never occurs in haystack.
106729 static void instrFunc(
106730 sqlite3_context *context,
106731 int argc,
106732 sqlite3_value **argv
106734 const unsigned char *zHaystack;
106735 const unsigned char *zNeedle;
106736 int nHaystack;
106737 int nNeedle;
106738 int typeHaystack, typeNeedle;
106739 int N = 1;
106740 int isText;
106742 UNUSED_PARAMETER(argc);
106743 typeHaystack = sqlite3_value_type(argv[0]);
106744 typeNeedle = sqlite3_value_type(argv[1]);
106745 if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
106746 nHaystack = sqlite3_value_bytes(argv[0]);
106747 nNeedle = sqlite3_value_bytes(argv[1]);
106748 if( nNeedle>0 ){
106749 if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
106750 zHaystack = sqlite3_value_blob(argv[0]);
106751 zNeedle = sqlite3_value_blob(argv[1]);
106752 isText = 0;
106753 }else{
106754 zHaystack = sqlite3_value_text(argv[0]);
106755 zNeedle = sqlite3_value_text(argv[1]);
106756 isText = 1;
106758 if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
106759 while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
106762 nHaystack--;
106763 zHaystack++;
106764 }while( isText && (zHaystack[0]&0xc0)==0x80 );
106766 if( nNeedle>nHaystack ) N = 0;
106768 sqlite3_result_int(context, N);
106772 ** Implementation of the printf() function.
106774 static void printfFunc(
106775 sqlite3_context *context,
106776 int argc,
106777 sqlite3_value **argv
106779 PrintfArguments x;
106780 StrAccum str;
106781 const char *zFormat;
106782 int n;
106783 sqlite3 *db = sqlite3_context_db_handle(context);
106785 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
106786 x.nArg = argc-1;
106787 x.nUsed = 0;
106788 x.apArg = argv+1;
106789 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
106790 str.printfFlags = SQLITE_PRINTF_SQLFUNC;
106791 sqlite3XPrintf(&str, zFormat, &x);
106792 n = str.nChar;
106793 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
106794 SQLITE_DYNAMIC);
106799 ** Implementation of the substr() function.
106801 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
106802 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
106803 ** of x. If x is text, then we actually count UTF-8 characters.
106804 ** If x is a blob, then we count bytes.
106806 ** If p1 is negative, then we begin abs(p1) from the end of x[].
106808 ** If p2 is negative, return the p2 characters preceding p1.
106810 static void substrFunc(
106811 sqlite3_context *context,
106812 int argc,
106813 sqlite3_value **argv
106815 const unsigned char *z;
106816 const unsigned char *z2;
106817 int len;
106818 int p0type;
106819 i64 p1, p2;
106820 int negP2 = 0;
106822 assert( argc==3 || argc==2 );
106823 if( sqlite3_value_type(argv[1])==SQLITE_NULL
106824 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
106826 return;
106828 p0type = sqlite3_value_type(argv[0]);
106829 p1 = sqlite3_value_int(argv[1]);
106830 if( p0type==SQLITE_BLOB ){
106831 len = sqlite3_value_bytes(argv[0]);
106832 z = sqlite3_value_blob(argv[0]);
106833 if( z==0 ) return;
106834 assert( len==sqlite3_value_bytes(argv[0]) );
106835 }else{
106836 z = sqlite3_value_text(argv[0]);
106837 if( z==0 ) return;
106838 len = 0;
106839 if( p1<0 ){
106840 for(z2=z; *z2; len++){
106841 SQLITE_SKIP_UTF8(z2);
106845 #ifdef SQLITE_SUBSTR_COMPATIBILITY
106846 /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
106847 ** as substr(X,1,N) - it returns the first N characters of X. This
106848 ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
106849 ** from 2009-02-02 for compatibility of applications that exploited the
106850 ** old buggy behavior. */
106851 if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
106852 #endif
106853 if( argc==3 ){
106854 p2 = sqlite3_value_int(argv[2]);
106855 if( p2<0 ){
106856 p2 = -p2;
106857 negP2 = 1;
106859 }else{
106860 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
106862 if( p1<0 ){
106863 p1 += len;
106864 if( p1<0 ){
106865 p2 += p1;
106866 if( p2<0 ) p2 = 0;
106867 p1 = 0;
106869 }else if( p1>0 ){
106870 p1--;
106871 }else if( p2>0 ){
106872 p2--;
106874 if( negP2 ){
106875 p1 -= p2;
106876 if( p1<0 ){
106877 p2 += p1;
106878 p1 = 0;
106881 assert( p1>=0 && p2>=0 );
106882 if( p0type!=SQLITE_BLOB ){
106883 while( *z && p1 ){
106884 SQLITE_SKIP_UTF8(z);
106885 p1--;
106887 for(z2=z; *z2 && p2; p2--){
106888 SQLITE_SKIP_UTF8(z2);
106890 sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
106891 SQLITE_UTF8);
106892 }else{
106893 if( p1+p2>len ){
106894 p2 = len-p1;
106895 if( p2<0 ) p2 = 0;
106897 sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
106902 ** Implementation of the round() function
106904 #ifndef SQLITE_OMIT_FLOATING_POINT
106905 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106906 int n = 0;
106907 double r;
106908 char *zBuf;
106909 assert( argc==1 || argc==2 );
106910 if( argc==2 ){
106911 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
106912 n = sqlite3_value_int(argv[1]);
106913 if( n>30 ) n = 30;
106914 if( n<0 ) n = 0;
106916 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
106917 r = sqlite3_value_double(argv[0]);
106918 /* If Y==0 and X will fit in a 64-bit int,
106919 ** handle the rounding directly,
106920 ** otherwise use printf.
106922 if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
106923 r = (double)((sqlite_int64)(r+0.5));
106924 }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
106925 r = -(double)((sqlite_int64)((-r)+0.5));
106926 }else{
106927 zBuf = sqlite3_mprintf("%.*f",n,r);
106928 if( zBuf==0 ){
106929 sqlite3_result_error_nomem(context);
106930 return;
106932 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
106933 sqlite3_free(zBuf);
106935 sqlite3_result_double(context, r);
106937 #endif
106940 ** Allocate nByte bytes of space using sqlite3Malloc(). If the
106941 ** allocation fails, call sqlite3_result_error_nomem() to notify
106942 ** the database handle that malloc() has failed and return NULL.
106943 ** If nByte is larger than the maximum string or blob length, then
106944 ** raise an SQLITE_TOOBIG exception and return NULL.
106946 static void *contextMalloc(sqlite3_context *context, i64 nByte){
106947 char *z;
106948 sqlite3 *db = sqlite3_context_db_handle(context);
106949 assert( nByte>0 );
106950 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
106951 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
106952 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
106953 sqlite3_result_error_toobig(context);
106954 z = 0;
106955 }else{
106956 z = sqlite3Malloc(nByte);
106957 if( !z ){
106958 sqlite3_result_error_nomem(context);
106961 return z;
106965 ** Implementation of the upper() and lower() SQL functions.
106967 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106968 char *z1;
106969 const char *z2;
106970 int i, n;
106971 UNUSED_PARAMETER(argc);
106972 z2 = (char*)sqlite3_value_text(argv[0]);
106973 n = sqlite3_value_bytes(argv[0]);
106974 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
106975 assert( z2==(char*)sqlite3_value_text(argv[0]) );
106976 if( z2 ){
106977 z1 = contextMalloc(context, ((i64)n)+1);
106978 if( z1 ){
106979 for(i=0; i<n; i++){
106980 z1[i] = (char)sqlite3Toupper(z2[i]);
106982 sqlite3_result_text(context, z1, n, sqlite3_free);
106986 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106987 char *z1;
106988 const char *z2;
106989 int i, n;
106990 UNUSED_PARAMETER(argc);
106991 z2 = (char*)sqlite3_value_text(argv[0]);
106992 n = sqlite3_value_bytes(argv[0]);
106993 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
106994 assert( z2==(char*)sqlite3_value_text(argv[0]) );
106995 if( z2 ){
106996 z1 = contextMalloc(context, ((i64)n)+1);
106997 if( z1 ){
106998 for(i=0; i<n; i++){
106999 z1[i] = sqlite3Tolower(z2[i]);
107001 sqlite3_result_text(context, z1, n, sqlite3_free);
107007 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
107008 ** as VDBE code so that unused argument values do not have to be computed.
107009 ** However, we still need some kind of function implementation for this
107010 ** routines in the function table. The noopFunc macro provides this.
107011 ** noopFunc will never be called so it doesn't matter what the implementation
107012 ** is. We might as well use the "version()" function as a substitute.
107014 #define noopFunc versionFunc /* Substitute function - never called */
107017 ** Implementation of random(). Return a random integer.
107019 static void randomFunc(
107020 sqlite3_context *context,
107021 int NotUsed,
107022 sqlite3_value **NotUsed2
107024 sqlite_int64 r;
107025 UNUSED_PARAMETER2(NotUsed, NotUsed2);
107026 sqlite3_randomness(sizeof(r), &r);
107027 if( r<0 ){
107028 /* We need to prevent a random number of 0x8000000000000000
107029 ** (or -9223372036854775808) since when you do abs() of that
107030 ** number of you get the same value back again. To do this
107031 ** in a way that is testable, mask the sign bit off of negative
107032 ** values, resulting in a positive value. Then take the
107033 ** 2s complement of that positive value. The end result can
107034 ** therefore be no less than -9223372036854775807.
107036 r = -(r & LARGEST_INT64);
107038 sqlite3_result_int64(context, r);
107042 ** Implementation of randomblob(N). Return a random blob
107043 ** that is N bytes long.
107045 static void randomBlob(
107046 sqlite3_context *context,
107047 int argc,
107048 sqlite3_value **argv
107050 int n;
107051 unsigned char *p;
107052 assert( argc==1 );
107053 UNUSED_PARAMETER(argc);
107054 n = sqlite3_value_int(argv[0]);
107055 if( n<1 ){
107056 n = 1;
107058 p = contextMalloc(context, n);
107059 if( p ){
107060 sqlite3_randomness(n, p);
107061 sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
107066 ** Implementation of the last_insert_rowid() SQL function. The return
107067 ** value is the same as the sqlite3_last_insert_rowid() API function.
107069 static void last_insert_rowid(
107070 sqlite3_context *context,
107071 int NotUsed,
107072 sqlite3_value **NotUsed2
107074 sqlite3 *db = sqlite3_context_db_handle(context);
107075 UNUSED_PARAMETER2(NotUsed, NotUsed2);
107076 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
107077 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
107078 ** function. */
107079 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
107083 ** Implementation of the changes() SQL function.
107085 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
107086 ** around the sqlite3_changes() C/C++ function and hence follows the same
107087 ** rules for counting changes.
107089 static void changes(
107090 sqlite3_context *context,
107091 int NotUsed,
107092 sqlite3_value **NotUsed2
107094 sqlite3 *db = sqlite3_context_db_handle(context);
107095 UNUSED_PARAMETER2(NotUsed, NotUsed2);
107096 sqlite3_result_int(context, sqlite3_changes(db));
107100 ** Implementation of the total_changes() SQL function. The return value is
107101 ** the same as the sqlite3_total_changes() API function.
107103 static void total_changes(
107104 sqlite3_context *context,
107105 int NotUsed,
107106 sqlite3_value **NotUsed2
107108 sqlite3 *db = sqlite3_context_db_handle(context);
107109 UNUSED_PARAMETER2(NotUsed, NotUsed2);
107110 /* IMP: R-52756-41993 This function is a wrapper around the
107111 ** sqlite3_total_changes() C/C++ interface. */
107112 sqlite3_result_int(context, sqlite3_total_changes(db));
107116 ** A structure defining how to do GLOB-style comparisons.
107118 struct compareInfo {
107119 u8 matchAll; /* "*" or "%" */
107120 u8 matchOne; /* "?" or "_" */
107121 u8 matchSet; /* "[" or 0 */
107122 u8 noCase; /* true to ignore case differences */
107126 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
107127 ** character is exactly one byte in size. Also, provde the Utf8Read()
107128 ** macro for fast reading of the next character in the common case where
107129 ** the next character is ASCII.
107131 #if defined(SQLITE_EBCDIC)
107132 # define sqlite3Utf8Read(A) (*((*A)++))
107133 # define Utf8Read(A) (*(A++))
107134 #else
107135 # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
107136 #endif
107138 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
107139 /* The correct SQL-92 behavior is for the LIKE operator to ignore
107140 ** case. Thus 'a' LIKE 'A' would be true. */
107141 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
107142 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
107143 ** is case sensitive causing 'a' LIKE 'A' to be false */
107144 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
107147 ** Possible error returns from patternMatch()
107149 #define SQLITE_MATCH 0
107150 #define SQLITE_NOMATCH 1
107151 #define SQLITE_NOWILDCARDMATCH 2
107154 ** Compare two UTF-8 strings for equality where the first string is
107155 ** a GLOB or LIKE expression. Return values:
107157 ** SQLITE_MATCH: Match
107158 ** SQLITE_NOMATCH: No match
107159 ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
107161 ** Globbing rules:
107163 ** '*' Matches any sequence of zero or more characters.
107165 ** '?' Matches exactly one character.
107167 ** [...] Matches one character from the enclosed list of
107168 ** characters.
107170 ** [^...] Matches one character not in the enclosed list.
107172 ** With the [...] and [^...] matching, a ']' character can be included
107173 ** in the list by making it the first character after '[' or '^'. A
107174 ** range of characters can be specified using '-'. Example:
107175 ** "[a-z]" matches any single lower-case letter. To match a '-', make
107176 ** it the last character in the list.
107178 ** Like matching rules:
107180 ** '%' Matches any sequence of zero or more characters
107182 *** '_' Matches any one character
107184 ** Ec Where E is the "esc" character and c is any other
107185 ** character, including '%', '_', and esc, match exactly c.
107187 ** The comments within this routine usually assume glob matching.
107189 ** This routine is usually quick, but can be N**2 in the worst case.
107191 static int patternCompare(
107192 const u8 *zPattern, /* The glob pattern */
107193 const u8 *zString, /* The string to compare against the glob */
107194 const struct compareInfo *pInfo, /* Information about how to do the compare */
107195 u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
107197 u32 c, c2; /* Next pattern and input string chars */
107198 u32 matchOne = pInfo->matchOne; /* "?" or "_" */
107199 u32 matchAll = pInfo->matchAll; /* "*" or "%" */
107200 u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
107201 const u8 *zEscaped = 0; /* One past the last escaped input char */
107203 while( (c = Utf8Read(zPattern))!=0 ){
107204 if( c==matchAll ){ /* Match "*" */
107205 /* Skip over multiple "*" characters in the pattern. If there
107206 ** are also "?" characters, skip those as well, but consume a
107207 ** single character of the input string for each "?" skipped */
107208 while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
107209 if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
107210 return SQLITE_NOWILDCARDMATCH;
107213 if( c==0 ){
107214 return SQLITE_MATCH; /* "*" at the end of the pattern matches */
107215 }else if( c==matchOther ){
107216 if( pInfo->matchSet==0 ){
107217 c = sqlite3Utf8Read(&zPattern);
107218 if( c==0 ) return SQLITE_NOWILDCARDMATCH;
107219 }else{
107220 /* "[...]" immediately follows the "*". We have to do a slow
107221 ** recursive search in this case, but it is an unusual case. */
107222 assert( matchOther<0x80 ); /* '[' is a single-byte character */
107223 while( *zString ){
107224 int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
107225 if( bMatch!=SQLITE_NOMATCH ) return bMatch;
107226 SQLITE_SKIP_UTF8(zString);
107228 return SQLITE_NOWILDCARDMATCH;
107232 /* At this point variable c contains the first character of the
107233 ** pattern string past the "*". Search in the input string for the
107234 ** first matching character and recursively continue the match from
107235 ** that point.
107237 ** For a case-insensitive search, set variable cx to be the same as
107238 ** c but in the other case and search the input string for either
107239 ** c or cx.
107241 if( c<=0x80 ){
107242 u32 cx;
107243 int bMatch;
107244 if( noCase ){
107245 cx = sqlite3Toupper(c);
107246 c = sqlite3Tolower(c);
107247 }else{
107248 cx = c;
107250 while( (c2 = *(zString++))!=0 ){
107251 if( c2!=c && c2!=cx ) continue;
107252 bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
107253 if( bMatch!=SQLITE_NOMATCH ) return bMatch;
107255 }else{
107256 int bMatch;
107257 while( (c2 = Utf8Read(zString))!=0 ){
107258 if( c2!=c ) continue;
107259 bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
107260 if( bMatch!=SQLITE_NOMATCH ) return bMatch;
107263 return SQLITE_NOWILDCARDMATCH;
107265 if( c==matchOther ){
107266 if( pInfo->matchSet==0 ){
107267 c = sqlite3Utf8Read(&zPattern);
107268 if( c==0 ) return SQLITE_NOMATCH;
107269 zEscaped = zPattern;
107270 }else{
107271 u32 prior_c = 0;
107272 int seen = 0;
107273 int invert = 0;
107274 c = sqlite3Utf8Read(&zString);
107275 if( c==0 ) return SQLITE_NOMATCH;
107276 c2 = sqlite3Utf8Read(&zPattern);
107277 if( c2=='^' ){
107278 invert = 1;
107279 c2 = sqlite3Utf8Read(&zPattern);
107281 if( c2==']' ){
107282 if( c==']' ) seen = 1;
107283 c2 = sqlite3Utf8Read(&zPattern);
107285 while( c2 && c2!=']' ){
107286 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
107287 c2 = sqlite3Utf8Read(&zPattern);
107288 if( c>=prior_c && c<=c2 ) seen = 1;
107289 prior_c = 0;
107290 }else{
107291 if( c==c2 ){
107292 seen = 1;
107294 prior_c = c2;
107296 c2 = sqlite3Utf8Read(&zPattern);
107298 if( c2==0 || (seen ^ invert)==0 ){
107299 return SQLITE_NOMATCH;
107301 continue;
107304 c2 = Utf8Read(zString);
107305 if( c==c2 ) continue;
107306 if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
107307 continue;
107309 if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
107310 return SQLITE_NOMATCH;
107312 return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
107316 ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
107317 ** non-zero if there is no match.
107319 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
107320 return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
107324 ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
107325 ** a miss - like strcmp().
107327 SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
107328 return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
107332 ** Count the number of times that the LIKE operator (or GLOB which is
107333 ** just a variation of LIKE) gets called. This is used for testing
107334 ** only.
107336 #ifdef SQLITE_TEST
107337 SQLITE_API int sqlite3_like_count = 0;
107338 #endif
107342 ** Implementation of the like() SQL function. This function implements
107343 ** the build-in LIKE operator. The first argument to the function is the
107344 ** pattern and the second argument is the string. So, the SQL statements:
107346 ** A LIKE B
107348 ** is implemented as like(B,A).
107350 ** This same function (with a different compareInfo structure) computes
107351 ** the GLOB operator.
107353 static void likeFunc(
107354 sqlite3_context *context,
107355 int argc,
107356 sqlite3_value **argv
107358 const unsigned char *zA, *zB;
107359 u32 escape;
107360 int nPat;
107361 sqlite3 *db = sqlite3_context_db_handle(context);
107362 struct compareInfo *pInfo = sqlite3_user_data(context);
107364 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
107365 if( sqlite3_value_type(argv[0])==SQLITE_BLOB
107366 || sqlite3_value_type(argv[1])==SQLITE_BLOB
107368 #ifdef SQLITE_TEST
107369 sqlite3_like_count++;
107370 #endif
107371 sqlite3_result_int(context, 0);
107372 return;
107374 #endif
107375 zB = sqlite3_value_text(argv[0]);
107376 zA = sqlite3_value_text(argv[1]);
107378 /* Limit the length of the LIKE or GLOB pattern to avoid problems
107379 ** of deep recursion and N*N behavior in patternCompare().
107381 nPat = sqlite3_value_bytes(argv[0]);
107382 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
107383 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
107384 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
107385 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
107386 return;
107388 assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
107390 if( argc==3 ){
107391 /* The escape character string must consist of a single UTF-8 character.
107392 ** Otherwise, return an error.
107394 const unsigned char *zEsc = sqlite3_value_text(argv[2]);
107395 if( zEsc==0 ) return;
107396 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
107397 sqlite3_result_error(context,
107398 "ESCAPE expression must be a single character", -1);
107399 return;
107401 escape = sqlite3Utf8Read(&zEsc);
107402 }else{
107403 escape = pInfo->matchSet;
107405 if( zA && zB ){
107406 #ifdef SQLITE_TEST
107407 sqlite3_like_count++;
107408 #endif
107409 sqlite3_result_int(context,
107410 patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
107415 ** Implementation of the NULLIF(x,y) function. The result is the first
107416 ** argument if the arguments are different. The result is NULL if the
107417 ** arguments are equal to each other.
107419 static void nullifFunc(
107420 sqlite3_context *context,
107421 int NotUsed,
107422 sqlite3_value **argv
107424 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
107425 UNUSED_PARAMETER(NotUsed);
107426 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
107427 sqlite3_result_value(context, argv[0]);
107432 ** Implementation of the sqlite_version() function. The result is the version
107433 ** of the SQLite library that is running.
107435 static void versionFunc(
107436 sqlite3_context *context,
107437 int NotUsed,
107438 sqlite3_value **NotUsed2
107440 UNUSED_PARAMETER2(NotUsed, NotUsed2);
107441 /* IMP: R-48699-48617 This function is an SQL wrapper around the
107442 ** sqlite3_libversion() C-interface. */
107443 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
107447 ** Implementation of the sqlite_source_id() function. The result is a string
107448 ** that identifies the particular version of the source code used to build
107449 ** SQLite.
107451 static void sourceidFunc(
107452 sqlite3_context *context,
107453 int NotUsed,
107454 sqlite3_value **NotUsed2
107456 UNUSED_PARAMETER2(NotUsed, NotUsed2);
107457 /* IMP: R-24470-31136 This function is an SQL wrapper around the
107458 ** sqlite3_sourceid() C interface. */
107459 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
107463 ** Implementation of the sqlite_log() function. This is a wrapper around
107464 ** sqlite3_log(). The return value is NULL. The function exists purely for
107465 ** its side-effects.
107467 static void errlogFunc(
107468 sqlite3_context *context,
107469 int argc,
107470 sqlite3_value **argv
107472 UNUSED_PARAMETER(argc);
107473 UNUSED_PARAMETER(context);
107474 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
107478 ** Implementation of the sqlite_compileoption_used() function.
107479 ** The result is an integer that identifies if the compiler option
107480 ** was used to build SQLite.
107482 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
107483 static void compileoptionusedFunc(
107484 sqlite3_context *context,
107485 int argc,
107486 sqlite3_value **argv
107488 const char *zOptName;
107489 assert( argc==1 );
107490 UNUSED_PARAMETER(argc);
107491 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
107492 ** function is a wrapper around the sqlite3_compileoption_used() C/C++
107493 ** function.
107495 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
107496 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
107499 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
107502 ** Implementation of the sqlite_compileoption_get() function.
107503 ** The result is a string that identifies the compiler options
107504 ** used to build SQLite.
107506 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
107507 static void compileoptiongetFunc(
107508 sqlite3_context *context,
107509 int argc,
107510 sqlite3_value **argv
107512 int n;
107513 assert( argc==1 );
107514 UNUSED_PARAMETER(argc);
107515 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
107516 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
107518 n = sqlite3_value_int(argv[0]);
107519 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
107521 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
107523 /* Array for converting from half-bytes (nybbles) into ASCII hex
107524 ** digits. */
107525 static const char hexdigits[] = {
107526 '0', '1', '2', '3', '4', '5', '6', '7',
107527 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
107531 ** Implementation of the QUOTE() function. This function takes a single
107532 ** argument. If the argument is numeric, the return value is the same as
107533 ** the argument. If the argument is NULL, the return value is the string
107534 ** "NULL". Otherwise, the argument is enclosed in single quotes with
107535 ** single-quote escapes.
107537 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
107538 assert( argc==1 );
107539 UNUSED_PARAMETER(argc);
107540 switch( sqlite3_value_type(argv[0]) ){
107541 case SQLITE_FLOAT: {
107542 double r1, r2;
107543 char zBuf[50];
107544 r1 = sqlite3_value_double(argv[0]);
107545 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
107546 sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
107547 if( r1!=r2 ){
107548 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
107550 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
107551 break;
107553 case SQLITE_INTEGER: {
107554 sqlite3_result_value(context, argv[0]);
107555 break;
107557 case SQLITE_BLOB: {
107558 char *zText = 0;
107559 char const *zBlob = sqlite3_value_blob(argv[0]);
107560 int nBlob = sqlite3_value_bytes(argv[0]);
107561 assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
107562 zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
107563 if( zText ){
107564 int i;
107565 for(i=0; i<nBlob; i++){
107566 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
107567 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
107569 zText[(nBlob*2)+2] = '\'';
107570 zText[(nBlob*2)+3] = '\0';
107571 zText[0] = 'X';
107572 zText[1] = '\'';
107573 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
107574 sqlite3_free(zText);
107576 break;
107578 case SQLITE_TEXT: {
107579 int i,j;
107580 u64 n;
107581 const unsigned char *zArg = sqlite3_value_text(argv[0]);
107582 char *z;
107584 if( zArg==0 ) return;
107585 for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
107586 z = contextMalloc(context, ((i64)i)+((i64)n)+3);
107587 if( z ){
107588 z[0] = '\'';
107589 for(i=0, j=1; zArg[i]; i++){
107590 z[j++] = zArg[i];
107591 if( zArg[i]=='\'' ){
107592 z[j++] = '\'';
107595 z[j++] = '\'';
107596 z[j] = 0;
107597 sqlite3_result_text(context, z, j, sqlite3_free);
107599 break;
107601 default: {
107602 assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
107603 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
107604 break;
107610 ** The unicode() function. Return the integer unicode code-point value
107611 ** for the first character of the input string.
107613 static void unicodeFunc(
107614 sqlite3_context *context,
107615 int argc,
107616 sqlite3_value **argv
107618 const unsigned char *z = sqlite3_value_text(argv[0]);
107619 (void)argc;
107620 if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
107624 ** The char() function takes zero or more arguments, each of which is
107625 ** an integer. It constructs a string where each character of the string
107626 ** is the unicode character for the corresponding integer argument.
107628 static void charFunc(
107629 sqlite3_context *context,
107630 int argc,
107631 sqlite3_value **argv
107633 unsigned char *z, *zOut;
107634 int i;
107635 zOut = z = sqlite3_malloc64( argc*4+1 );
107636 if( z==0 ){
107637 sqlite3_result_error_nomem(context);
107638 return;
107640 for(i=0; i<argc; i++){
107641 sqlite3_int64 x;
107642 unsigned c;
107643 x = sqlite3_value_int64(argv[i]);
107644 if( x<0 || x>0x10ffff ) x = 0xfffd;
107645 c = (unsigned)(x & 0x1fffff);
107646 if( c<0x00080 ){
107647 *zOut++ = (u8)(c&0xFF);
107648 }else if( c<0x00800 ){
107649 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
107650 *zOut++ = 0x80 + (u8)(c & 0x3F);
107651 }else if( c<0x10000 ){
107652 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
107653 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
107654 *zOut++ = 0x80 + (u8)(c & 0x3F);
107655 }else{
107656 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
107657 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
107658 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
107659 *zOut++ = 0x80 + (u8)(c & 0x3F);
107662 sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
107666 ** The hex() function. Interpret the argument as a blob. Return
107667 ** a hexadecimal rendering as text.
107669 static void hexFunc(
107670 sqlite3_context *context,
107671 int argc,
107672 sqlite3_value **argv
107674 int i, n;
107675 const unsigned char *pBlob;
107676 char *zHex, *z;
107677 assert( argc==1 );
107678 UNUSED_PARAMETER(argc);
107679 pBlob = sqlite3_value_blob(argv[0]);
107680 n = sqlite3_value_bytes(argv[0]);
107681 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
107682 z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
107683 if( zHex ){
107684 for(i=0; i<n; i++, pBlob++){
107685 unsigned char c = *pBlob;
107686 *(z++) = hexdigits[(c>>4)&0xf];
107687 *(z++) = hexdigits[c&0xf];
107689 *z = 0;
107690 sqlite3_result_text(context, zHex, n*2, sqlite3_free);
107695 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
107697 static void zeroblobFunc(
107698 sqlite3_context *context,
107699 int argc,
107700 sqlite3_value **argv
107702 i64 n;
107703 int rc;
107704 assert( argc==1 );
107705 UNUSED_PARAMETER(argc);
107706 n = sqlite3_value_int64(argv[0]);
107707 if( n<0 ) n = 0;
107708 rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
107709 if( rc ){
107710 sqlite3_result_error_code(context, rc);
107715 ** The replace() function. Three arguments are all strings: call
107716 ** them A, B, and C. The result is also a string which is derived
107717 ** from A by replacing every occurrence of B with C. The match
107718 ** must be exact. Collating sequences are not used.
107720 static void replaceFunc(
107721 sqlite3_context *context,
107722 int argc,
107723 sqlite3_value **argv
107725 const unsigned char *zStr; /* The input string A */
107726 const unsigned char *zPattern; /* The pattern string B */
107727 const unsigned char *zRep; /* The replacement string C */
107728 unsigned char *zOut; /* The output */
107729 int nStr; /* Size of zStr */
107730 int nPattern; /* Size of zPattern */
107731 int nRep; /* Size of zRep */
107732 i64 nOut; /* Maximum size of zOut */
107733 int loopLimit; /* Last zStr[] that might match zPattern[] */
107734 int i, j; /* Loop counters */
107736 assert( argc==3 );
107737 UNUSED_PARAMETER(argc);
107738 zStr = sqlite3_value_text(argv[0]);
107739 if( zStr==0 ) return;
107740 nStr = sqlite3_value_bytes(argv[0]);
107741 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
107742 zPattern = sqlite3_value_text(argv[1]);
107743 if( zPattern==0 ){
107744 assert( sqlite3_value_type(argv[1])==SQLITE_NULL
107745 || sqlite3_context_db_handle(context)->mallocFailed );
107746 return;
107748 if( zPattern[0]==0 ){
107749 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
107750 sqlite3_result_value(context, argv[0]);
107751 return;
107753 nPattern = sqlite3_value_bytes(argv[1]);
107754 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
107755 zRep = sqlite3_value_text(argv[2]);
107756 if( zRep==0 ) return;
107757 nRep = sqlite3_value_bytes(argv[2]);
107758 assert( zRep==sqlite3_value_text(argv[2]) );
107759 nOut = nStr + 1;
107760 assert( nOut<SQLITE_MAX_LENGTH );
107761 zOut = contextMalloc(context, (i64)nOut);
107762 if( zOut==0 ){
107763 return;
107765 loopLimit = nStr - nPattern;
107766 for(i=j=0; i<=loopLimit; i++){
107767 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
107768 zOut[j++] = zStr[i];
107769 }else{
107770 u8 *zOld;
107771 sqlite3 *db = sqlite3_context_db_handle(context);
107772 nOut += nRep - nPattern;
107773 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
107774 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
107775 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
107776 sqlite3_result_error_toobig(context);
107777 sqlite3_free(zOut);
107778 return;
107780 zOld = zOut;
107781 zOut = sqlite3_realloc64(zOut, (int)nOut);
107782 if( zOut==0 ){
107783 sqlite3_result_error_nomem(context);
107784 sqlite3_free(zOld);
107785 return;
107787 memcpy(&zOut[j], zRep, nRep);
107788 j += nRep;
107789 i += nPattern-1;
107792 assert( j+nStr-i+1==nOut );
107793 memcpy(&zOut[j], &zStr[i], nStr-i);
107794 j += nStr - i;
107795 assert( j<=nOut );
107796 zOut[j] = 0;
107797 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
107801 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
107802 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
107804 static void trimFunc(
107805 sqlite3_context *context,
107806 int argc,
107807 sqlite3_value **argv
107809 const unsigned char *zIn; /* Input string */
107810 const unsigned char *zCharSet; /* Set of characters to trim */
107811 int nIn; /* Number of bytes in input */
107812 int flags; /* 1: trimleft 2: trimright 3: trim */
107813 int i; /* Loop counter */
107814 unsigned char *aLen = 0; /* Length of each character in zCharSet */
107815 unsigned char **azChar = 0; /* Individual characters in zCharSet */
107816 int nChar; /* Number of characters in zCharSet */
107818 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
107819 return;
107821 zIn = sqlite3_value_text(argv[0]);
107822 if( zIn==0 ) return;
107823 nIn = sqlite3_value_bytes(argv[0]);
107824 assert( zIn==sqlite3_value_text(argv[0]) );
107825 if( argc==1 ){
107826 static const unsigned char lenOne[] = { 1 };
107827 static unsigned char * const azOne[] = { (u8*)" " };
107828 nChar = 1;
107829 aLen = (u8*)lenOne;
107830 azChar = (unsigned char **)azOne;
107831 zCharSet = 0;
107832 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
107833 return;
107834 }else{
107835 const unsigned char *z;
107836 for(z=zCharSet, nChar=0; *z; nChar++){
107837 SQLITE_SKIP_UTF8(z);
107839 if( nChar>0 ){
107840 azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
107841 if( azChar==0 ){
107842 return;
107844 aLen = (unsigned char*)&azChar[nChar];
107845 for(z=zCharSet, nChar=0; *z; nChar++){
107846 azChar[nChar] = (unsigned char *)z;
107847 SQLITE_SKIP_UTF8(z);
107848 aLen[nChar] = (u8)(z - azChar[nChar]);
107852 if( nChar>0 ){
107853 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
107854 if( flags & 1 ){
107855 while( nIn>0 ){
107856 int len = 0;
107857 for(i=0; i<nChar; i++){
107858 len = aLen[i];
107859 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
107861 if( i>=nChar ) break;
107862 zIn += len;
107863 nIn -= len;
107866 if( flags & 2 ){
107867 while( nIn>0 ){
107868 int len = 0;
107869 for(i=0; i<nChar; i++){
107870 len = aLen[i];
107871 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
107873 if( i>=nChar ) break;
107874 nIn -= len;
107877 if( zCharSet ){
107878 sqlite3_free(azChar);
107881 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
107885 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
107887 ** The "unknown" function is automatically substituted in place of
107888 ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
107889 ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
107890 ** When the "sqlite3" command-line shell is built using this functionality,
107891 ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
107892 ** involving application-defined functions to be examined in a generic
107893 ** sqlite3 shell.
107895 static void unknownFunc(
107896 sqlite3_context *context,
107897 int argc,
107898 sqlite3_value **argv
107900 /* no-op */
107902 #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
107905 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
107906 ** is only available if the SQLITE_SOUNDEX compile-time option is used
107907 ** when SQLite is built.
107909 #ifdef SQLITE_SOUNDEX
107911 ** Compute the soundex encoding of a word.
107913 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
107914 ** soundex encoding of the string X.
107916 static void soundexFunc(
107917 sqlite3_context *context,
107918 int argc,
107919 sqlite3_value **argv
107921 char zResult[8];
107922 const u8 *zIn;
107923 int i, j;
107924 static const unsigned char iCode[] = {
107925 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107926 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107927 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107928 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107929 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
107930 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
107931 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
107932 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
107934 assert( argc==1 );
107935 zIn = (u8*)sqlite3_value_text(argv[0]);
107936 if( zIn==0 ) zIn = (u8*)"";
107937 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
107938 if( zIn[i] ){
107939 u8 prevcode = iCode[zIn[i]&0x7f];
107940 zResult[0] = sqlite3Toupper(zIn[i]);
107941 for(j=1; j<4 && zIn[i]; i++){
107942 int code = iCode[zIn[i]&0x7f];
107943 if( code>0 ){
107944 if( code!=prevcode ){
107945 prevcode = code;
107946 zResult[j++] = code + '0';
107948 }else{
107949 prevcode = 0;
107952 while( j<4 ){
107953 zResult[j++] = '0';
107955 zResult[j] = 0;
107956 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
107957 }else{
107958 /* IMP: R-64894-50321 The string "?000" is returned if the argument
107959 ** is NULL or contains no ASCII alphabetic characters. */
107960 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
107963 #endif /* SQLITE_SOUNDEX */
107965 #ifndef SQLITE_OMIT_LOAD_EXTENSION
107967 ** A function that loads a shared-library extension then returns NULL.
107969 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
107970 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
107971 const char *zProc;
107972 sqlite3 *db = sqlite3_context_db_handle(context);
107973 char *zErrMsg = 0;
107975 /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
107976 ** flag is set. See the sqlite3_enable_load_extension() API.
107978 if( (db->flags & SQLITE_LoadExtFunc)==0 ){
107979 sqlite3_result_error(context, "not authorized", -1);
107980 return;
107983 if( argc==2 ){
107984 zProc = (const char *)sqlite3_value_text(argv[1]);
107985 }else{
107986 zProc = 0;
107988 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
107989 sqlite3_result_error(context, zErrMsg, -1);
107990 sqlite3_free(zErrMsg);
107993 #endif
107997 ** An instance of the following structure holds the context of a
107998 ** sum() or avg() aggregate computation.
108000 typedef struct SumCtx SumCtx;
108001 struct SumCtx {
108002 double rSum; /* Floating point sum */
108003 i64 iSum; /* Integer sum */
108004 i64 cnt; /* Number of elements summed */
108005 u8 overflow; /* True if integer overflow seen */
108006 u8 approx; /* True if non-integer value was input to the sum */
108010 ** Routines used to compute the sum, average, and total.
108012 ** The SUM() function follows the (broken) SQL standard which means
108013 ** that it returns NULL if it sums over no inputs. TOTAL returns
108014 ** 0.0 in that case. In addition, TOTAL always returns a float where
108015 ** SUM might return an integer if it never encounters a floating point
108016 ** value. TOTAL never fails, but SUM might through an exception if
108017 ** it overflows an integer.
108019 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
108020 SumCtx *p;
108021 int type;
108022 assert( argc==1 );
108023 UNUSED_PARAMETER(argc);
108024 p = sqlite3_aggregate_context(context, sizeof(*p));
108025 type = sqlite3_value_numeric_type(argv[0]);
108026 if( p && type!=SQLITE_NULL ){
108027 p->cnt++;
108028 if( type==SQLITE_INTEGER ){
108029 i64 v = sqlite3_value_int64(argv[0]);
108030 p->rSum += v;
108031 if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
108032 p->overflow = 1;
108034 }else{
108035 p->rSum += sqlite3_value_double(argv[0]);
108036 p->approx = 1;
108040 static void sumFinalize(sqlite3_context *context){
108041 SumCtx *p;
108042 p = sqlite3_aggregate_context(context, 0);
108043 if( p && p->cnt>0 ){
108044 if( p->overflow ){
108045 sqlite3_result_error(context,"integer overflow",-1);
108046 }else if( p->approx ){
108047 sqlite3_result_double(context, p->rSum);
108048 }else{
108049 sqlite3_result_int64(context, p->iSum);
108053 static void avgFinalize(sqlite3_context *context){
108054 SumCtx *p;
108055 p = sqlite3_aggregate_context(context, 0);
108056 if( p && p->cnt>0 ){
108057 sqlite3_result_double(context, p->rSum/(double)p->cnt);
108060 static void totalFinalize(sqlite3_context *context){
108061 SumCtx *p;
108062 p = sqlite3_aggregate_context(context, 0);
108063 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
108064 sqlite3_result_double(context, p ? p->rSum : (double)0);
108068 ** The following structure keeps track of state information for the
108069 ** count() aggregate function.
108071 typedef struct CountCtx CountCtx;
108072 struct CountCtx {
108073 i64 n;
108077 ** Routines to implement the count() aggregate function.
108079 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
108080 CountCtx *p;
108081 p = sqlite3_aggregate_context(context, sizeof(*p));
108082 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
108083 p->n++;
108086 #ifndef SQLITE_OMIT_DEPRECATED
108087 /* The sqlite3_aggregate_count() function is deprecated. But just to make
108088 ** sure it still operates correctly, verify that its count agrees with our
108089 ** internal count when using count(*) and when the total count can be
108090 ** expressed as a 32-bit integer. */
108091 assert( argc==1 || p==0 || p->n>0x7fffffff
108092 || p->n==sqlite3_aggregate_count(context) );
108093 #endif
108095 static void countFinalize(sqlite3_context *context){
108096 CountCtx *p;
108097 p = sqlite3_aggregate_context(context, 0);
108098 sqlite3_result_int64(context, p ? p->n : 0);
108102 ** Routines to implement min() and max() aggregate functions.
108104 static void minmaxStep(
108105 sqlite3_context *context,
108106 int NotUsed,
108107 sqlite3_value **argv
108109 Mem *pArg = (Mem *)argv[0];
108110 Mem *pBest;
108111 UNUSED_PARAMETER(NotUsed);
108113 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
108114 if( !pBest ) return;
108116 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
108117 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
108118 }else if( pBest->flags ){
108119 int max;
108120 int cmp;
108121 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
108122 /* This step function is used for both the min() and max() aggregates,
108123 ** the only difference between the two being that the sense of the
108124 ** comparison is inverted. For the max() aggregate, the
108125 ** sqlite3_user_data() function returns (void *)-1. For min() it
108126 ** returns (void *)db, where db is the sqlite3* database pointer.
108127 ** Therefore the next statement sets variable 'max' to 1 for the max()
108128 ** aggregate, or 0 for min().
108130 max = sqlite3_user_data(context)!=0;
108131 cmp = sqlite3MemCompare(pBest, pArg, pColl);
108132 if( (max && cmp<0) || (!max && cmp>0) ){
108133 sqlite3VdbeMemCopy(pBest, pArg);
108134 }else{
108135 sqlite3SkipAccumulatorLoad(context);
108137 }else{
108138 pBest->db = sqlite3_context_db_handle(context);
108139 sqlite3VdbeMemCopy(pBest, pArg);
108142 static void minMaxFinalize(sqlite3_context *context){
108143 sqlite3_value *pRes;
108144 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
108145 if( pRes ){
108146 if( pRes->flags ){
108147 sqlite3_result_value(context, pRes);
108149 sqlite3VdbeMemRelease(pRes);
108154 ** group_concat(EXPR, ?SEPARATOR?)
108156 static void groupConcatStep(
108157 sqlite3_context *context,
108158 int argc,
108159 sqlite3_value **argv
108161 const char *zVal;
108162 StrAccum *pAccum;
108163 const char *zSep;
108164 int nVal, nSep;
108165 assert( argc==1 || argc==2 );
108166 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
108167 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
108169 if( pAccum ){
108170 sqlite3 *db = sqlite3_context_db_handle(context);
108171 int firstTerm = pAccum->mxAlloc==0;
108172 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
108173 if( !firstTerm ){
108174 if( argc==2 ){
108175 zSep = (char*)sqlite3_value_text(argv[1]);
108176 nSep = sqlite3_value_bytes(argv[1]);
108177 }else{
108178 zSep = ",";
108179 nSep = 1;
108181 if( zSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
108183 zVal = (char*)sqlite3_value_text(argv[0]);
108184 nVal = sqlite3_value_bytes(argv[0]);
108185 if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
108188 static void groupConcatFinalize(sqlite3_context *context){
108189 StrAccum *pAccum;
108190 pAccum = sqlite3_aggregate_context(context, 0);
108191 if( pAccum ){
108192 if( pAccum->accError==STRACCUM_TOOBIG ){
108193 sqlite3_result_error_toobig(context);
108194 }else if( pAccum->accError==STRACCUM_NOMEM ){
108195 sqlite3_result_error_nomem(context);
108196 }else{
108197 sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
108198 sqlite3_free);
108204 ** This routine does per-connection function registration. Most
108205 ** of the built-in functions above are part of the global function set.
108206 ** This routine only deals with those that are not global.
108208 SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
108209 int rc = sqlite3_overload_function(db, "MATCH", 2);
108210 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
108211 if( rc==SQLITE_NOMEM ){
108212 sqlite3OomFault(db);
108217 ** Set the LIKEOPT flag on the 2-argument function with the given name.
108219 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
108220 FuncDef *pDef;
108221 pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
108222 if( ALWAYS(pDef) ){
108223 pDef->funcFlags |= flagVal;
108228 ** Register the built-in LIKE and GLOB functions. The caseSensitive
108229 ** parameter determines whether or not the LIKE operator is case
108230 ** sensitive. GLOB is always case sensitive.
108232 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
108233 struct compareInfo *pInfo;
108234 if( caseSensitive ){
108235 pInfo = (struct compareInfo*)&likeInfoAlt;
108236 }else{
108237 pInfo = (struct compareInfo*)&likeInfoNorm;
108239 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
108240 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
108241 sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
108242 (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
108243 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
108244 setLikeOptFlag(db, "like",
108245 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
108249 ** pExpr points to an expression which implements a function. If
108250 ** it is appropriate to apply the LIKE optimization to that function
108251 ** then set aWc[0] through aWc[2] to the wildcard characters and the
108252 ** escape character and then return TRUE. If the function is not a
108253 ** LIKE-style function then return FALSE.
108255 ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
108256 ** operator if c is a string literal that is exactly one byte in length.
108257 ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
108258 ** no ESCAPE clause.
108260 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
108261 ** the function (default for LIKE). If the function makes the distinction
108262 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
108263 ** false.
108265 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
108266 FuncDef *pDef;
108267 int nExpr;
108268 if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
108269 return 0;
108271 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
108272 nExpr = pExpr->x.pList->nExpr;
108273 pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
108274 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
108275 return 0;
108277 if( nExpr<3 ){
108278 aWc[3] = 0;
108279 }else{
108280 Expr *pEscape = pExpr->x.pList->a[2].pExpr;
108281 char *zEscape;
108282 if( pEscape->op!=TK_STRING ) return 0;
108283 zEscape = pEscape->u.zToken;
108284 if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
108285 aWc[3] = zEscape[0];
108288 /* The memcpy() statement assumes that the wildcard characters are
108289 ** the first three statements in the compareInfo structure. The
108290 ** asserts() that follow verify that assumption
108292 memcpy(aWc, pDef->pUserData, 3);
108293 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
108294 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
108295 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
108296 *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
108297 return 1;
108301 ** All of the FuncDef structures in the aBuiltinFunc[] array above
108302 ** to the global function hash table. This occurs at start-time (as
108303 ** a consequence of calling sqlite3_initialize()).
108305 ** After this routine runs
108307 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
108309 ** The following array holds FuncDef structures for all of the functions
108310 ** defined in this file.
108312 ** The array cannot be constant since changes are made to the
108313 ** FuncDef.pHash elements at start-time. The elements of this array
108314 ** are read-only after initialization is complete.
108316 ** For peak efficiency, put the most frequently used function last.
108318 static FuncDef aBuiltinFunc[] = {
108319 #ifdef SQLITE_SOUNDEX
108320 FUNCTION(soundex, 1, 0, 0, soundexFunc ),
108321 #endif
108322 #ifndef SQLITE_OMIT_LOAD_EXTENSION
108323 VFUNCTION(load_extension, 1, 0, 0, loadExt ),
108324 VFUNCTION(load_extension, 2, 0, 0, loadExt ),
108325 #endif
108326 #if SQLITE_USER_AUTHENTICATION
108327 FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
108328 #endif
108329 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
108330 DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
108331 DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
108332 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
108333 FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
108334 FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
108335 FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
108336 #ifdef SQLITE_DEBUG
108337 FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY),
108338 #endif
108339 FUNCTION(ltrim, 1, 1, 0, trimFunc ),
108340 FUNCTION(ltrim, 2, 1, 0, trimFunc ),
108341 FUNCTION(rtrim, 1, 2, 0, trimFunc ),
108342 FUNCTION(rtrim, 2, 2, 0, trimFunc ),
108343 FUNCTION(trim, 1, 3, 0, trimFunc ),
108344 FUNCTION(trim, 2, 3, 0, trimFunc ),
108345 FUNCTION(min, -1, 0, 1, minmaxFunc ),
108346 FUNCTION(min, 0, 0, 1, 0 ),
108347 AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
108348 SQLITE_FUNC_MINMAX ),
108349 FUNCTION(max, -1, 1, 1, minmaxFunc ),
108350 FUNCTION(max, 0, 1, 1, 0 ),
108351 AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
108352 SQLITE_FUNC_MINMAX ),
108353 FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
108354 FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
108355 FUNCTION(instr, 2, 0, 0, instrFunc ),
108356 FUNCTION(printf, -1, 0, 0, printfFunc ),
108357 FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
108358 FUNCTION(char, -1, 0, 0, charFunc ),
108359 FUNCTION(abs, 1, 0, 0, absFunc ),
108360 #ifndef SQLITE_OMIT_FLOATING_POINT
108361 FUNCTION(round, 1, 0, 0, roundFunc ),
108362 FUNCTION(round, 2, 0, 0, roundFunc ),
108363 #endif
108364 FUNCTION(upper, 1, 0, 0, upperFunc ),
108365 FUNCTION(lower, 1, 0, 0, lowerFunc ),
108366 FUNCTION(hex, 1, 0, 0, hexFunc ),
108367 FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
108368 VFUNCTION(random, 0, 0, 0, randomFunc ),
108369 VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
108370 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
108371 DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
108372 DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
108373 FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
108374 FUNCTION(quote, 1, 0, 0, quoteFunc ),
108375 VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
108376 VFUNCTION(changes, 0, 0, 0, changes ),
108377 VFUNCTION(total_changes, 0, 0, 0, total_changes ),
108378 FUNCTION(replace, 3, 0, 0, replaceFunc ),
108379 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
108380 FUNCTION(substr, 2, 0, 0, substrFunc ),
108381 FUNCTION(substr, 3, 0, 0, substrFunc ),
108382 AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
108383 AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
108384 AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
108385 AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
108386 SQLITE_FUNC_COUNT ),
108387 AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
108388 AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
108389 AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
108391 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
108392 #ifdef SQLITE_CASE_SENSITIVE_LIKE
108393 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
108394 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
108395 #else
108396 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
108397 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
108398 #endif
108399 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
108400 FUNCTION(unknown, -1, 0, 0, unknownFunc ),
108401 #endif
108402 FUNCTION(coalesce, 1, 0, 0, 0 ),
108403 FUNCTION(coalesce, 0, 0, 0, 0 ),
108404 FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
108406 #ifndef SQLITE_OMIT_ALTERTABLE
108407 sqlite3AlterFunctions();
108408 #endif
108409 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
108410 sqlite3AnalyzeFunctions();
108411 #endif
108412 sqlite3RegisterDateTimeFunctions();
108413 sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
108415 #if 0 /* Enable to print out how the built-in functions are hashed */
108417 int i;
108418 FuncDef *p;
108419 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
108420 printf("FUNC-HASH %02d:", i);
108421 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
108422 int n = sqlite3Strlen30(p->zName);
108423 int h = p->zName[0] + n;
108424 printf(" %s(%d)", p->zName, h);
108426 printf("\n");
108429 #endif
108432 /************** End of func.c ************************************************/
108433 /************** Begin file fkey.c ********************************************/
108436 ** The author disclaims copyright to this source code. In place of
108437 ** a legal notice, here is a blessing:
108439 ** May you do good and not evil.
108440 ** May you find forgiveness for yourself and forgive others.
108441 ** May you share freely, never taking more than you give.
108443 *************************************************************************
108444 ** This file contains code used by the compiler to add foreign key
108445 ** support to compiled SQL statements.
108447 /* #include "sqliteInt.h" */
108449 #ifndef SQLITE_OMIT_FOREIGN_KEY
108450 #ifndef SQLITE_OMIT_TRIGGER
108453 ** Deferred and Immediate FKs
108454 ** --------------------------
108456 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
108457 ** If an immediate foreign key constraint is violated,
108458 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
108459 ** statement transaction rolled back. If a
108460 ** deferred foreign key constraint is violated, no action is taken
108461 ** immediately. However if the application attempts to commit the
108462 ** transaction before fixing the constraint violation, the attempt fails.
108464 ** Deferred constraints are implemented using a simple counter associated
108465 ** with the database handle. The counter is set to zero each time a
108466 ** database transaction is opened. Each time a statement is executed
108467 ** that causes a foreign key violation, the counter is incremented. Each
108468 ** time a statement is executed that removes an existing violation from
108469 ** the database, the counter is decremented. When the transaction is
108470 ** committed, the commit fails if the current value of the counter is
108471 ** greater than zero. This scheme has two big drawbacks:
108473 ** * When a commit fails due to a deferred foreign key constraint,
108474 ** there is no way to tell which foreign constraint is not satisfied,
108475 ** or which row it is not satisfied for.
108477 ** * If the database contains foreign key violations when the
108478 ** transaction is opened, this may cause the mechanism to malfunction.
108480 ** Despite these problems, this approach is adopted as it seems simpler
108481 ** than the alternatives.
108483 ** INSERT operations:
108485 ** I.1) For each FK for which the table is the child table, search
108486 ** the parent table for a match. If none is found increment the
108487 ** constraint counter.
108489 ** I.2) For each FK for which the table is the parent table,
108490 ** search the child table for rows that correspond to the new
108491 ** row in the parent table. Decrement the counter for each row
108492 ** found (as the constraint is now satisfied).
108494 ** DELETE operations:
108496 ** D.1) For each FK for which the table is the child table,
108497 ** search the parent table for a row that corresponds to the
108498 ** deleted row in the child table. If such a row is not found,
108499 ** decrement the counter.
108501 ** D.2) For each FK for which the table is the parent table, search
108502 ** the child table for rows that correspond to the deleted row
108503 ** in the parent table. For each found increment the counter.
108505 ** UPDATE operations:
108507 ** An UPDATE command requires that all 4 steps above are taken, but only
108508 ** for FK constraints for which the affected columns are actually
108509 ** modified (values must be compared at runtime).
108511 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
108512 ** This simplifies the implementation a bit.
108514 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
108515 ** resolution is considered to delete rows before the new row is inserted.
108516 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
108517 ** is thrown, even if the FK constraint would be satisfied after the new
108518 ** row is inserted.
108520 ** Immediate constraints are usually handled similarly. The only difference
108521 ** is that the counter used is stored as part of each individual statement
108522 ** object (struct Vdbe). If, after the statement has run, its immediate
108523 ** constraint counter is greater than zero,
108524 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
108525 ** and the statement transaction is rolled back. An exception is an INSERT
108526 ** statement that inserts a single row only (no triggers). In this case,
108527 ** instead of using a counter, an exception is thrown immediately if the
108528 ** INSERT violates a foreign key constraint. This is necessary as such
108529 ** an INSERT does not open a statement transaction.
108531 ** TODO: How should dropping a table be handled? How should renaming a
108532 ** table be handled?
108535 ** Query API Notes
108536 ** ---------------
108538 ** Before coding an UPDATE or DELETE row operation, the code-generator
108539 ** for those two operations needs to know whether or not the operation
108540 ** requires any FK processing and, if so, which columns of the original
108541 ** row are required by the FK processing VDBE code (i.e. if FKs were
108542 ** implemented using triggers, which of the old.* columns would be
108543 ** accessed). No information is required by the code-generator before
108544 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
108545 ** generation code to query for this information are:
108547 ** sqlite3FkRequired() - Test to see if FK processing is required.
108548 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
108551 ** Externally accessible module functions
108552 ** --------------------------------------
108554 ** sqlite3FkCheck() - Check for foreign key violations.
108555 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
108556 ** sqlite3FkDelete() - Delete an FKey structure.
108560 ** VDBE Calling Convention
108561 ** -----------------------
108563 ** Example:
108565 ** For the following INSERT statement:
108567 ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
108568 ** INSERT INTO t1 VALUES(1, 2, 3.1);
108570 ** Register (x): 2 (type integer)
108571 ** Register (x+1): 1 (type integer)
108572 ** Register (x+2): NULL (type NULL)
108573 ** Register (x+3): 3.1 (type real)
108577 ** A foreign key constraint requires that the key columns in the parent
108578 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
108579 ** Given that pParent is the parent table for foreign key constraint pFKey,
108580 ** search the schema for a unique index on the parent key columns.
108582 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
108583 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
108584 ** is set to point to the unique index.
108586 ** If the parent key consists of a single column (the foreign key constraint
108587 ** is not a composite foreign key), output variable *paiCol is set to NULL.
108588 ** Otherwise, it is set to point to an allocated array of size N, where
108589 ** N is the number of columns in the parent key. The first element of the
108590 ** array is the index of the child table column that is mapped by the FK
108591 ** constraint to the parent table column stored in the left-most column
108592 ** of index *ppIdx. The second element of the array is the index of the
108593 ** child table column that corresponds to the second left-most column of
108594 ** *ppIdx, and so on.
108596 ** If the required index cannot be found, either because:
108598 ** 1) The named parent key columns do not exist, or
108600 ** 2) The named parent key columns do exist, but are not subject to a
108601 ** UNIQUE or PRIMARY KEY constraint, or
108603 ** 3) No parent key columns were provided explicitly as part of the
108604 ** foreign key definition, and the parent table does not have a
108605 ** PRIMARY KEY, or
108607 ** 4) No parent key columns were provided explicitly as part of the
108608 ** foreign key definition, and the PRIMARY KEY of the parent table
108609 ** consists of a different number of columns to the child key in
108610 ** the child table.
108612 ** then non-zero is returned, and a "foreign key mismatch" error loaded
108613 ** into pParse. If an OOM error occurs, non-zero is returned and the
108614 ** pParse->db->mallocFailed flag is set.
108616 SQLITE_PRIVATE int sqlite3FkLocateIndex(
108617 Parse *pParse, /* Parse context to store any error in */
108618 Table *pParent, /* Parent table of FK constraint pFKey */
108619 FKey *pFKey, /* Foreign key to find index for */
108620 Index **ppIdx, /* OUT: Unique index on parent table */
108621 int **paiCol /* OUT: Map of index columns in pFKey */
108623 Index *pIdx = 0; /* Value to return via *ppIdx */
108624 int *aiCol = 0; /* Value to return via *paiCol */
108625 int nCol = pFKey->nCol; /* Number of columns in parent key */
108626 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
108628 /* The caller is responsible for zeroing output parameters. */
108629 assert( ppIdx && *ppIdx==0 );
108630 assert( !paiCol || *paiCol==0 );
108631 assert( pParse );
108633 /* If this is a non-composite (single column) foreign key, check if it
108634 ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
108635 ** and *paiCol set to zero and return early.
108637 ** Otherwise, for a composite foreign key (more than one column), allocate
108638 ** space for the aiCol array (returned via output parameter *paiCol).
108639 ** Non-composite foreign keys do not require the aiCol array.
108641 if( nCol==1 ){
108642 /* The FK maps to the IPK if any of the following are true:
108644 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
108645 ** mapped to the primary key of table pParent, or
108646 ** 2) The FK is explicitly mapped to a column declared as INTEGER
108647 ** PRIMARY KEY.
108649 if( pParent->iPKey>=0 ){
108650 if( !zKey ) return 0;
108651 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
108653 }else if( paiCol ){
108654 assert( nCol>1 );
108655 aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
108656 if( !aiCol ) return 1;
108657 *paiCol = aiCol;
108660 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
108661 if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
108662 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
108663 ** of columns. If each indexed column corresponds to a foreign key
108664 ** column of pFKey, then this index is a winner. */
108666 if( zKey==0 ){
108667 /* If zKey is NULL, then this foreign key is implicitly mapped to
108668 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
108669 ** identified by the test. */
108670 if( IsPrimaryKeyIndex(pIdx) ){
108671 if( aiCol ){
108672 int i;
108673 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
108675 break;
108677 }else{
108678 /* If zKey is non-NULL, then this foreign key was declared to
108679 ** map to an explicit list of columns in table pParent. Check if this
108680 ** index matches those columns. Also, check that the index uses
108681 ** the default collation sequences for each column. */
108682 int i, j;
108683 for(i=0; i<nCol; i++){
108684 i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
108685 const char *zDfltColl; /* Def. collation for column */
108686 char *zIdxCol; /* Name of indexed column */
108688 if( iCol<0 ) break; /* No foreign keys against expression indexes */
108690 /* If the index uses a collation sequence that is different from
108691 ** the default collation sequence for the column, this index is
108692 ** unusable. Bail out early in this case. */
108693 zDfltColl = pParent->aCol[iCol].zColl;
108694 if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
108695 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
108697 zIdxCol = pParent->aCol[iCol].zName;
108698 for(j=0; j<nCol; j++){
108699 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
108700 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
108701 break;
108704 if( j==nCol ) break;
108706 if( i==nCol ) break; /* pIdx is usable */
108711 if( !pIdx ){
108712 if( !pParse->disableTriggers ){
108713 sqlite3ErrorMsg(pParse,
108714 "foreign key mismatch - \"%w\" referencing \"%w\"",
108715 pFKey->pFrom->zName, pFKey->zTo);
108717 sqlite3DbFree(pParse->db, aiCol);
108718 return 1;
108721 *ppIdx = pIdx;
108722 return 0;
108726 ** This function is called when a row is inserted into or deleted from the
108727 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
108728 ** on the child table of pFKey, this function is invoked twice for each row
108729 ** affected - once to "delete" the old row, and then again to "insert" the
108730 ** new row.
108732 ** Each time it is called, this function generates VDBE code to locate the
108733 ** row in the parent table that corresponds to the row being inserted into
108734 ** or deleted from the child table. If the parent row can be found, no
108735 ** special action is taken. Otherwise, if the parent row can *not* be
108736 ** found in the parent table:
108738 ** Operation | FK type | Action taken
108739 ** --------------------------------------------------------------------------
108740 ** INSERT immediate Increment the "immediate constraint counter".
108742 ** DELETE immediate Decrement the "immediate constraint counter".
108744 ** INSERT deferred Increment the "deferred constraint counter".
108746 ** DELETE deferred Decrement the "deferred constraint counter".
108748 ** These operations are identified in the comment at the top of this file
108749 ** (fkey.c) as "I.1" and "D.1".
108751 static void fkLookupParent(
108752 Parse *pParse, /* Parse context */
108753 int iDb, /* Index of database housing pTab */
108754 Table *pTab, /* Parent table of FK pFKey */
108755 Index *pIdx, /* Unique index on parent key columns in pTab */
108756 FKey *pFKey, /* Foreign key constraint */
108757 int *aiCol, /* Map from parent key columns to child table columns */
108758 int regData, /* Address of array containing child table row */
108759 int nIncr, /* Increment constraint counter by this */
108760 int isIgnore /* If true, pretend pTab contains all NULL values */
108762 int i; /* Iterator variable */
108763 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
108764 int iCur = pParse->nTab - 1; /* Cursor number to use */
108765 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
108767 /* If nIncr is less than zero, then check at runtime if there are any
108768 ** outstanding constraints to resolve. If there are not, there is no need
108769 ** to check if deleting this row resolves any outstanding violations.
108771 ** Check if any of the key columns in the child table row are NULL. If
108772 ** any are, then the constraint is considered satisfied. No need to
108773 ** search for a matching row in the parent table. */
108774 if( nIncr<0 ){
108775 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
108776 VdbeCoverage(v);
108778 for(i=0; i<pFKey->nCol; i++){
108779 int iReg = aiCol[i] + regData + 1;
108780 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
108783 if( isIgnore==0 ){
108784 if( pIdx==0 ){
108785 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
108786 ** column of the parent table (table pTab). */
108787 int iMustBeInt; /* Address of MustBeInt instruction */
108788 int regTemp = sqlite3GetTempReg(pParse);
108790 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
108791 ** apply the affinity of the parent key). If this fails, then there
108792 ** is no matching parent key. Before using MustBeInt, make a copy of
108793 ** the value. Otherwise, the value inserted into the child key column
108794 ** will have INTEGER affinity applied to it, which may not be correct. */
108795 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
108796 iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
108797 VdbeCoverage(v);
108799 /* If the parent table is the same as the child table, and we are about
108800 ** to increment the constraint-counter (i.e. this is an INSERT operation),
108801 ** then check if the row being inserted matches itself. If so, do not
108802 ** increment the constraint-counter. */
108803 if( pTab==pFKey->pFrom && nIncr==1 ){
108804 sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
108805 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108808 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
108809 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
108810 sqlite3VdbeGoto(v, iOk);
108811 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
108812 sqlite3VdbeJumpHere(v, iMustBeInt);
108813 sqlite3ReleaseTempReg(pParse, regTemp);
108814 }else{
108815 int nCol = pFKey->nCol;
108816 int regTemp = sqlite3GetTempRange(pParse, nCol);
108817 int regRec = sqlite3GetTempReg(pParse);
108819 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
108820 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
108821 for(i=0; i<nCol; i++){
108822 sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
108825 /* If the parent table is the same as the child table, and we are about
108826 ** to increment the constraint-counter (i.e. this is an INSERT operation),
108827 ** then check if the row being inserted matches itself. If so, do not
108828 ** increment the constraint-counter.
108830 ** If any of the parent-key values are NULL, then the row cannot match
108831 ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
108832 ** of the parent-key values are NULL (at this point it is known that
108833 ** none of the child key values are).
108835 if( pTab==pFKey->pFrom && nIncr==1 ){
108836 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
108837 for(i=0; i<nCol; i++){
108838 int iChild = aiCol[i]+1+regData;
108839 int iParent = pIdx->aiColumn[i]+1+regData;
108840 assert( pIdx->aiColumn[i]>=0 );
108841 assert( aiCol[i]!=pTab->iPKey );
108842 if( pIdx->aiColumn[i]==pTab->iPKey ){
108843 /* The parent key is a composite key that includes the IPK column */
108844 iParent = regData;
108846 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
108847 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
108849 sqlite3VdbeGoto(v, iOk);
108852 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
108853 sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
108854 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
108856 sqlite3ReleaseTempReg(pParse, regRec);
108857 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
108861 if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
108862 && !pParse->pToplevel
108863 && !pParse->isMultiWrite
108865 /* Special case: If this is an INSERT statement that will insert exactly
108866 ** one row into the table, raise a constraint immediately instead of
108867 ** incrementing a counter. This is necessary as the VM code is being
108868 ** generated for will not open a statement transaction. */
108869 assert( nIncr==1 );
108870 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
108871 OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
108872 }else{
108873 if( nIncr>0 && pFKey->isDeferred==0 ){
108874 sqlite3MayAbort(pParse);
108876 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
108879 sqlite3VdbeResolveLabel(v, iOk);
108880 sqlite3VdbeAddOp1(v, OP_Close, iCur);
108885 ** Return an Expr object that refers to a memory register corresponding
108886 ** to column iCol of table pTab.
108888 ** regBase is the first of an array of register that contains the data
108889 ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
108890 ** column. regBase+2 holds the second column, and so forth.
108892 static Expr *exprTableRegister(
108893 Parse *pParse, /* Parsing and code generating context */
108894 Table *pTab, /* The table whose content is at r[regBase]... */
108895 int regBase, /* Contents of table pTab */
108896 i16 iCol /* Which column of pTab is desired */
108898 Expr *pExpr;
108899 Column *pCol;
108900 const char *zColl;
108901 sqlite3 *db = pParse->db;
108903 pExpr = sqlite3Expr(db, TK_REGISTER, 0);
108904 if( pExpr ){
108905 if( iCol>=0 && iCol!=pTab->iPKey ){
108906 pCol = &pTab->aCol[iCol];
108907 pExpr->iTable = regBase + iCol + 1;
108908 pExpr->affinity = pCol->affinity;
108909 zColl = pCol->zColl;
108910 if( zColl==0 ) zColl = db->pDfltColl->zName;
108911 pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
108912 }else{
108913 pExpr->iTable = regBase;
108914 pExpr->affinity = SQLITE_AFF_INTEGER;
108917 return pExpr;
108921 ** Return an Expr object that refers to column iCol of table pTab which
108922 ** has cursor iCur.
108924 static Expr *exprTableColumn(
108925 sqlite3 *db, /* The database connection */
108926 Table *pTab, /* The table whose column is desired */
108927 int iCursor, /* The open cursor on the table */
108928 i16 iCol /* The column that is wanted */
108930 Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
108931 if( pExpr ){
108932 pExpr->pTab = pTab;
108933 pExpr->iTable = iCursor;
108934 pExpr->iColumn = iCol;
108936 return pExpr;
108940 ** This function is called to generate code executed when a row is deleted
108941 ** from the parent table of foreign key constraint pFKey and, if pFKey is
108942 ** deferred, when a row is inserted into the same table. When generating
108943 ** code for an SQL UPDATE operation, this function may be called twice -
108944 ** once to "delete" the old row and once to "insert" the new row.
108946 ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
108947 ** the number of FK violations in the db) or +1 when deleting one (as this
108948 ** may increase the number of FK constraint problems).
108950 ** The code generated by this function scans through the rows in the child
108951 ** table that correspond to the parent table row being deleted or inserted.
108952 ** For each child row found, one of the following actions is taken:
108954 ** Operation | FK type | Action taken
108955 ** --------------------------------------------------------------------------
108956 ** DELETE immediate Increment the "immediate constraint counter".
108957 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
108958 ** throw a "FOREIGN KEY constraint failed" exception.
108960 ** INSERT immediate Decrement the "immediate constraint counter".
108962 ** DELETE deferred Increment the "deferred constraint counter".
108963 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
108964 ** throw a "FOREIGN KEY constraint failed" exception.
108966 ** INSERT deferred Decrement the "deferred constraint counter".
108968 ** These operations are identified in the comment at the top of this file
108969 ** (fkey.c) as "I.2" and "D.2".
108971 static void fkScanChildren(
108972 Parse *pParse, /* Parse context */
108973 SrcList *pSrc, /* The child table to be scanned */
108974 Table *pTab, /* The parent table */
108975 Index *pIdx, /* Index on parent covering the foreign key */
108976 FKey *pFKey, /* The foreign key linking pSrc to pTab */
108977 int *aiCol, /* Map from pIdx cols to child table cols */
108978 int regData, /* Parent row data starts here */
108979 int nIncr /* Amount to increment deferred counter by */
108981 sqlite3 *db = pParse->db; /* Database handle */
108982 int i; /* Iterator variable */
108983 Expr *pWhere = 0; /* WHERE clause to scan with */
108984 NameContext sNameContext; /* Context used to resolve WHERE clause */
108985 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
108986 int iFkIfZero = 0; /* Address of OP_FkIfZero */
108987 Vdbe *v = sqlite3GetVdbe(pParse);
108989 assert( pIdx==0 || pIdx->pTable==pTab );
108990 assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
108991 assert( pIdx!=0 || pFKey->nCol==1 );
108992 assert( pIdx!=0 || HasRowid(pTab) );
108994 if( nIncr<0 ){
108995 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
108996 VdbeCoverage(v);
108999 /* Create an Expr object representing an SQL expression like:
109001 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
109003 ** The collation sequence used for the comparison should be that of
109004 ** the parent key columns. The affinity of the parent key column should
109005 ** be applied to each child key value before the comparison takes place.
109007 for(i=0; i<pFKey->nCol; i++){
109008 Expr *pLeft; /* Value from parent table row */
109009 Expr *pRight; /* Column ref to child table */
109010 Expr *pEq; /* Expression (pLeft = pRight) */
109011 i16 iCol; /* Index of column in child table */
109012 const char *zCol; /* Name of column in child table */
109014 iCol = pIdx ? pIdx->aiColumn[i] : -1;
109015 pLeft = exprTableRegister(pParse, pTab, regData, iCol);
109016 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
109017 assert( iCol>=0 );
109018 zCol = pFKey->pFrom->aCol[iCol].zName;
109019 pRight = sqlite3Expr(db, TK_ID, zCol);
109020 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
109021 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
109024 /* If the child table is the same as the parent table, then add terms
109025 ** to the WHERE clause that prevent this entry from being scanned.
109026 ** The added WHERE clause terms are like this:
109028 ** $current_rowid!=rowid
109029 ** NOT( $current_a==a AND $current_b==b AND ... )
109031 ** The first form is used for rowid tables. The second form is used
109032 ** for WITHOUT ROWID tables. In the second form, the primary key is
109033 ** (a,b,...)
109035 if( pTab==pFKey->pFrom && nIncr>0 ){
109036 Expr *pNe; /* Expression (pLeft != pRight) */
109037 Expr *pLeft; /* Value from parent table row */
109038 Expr *pRight; /* Column ref to child table */
109039 if( HasRowid(pTab) ){
109040 pLeft = exprTableRegister(pParse, pTab, regData, -1);
109041 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
109042 pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
109043 }else{
109044 Expr *pEq, *pAll = 0;
109045 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
109046 assert( pIdx!=0 );
109047 for(i=0; i<pPk->nKeyCol; i++){
109048 i16 iCol = pIdx->aiColumn[i];
109049 assert( iCol>=0 );
109050 pLeft = exprTableRegister(pParse, pTab, regData, iCol);
109051 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
109052 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
109053 pAll = sqlite3ExprAnd(db, pAll, pEq);
109055 pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
109057 pWhere = sqlite3ExprAnd(db, pWhere, pNe);
109060 /* Resolve the references in the WHERE clause. */
109061 memset(&sNameContext, 0, sizeof(NameContext));
109062 sNameContext.pSrcList = pSrc;
109063 sNameContext.pParse = pParse;
109064 sqlite3ResolveExprNames(&sNameContext, pWhere);
109066 /* Create VDBE to loop through the entries in pSrc that match the WHERE
109067 ** clause. For each row found, increment either the deferred or immediate
109068 ** foreign key constraint counter. */
109069 if( pParse->nErr==0 ){
109070 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
109071 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
109072 if( pWInfo ){
109073 sqlite3WhereEnd(pWInfo);
109077 /* Clean up the WHERE clause constructed above. */
109078 sqlite3ExprDelete(db, pWhere);
109079 if( iFkIfZero ){
109080 sqlite3VdbeJumpHere(v, iFkIfZero);
109085 ** This function returns a linked list of FKey objects (connected by
109086 ** FKey.pNextTo) holding all children of table pTab. For example,
109087 ** given the following schema:
109089 ** CREATE TABLE t1(a PRIMARY KEY);
109090 ** CREATE TABLE t2(b REFERENCES t1(a);
109092 ** Calling this function with table "t1" as an argument returns a pointer
109093 ** to the FKey structure representing the foreign key constraint on table
109094 ** "t2". Calling this function with "t2" as the argument would return a
109095 ** NULL pointer (as there are no FK constraints for which t2 is the parent
109096 ** table).
109098 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
109099 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
109103 ** The second argument is a Trigger structure allocated by the
109104 ** fkActionTrigger() routine. This function deletes the Trigger structure
109105 ** and all of its sub-components.
109107 ** The Trigger structure or any of its sub-components may be allocated from
109108 ** the lookaside buffer belonging to database handle dbMem.
109110 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
109111 if( p ){
109112 TriggerStep *pStep = p->step_list;
109113 sqlite3ExprDelete(dbMem, pStep->pWhere);
109114 sqlite3ExprListDelete(dbMem, pStep->pExprList);
109115 sqlite3SelectDelete(dbMem, pStep->pSelect);
109116 sqlite3ExprDelete(dbMem, p->pWhen);
109117 sqlite3DbFree(dbMem, p);
109122 ** This function is called to generate code that runs when table pTab is
109123 ** being dropped from the database. The SrcList passed as the second argument
109124 ** to this function contains a single entry guaranteed to resolve to
109125 ** table pTab.
109127 ** Normally, no code is required. However, if either
109129 ** (a) The table is the parent table of a FK constraint, or
109130 ** (b) The table is the child table of a deferred FK constraint and it is
109131 ** determined at runtime that there are outstanding deferred FK
109132 ** constraint violations in the database,
109134 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
109135 ** the table from the database. Triggers are disabled while running this
109136 ** DELETE, but foreign key actions are not.
109138 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
109139 sqlite3 *db = pParse->db;
109140 if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
109141 int iSkip = 0;
109142 Vdbe *v = sqlite3GetVdbe(pParse);
109144 assert( v ); /* VDBE has already been allocated */
109145 if( sqlite3FkReferences(pTab)==0 ){
109146 /* Search for a deferred foreign key constraint for which this table
109147 ** is the child table. If one cannot be found, return without
109148 ** generating any VDBE code. If one can be found, then jump over
109149 ** the entire DELETE if there are no outstanding deferred constraints
109150 ** when this statement is run. */
109151 FKey *p;
109152 for(p=pTab->pFKey; p; p=p->pNextFrom){
109153 if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
109155 if( !p ) return;
109156 iSkip = sqlite3VdbeMakeLabel(v);
109157 sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
109160 pParse->disableTriggers = 1;
109161 sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
109162 pParse->disableTriggers = 0;
109164 /* If the DELETE has generated immediate foreign key constraint
109165 ** violations, halt the VDBE and return an error at this point, before
109166 ** any modifications to the schema are made. This is because statement
109167 ** transactions are not able to rollback schema changes.
109169 ** If the SQLITE_DeferFKs flag is set, then this is not required, as
109170 ** the statement transaction will not be rolled back even if FK
109171 ** constraints are violated.
109173 if( (db->flags & SQLITE_DeferFKs)==0 ){
109174 sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
109175 VdbeCoverage(v);
109176 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
109177 OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
109180 if( iSkip ){
109181 sqlite3VdbeResolveLabel(v, iSkip);
109188 ** The second argument points to an FKey object representing a foreign key
109189 ** for which pTab is the child table. An UPDATE statement against pTab
109190 ** is currently being processed. For each column of the table that is
109191 ** actually updated, the corresponding element in the aChange[] array
109192 ** is zero or greater (if a column is unmodified the corresponding element
109193 ** is set to -1). If the rowid column is modified by the UPDATE statement
109194 ** the bChngRowid argument is non-zero.
109196 ** This function returns true if any of the columns that are part of the
109197 ** child key for FK constraint *p are modified.
109199 static int fkChildIsModified(
109200 Table *pTab, /* Table being updated */
109201 FKey *p, /* Foreign key for which pTab is the child */
109202 int *aChange, /* Array indicating modified columns */
109203 int bChngRowid /* True if rowid is modified by this update */
109205 int i;
109206 for(i=0; i<p->nCol; i++){
109207 int iChildKey = p->aCol[i].iFrom;
109208 if( aChange[iChildKey]>=0 ) return 1;
109209 if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
109211 return 0;
109215 ** The second argument points to an FKey object representing a foreign key
109216 ** for which pTab is the parent table. An UPDATE statement against pTab
109217 ** is currently being processed. For each column of the table that is
109218 ** actually updated, the corresponding element in the aChange[] array
109219 ** is zero or greater (if a column is unmodified the corresponding element
109220 ** is set to -1). If the rowid column is modified by the UPDATE statement
109221 ** the bChngRowid argument is non-zero.
109223 ** This function returns true if any of the columns that are part of the
109224 ** parent key for FK constraint *p are modified.
109226 static int fkParentIsModified(
109227 Table *pTab,
109228 FKey *p,
109229 int *aChange,
109230 int bChngRowid
109232 int i;
109233 for(i=0; i<p->nCol; i++){
109234 char *zKey = p->aCol[i].zCol;
109235 int iKey;
109236 for(iKey=0; iKey<pTab->nCol; iKey++){
109237 if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
109238 Column *pCol = &pTab->aCol[iKey];
109239 if( zKey ){
109240 if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
109241 }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
109242 return 1;
109247 return 0;
109251 ** Return true if the parser passed as the first argument is being
109252 ** used to code a trigger that is really a "SET NULL" action belonging
109253 ** to trigger pFKey.
109255 static int isSetNullAction(Parse *pParse, FKey *pFKey){
109256 Parse *pTop = sqlite3ParseToplevel(pParse);
109257 if( pTop->pTriggerPrg ){
109258 Trigger *p = pTop->pTriggerPrg->pTrigger;
109259 if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
109260 || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
109262 return 1;
109265 return 0;
109269 ** This function is called when inserting, deleting or updating a row of
109270 ** table pTab to generate VDBE code to perform foreign key constraint
109271 ** processing for the operation.
109273 ** For a DELETE operation, parameter regOld is passed the index of the
109274 ** first register in an array of (pTab->nCol+1) registers containing the
109275 ** rowid of the row being deleted, followed by each of the column values
109276 ** of the row being deleted, from left to right. Parameter regNew is passed
109277 ** zero in this case.
109279 ** For an INSERT operation, regOld is passed zero and regNew is passed the
109280 ** first register of an array of (pTab->nCol+1) registers containing the new
109281 ** row data.
109283 ** For an UPDATE operation, this function is called twice. Once before
109284 ** the original record is deleted from the table using the calling convention
109285 ** described for DELETE. Then again after the original record is deleted
109286 ** but before the new record is inserted using the INSERT convention.
109288 SQLITE_PRIVATE void sqlite3FkCheck(
109289 Parse *pParse, /* Parse context */
109290 Table *pTab, /* Row is being deleted from this table */
109291 int regOld, /* Previous row data is stored here */
109292 int regNew, /* New row data is stored here */
109293 int *aChange, /* Array indicating UPDATEd columns (or 0) */
109294 int bChngRowid /* True if rowid is UPDATEd */
109296 sqlite3 *db = pParse->db; /* Database handle */
109297 FKey *pFKey; /* Used to iterate through FKs */
109298 int iDb; /* Index of database containing pTab */
109299 const char *zDb; /* Name of database containing pTab */
109300 int isIgnoreErrors = pParse->disableTriggers;
109302 /* Exactly one of regOld and regNew should be non-zero. */
109303 assert( (regOld==0)!=(regNew==0) );
109305 /* If foreign-keys are disabled, this function is a no-op. */
109306 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
109308 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
109309 zDb = db->aDb[iDb].zDbSName;
109311 /* Loop through all the foreign key constraints for which pTab is the
109312 ** child table (the table that the foreign key definition is part of). */
109313 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
109314 Table *pTo; /* Parent table of foreign key pFKey */
109315 Index *pIdx = 0; /* Index on key columns in pTo */
109316 int *aiFree = 0;
109317 int *aiCol;
109318 int iCol;
109319 int i;
109320 int bIgnore = 0;
109322 if( aChange
109323 && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
109324 && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
109326 continue;
109329 /* Find the parent table of this foreign key. Also find a unique index
109330 ** on the parent key columns in the parent table. If either of these
109331 ** schema items cannot be located, set an error in pParse and return
109332 ** early. */
109333 if( pParse->disableTriggers ){
109334 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
109335 }else{
109336 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
109338 if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
109339 assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
109340 if( !isIgnoreErrors || db->mallocFailed ) return;
109341 if( pTo==0 ){
109342 /* If isIgnoreErrors is true, then a table is being dropped. In this
109343 ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
109344 ** before actually dropping it in order to check FK constraints.
109345 ** If the parent table of an FK constraint on the current table is
109346 ** missing, behave as if it is empty. i.e. decrement the relevant
109347 ** FK counter for each row of the current table with non-NULL keys.
109349 Vdbe *v = sqlite3GetVdbe(pParse);
109350 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
109351 for(i=0; i<pFKey->nCol; i++){
109352 int iReg = pFKey->aCol[i].iFrom + regOld + 1;
109353 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
109355 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
109357 continue;
109359 assert( pFKey->nCol==1 || (aiFree && pIdx) );
109361 if( aiFree ){
109362 aiCol = aiFree;
109363 }else{
109364 iCol = pFKey->aCol[0].iFrom;
109365 aiCol = &iCol;
109367 for(i=0; i<pFKey->nCol; i++){
109368 if( aiCol[i]==pTab->iPKey ){
109369 aiCol[i] = -1;
109371 assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
109372 #ifndef SQLITE_OMIT_AUTHORIZATION
109373 /* Request permission to read the parent key columns. If the
109374 ** authorization callback returns SQLITE_IGNORE, behave as if any
109375 ** values read from the parent table are NULL. */
109376 if( db->xAuth ){
109377 int rcauth;
109378 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
109379 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
109380 bIgnore = (rcauth==SQLITE_IGNORE);
109382 #endif
109385 /* Take a shared-cache advisory read-lock on the parent table. Allocate
109386 ** a cursor to use to search the unique index on the parent key columns
109387 ** in the parent table. */
109388 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
109389 pParse->nTab++;
109391 if( regOld!=0 ){
109392 /* A row is being removed from the child table. Search for the parent.
109393 ** If the parent does not exist, removing the child row resolves an
109394 ** outstanding foreign key constraint violation. */
109395 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
109397 if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
109398 /* A row is being added to the child table. If a parent row cannot
109399 ** be found, adding the child row has violated the FK constraint.
109401 ** If this operation is being performed as part of a trigger program
109402 ** that is actually a "SET NULL" action belonging to this very
109403 ** foreign key, then omit this scan altogether. As all child key
109404 ** values are guaranteed to be NULL, it is not possible for adding
109405 ** this row to cause an FK violation. */
109406 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
109409 sqlite3DbFree(db, aiFree);
109412 /* Loop through all the foreign key constraints that refer to this table.
109413 ** (the "child" constraints) */
109414 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
109415 Index *pIdx = 0; /* Foreign key index for pFKey */
109416 SrcList *pSrc;
109417 int *aiCol = 0;
109419 if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
109420 continue;
109423 if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
109424 && !pParse->pToplevel && !pParse->isMultiWrite
109426 assert( regOld==0 && regNew!=0 );
109427 /* Inserting a single row into a parent table cannot cause (or fix)
109428 ** an immediate foreign key violation. So do nothing in this case. */
109429 continue;
109432 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
109433 if( !isIgnoreErrors || db->mallocFailed ) return;
109434 continue;
109436 assert( aiCol || pFKey->nCol==1 );
109438 /* Create a SrcList structure containing the child table. We need the
109439 ** child table as a SrcList for sqlite3WhereBegin() */
109440 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
109441 if( pSrc ){
109442 struct SrcList_item *pItem = pSrc->a;
109443 pItem->pTab = pFKey->pFrom;
109444 pItem->zName = pFKey->pFrom->zName;
109445 pItem->pTab->nTabRef++;
109446 pItem->iCursor = pParse->nTab++;
109448 if( regNew!=0 ){
109449 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
109451 if( regOld!=0 ){
109452 int eAction = pFKey->aAction[aChange!=0];
109453 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
109454 /* If this is a deferred FK constraint, or a CASCADE or SET NULL
109455 ** action applies, then any foreign key violations caused by
109456 ** removing the parent key will be rectified by the action trigger.
109457 ** So do not set the "may-abort" flag in this case.
109459 ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
109460 ** may-abort flag will eventually be set on this statement anyway
109461 ** (when this function is called as part of processing the UPDATE
109462 ** within the action trigger).
109464 ** Note 2: At first glance it may seem like SQLite could simply omit
109465 ** all OP_FkCounter related scans when either CASCADE or SET NULL
109466 ** applies. The trouble starts if the CASCADE or SET NULL action
109467 ** trigger causes other triggers or action rules attached to the
109468 ** child table to fire. In these cases the fk constraint counters
109469 ** might be set incorrectly if any OP_FkCounter related scans are
109470 ** omitted. */
109471 if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
109472 sqlite3MayAbort(pParse);
109475 pItem->zName = 0;
109476 sqlite3SrcListDelete(db, pSrc);
109478 sqlite3DbFree(db, aiCol);
109482 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
109485 ** This function is called before generating code to update or delete a
109486 ** row contained in table pTab.
109488 SQLITE_PRIVATE u32 sqlite3FkOldmask(
109489 Parse *pParse, /* Parse context */
109490 Table *pTab /* Table being modified */
109492 u32 mask = 0;
109493 if( pParse->db->flags&SQLITE_ForeignKeys ){
109494 FKey *p;
109495 int i;
109496 for(p=pTab->pFKey; p; p=p->pNextFrom){
109497 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
109499 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
109500 Index *pIdx = 0;
109501 sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
109502 if( pIdx ){
109503 for(i=0; i<pIdx->nKeyCol; i++){
109504 assert( pIdx->aiColumn[i]>=0 );
109505 mask |= COLUMN_MASK(pIdx->aiColumn[i]);
109510 return mask;
109515 ** This function is called before generating code to update or delete a
109516 ** row contained in table pTab. If the operation is a DELETE, then
109517 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
109518 ** to an array of size N, where N is the number of columns in table pTab.
109519 ** If the i'th column is not modified by the UPDATE, then the corresponding
109520 ** entry in the aChange[] array is set to -1. If the column is modified,
109521 ** the value is 0 or greater. Parameter chngRowid is set to true if the
109522 ** UPDATE statement modifies the rowid fields of the table.
109524 ** If any foreign key processing will be required, this function returns
109525 ** non-zero. If there is no foreign key related processing, this function
109526 ** returns zero.
109528 ** For an UPDATE, this function returns 2 if:
109530 ** * There are any FKs for which pTab is the child and the parent table, or
109531 ** * the UPDATE modifies one or more parent keys for which the action is
109532 ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
109534 ** Or, assuming some other foreign key processing is required, 1.
109536 SQLITE_PRIVATE int sqlite3FkRequired(
109537 Parse *pParse, /* Parse context */
109538 Table *pTab, /* Table being modified */
109539 int *aChange, /* Non-NULL for UPDATE operations */
109540 int chngRowid /* True for UPDATE that affects rowid */
109542 int eRet = 0;
109543 if( pParse->db->flags&SQLITE_ForeignKeys ){
109544 if( !aChange ){
109545 /* A DELETE operation. Foreign key processing is required if the
109546 ** table in question is either the child or parent table for any
109547 ** foreign key constraint. */
109548 eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
109549 }else{
109550 /* This is an UPDATE. Foreign key processing is only required if the
109551 ** operation modifies one or more child or parent key columns. */
109552 FKey *p;
109554 /* Check if any child key columns are being modified. */
109555 for(p=pTab->pFKey; p; p=p->pNextFrom){
109556 if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
109557 if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
109558 eRet = 1;
109562 /* Check if any parent key columns are being modified. */
109563 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
109564 if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
109565 if( p->aAction[1]!=OE_None ) return 2;
109566 eRet = 1;
109571 return eRet;
109575 ** This function is called when an UPDATE or DELETE operation is being
109576 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
109577 ** If the current operation is an UPDATE, then the pChanges parameter is
109578 ** passed a pointer to the list of columns being modified. If it is a
109579 ** DELETE, pChanges is passed a NULL pointer.
109581 ** It returns a pointer to a Trigger structure containing a trigger
109582 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
109583 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
109584 ** returned (these actions require no special handling by the triggers
109585 ** sub-system, code for them is created by fkScanChildren()).
109587 ** For example, if pFKey is the foreign key and pTab is table "p" in
109588 ** the following schema:
109590 ** CREATE TABLE p(pk PRIMARY KEY);
109591 ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
109593 ** then the returned trigger structure is equivalent to:
109595 ** CREATE TRIGGER ... DELETE ON p BEGIN
109596 ** DELETE FROM c WHERE ck = old.pk;
109597 ** END;
109599 ** The returned pointer is cached as part of the foreign key object. It
109600 ** is eventually freed along with the rest of the foreign key object by
109601 ** sqlite3FkDelete().
109603 static Trigger *fkActionTrigger(
109604 Parse *pParse, /* Parse context */
109605 Table *pTab, /* Table being updated or deleted from */
109606 FKey *pFKey, /* Foreign key to get action for */
109607 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
109609 sqlite3 *db = pParse->db; /* Database handle */
109610 int action; /* One of OE_None, OE_Cascade etc. */
109611 Trigger *pTrigger; /* Trigger definition to return */
109612 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
109614 action = pFKey->aAction[iAction];
109615 if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
109616 return 0;
109618 pTrigger = pFKey->apTrigger[iAction];
109620 if( action!=OE_None && !pTrigger ){
109621 char const *zFrom; /* Name of child table */
109622 int nFrom; /* Length in bytes of zFrom */
109623 Index *pIdx = 0; /* Parent key index for this FK */
109624 int *aiCol = 0; /* child table cols -> parent key cols */
109625 TriggerStep *pStep = 0; /* First (only) step of trigger program */
109626 Expr *pWhere = 0; /* WHERE clause of trigger step */
109627 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
109628 Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
109629 int i; /* Iterator variable */
109630 Expr *pWhen = 0; /* WHEN clause for the trigger */
109632 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
109633 assert( aiCol || pFKey->nCol==1 );
109635 for(i=0; i<pFKey->nCol; i++){
109636 Token tOld = { "old", 3 }; /* Literal "old" token */
109637 Token tNew = { "new", 3 }; /* Literal "new" token */
109638 Token tFromCol; /* Name of column in child table */
109639 Token tToCol; /* Name of column in parent table */
109640 int iFromCol; /* Idx of column in child table */
109641 Expr *pEq; /* tFromCol = OLD.tToCol */
109643 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
109644 assert( iFromCol>=0 );
109645 assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
109646 assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
109647 sqlite3TokenInit(&tToCol,
109648 pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
109649 sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
109651 /* Create the expression "OLD.zToCol = zFromCol". It is important
109652 ** that the "OLD.zToCol" term is on the LHS of the = operator, so
109653 ** that the affinity and collation sequence associated with the
109654 ** parent table are used for the comparison. */
109655 pEq = sqlite3PExpr(pParse, TK_EQ,
109656 sqlite3PExpr(pParse, TK_DOT,
109657 sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
109658 sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
109659 sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
109661 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
109663 /* For ON UPDATE, construct the next term of the WHEN clause.
109664 ** The final WHEN clause will be like this:
109666 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
109668 if( pChanges ){
109669 pEq = sqlite3PExpr(pParse, TK_IS,
109670 sqlite3PExpr(pParse, TK_DOT,
109671 sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
109672 sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
109673 sqlite3PExpr(pParse, TK_DOT,
109674 sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
109675 sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
109677 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
109680 if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
109681 Expr *pNew;
109682 if( action==OE_Cascade ){
109683 pNew = sqlite3PExpr(pParse, TK_DOT,
109684 sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
109685 sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
109686 }else if( action==OE_SetDflt ){
109687 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
109688 if( pDflt ){
109689 pNew = sqlite3ExprDup(db, pDflt, 0);
109690 }else{
109691 pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
109693 }else{
109694 pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
109696 pList = sqlite3ExprListAppend(pParse, pList, pNew);
109697 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
109700 sqlite3DbFree(db, aiCol);
109702 zFrom = pFKey->pFrom->zName;
109703 nFrom = sqlite3Strlen30(zFrom);
109705 if( action==OE_Restrict ){
109706 Token tFrom;
109707 Expr *pRaise;
109709 tFrom.z = zFrom;
109710 tFrom.n = nFrom;
109711 pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
109712 if( pRaise ){
109713 pRaise->affinity = OE_Abort;
109715 pSelect = sqlite3SelectNew(pParse,
109716 sqlite3ExprListAppend(pParse, 0, pRaise),
109717 sqlite3SrcListAppend(db, 0, &tFrom, 0),
109718 pWhere,
109719 0, 0, 0, 0, 0, 0
109721 pWhere = 0;
109724 /* Disable lookaside memory allocation */
109725 db->lookaside.bDisable++;
109727 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
109728 sizeof(Trigger) + /* struct Trigger */
109729 sizeof(TriggerStep) + /* Single step in trigger program */
109730 nFrom + 1 /* Space for pStep->zTarget */
109732 if( pTrigger ){
109733 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
109734 pStep->zTarget = (char *)&pStep[1];
109735 memcpy((char *)pStep->zTarget, zFrom, nFrom);
109737 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
109738 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
109739 pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
109740 if( pWhen ){
109741 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
109742 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
109746 /* Re-enable the lookaside buffer, if it was disabled earlier. */
109747 db->lookaside.bDisable--;
109749 sqlite3ExprDelete(db, pWhere);
109750 sqlite3ExprDelete(db, pWhen);
109751 sqlite3ExprListDelete(db, pList);
109752 sqlite3SelectDelete(db, pSelect);
109753 if( db->mallocFailed==1 ){
109754 fkTriggerDelete(db, pTrigger);
109755 return 0;
109757 assert( pStep!=0 );
109759 switch( action ){
109760 case OE_Restrict:
109761 pStep->op = TK_SELECT;
109762 break;
109763 case OE_Cascade:
109764 if( !pChanges ){
109765 pStep->op = TK_DELETE;
109766 break;
109768 default:
109769 pStep->op = TK_UPDATE;
109771 pStep->pTrig = pTrigger;
109772 pTrigger->pSchema = pTab->pSchema;
109773 pTrigger->pTabSchema = pTab->pSchema;
109774 pFKey->apTrigger[iAction] = pTrigger;
109775 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
109778 return pTrigger;
109782 ** This function is called when deleting or updating a row to implement
109783 ** any required CASCADE, SET NULL or SET DEFAULT actions.
109785 SQLITE_PRIVATE void sqlite3FkActions(
109786 Parse *pParse, /* Parse context */
109787 Table *pTab, /* Table being updated or deleted from */
109788 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
109789 int regOld, /* Address of array containing old row */
109790 int *aChange, /* Array indicating UPDATEd columns (or 0) */
109791 int bChngRowid /* True if rowid is UPDATEd */
109793 /* If foreign-key support is enabled, iterate through all FKs that
109794 ** refer to table pTab. If there is an action associated with the FK
109795 ** for this operation (either update or delete), invoke the associated
109796 ** trigger sub-program. */
109797 if( pParse->db->flags&SQLITE_ForeignKeys ){
109798 FKey *pFKey; /* Iterator variable */
109799 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
109800 if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
109801 Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
109802 if( pAct ){
109803 sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
109810 #endif /* ifndef SQLITE_OMIT_TRIGGER */
109813 ** Free all memory associated with foreign key definitions attached to
109814 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
109815 ** hash table.
109817 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
109818 FKey *pFKey; /* Iterator variable */
109819 FKey *pNext; /* Copy of pFKey->pNextFrom */
109821 assert( db==0 || IsVirtual(pTab)
109822 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
109823 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
109825 /* Remove the FK from the fkeyHash hash table. */
109826 if( !db || db->pnBytesFreed==0 ){
109827 if( pFKey->pPrevTo ){
109828 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
109829 }else{
109830 void *p = (void *)pFKey->pNextTo;
109831 const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
109832 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
109834 if( pFKey->pNextTo ){
109835 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
109839 /* EV: R-30323-21917 Each foreign key constraint in SQLite is
109840 ** classified as either immediate or deferred.
109842 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
109844 /* Delete any triggers created to implement actions for this FK. */
109845 #ifndef SQLITE_OMIT_TRIGGER
109846 fkTriggerDelete(db, pFKey->apTrigger[0]);
109847 fkTriggerDelete(db, pFKey->apTrigger[1]);
109848 #endif
109850 pNext = pFKey->pNextFrom;
109851 sqlite3DbFree(db, pFKey);
109854 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
109856 /************** End of fkey.c ************************************************/
109857 /************** Begin file insert.c ******************************************/
109859 ** 2001 September 15
109861 ** The author disclaims copyright to this source code. In place of
109862 ** a legal notice, here is a blessing:
109864 ** May you do good and not evil.
109865 ** May you find forgiveness for yourself and forgive others.
109866 ** May you share freely, never taking more than you give.
109868 *************************************************************************
109869 ** This file contains C code routines that are called by the parser
109870 ** to handle INSERT statements in SQLite.
109872 /* #include "sqliteInt.h" */
109875 ** Generate code that will
109877 ** (1) acquire a lock for table pTab then
109878 ** (2) open pTab as cursor iCur.
109880 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
109881 ** for that table that is actually opened.
109883 SQLITE_PRIVATE void sqlite3OpenTable(
109884 Parse *pParse, /* Generate code into this VDBE */
109885 int iCur, /* The cursor number of the table */
109886 int iDb, /* The database index in sqlite3.aDb[] */
109887 Table *pTab, /* The table to be opened */
109888 int opcode /* OP_OpenRead or OP_OpenWrite */
109890 Vdbe *v;
109891 assert( !IsVirtual(pTab) );
109892 v = sqlite3GetVdbe(pParse);
109893 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
109894 sqlite3TableLock(pParse, iDb, pTab->tnum,
109895 (opcode==OP_OpenWrite)?1:0, pTab->zName);
109896 if( HasRowid(pTab) ){
109897 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
109898 VdbeComment((v, "%s", pTab->zName));
109899 }else{
109900 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
109901 assert( pPk!=0 );
109902 assert( pPk->tnum==pTab->tnum );
109903 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
109904 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
109905 VdbeComment((v, "%s", pTab->zName));
109910 ** Return a pointer to the column affinity string associated with index
109911 ** pIdx. A column affinity string has one character for each column in
109912 ** the table, according to the affinity of the column:
109914 ** Character Column affinity
109915 ** ------------------------------
109916 ** 'A' BLOB
109917 ** 'B' TEXT
109918 ** 'C' NUMERIC
109919 ** 'D' INTEGER
109920 ** 'F' REAL
109922 ** An extra 'D' is appended to the end of the string to cover the
109923 ** rowid that appears as the last column in every index.
109925 ** Memory for the buffer containing the column index affinity string
109926 ** is managed along with the rest of the Index structure. It will be
109927 ** released when sqlite3DeleteIndex() is called.
109929 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
109930 if( !pIdx->zColAff ){
109931 /* The first time a column affinity string for a particular index is
109932 ** required, it is allocated and populated here. It is then stored as
109933 ** a member of the Index structure for subsequent use.
109935 ** The column affinity string will eventually be deleted by
109936 ** sqliteDeleteIndex() when the Index structure itself is cleaned
109937 ** up.
109939 int n;
109940 Table *pTab = pIdx->pTable;
109941 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
109942 if( !pIdx->zColAff ){
109943 sqlite3OomFault(db);
109944 return 0;
109946 for(n=0; n<pIdx->nColumn; n++){
109947 i16 x = pIdx->aiColumn[n];
109948 if( x>=0 ){
109949 pIdx->zColAff[n] = pTab->aCol[x].affinity;
109950 }else if( x==XN_ROWID ){
109951 pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
109952 }else{
109953 char aff;
109954 assert( x==XN_EXPR );
109955 assert( pIdx->aColExpr!=0 );
109956 aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
109957 if( aff==0 ) aff = SQLITE_AFF_BLOB;
109958 pIdx->zColAff[n] = aff;
109961 pIdx->zColAff[n] = 0;
109964 return pIdx->zColAff;
109968 ** Compute the affinity string for table pTab, if it has not already been
109969 ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
109971 ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
109972 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
109973 ** for register iReg and following. Or if affinities exists and iReg==0,
109974 ** then just set the P4 operand of the previous opcode (which should be
109975 ** an OP_MakeRecord) to the affinity string.
109977 ** A column affinity string has one character per column:
109979 ** Character Column affinity
109980 ** ------------------------------
109981 ** 'A' BLOB
109982 ** 'B' TEXT
109983 ** 'C' NUMERIC
109984 ** 'D' INTEGER
109985 ** 'E' REAL
109987 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
109988 int i;
109989 char *zColAff = pTab->zColAff;
109990 if( zColAff==0 ){
109991 sqlite3 *db = sqlite3VdbeDb(v);
109992 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
109993 if( !zColAff ){
109994 sqlite3OomFault(db);
109995 return;
109998 for(i=0; i<pTab->nCol; i++){
109999 zColAff[i] = pTab->aCol[i].affinity;
110002 zColAff[i--] = 0;
110003 }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
110004 pTab->zColAff = zColAff;
110006 i = sqlite3Strlen30(zColAff);
110007 if( i ){
110008 if( iReg ){
110009 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
110010 }else{
110011 sqlite3VdbeChangeP4(v, -1, zColAff, i);
110017 ** Return non-zero if the table pTab in database iDb or any of its indices
110018 ** have been opened at any point in the VDBE program. This is used to see if
110019 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
110020 ** run without using a temporary table for the results of the SELECT.
110022 static int readsTable(Parse *p, int iDb, Table *pTab){
110023 Vdbe *v = sqlite3GetVdbe(p);
110024 int i;
110025 int iEnd = sqlite3VdbeCurrentAddr(v);
110026 #ifndef SQLITE_OMIT_VIRTUALTABLE
110027 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
110028 #endif
110030 for(i=1; i<iEnd; i++){
110031 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
110032 assert( pOp!=0 );
110033 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
110034 Index *pIndex;
110035 int tnum = pOp->p2;
110036 if( tnum==pTab->tnum ){
110037 return 1;
110039 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
110040 if( tnum==pIndex->tnum ){
110041 return 1;
110045 #ifndef SQLITE_OMIT_VIRTUALTABLE
110046 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
110047 assert( pOp->p4.pVtab!=0 );
110048 assert( pOp->p4type==P4_VTAB );
110049 return 1;
110051 #endif
110053 return 0;
110056 #ifndef SQLITE_OMIT_AUTOINCREMENT
110058 ** Locate or create an AutoincInfo structure associated with table pTab
110059 ** which is in database iDb. Return the register number for the register
110060 ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
110061 ** table. (Also return zero when doing a VACUUM since we do not want to
110062 ** update the AUTOINCREMENT counters during a VACUUM.)
110064 ** There is at most one AutoincInfo structure per table even if the
110065 ** same table is autoincremented multiple times due to inserts within
110066 ** triggers. A new AutoincInfo structure is created if this is the
110067 ** first use of table pTab. On 2nd and subsequent uses, the original
110068 ** AutoincInfo structure is used.
110070 ** Three memory locations are allocated:
110072 ** (1) Register to hold the name of the pTab table.
110073 ** (2) Register to hold the maximum ROWID of pTab.
110074 ** (3) Register to hold the rowid in sqlite_sequence of pTab
110076 ** The 2nd register is the one that is returned. That is all the
110077 ** insert routine needs to know about.
110079 static int autoIncBegin(
110080 Parse *pParse, /* Parsing context */
110081 int iDb, /* Index of the database holding pTab */
110082 Table *pTab /* The table we are writing to */
110084 int memId = 0; /* Register holding maximum rowid */
110085 if( (pTab->tabFlags & TF_Autoincrement)!=0
110086 && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
110088 Parse *pToplevel = sqlite3ParseToplevel(pParse);
110089 AutoincInfo *pInfo;
110091 pInfo = pToplevel->pAinc;
110092 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
110093 if( pInfo==0 ){
110094 pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
110095 if( pInfo==0 ) return 0;
110096 pInfo->pNext = pToplevel->pAinc;
110097 pToplevel->pAinc = pInfo;
110098 pInfo->pTab = pTab;
110099 pInfo->iDb = iDb;
110100 pToplevel->nMem++; /* Register to hold name of table */
110101 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
110102 pToplevel->nMem++; /* Rowid in sqlite_sequence */
110104 memId = pInfo->regCtr;
110106 return memId;
110110 ** This routine generates code that will initialize all of the
110111 ** register used by the autoincrement tracker.
110113 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
110114 AutoincInfo *p; /* Information about an AUTOINCREMENT */
110115 sqlite3 *db = pParse->db; /* The database connection */
110116 Db *pDb; /* Database only autoinc table */
110117 int memId; /* Register holding max rowid */
110118 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
110120 /* This routine is never called during trigger-generation. It is
110121 ** only called from the top-level */
110122 assert( pParse->pTriggerTab==0 );
110123 assert( sqlite3IsToplevel(pParse) );
110125 assert( v ); /* We failed long ago if this is not so */
110126 for(p = pParse->pAinc; p; p = p->pNext){
110127 static const int iLn = VDBE_OFFSET_LINENO(2);
110128 static const VdbeOpList autoInc[] = {
110129 /* 0 */ {OP_Null, 0, 0, 0},
110130 /* 1 */ {OP_Rewind, 0, 9, 0},
110131 /* 2 */ {OP_Column, 0, 0, 0},
110132 /* 3 */ {OP_Ne, 0, 7, 0},
110133 /* 4 */ {OP_Rowid, 0, 0, 0},
110134 /* 5 */ {OP_Column, 0, 1, 0},
110135 /* 6 */ {OP_Goto, 0, 9, 0},
110136 /* 7 */ {OP_Next, 0, 2, 0},
110137 /* 8 */ {OP_Integer, 0, 0, 0},
110138 /* 9 */ {OP_Close, 0, 0, 0}
110140 VdbeOp *aOp;
110141 pDb = &db->aDb[p->iDb];
110142 memId = p->regCtr;
110143 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
110144 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
110145 sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
110146 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
110147 if( aOp==0 ) break;
110148 aOp[0].p2 = memId;
110149 aOp[0].p3 = memId+1;
110150 aOp[2].p3 = memId;
110151 aOp[3].p1 = memId-1;
110152 aOp[3].p3 = memId;
110153 aOp[3].p5 = SQLITE_JUMPIFNULL;
110154 aOp[4].p2 = memId+1;
110155 aOp[5].p3 = memId;
110156 aOp[8].p2 = memId;
110161 ** Update the maximum rowid for an autoincrement calculation.
110163 ** This routine should be called when the regRowid register holds a
110164 ** new rowid that is about to be inserted. If that new rowid is
110165 ** larger than the maximum rowid in the memId memory cell, then the
110166 ** memory cell is updated.
110168 static void autoIncStep(Parse *pParse, int memId, int regRowid){
110169 if( memId>0 ){
110170 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
110175 ** This routine generates the code needed to write autoincrement
110176 ** maximum rowid values back into the sqlite_sequence register.
110177 ** Every statement that might do an INSERT into an autoincrement
110178 ** table (either directly or through triggers) needs to call this
110179 ** routine just before the "exit" code.
110181 static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
110182 AutoincInfo *p;
110183 Vdbe *v = pParse->pVdbe;
110184 sqlite3 *db = pParse->db;
110186 assert( v );
110187 for(p = pParse->pAinc; p; p = p->pNext){
110188 static const int iLn = VDBE_OFFSET_LINENO(2);
110189 static const VdbeOpList autoIncEnd[] = {
110190 /* 0 */ {OP_NotNull, 0, 2, 0},
110191 /* 1 */ {OP_NewRowid, 0, 0, 0},
110192 /* 2 */ {OP_MakeRecord, 0, 2, 0},
110193 /* 3 */ {OP_Insert, 0, 0, 0},
110194 /* 4 */ {OP_Close, 0, 0, 0}
110196 VdbeOp *aOp;
110197 Db *pDb = &db->aDb[p->iDb];
110198 int iRec;
110199 int memId = p->regCtr;
110201 iRec = sqlite3GetTempReg(pParse);
110202 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
110203 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
110204 aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
110205 if( aOp==0 ) break;
110206 aOp[0].p1 = memId+1;
110207 aOp[1].p2 = memId+1;
110208 aOp[2].p1 = memId-1;
110209 aOp[2].p3 = iRec;
110210 aOp[3].p2 = iRec;
110211 aOp[3].p3 = memId+1;
110212 aOp[3].p5 = OPFLAG_APPEND;
110213 sqlite3ReleaseTempReg(pParse, iRec);
110216 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
110217 if( pParse->pAinc ) autoIncrementEnd(pParse);
110219 #else
110221 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
110222 ** above are all no-ops
110224 # define autoIncBegin(A,B,C) (0)
110225 # define autoIncStep(A,B,C)
110226 #endif /* SQLITE_OMIT_AUTOINCREMENT */
110229 /* Forward declaration */
110230 static int xferOptimization(
110231 Parse *pParse, /* Parser context */
110232 Table *pDest, /* The table we are inserting into */
110233 Select *pSelect, /* A SELECT statement to use as the data source */
110234 int onError, /* How to handle constraint errors */
110235 int iDbDest /* The database of pDest */
110239 ** This routine is called to handle SQL of the following forms:
110241 ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
110242 ** insert into TABLE (IDLIST) select
110243 ** insert into TABLE (IDLIST) default values
110245 ** The IDLIST following the table name is always optional. If omitted,
110246 ** then a list of all (non-hidden) columns for the table is substituted.
110247 ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
110248 ** is omitted.
110250 ** For the pSelect parameter holds the values to be inserted for the
110251 ** first two forms shown above. A VALUES clause is really just short-hand
110252 ** for a SELECT statement that omits the FROM clause and everything else
110253 ** that follows. If the pSelect parameter is NULL, that means that the
110254 ** DEFAULT VALUES form of the INSERT statement is intended.
110256 ** The code generated follows one of four templates. For a simple
110257 ** insert with data coming from a single-row VALUES clause, the code executes
110258 ** once straight down through. Pseudo-code follows (we call this
110259 ** the "1st template"):
110261 ** open write cursor to <table> and its indices
110262 ** put VALUES clause expressions into registers
110263 ** write the resulting record into <table>
110264 ** cleanup
110266 ** The three remaining templates assume the statement is of the form
110268 ** INSERT INTO <table> SELECT ...
110270 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
110271 ** in other words if the SELECT pulls all columns from a single table
110272 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
110273 ** if <table2> and <table1> are distinct tables but have identical
110274 ** schemas, including all the same indices, then a special optimization
110275 ** is invoked that copies raw records from <table2> over to <table1>.
110276 ** See the xferOptimization() function for the implementation of this
110277 ** template. This is the 2nd template.
110279 ** open a write cursor to <table>
110280 ** open read cursor on <table2>
110281 ** transfer all records in <table2> over to <table>
110282 ** close cursors
110283 ** foreach index on <table>
110284 ** open a write cursor on the <table> index
110285 ** open a read cursor on the corresponding <table2> index
110286 ** transfer all records from the read to the write cursors
110287 ** close cursors
110288 ** end foreach
110290 ** The 3rd template is for when the second template does not apply
110291 ** and the SELECT clause does not read from <table> at any time.
110292 ** The generated code follows this template:
110294 ** X <- A
110295 ** goto B
110296 ** A: setup for the SELECT
110297 ** loop over the rows in the SELECT
110298 ** load values into registers R..R+n
110299 ** yield X
110300 ** end loop
110301 ** cleanup after the SELECT
110302 ** end-coroutine X
110303 ** B: open write cursor to <table> and its indices
110304 ** C: yield X, at EOF goto D
110305 ** insert the select result into <table> from R..R+n
110306 ** goto C
110307 ** D: cleanup
110309 ** The 4th template is used if the insert statement takes its
110310 ** values from a SELECT but the data is being inserted into a table
110311 ** that is also read as part of the SELECT. In the third form,
110312 ** we have to use an intermediate table to store the results of
110313 ** the select. The template is like this:
110315 ** X <- A
110316 ** goto B
110317 ** A: setup for the SELECT
110318 ** loop over the tables in the SELECT
110319 ** load value into register R..R+n
110320 ** yield X
110321 ** end loop
110322 ** cleanup after the SELECT
110323 ** end co-routine R
110324 ** B: open temp table
110325 ** L: yield X, at EOF goto M
110326 ** insert row from R..R+n into temp table
110327 ** goto L
110328 ** M: open write cursor to <table> and its indices
110329 ** rewind temp table
110330 ** C: loop over rows of intermediate table
110331 ** transfer values form intermediate table into <table>
110332 ** end loop
110333 ** D: cleanup
110335 SQLITE_PRIVATE void sqlite3Insert(
110336 Parse *pParse, /* Parser context */
110337 SrcList *pTabList, /* Name of table into which we are inserting */
110338 Select *pSelect, /* A SELECT statement to use as the data source */
110339 IdList *pColumn, /* Column names corresponding to IDLIST. */
110340 int onError /* How to handle constraint errors */
110342 sqlite3 *db; /* The main database structure */
110343 Table *pTab; /* The table to insert into. aka TABLE */
110344 int i, j; /* Loop counters */
110345 Vdbe *v; /* Generate code into this virtual machine */
110346 Index *pIdx; /* For looping over indices of the table */
110347 int nColumn; /* Number of columns in the data */
110348 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
110349 int iDataCur = 0; /* VDBE cursor that is the main data repository */
110350 int iIdxCur = 0; /* First index cursor */
110351 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
110352 int endOfLoop; /* Label for the end of the insertion loop */
110353 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
110354 int addrInsTop = 0; /* Jump to label "D" */
110355 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
110356 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
110357 int iDb; /* Index of database holding TABLE */
110358 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
110359 u8 appendFlag = 0; /* True if the insert is likely to be an append */
110360 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
110361 u8 bIdListInOrder; /* True if IDLIST is in table order */
110362 ExprList *pList = 0; /* List of VALUES() to be inserted */
110364 /* Register allocations */
110365 int regFromSelect = 0;/* Base register for data coming from SELECT */
110366 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
110367 int regRowCount = 0; /* Memory cell used for the row counter */
110368 int regIns; /* Block of regs holding rowid+data being inserted */
110369 int regRowid; /* registers holding insert rowid */
110370 int regData; /* register holding first column to insert */
110371 int *aRegIdx = 0; /* One register allocated to each index */
110373 #ifndef SQLITE_OMIT_TRIGGER
110374 int isView; /* True if attempting to insert into a view */
110375 Trigger *pTrigger; /* List of triggers on pTab, if required */
110376 int tmask; /* Mask of trigger times */
110377 #endif
110379 db = pParse->db;
110380 if( pParse->nErr || db->mallocFailed ){
110381 goto insert_cleanup;
110383 dest.iSDParm = 0; /* Suppress a harmless compiler warning */
110385 /* If the Select object is really just a simple VALUES() list with a
110386 ** single row (the common case) then keep that one row of values
110387 ** and discard the other (unused) parts of the pSelect object
110389 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
110390 pList = pSelect->pEList;
110391 pSelect->pEList = 0;
110392 sqlite3SelectDelete(db, pSelect);
110393 pSelect = 0;
110396 /* Locate the table into which we will be inserting new information.
110398 assert( pTabList->nSrc==1 );
110399 pTab = sqlite3SrcListLookup(pParse, pTabList);
110400 if( pTab==0 ){
110401 goto insert_cleanup;
110403 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110404 assert( iDb<db->nDb );
110405 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
110406 db->aDb[iDb].zDbSName) ){
110407 goto insert_cleanup;
110409 withoutRowid = !HasRowid(pTab);
110411 /* Figure out if we have any triggers and if the table being
110412 ** inserted into is a view
110414 #ifndef SQLITE_OMIT_TRIGGER
110415 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
110416 isView = pTab->pSelect!=0;
110417 #else
110418 # define pTrigger 0
110419 # define tmask 0
110420 # define isView 0
110421 #endif
110422 #ifdef SQLITE_OMIT_VIEW
110423 # undef isView
110424 # define isView 0
110425 #endif
110426 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
110428 /* If pTab is really a view, make sure it has been initialized.
110429 ** ViewGetColumnNames() is a no-op if pTab is not a view.
110431 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
110432 goto insert_cleanup;
110435 /* Cannot insert into a read-only table.
110437 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
110438 goto insert_cleanup;
110441 /* Allocate a VDBE
110443 v = sqlite3GetVdbe(pParse);
110444 if( v==0 ) goto insert_cleanup;
110445 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
110446 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
110448 #ifndef SQLITE_OMIT_XFER_OPT
110449 /* If the statement is of the form
110451 ** INSERT INTO <table1> SELECT * FROM <table2>;
110453 ** Then special optimizations can be applied that make the transfer
110454 ** very fast and which reduce fragmentation of indices.
110456 ** This is the 2nd template.
110458 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
110459 assert( !pTrigger );
110460 assert( pList==0 );
110461 goto insert_end;
110463 #endif /* SQLITE_OMIT_XFER_OPT */
110465 /* If this is an AUTOINCREMENT table, look up the sequence number in the
110466 ** sqlite_sequence table and store it in memory cell regAutoinc.
110468 regAutoinc = autoIncBegin(pParse, iDb, pTab);
110470 /* Allocate registers for holding the rowid of the new row,
110471 ** the content of the new row, and the assembled row record.
110473 regRowid = regIns = pParse->nMem+1;
110474 pParse->nMem += pTab->nCol + 1;
110475 if( IsVirtual(pTab) ){
110476 regRowid++;
110477 pParse->nMem++;
110479 regData = regRowid+1;
110481 /* If the INSERT statement included an IDLIST term, then make sure
110482 ** all elements of the IDLIST really are columns of the table and
110483 ** remember the column indices.
110485 ** If the table has an INTEGER PRIMARY KEY column and that column
110486 ** is named in the IDLIST, then record in the ipkColumn variable
110487 ** the index into IDLIST of the primary key column. ipkColumn is
110488 ** the index of the primary key as it appears in IDLIST, not as
110489 ** is appears in the original table. (The index of the INTEGER
110490 ** PRIMARY KEY in the original table is pTab->iPKey.)
110492 bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
110493 if( pColumn ){
110494 for(i=0; i<pColumn->nId; i++){
110495 pColumn->a[i].idx = -1;
110497 for(i=0; i<pColumn->nId; i++){
110498 for(j=0; j<pTab->nCol; j++){
110499 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
110500 pColumn->a[i].idx = j;
110501 if( i!=j ) bIdListInOrder = 0;
110502 if( j==pTab->iPKey ){
110503 ipkColumn = i; assert( !withoutRowid );
110505 break;
110508 if( j>=pTab->nCol ){
110509 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
110510 ipkColumn = i;
110511 bIdListInOrder = 0;
110512 }else{
110513 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
110514 pTabList, 0, pColumn->a[i].zName);
110515 pParse->checkSchema = 1;
110516 goto insert_cleanup;
110522 /* Figure out how many columns of data are supplied. If the data
110523 ** is coming from a SELECT statement, then generate a co-routine that
110524 ** produces a single row of the SELECT on each invocation. The
110525 ** co-routine is the common header to the 3rd and 4th templates.
110527 if( pSelect ){
110528 /* Data is coming from a SELECT or from a multi-row VALUES clause.
110529 ** Generate a co-routine to run the SELECT. */
110530 int regYield; /* Register holding co-routine entry-point */
110531 int addrTop; /* Top of the co-routine */
110532 int rc; /* Result code */
110534 regYield = ++pParse->nMem;
110535 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
110536 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
110537 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
110538 dest.iSdst = bIdListInOrder ? regData : 0;
110539 dest.nSdst = pTab->nCol;
110540 rc = sqlite3Select(pParse, pSelect, &dest);
110541 regFromSelect = dest.iSdst;
110542 if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
110543 sqlite3VdbeEndCoroutine(v, regYield);
110544 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
110545 assert( pSelect->pEList );
110546 nColumn = pSelect->pEList->nExpr;
110548 /* Set useTempTable to TRUE if the result of the SELECT statement
110549 ** should be written into a temporary table (template 4). Set to
110550 ** FALSE if each output row of the SELECT can be written directly into
110551 ** the destination table (template 3).
110553 ** A temp table must be used if the table being updated is also one
110554 ** of the tables being read by the SELECT statement. Also use a
110555 ** temp table in the case of row triggers.
110557 if( pTrigger || readsTable(pParse, iDb, pTab) ){
110558 useTempTable = 1;
110561 if( useTempTable ){
110562 /* Invoke the coroutine to extract information from the SELECT
110563 ** and add it to a transient table srcTab. The code generated
110564 ** here is from the 4th template:
110566 ** B: open temp table
110567 ** L: yield X, goto M at EOF
110568 ** insert row from R..R+n into temp table
110569 ** goto L
110570 ** M: ...
110572 int regRec; /* Register to hold packed record */
110573 int regTempRowid; /* Register to hold temp table ROWID */
110574 int addrL; /* Label "L" */
110576 srcTab = pParse->nTab++;
110577 regRec = sqlite3GetTempReg(pParse);
110578 regTempRowid = sqlite3GetTempReg(pParse);
110579 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
110580 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
110581 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
110582 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
110583 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
110584 sqlite3VdbeGoto(v, addrL);
110585 sqlite3VdbeJumpHere(v, addrL);
110586 sqlite3ReleaseTempReg(pParse, regRec);
110587 sqlite3ReleaseTempReg(pParse, regTempRowid);
110589 }else{
110590 /* This is the case if the data for the INSERT is coming from a
110591 ** single-row VALUES clause
110593 NameContext sNC;
110594 memset(&sNC, 0, sizeof(sNC));
110595 sNC.pParse = pParse;
110596 srcTab = -1;
110597 assert( useTempTable==0 );
110598 if( pList ){
110599 nColumn = pList->nExpr;
110600 if( sqlite3ResolveExprListNames(&sNC, pList) ){
110601 goto insert_cleanup;
110603 }else{
110604 nColumn = 0;
110608 /* If there is no IDLIST term but the table has an integer primary
110609 ** key, the set the ipkColumn variable to the integer primary key
110610 ** column index in the original table definition.
110612 if( pColumn==0 && nColumn>0 ){
110613 ipkColumn = pTab->iPKey;
110616 /* Make sure the number of columns in the source data matches the number
110617 ** of columns to be inserted into the table.
110619 for(i=0; i<pTab->nCol; i++){
110620 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
110622 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
110623 sqlite3ErrorMsg(pParse,
110624 "table %S has %d columns but %d values were supplied",
110625 pTabList, 0, pTab->nCol-nHidden, nColumn);
110626 goto insert_cleanup;
110628 if( pColumn!=0 && nColumn!=pColumn->nId ){
110629 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
110630 goto insert_cleanup;
110633 /* Initialize the count of rows to be inserted
110635 if( db->flags & SQLITE_CountRows ){
110636 regRowCount = ++pParse->nMem;
110637 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
110640 /* If this is not a view, open the table and and all indices */
110641 if( !isView ){
110642 int nIdx;
110643 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
110644 &iDataCur, &iIdxCur);
110645 aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
110646 if( aRegIdx==0 ){
110647 goto insert_cleanup;
110649 for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
110650 assert( pIdx );
110651 aRegIdx[i] = ++pParse->nMem;
110652 pParse->nMem += pIdx->nColumn;
110656 /* This is the top of the main insertion loop */
110657 if( useTempTable ){
110658 /* This block codes the top of loop only. The complete loop is the
110659 ** following pseudocode (template 4):
110661 ** rewind temp table, if empty goto D
110662 ** C: loop over rows of intermediate table
110663 ** transfer values form intermediate table into <table>
110664 ** end loop
110665 ** D: ...
110667 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
110668 addrCont = sqlite3VdbeCurrentAddr(v);
110669 }else if( pSelect ){
110670 /* This block codes the top of loop only. The complete loop is the
110671 ** following pseudocode (template 3):
110673 ** C: yield X, at EOF goto D
110674 ** insert the select result into <table> from R..R+n
110675 ** goto C
110676 ** D: ...
110678 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
110679 VdbeCoverage(v);
110682 /* Run the BEFORE and INSTEAD OF triggers, if there are any
110684 endOfLoop = sqlite3VdbeMakeLabel(v);
110685 if( tmask & TRIGGER_BEFORE ){
110686 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
110688 /* build the NEW.* reference row. Note that if there is an INTEGER
110689 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
110690 ** translated into a unique ID for the row. But on a BEFORE trigger,
110691 ** we do not know what the unique ID will be (because the insert has
110692 ** not happened yet) so we substitute a rowid of -1
110694 if( ipkColumn<0 ){
110695 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
110696 }else{
110697 int addr1;
110698 assert( !withoutRowid );
110699 if( useTempTable ){
110700 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
110701 }else{
110702 assert( pSelect==0 ); /* Otherwise useTempTable is true */
110703 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
110705 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
110706 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
110707 sqlite3VdbeJumpHere(v, addr1);
110708 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
110711 /* Cannot have triggers on a virtual table. If it were possible,
110712 ** this block would have to account for hidden column.
110714 assert( !IsVirtual(pTab) );
110716 /* Create the new column data
110718 for(i=j=0; i<pTab->nCol; i++){
110719 if( pColumn ){
110720 for(j=0; j<pColumn->nId; j++){
110721 if( pColumn->a[j].idx==i ) break;
110724 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
110725 || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
110726 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
110727 }else if( useTempTable ){
110728 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
110729 }else{
110730 assert( pSelect==0 ); /* Otherwise useTempTable is true */
110731 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
110733 if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
110736 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
110737 ** do not attempt any conversions before assembling the record.
110738 ** If this is a real table, attempt conversions as required by the
110739 ** table column affinities.
110741 if( !isView ){
110742 sqlite3TableAffinity(v, pTab, regCols+1);
110745 /* Fire BEFORE or INSTEAD OF triggers */
110746 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
110747 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
110749 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
110752 /* Compute the content of the next row to insert into a range of
110753 ** registers beginning at regIns.
110755 if( !isView ){
110756 if( IsVirtual(pTab) ){
110757 /* The row that the VUpdate opcode will delete: none */
110758 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
110760 if( ipkColumn>=0 ){
110761 if( useTempTable ){
110762 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
110763 }else if( pSelect ){
110764 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
110765 }else{
110766 VdbeOp *pOp;
110767 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
110768 pOp = sqlite3VdbeGetOp(v, -1);
110769 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
110770 appendFlag = 1;
110771 pOp->opcode = OP_NewRowid;
110772 pOp->p1 = iDataCur;
110773 pOp->p2 = regRowid;
110774 pOp->p3 = regAutoinc;
110777 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
110778 ** to generate a unique primary key value.
110780 if( !appendFlag ){
110781 int addr1;
110782 if( !IsVirtual(pTab) ){
110783 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
110784 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
110785 sqlite3VdbeJumpHere(v, addr1);
110786 }else{
110787 addr1 = sqlite3VdbeCurrentAddr(v);
110788 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
110790 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
110792 }else if( IsVirtual(pTab) || withoutRowid ){
110793 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
110794 }else{
110795 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
110796 appendFlag = 1;
110798 autoIncStep(pParse, regAutoinc, regRowid);
110800 /* Compute data for all columns of the new entry, beginning
110801 ** with the first column.
110803 nHidden = 0;
110804 for(i=0; i<pTab->nCol; i++){
110805 int iRegStore = regRowid+1+i;
110806 if( i==pTab->iPKey ){
110807 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
110808 ** Whenever this column is read, the rowid will be substituted
110809 ** in its place. Hence, fill this column with a NULL to avoid
110810 ** taking up data space with information that will never be used.
110811 ** As there may be shallow copies of this value, make it a soft-NULL */
110812 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
110813 continue;
110815 if( pColumn==0 ){
110816 if( IsHiddenColumn(&pTab->aCol[i]) ){
110817 j = -1;
110818 nHidden++;
110819 }else{
110820 j = i - nHidden;
110822 }else{
110823 for(j=0; j<pColumn->nId; j++){
110824 if( pColumn->a[j].idx==i ) break;
110827 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
110828 sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
110829 }else if( useTempTable ){
110830 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
110831 }else if( pSelect ){
110832 if( regFromSelect!=regData ){
110833 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
110835 }else{
110836 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
110840 /* Generate code to check constraints and generate index keys and
110841 ** do the insertion.
110843 #ifndef SQLITE_OMIT_VIRTUALTABLE
110844 if( IsVirtual(pTab) ){
110845 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
110846 sqlite3VtabMakeWritable(pParse, pTab);
110847 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
110848 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
110849 sqlite3MayAbort(pParse);
110850 }else
110851 #endif
110853 int isReplace; /* Set to true if constraints may cause a replace */
110854 int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
110855 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
110856 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
110858 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
110860 /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
110861 ** constraints or (b) there are no triggers and this table is not a
110862 ** parent table in a foreign key constraint. It is safe to set the
110863 ** flag in the second case as if any REPLACE constraint is hit, an
110864 ** OP_Delete or OP_IdxDelete instruction will be executed on each
110865 ** cursor that is disturbed. And these instructions both clear the
110866 ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
110867 ** functionality. */
110868 bUseSeek = (isReplace==0 || (pTrigger==0 &&
110869 ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
110871 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
110872 regIns, aRegIdx, 0, appendFlag, bUseSeek
110877 /* Update the count of rows that are inserted
110879 if( (db->flags & SQLITE_CountRows)!=0 ){
110880 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
110883 if( pTrigger ){
110884 /* Code AFTER triggers */
110885 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
110886 pTab, regData-2-pTab->nCol, onError, endOfLoop);
110889 /* The bottom of the main insertion loop, if the data source
110890 ** is a SELECT statement.
110892 sqlite3VdbeResolveLabel(v, endOfLoop);
110893 if( useTempTable ){
110894 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
110895 sqlite3VdbeJumpHere(v, addrInsTop);
110896 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
110897 }else if( pSelect ){
110898 sqlite3VdbeGoto(v, addrCont);
110899 sqlite3VdbeJumpHere(v, addrInsTop);
110902 insert_end:
110903 /* Update the sqlite_sequence table by storing the content of the
110904 ** maximum rowid counter values recorded while inserting into
110905 ** autoincrement tables.
110907 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
110908 sqlite3AutoincrementEnd(pParse);
110912 ** Return the number of rows inserted. If this routine is
110913 ** generating code because of a call to sqlite3NestedParse(), do not
110914 ** invoke the callback function.
110916 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
110917 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
110918 sqlite3VdbeSetNumCols(v, 1);
110919 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
110922 insert_cleanup:
110923 sqlite3SrcListDelete(db, pTabList);
110924 sqlite3ExprListDelete(db, pList);
110925 sqlite3SelectDelete(db, pSelect);
110926 sqlite3IdListDelete(db, pColumn);
110927 sqlite3DbFree(db, aRegIdx);
110930 /* Make sure "isView" and other macros defined above are undefined. Otherwise
110931 ** they may interfere with compilation of other functions in this file
110932 ** (or in another file, if this file becomes part of the amalgamation). */
110933 #ifdef isView
110934 #undef isView
110935 #endif
110936 #ifdef pTrigger
110937 #undef pTrigger
110938 #endif
110939 #ifdef tmask
110940 #undef tmask
110941 #endif
110944 ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
110946 #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
110947 #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
110949 /* This is the Walker callback from checkConstraintUnchanged(). Set
110950 ** bit 0x01 of pWalker->eCode if
110951 ** pWalker->eCode to 0 if this expression node references any of the
110952 ** columns that are being modifed by an UPDATE statement.
110954 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
110955 if( pExpr->op==TK_COLUMN ){
110956 assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
110957 if( pExpr->iColumn>=0 ){
110958 if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
110959 pWalker->eCode |= CKCNSTRNT_COLUMN;
110961 }else{
110962 pWalker->eCode |= CKCNSTRNT_ROWID;
110965 return WRC_Continue;
110969 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
110970 ** only columns that are modified by the UPDATE are those for which
110971 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
110973 ** Return true if CHECK constraint pExpr does not use any of the
110974 ** changing columns (or the rowid if it is changing). In other words,
110975 ** return true if this CHECK constraint can be skipped when validating
110976 ** the new row in the UPDATE statement.
110978 static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
110979 Walker w;
110980 memset(&w, 0, sizeof(w));
110981 w.eCode = 0;
110982 w.xExprCallback = checkConstraintExprNode;
110983 w.u.aiCol = aiChng;
110984 sqlite3WalkExpr(&w, pExpr);
110985 if( !chngRowid ){
110986 testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
110987 w.eCode &= ~CKCNSTRNT_ROWID;
110989 testcase( w.eCode==0 );
110990 testcase( w.eCode==CKCNSTRNT_COLUMN );
110991 testcase( w.eCode==CKCNSTRNT_ROWID );
110992 testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
110993 return !w.eCode;
110997 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
110998 ** on table pTab.
111000 ** The regNewData parameter is the first register in a range that contains
111001 ** the data to be inserted or the data after the update. There will be
111002 ** pTab->nCol+1 registers in this range. The first register (the one
111003 ** that regNewData points to) will contain the new rowid, or NULL in the
111004 ** case of a WITHOUT ROWID table. The second register in the range will
111005 ** contain the content of the first table column. The third register will
111006 ** contain the content of the second table column. And so forth.
111008 ** The regOldData parameter is similar to regNewData except that it contains
111009 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
111010 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
111011 ** checking regOldData for zero.
111013 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
111014 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
111015 ** might be modified by the UPDATE. If pkChng is false, then the key of
111016 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
111018 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
111019 ** was explicitly specified as part of the INSERT statement. If pkChng
111020 ** is zero, it means that the either rowid is computed automatically or
111021 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
111022 ** pkChng will only be true if the INSERT statement provides an integer
111023 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
111025 ** The code generated by this routine will store new index entries into
111026 ** registers identified by aRegIdx[]. No index entry is created for
111027 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
111028 ** the same as the order of indices on the linked list of indices
111029 ** at pTab->pIndex.
111031 ** The caller must have already opened writeable cursors on the main
111032 ** table and all applicable indices (that is to say, all indices for which
111033 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
111034 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
111035 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
111036 ** for the first index in the pTab->pIndex list. Cursors for other indices
111037 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
111039 ** This routine also generates code to check constraints. NOT NULL,
111040 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
111041 ** then the appropriate action is performed. There are five possible
111042 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
111044 ** Constraint type Action What Happens
111045 ** --------------- ---------- ----------------------------------------
111046 ** any ROLLBACK The current transaction is rolled back and
111047 ** sqlite3_step() returns immediately with a
111048 ** return code of SQLITE_CONSTRAINT.
111050 ** any ABORT Back out changes from the current command
111051 ** only (do not do a complete rollback) then
111052 ** cause sqlite3_step() to return immediately
111053 ** with SQLITE_CONSTRAINT.
111055 ** any FAIL Sqlite3_step() returns immediately with a
111056 ** return code of SQLITE_CONSTRAINT. The
111057 ** transaction is not rolled back and any
111058 ** changes to prior rows are retained.
111060 ** any IGNORE The attempt in insert or update the current
111061 ** row is skipped, without throwing an error.
111062 ** Processing continues with the next row.
111063 ** (There is an immediate jump to ignoreDest.)
111065 ** NOT NULL REPLACE The NULL value is replace by the default
111066 ** value for that column. If the default value
111067 ** is NULL, the action is the same as ABORT.
111069 ** UNIQUE REPLACE The other row that conflicts with the row
111070 ** being inserted is removed.
111072 ** CHECK REPLACE Illegal. The results in an exception.
111074 ** Which action to take is determined by the overrideError parameter.
111075 ** Or if overrideError==OE_Default, then the pParse->onError parameter
111076 ** is used. Or if pParse->onError==OE_Default then the onError value
111077 ** for the constraint is used.
111079 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
111080 Parse *pParse, /* The parser context */
111081 Table *pTab, /* The table being inserted or updated */
111082 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
111083 int iDataCur, /* Canonical data cursor (main table or PK index) */
111084 int iIdxCur, /* First index cursor */
111085 int regNewData, /* First register in a range holding values to insert */
111086 int regOldData, /* Previous content. 0 for INSERTs */
111087 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
111088 u8 overrideError, /* Override onError to this if not OE_Default */
111089 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
111090 int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
111091 int *aiChng /* column i is unchanged if aiChng[i]<0 */
111093 Vdbe *v; /* VDBE under constrution */
111094 Index *pIdx; /* Pointer to one of the indices */
111095 Index *pPk = 0; /* The PRIMARY KEY index */
111096 sqlite3 *db; /* Database connection */
111097 int i; /* loop counter */
111098 int ix; /* Index loop counter */
111099 int nCol; /* Number of columns */
111100 int onError; /* Conflict resolution strategy */
111101 int addr1; /* Address of jump instruction */
111102 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
111103 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
111104 int ipkTop = 0; /* Top of the rowid change constraint check */
111105 int ipkBottom = 0; /* Bottom of the rowid change constraint check */
111106 u8 isUpdate; /* True if this is an UPDATE operation */
111107 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
111109 isUpdate = regOldData!=0;
111110 db = pParse->db;
111111 v = sqlite3GetVdbe(pParse);
111112 assert( v!=0 );
111113 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
111114 nCol = pTab->nCol;
111116 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
111117 ** normal rowid tables. nPkField is the number of key fields in the
111118 ** pPk index or 1 for a rowid table. In other words, nPkField is the
111119 ** number of fields in the true primary key of the table. */
111120 if( HasRowid(pTab) ){
111121 pPk = 0;
111122 nPkField = 1;
111123 }else{
111124 pPk = sqlite3PrimaryKeyIndex(pTab);
111125 nPkField = pPk->nKeyCol;
111128 /* Record that this module has started */
111129 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
111130 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
111132 /* Test all NOT NULL constraints.
111134 for(i=0; i<nCol; i++){
111135 if( i==pTab->iPKey ){
111136 continue; /* ROWID is never NULL */
111138 if( aiChng && aiChng[i]<0 ){
111139 /* Don't bother checking for NOT NULL on columns that do not change */
111140 continue;
111142 onError = pTab->aCol[i].notNull;
111143 if( onError==OE_None ) continue; /* This column is allowed to be NULL */
111144 if( overrideError!=OE_Default ){
111145 onError = overrideError;
111146 }else if( onError==OE_Default ){
111147 onError = OE_Abort;
111149 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
111150 onError = OE_Abort;
111152 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
111153 || onError==OE_Ignore || onError==OE_Replace );
111154 switch( onError ){
111155 case OE_Abort:
111156 sqlite3MayAbort(pParse);
111157 /* Fall through */
111158 case OE_Rollback:
111159 case OE_Fail: {
111160 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
111161 pTab->aCol[i].zName);
111162 sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
111163 regNewData+1+i);
111164 sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
111165 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
111166 VdbeCoverage(v);
111167 break;
111169 case OE_Ignore: {
111170 sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
111171 VdbeCoverage(v);
111172 break;
111174 default: {
111175 assert( onError==OE_Replace );
111176 addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
111177 VdbeCoverage(v);
111178 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
111179 sqlite3VdbeJumpHere(v, addr1);
111180 break;
111185 /* Test all CHECK constraints
111187 #ifndef SQLITE_OMIT_CHECK
111188 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
111189 ExprList *pCheck = pTab->pCheck;
111190 pParse->iSelfTab = -(regNewData+1);
111191 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
111192 for(i=0; i<pCheck->nExpr; i++){
111193 int allOk;
111194 Expr *pExpr = pCheck->a[i].pExpr;
111195 if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
111196 allOk = sqlite3VdbeMakeLabel(v);
111197 sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
111198 if( onError==OE_Ignore ){
111199 sqlite3VdbeGoto(v, ignoreDest);
111200 }else{
111201 char *zName = pCheck->a[i].zName;
111202 if( zName==0 ) zName = pTab->zName;
111203 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
111204 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
111205 onError, zName, P4_TRANSIENT,
111206 P5_ConstraintCheck);
111208 sqlite3VdbeResolveLabel(v, allOk);
111210 pParse->iSelfTab = 0;
111212 #endif /* !defined(SQLITE_OMIT_CHECK) */
111214 /* If rowid is changing, make sure the new rowid does not previously
111215 ** exist in the table.
111217 if( pkChng && pPk==0 ){
111218 int addrRowidOk = sqlite3VdbeMakeLabel(v);
111220 /* Figure out what action to take in case of a rowid collision */
111221 onError = pTab->keyConf;
111222 if( overrideError!=OE_Default ){
111223 onError = overrideError;
111224 }else if( onError==OE_Default ){
111225 onError = OE_Abort;
111228 if( isUpdate ){
111229 /* pkChng!=0 does not mean that the rowid has changed, only that
111230 ** it might have changed. Skip the conflict logic below if the rowid
111231 ** is unchanged. */
111232 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
111233 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
111234 VdbeCoverage(v);
111237 /* If the response to a rowid conflict is REPLACE but the response
111238 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
111239 ** to defer the running of the rowid conflict checking until after
111240 ** the UNIQUE constraints have run.
111242 if( onError==OE_Replace && overrideError!=OE_Replace ){
111243 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111244 if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
111245 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
111246 break;
111251 /* Check to see if the new rowid already exists in the table. Skip
111252 ** the following conflict logic if it does not. */
111253 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
111254 VdbeCoverage(v);
111256 /* Generate code that deals with a rowid collision */
111257 switch( onError ){
111258 default: {
111259 onError = OE_Abort;
111260 /* Fall thru into the next case */
111262 case OE_Rollback:
111263 case OE_Abort:
111264 case OE_Fail: {
111265 sqlite3RowidConstraint(pParse, onError, pTab);
111266 break;
111268 case OE_Replace: {
111269 /* If there are DELETE triggers on this table and the
111270 ** recursive-triggers flag is set, call GenerateRowDelete() to
111271 ** remove the conflicting row from the table. This will fire
111272 ** the triggers and remove both the table and index b-tree entries.
111274 ** Otherwise, if there are no triggers or the recursive-triggers
111275 ** flag is not set, but the table has one or more indexes, call
111276 ** GenerateRowIndexDelete(). This removes the index b-tree entries
111277 ** only. The table b-tree entry will be replaced by the new entry
111278 ** when it is inserted.
111280 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
111281 ** also invoke MultiWrite() to indicate that this VDBE may require
111282 ** statement rollback (if the statement is aborted after the delete
111283 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
111284 ** but being more selective here allows statements like:
111286 ** REPLACE INTO t(rowid) VALUES($newrowid)
111288 ** to run without a statement journal if there are no indexes on the
111289 ** table.
111291 Trigger *pTrigger = 0;
111292 if( db->flags&SQLITE_RecTriggers ){
111293 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
111295 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
111296 sqlite3MultiWrite(pParse);
111297 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
111298 regNewData, 1, 0, OE_Replace, 1, -1);
111299 }else{
111300 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
111301 if( HasRowid(pTab) ){
111302 /* This OP_Delete opcode fires the pre-update-hook only. It does
111303 ** not modify the b-tree. It is more efficient to let the coming
111304 ** OP_Insert replace the existing entry than it is to delete the
111305 ** existing entry and then insert a new one. */
111306 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
111307 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
111309 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
111310 if( pTab->pIndex ){
111311 sqlite3MultiWrite(pParse);
111312 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
111315 seenReplace = 1;
111316 break;
111318 case OE_Ignore: {
111319 /*assert( seenReplace==0 );*/
111320 sqlite3VdbeGoto(v, ignoreDest);
111321 break;
111324 sqlite3VdbeResolveLabel(v, addrRowidOk);
111325 if( ipkTop ){
111326 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
111327 sqlite3VdbeJumpHere(v, ipkTop);
111331 /* Test all UNIQUE constraints by creating entries for each UNIQUE
111332 ** index and making sure that duplicate entries do not already exist.
111333 ** Compute the revised record entries for indices as we go.
111335 ** This loop also handles the case of the PRIMARY KEY index for a
111336 ** WITHOUT ROWID table.
111338 for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
111339 int regIdx; /* Range of registers hold conent for pIdx */
111340 int regR; /* Range of registers holding conflicting PK */
111341 int iThisCur; /* Cursor for this UNIQUE index */
111342 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
111344 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
111345 if( bAffinityDone==0 ){
111346 sqlite3TableAffinity(v, pTab, regNewData+1);
111347 bAffinityDone = 1;
111349 iThisCur = iIdxCur+ix;
111350 addrUniqueOk = sqlite3VdbeMakeLabel(v);
111352 /* Skip partial indices for which the WHERE clause is not true */
111353 if( pIdx->pPartIdxWhere ){
111354 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
111355 pParse->iSelfTab = -(regNewData+1);
111356 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
111357 SQLITE_JUMPIFNULL);
111358 pParse->iSelfTab = 0;
111361 /* Create a record for this index entry as it should appear after
111362 ** the insert or update. Store that record in the aRegIdx[ix] register
111364 regIdx = aRegIdx[ix]+1;
111365 for(i=0; i<pIdx->nColumn; i++){
111366 int iField = pIdx->aiColumn[i];
111367 int x;
111368 if( iField==XN_EXPR ){
111369 pParse->iSelfTab = -(regNewData+1);
111370 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
111371 pParse->iSelfTab = 0;
111372 VdbeComment((v, "%s column %d", pIdx->zName, i));
111373 }else{
111374 if( iField==XN_ROWID || iField==pTab->iPKey ){
111375 x = regNewData;
111376 }else{
111377 x = iField + regNewData + 1;
111379 sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
111380 VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
111383 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
111384 VdbeComment((v, "for %s", pIdx->zName));
111385 #ifdef SQLITE_ENABLE_NULL_TRIM
111386 if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
111387 #endif
111389 /* In an UPDATE operation, if this index is the PRIMARY KEY index
111390 ** of a WITHOUT ROWID table and there has been no change the
111391 ** primary key, then no collision is possible. The collision detection
111392 ** logic below can all be skipped. */
111393 if( isUpdate && pPk==pIdx && pkChng==0 ){
111394 sqlite3VdbeResolveLabel(v, addrUniqueOk);
111395 continue;
111398 /* Find out what action to take in case there is a uniqueness conflict */
111399 onError = pIdx->onError;
111400 if( onError==OE_None ){
111401 sqlite3VdbeResolveLabel(v, addrUniqueOk);
111402 continue; /* pIdx is not a UNIQUE index */
111404 if( overrideError!=OE_Default ){
111405 onError = overrideError;
111406 }else if( onError==OE_Default ){
111407 onError = OE_Abort;
111410 /* Collision detection may be omitted if all of the following are true:
111411 ** (1) The conflict resolution algorithm is REPLACE
111412 ** (2) The table is a WITHOUT ROWID table
111413 ** (3) There are no secondary indexes on the table
111414 ** (4) No delete triggers need to be fired if there is a conflict
111415 ** (5) No FK constraint counters need to be updated if a conflict occurs.
111417 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
111418 && pPk==pIdx /* Condition 2 */
111419 && onError==OE_Replace /* Condition 1 */
111420 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
111421 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
111422 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
111423 (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
111425 sqlite3VdbeResolveLabel(v, addrUniqueOk);
111426 continue;
111429 /* Check to see if the new index entry will be unique */
111430 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
111431 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
111433 /* Generate code to handle collisions */
111434 regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
111435 if( isUpdate || onError==OE_Replace ){
111436 if( HasRowid(pTab) ){
111437 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
111438 /* Conflict only if the rowid of the existing index entry
111439 ** is different from old-rowid */
111440 if( isUpdate ){
111441 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
111442 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
111443 VdbeCoverage(v);
111445 }else{
111446 int x;
111447 /* Extract the PRIMARY KEY from the end of the index entry and
111448 ** store it in registers regR..regR+nPk-1 */
111449 if( pIdx!=pPk ){
111450 for(i=0; i<pPk->nKeyCol; i++){
111451 assert( pPk->aiColumn[i]>=0 );
111452 x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
111453 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
111454 VdbeComment((v, "%s.%s", pTab->zName,
111455 pTab->aCol[pPk->aiColumn[i]].zName));
111458 if( isUpdate ){
111459 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
111460 ** table, only conflict if the new PRIMARY KEY values are actually
111461 ** different from the old.
111463 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
111464 ** of the matched index row are different from the original PRIMARY
111465 ** KEY values of this row before the update. */
111466 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
111467 int op = OP_Ne;
111468 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
111470 for(i=0; i<pPk->nKeyCol; i++){
111471 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
111472 x = pPk->aiColumn[i];
111473 assert( x>=0 );
111474 if( i==(pPk->nKeyCol-1) ){
111475 addrJump = addrUniqueOk;
111476 op = OP_Eq;
111478 sqlite3VdbeAddOp4(v, op,
111479 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
111481 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
111482 VdbeCoverageIf(v, op==OP_Eq);
111483 VdbeCoverageIf(v, op==OP_Ne);
111489 /* Generate code that executes if the new index entry is not unique */
111490 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
111491 || onError==OE_Ignore || onError==OE_Replace );
111492 switch( onError ){
111493 case OE_Rollback:
111494 case OE_Abort:
111495 case OE_Fail: {
111496 sqlite3UniqueConstraint(pParse, onError, pIdx);
111497 break;
111499 case OE_Ignore: {
111500 sqlite3VdbeGoto(v, ignoreDest);
111501 break;
111503 default: {
111504 Trigger *pTrigger = 0;
111505 assert( onError==OE_Replace );
111506 sqlite3MultiWrite(pParse);
111507 if( db->flags&SQLITE_RecTriggers ){
111508 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
111510 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
111511 regR, nPkField, 0, OE_Replace,
111512 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
111513 seenReplace = 1;
111514 break;
111517 sqlite3VdbeResolveLabel(v, addrUniqueOk);
111518 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
111520 if( ipkTop ){
111521 sqlite3VdbeGoto(v, ipkTop+1);
111522 sqlite3VdbeJumpHere(v, ipkBottom);
111525 *pbMayReplace = seenReplace;
111526 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
111529 #ifdef SQLITE_ENABLE_NULL_TRIM
111531 ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
111532 ** to be the number of columns in table pTab that must not be NULL-trimmed.
111534 ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
111536 SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
111537 u16 i;
111539 /* Records with omitted columns are only allowed for schema format
111540 ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
111541 if( pTab->pSchema->file_format<2 ) return;
111543 for(i=pTab->nCol-1; i>0; i--){
111544 if( pTab->aCol[i].pDflt!=0 ) break;
111545 if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
111547 sqlite3VdbeChangeP5(v, i+1);
111549 #endif
111552 ** This routine generates code to finish the INSERT or UPDATE operation
111553 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
111554 ** A consecutive range of registers starting at regNewData contains the
111555 ** rowid and the content to be inserted.
111557 ** The arguments to this routine should be the same as the first six
111558 ** arguments to sqlite3GenerateConstraintChecks.
111560 SQLITE_PRIVATE void sqlite3CompleteInsertion(
111561 Parse *pParse, /* The parser context */
111562 Table *pTab, /* the table into which we are inserting */
111563 int iDataCur, /* Cursor of the canonical data source */
111564 int iIdxCur, /* First index cursor */
111565 int regNewData, /* Range of content */
111566 int *aRegIdx, /* Register used by each index. 0 for unused indices */
111567 int update_flags, /* True for UPDATE, False for INSERT */
111568 int appendBias, /* True if this is likely to be an append */
111569 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
111571 Vdbe *v; /* Prepared statements under construction */
111572 Index *pIdx; /* An index being inserted or updated */
111573 u8 pik_flags; /* flag values passed to the btree insert */
111574 int regData; /* Content registers (after the rowid) */
111575 int regRec; /* Register holding assembled record for the table */
111576 int i; /* Loop counter */
111577 u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
111579 assert( update_flags==0
111580 || update_flags==OPFLAG_ISUPDATE
111581 || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
111584 v = sqlite3GetVdbe(pParse);
111585 assert( v!=0 );
111586 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
111587 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
111588 if( aRegIdx[i]==0 ) continue;
111589 bAffinityDone = 1;
111590 if( pIdx->pPartIdxWhere ){
111591 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
111592 VdbeCoverage(v);
111594 pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
111595 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
111596 assert( pParse->nested==0 );
111597 pik_flags |= OPFLAG_NCHANGE;
111598 pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
111599 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
111600 if( update_flags==0 ){
111601 sqlite3VdbeAddOp4(v, OP_InsertInt,
111602 iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
111604 sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
111606 #endif
111608 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
111609 aRegIdx[i]+1,
111610 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
111611 sqlite3VdbeChangeP5(v, pik_flags);
111613 if( !HasRowid(pTab) ) return;
111614 regData = regNewData + 1;
111615 regRec = sqlite3GetTempReg(pParse);
111616 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
111617 sqlite3SetMakeRecordP5(v, pTab);
111618 if( !bAffinityDone ){
111619 sqlite3TableAffinity(v, pTab, 0);
111620 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
111622 if( pParse->nested ){
111623 pik_flags = 0;
111624 }else{
111625 pik_flags = OPFLAG_NCHANGE;
111626 pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
111628 if( appendBias ){
111629 pik_flags |= OPFLAG_APPEND;
111631 if( useSeekResult ){
111632 pik_flags |= OPFLAG_USESEEKRESULT;
111634 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
111635 if( !pParse->nested ){
111636 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
111638 sqlite3VdbeChangeP5(v, pik_flags);
111642 ** Allocate cursors for the pTab table and all its indices and generate
111643 ** code to open and initialized those cursors.
111645 ** The cursor for the object that contains the complete data (normally
111646 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
111647 ** ROWID table) is returned in *piDataCur. The first index cursor is
111648 ** returned in *piIdxCur. The number of indices is returned.
111650 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
111651 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
111652 ** If iBase is negative, then allocate the next available cursor.
111654 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
111655 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
111656 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
111657 ** pTab->pIndex list.
111659 ** If pTab is a virtual table, then this routine is a no-op and the
111660 ** *piDataCur and *piIdxCur values are left uninitialized.
111662 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
111663 Parse *pParse, /* Parsing context */
111664 Table *pTab, /* Table to be opened */
111665 int op, /* OP_OpenRead or OP_OpenWrite */
111666 u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
111667 int iBase, /* Use this for the table cursor, if there is one */
111668 u8 *aToOpen, /* If not NULL: boolean for each table and index */
111669 int *piDataCur, /* Write the database source cursor number here */
111670 int *piIdxCur /* Write the first index cursor number here */
111672 int i;
111673 int iDb;
111674 int iDataCur;
111675 Index *pIdx;
111676 Vdbe *v;
111678 assert( op==OP_OpenRead || op==OP_OpenWrite );
111679 assert( op==OP_OpenWrite || p5==0 );
111680 if( IsVirtual(pTab) ){
111681 /* This routine is a no-op for virtual tables. Leave the output
111682 ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
111683 ** can detect if they are used by mistake in the caller. */
111684 return 0;
111686 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
111687 v = sqlite3GetVdbe(pParse);
111688 assert( v!=0 );
111689 if( iBase<0 ) iBase = pParse->nTab;
111690 iDataCur = iBase++;
111691 if( piDataCur ) *piDataCur = iDataCur;
111692 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
111693 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
111694 }else{
111695 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
111697 if( piIdxCur ) *piIdxCur = iBase;
111698 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
111699 int iIdxCur = iBase++;
111700 assert( pIdx->pSchema==pTab->pSchema );
111701 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
111702 if( piDataCur ) *piDataCur = iIdxCur;
111703 p5 = 0;
111705 if( aToOpen==0 || aToOpen[i+1] ){
111706 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
111707 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
111708 sqlite3VdbeChangeP5(v, p5);
111709 VdbeComment((v, "%s", pIdx->zName));
111712 if( iBase>pParse->nTab ) pParse->nTab = iBase;
111713 return i;
111717 #ifdef SQLITE_TEST
111719 ** The following global variable is incremented whenever the
111720 ** transfer optimization is used. This is used for testing
111721 ** purposes only - to make sure the transfer optimization really
111722 ** is happening when it is supposed to.
111724 SQLITE_API int sqlite3_xferopt_count;
111725 #endif /* SQLITE_TEST */
111728 #ifndef SQLITE_OMIT_XFER_OPT
111730 ** Check to see if index pSrc is compatible as a source of data
111731 ** for index pDest in an insert transfer optimization. The rules
111732 ** for a compatible index:
111734 ** * The index is over the same set of columns
111735 ** * The same DESC and ASC markings occurs on all columns
111736 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
111737 ** * The same collating sequence on each column
111738 ** * The index has the exact same WHERE clause
111740 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
111741 int i;
111742 assert( pDest && pSrc );
111743 assert( pDest->pTable!=pSrc->pTable );
111744 if( pDest->nKeyCol!=pSrc->nKeyCol ){
111745 return 0; /* Different number of columns */
111747 if( pDest->onError!=pSrc->onError ){
111748 return 0; /* Different conflict resolution strategies */
111750 for(i=0; i<pSrc->nKeyCol; i++){
111751 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
111752 return 0; /* Different columns indexed */
111754 if( pSrc->aiColumn[i]==XN_EXPR ){
111755 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
111756 if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
111757 pDest->aColExpr->a[i].pExpr, -1)!=0 ){
111758 return 0; /* Different expressions in the index */
111761 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
111762 return 0; /* Different sort orders */
111764 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
111765 return 0; /* Different collating sequences */
111768 if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
111769 return 0; /* Different WHERE clauses */
111772 /* If no test above fails then the indices must be compatible */
111773 return 1;
111777 ** Attempt the transfer optimization on INSERTs of the form
111779 ** INSERT INTO tab1 SELECT * FROM tab2;
111781 ** The xfer optimization transfers raw records from tab2 over to tab1.
111782 ** Columns are not decoded and reassembled, which greatly improves
111783 ** performance. Raw index records are transferred in the same way.
111785 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
111786 ** There are lots of rules for determining compatibility - see comments
111787 ** embedded in the code for details.
111789 ** This routine returns TRUE if the optimization is guaranteed to be used.
111790 ** Sometimes the xfer optimization will only work if the destination table
111791 ** is empty - a factor that can only be determined at run-time. In that
111792 ** case, this routine generates code for the xfer optimization but also
111793 ** does a test to see if the destination table is empty and jumps over the
111794 ** xfer optimization code if the test fails. In that case, this routine
111795 ** returns FALSE so that the caller will know to go ahead and generate
111796 ** an unoptimized transfer. This routine also returns FALSE if there
111797 ** is no chance that the xfer optimization can be applied.
111799 ** This optimization is particularly useful at making VACUUM run faster.
111801 static int xferOptimization(
111802 Parse *pParse, /* Parser context */
111803 Table *pDest, /* The table we are inserting into */
111804 Select *pSelect, /* A SELECT statement to use as the data source */
111805 int onError, /* How to handle constraint errors */
111806 int iDbDest /* The database of pDest */
111808 sqlite3 *db = pParse->db;
111809 ExprList *pEList; /* The result set of the SELECT */
111810 Table *pSrc; /* The table in the FROM clause of SELECT */
111811 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
111812 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
111813 int i; /* Loop counter */
111814 int iDbSrc; /* The database of pSrc */
111815 int iSrc, iDest; /* Cursors from source and destination */
111816 int addr1, addr2; /* Loop addresses */
111817 int emptyDestTest = 0; /* Address of test for empty pDest */
111818 int emptySrcTest = 0; /* Address of test for empty pSrc */
111819 Vdbe *v; /* The VDBE we are building */
111820 int regAutoinc; /* Memory register used by AUTOINC */
111821 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
111822 int regData, regRowid; /* Registers holding data and rowid */
111824 if( pSelect==0 ){
111825 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
111827 if( pParse->pWith || pSelect->pWith ){
111828 /* Do not attempt to process this query if there are an WITH clauses
111829 ** attached to it. Proceeding may generate a false "no such table: xxx"
111830 ** error if pSelect reads from a CTE named "xxx". */
111831 return 0;
111833 if( sqlite3TriggerList(pParse, pDest) ){
111834 return 0; /* tab1 must not have triggers */
111836 #ifndef SQLITE_OMIT_VIRTUALTABLE
111837 if( IsVirtual(pDest) ){
111838 return 0; /* tab1 must not be a virtual table */
111840 #endif
111841 if( onError==OE_Default ){
111842 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
111843 if( onError==OE_Default ) onError = OE_Abort;
111845 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
111846 if( pSelect->pSrc->nSrc!=1 ){
111847 return 0; /* FROM clause must have exactly one term */
111849 if( pSelect->pSrc->a[0].pSelect ){
111850 return 0; /* FROM clause cannot contain a subquery */
111852 if( pSelect->pWhere ){
111853 return 0; /* SELECT may not have a WHERE clause */
111855 if( pSelect->pOrderBy ){
111856 return 0; /* SELECT may not have an ORDER BY clause */
111858 /* Do not need to test for a HAVING clause. If HAVING is present but
111859 ** there is no ORDER BY, we will get an error. */
111860 if( pSelect->pGroupBy ){
111861 return 0; /* SELECT may not have a GROUP BY clause */
111863 if( pSelect->pLimit ){
111864 return 0; /* SELECT may not have a LIMIT clause */
111866 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
111867 if( pSelect->pPrior ){
111868 return 0; /* SELECT may not be a compound query */
111870 if( pSelect->selFlags & SF_Distinct ){
111871 return 0; /* SELECT may not be DISTINCT */
111873 pEList = pSelect->pEList;
111874 assert( pEList!=0 );
111875 if( pEList->nExpr!=1 ){
111876 return 0; /* The result set must have exactly one column */
111878 assert( pEList->a[0].pExpr );
111879 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
111880 return 0; /* The result set must be the special operator "*" */
111883 /* At this point we have established that the statement is of the
111884 ** correct syntactic form to participate in this optimization. Now
111885 ** we have to check the semantics.
111887 pItem = pSelect->pSrc->a;
111888 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
111889 if( pSrc==0 ){
111890 return 0; /* FROM clause does not contain a real table */
111892 if( pSrc==pDest ){
111893 return 0; /* tab1 and tab2 may not be the same table */
111895 if( HasRowid(pDest)!=HasRowid(pSrc) ){
111896 return 0; /* source and destination must both be WITHOUT ROWID or not */
111898 #ifndef SQLITE_OMIT_VIRTUALTABLE
111899 if( IsVirtual(pSrc) ){
111900 return 0; /* tab2 must not be a virtual table */
111902 #endif
111903 if( pSrc->pSelect ){
111904 return 0; /* tab2 may not be a view */
111906 if( pDest->nCol!=pSrc->nCol ){
111907 return 0; /* Number of columns must be the same in tab1 and tab2 */
111909 if( pDest->iPKey!=pSrc->iPKey ){
111910 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
111912 for(i=0; i<pDest->nCol; i++){
111913 Column *pDestCol = &pDest->aCol[i];
111914 Column *pSrcCol = &pSrc->aCol[i];
111915 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
111916 if( (db->mDbFlags & DBFLAG_Vacuum)==0
111917 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
111919 return 0; /* Neither table may have __hidden__ columns */
111921 #endif
111922 if( pDestCol->affinity!=pSrcCol->affinity ){
111923 return 0; /* Affinity must be the same on all columns */
111925 if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
111926 return 0; /* Collating sequence must be the same on all columns */
111928 if( pDestCol->notNull && !pSrcCol->notNull ){
111929 return 0; /* tab2 must be NOT NULL if tab1 is */
111931 /* Default values for second and subsequent columns need to match. */
111932 if( i>0 ){
111933 assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
111934 assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
111935 if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
111936 || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
111937 pSrcCol->pDflt->u.zToken)!=0)
111939 return 0; /* Default values must be the same for all columns */
111943 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
111944 if( IsUniqueIndex(pDestIdx) ){
111945 destHasUniqueIdx = 1;
111947 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
111948 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
111950 if( pSrcIdx==0 ){
111951 return 0; /* pDestIdx has no corresponding index in pSrc */
111954 #ifndef SQLITE_OMIT_CHECK
111955 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
111956 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
111958 #endif
111959 #ifndef SQLITE_OMIT_FOREIGN_KEY
111960 /* Disallow the transfer optimization if the destination table constains
111961 ** any foreign key constraints. This is more restrictive than necessary.
111962 ** But the main beneficiary of the transfer optimization is the VACUUM
111963 ** command, and the VACUUM command disables foreign key constraints. So
111964 ** the extra complication to make this rule less restrictive is probably
111965 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
111967 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
111968 return 0;
111970 #endif
111971 if( (db->flags & SQLITE_CountRows)!=0 ){
111972 return 0; /* xfer opt does not play well with PRAGMA count_changes */
111975 /* If we get this far, it means that the xfer optimization is at
111976 ** least a possibility, though it might only work if the destination
111977 ** table (tab1) is initially empty.
111979 #ifdef SQLITE_TEST
111980 sqlite3_xferopt_count++;
111981 #endif
111982 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
111983 v = sqlite3GetVdbe(pParse);
111984 sqlite3CodeVerifySchema(pParse, iDbSrc);
111985 iSrc = pParse->nTab++;
111986 iDest = pParse->nTab++;
111987 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
111988 regData = sqlite3GetTempReg(pParse);
111989 regRowid = sqlite3GetTempReg(pParse);
111990 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
111991 assert( HasRowid(pDest) || destHasUniqueIdx );
111992 if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
111993 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
111994 || destHasUniqueIdx /* (2) */
111995 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
111997 /* In some circumstances, we are able to run the xfer optimization
111998 ** only if the destination table is initially empty. Unless the
111999 ** DBFLAG_Vacuum flag is set, this block generates code to make
112000 ** that determination. If DBFLAG_Vacuum is set, then the destination
112001 ** table is always empty.
112003 ** Conditions under which the destination must be empty:
112005 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
112006 ** (If the destination is not initially empty, the rowid fields
112007 ** of index entries might need to change.)
112009 ** (2) The destination has a unique index. (The xfer optimization
112010 ** is unable to test uniqueness.)
112012 ** (3) onError is something other than OE_Abort and OE_Rollback.
112014 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
112015 emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
112016 sqlite3VdbeJumpHere(v, addr1);
112018 if( HasRowid(pSrc) ){
112019 u8 insFlags;
112020 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
112021 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
112022 if( pDest->iPKey>=0 ){
112023 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
112024 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
112025 VdbeCoverage(v);
112026 sqlite3RowidConstraint(pParse, onError, pDest);
112027 sqlite3VdbeJumpHere(v, addr2);
112028 autoIncStep(pParse, regAutoinc, regRowid);
112029 }else if( pDest->pIndex==0 ){
112030 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
112031 }else{
112032 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
112033 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
112035 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
112036 if( db->mDbFlags & DBFLAG_Vacuum ){
112037 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
112038 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
112039 OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
112040 }else{
112041 insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
112043 sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
112044 (char*)pDest, P4_TABLE);
112045 sqlite3VdbeChangeP5(v, insFlags);
112046 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
112047 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
112048 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
112049 }else{
112050 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
112051 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
112053 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
112054 u8 idxInsFlags = 0;
112055 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
112056 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
112058 assert( pSrcIdx );
112059 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
112060 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
112061 VdbeComment((v, "%s", pSrcIdx->zName));
112062 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
112063 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
112064 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
112065 VdbeComment((v, "%s", pDestIdx->zName));
112066 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
112067 sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
112068 if( db->mDbFlags & DBFLAG_Vacuum ){
112069 /* This INSERT command is part of a VACUUM operation, which guarantees
112070 ** that the destination table is empty. If all indexed columns use
112071 ** collation sequence BINARY, then it can also be assumed that the
112072 ** index will be populated by inserting keys in strictly sorted
112073 ** order. In this case, instead of seeking within the b-tree as part
112074 ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
112075 ** OP_IdxInsert to seek to the point within the b-tree where each key
112076 ** should be inserted. This is faster.
112078 ** If any of the indexed columns use a collation sequence other than
112079 ** BINARY, this optimization is disabled. This is because the user
112080 ** might change the definition of a collation sequence and then run
112081 ** a VACUUM command. In that case keys may not be written in strictly
112082 ** sorted order. */
112083 for(i=0; i<pSrcIdx->nColumn; i++){
112084 const char *zColl = pSrcIdx->azColl[i];
112085 if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
112087 if( i==pSrcIdx->nColumn ){
112088 idxInsFlags = OPFLAG_USESEEKRESULT;
112089 sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
112092 if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
112093 idxInsFlags |= OPFLAG_NCHANGE;
112095 sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
112096 sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
112097 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
112098 sqlite3VdbeJumpHere(v, addr1);
112099 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
112100 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
112102 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
112103 sqlite3ReleaseTempReg(pParse, regRowid);
112104 sqlite3ReleaseTempReg(pParse, regData);
112105 if( emptyDestTest ){
112106 sqlite3AutoincrementEnd(pParse);
112107 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
112108 sqlite3VdbeJumpHere(v, emptyDestTest);
112109 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
112110 return 0;
112111 }else{
112112 return 1;
112115 #endif /* SQLITE_OMIT_XFER_OPT */
112117 /************** End of insert.c **********************************************/
112118 /************** Begin file legacy.c ******************************************/
112120 ** 2001 September 15
112122 ** The author disclaims copyright to this source code. In place of
112123 ** a legal notice, here is a blessing:
112125 ** May you do good and not evil.
112126 ** May you find forgiveness for yourself and forgive others.
112127 ** May you share freely, never taking more than you give.
112129 *************************************************************************
112130 ** Main file for the SQLite library. The routines in this file
112131 ** implement the programmer interface to the library. Routines in
112132 ** other files are for internal use by SQLite and should not be
112133 ** accessed by users of the library.
112136 /* #include "sqliteInt.h" */
112139 ** Execute SQL code. Return one of the SQLITE_ success/failure
112140 ** codes. Also write an error message into memory obtained from
112141 ** malloc() and make *pzErrMsg point to that message.
112143 ** If the SQL is a query, then for each row in the query result
112144 ** the xCallback() function is called. pArg becomes the first
112145 ** argument to xCallback(). If xCallback=NULL then no callback
112146 ** is invoked, even for queries.
112148 SQLITE_API int sqlite3_exec(
112149 sqlite3 *db, /* The database on which the SQL executes */
112150 const char *zSql, /* The SQL to be executed */
112151 sqlite3_callback xCallback, /* Invoke this callback routine */
112152 void *pArg, /* First argument to xCallback() */
112153 char **pzErrMsg /* Write error messages here */
112155 int rc = SQLITE_OK; /* Return code */
112156 const char *zLeftover; /* Tail of unprocessed SQL */
112157 sqlite3_stmt *pStmt = 0; /* The current SQL statement */
112158 char **azCols = 0; /* Names of result columns */
112159 int callbackIsInit; /* True if callback data is initialized */
112161 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
112162 if( zSql==0 ) zSql = "";
112164 sqlite3_mutex_enter(db->mutex);
112165 sqlite3Error(db, SQLITE_OK);
112166 while( rc==SQLITE_OK && zSql[0] ){
112167 int nCol;
112168 char **azVals = 0;
112170 pStmt = 0;
112171 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
112172 assert( rc==SQLITE_OK || pStmt==0 );
112173 if( rc!=SQLITE_OK ){
112174 continue;
112176 if( !pStmt ){
112177 /* this happens for a comment or white-space */
112178 zSql = zLeftover;
112179 continue;
112182 callbackIsInit = 0;
112183 nCol = sqlite3_column_count(pStmt);
112185 while( 1 ){
112186 int i;
112187 rc = sqlite3_step(pStmt);
112189 /* Invoke the callback function if required */
112190 if( xCallback && (SQLITE_ROW==rc ||
112191 (SQLITE_DONE==rc && !callbackIsInit
112192 && db->flags&SQLITE_NullCallback)) ){
112193 if( !callbackIsInit ){
112194 azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
112195 if( azCols==0 ){
112196 goto exec_out;
112198 for(i=0; i<nCol; i++){
112199 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
112200 /* sqlite3VdbeSetColName() installs column names as UTF8
112201 ** strings so there is no way for sqlite3_column_name() to fail. */
112202 assert( azCols[i]!=0 );
112204 callbackIsInit = 1;
112206 if( rc==SQLITE_ROW ){
112207 azVals = &azCols[nCol];
112208 for(i=0; i<nCol; i++){
112209 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
112210 if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
112211 sqlite3OomFault(db);
112212 goto exec_out;
112215 azVals[i] = 0;
112217 if( xCallback(pArg, nCol, azVals, azCols) ){
112218 /* EVIDENCE-OF: R-38229-40159 If the callback function to
112219 ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
112220 ** return SQLITE_ABORT. */
112221 rc = SQLITE_ABORT;
112222 sqlite3VdbeFinalize((Vdbe *)pStmt);
112223 pStmt = 0;
112224 sqlite3Error(db, SQLITE_ABORT);
112225 goto exec_out;
112229 if( rc!=SQLITE_ROW ){
112230 rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
112231 pStmt = 0;
112232 zSql = zLeftover;
112233 while( sqlite3Isspace(zSql[0]) ) zSql++;
112234 break;
112238 sqlite3DbFree(db, azCols);
112239 azCols = 0;
112242 exec_out:
112243 if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
112244 sqlite3DbFree(db, azCols);
112246 rc = sqlite3ApiExit(db, rc);
112247 if( rc!=SQLITE_OK && pzErrMsg ){
112248 *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
112249 if( *pzErrMsg==0 ){
112250 rc = SQLITE_NOMEM_BKPT;
112251 sqlite3Error(db, SQLITE_NOMEM);
112253 }else if( pzErrMsg ){
112254 *pzErrMsg = 0;
112257 assert( (rc&db->errMask)==rc );
112258 sqlite3_mutex_leave(db->mutex);
112259 return rc;
112262 /************** End of legacy.c **********************************************/
112263 /************** Begin file loadext.c *****************************************/
112265 ** 2006 June 7
112267 ** The author disclaims copyright to this source code. In place of
112268 ** a legal notice, here is a blessing:
112270 ** May you do good and not evil.
112271 ** May you find forgiveness for yourself and forgive others.
112272 ** May you share freely, never taking more than you give.
112274 *************************************************************************
112275 ** This file contains code used to dynamically load extensions into
112276 ** the SQLite library.
112279 #ifndef SQLITE_CORE
112280 #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
112281 #endif
112282 /************** Include sqlite3ext.h in the middle of loadext.c **************/
112283 /************** Begin file sqlite3ext.h **************************************/
112285 ** 2006 June 7
112287 ** The author disclaims copyright to this source code. In place of
112288 ** a legal notice, here is a blessing:
112290 ** May you do good and not evil.
112291 ** May you find forgiveness for yourself and forgive others.
112292 ** May you share freely, never taking more than you give.
112294 *************************************************************************
112295 ** This header file defines the SQLite interface for use by
112296 ** shared libraries that want to be imported as extensions into
112297 ** an SQLite instance. Shared libraries that intend to be loaded
112298 ** as extensions by SQLite should #include this file instead of
112299 ** sqlite3.h.
112301 #ifndef SQLITE3EXT_H
112302 #define SQLITE3EXT_H
112303 /* #include "sqlite3.h" */
112306 ** The following structure holds pointers to all of the SQLite API
112307 ** routines.
112309 ** WARNING: In order to maintain backwards compatibility, add new
112310 ** interfaces to the end of this structure only. If you insert new
112311 ** interfaces in the middle of this structure, then older different
112312 ** versions of SQLite will not be able to load each other's shared
112313 ** libraries!
112315 struct sqlite3_api_routines {
112316 void * (*aggregate_context)(sqlite3_context*,int nBytes);
112317 int (*aggregate_count)(sqlite3_context*);
112318 int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
112319 int (*bind_double)(sqlite3_stmt*,int,double);
112320 int (*bind_int)(sqlite3_stmt*,int,int);
112321 int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
112322 int (*bind_null)(sqlite3_stmt*,int);
112323 int (*bind_parameter_count)(sqlite3_stmt*);
112324 int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
112325 const char * (*bind_parameter_name)(sqlite3_stmt*,int);
112326 int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
112327 int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
112328 int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
112329 int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
112330 int (*busy_timeout)(sqlite3*,int ms);
112331 int (*changes)(sqlite3*);
112332 int (*close)(sqlite3*);
112333 int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
112334 int eTextRep,const char*));
112335 int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
112336 int eTextRep,const void*));
112337 const void * (*column_blob)(sqlite3_stmt*,int iCol);
112338 int (*column_bytes)(sqlite3_stmt*,int iCol);
112339 int (*column_bytes16)(sqlite3_stmt*,int iCol);
112340 int (*column_count)(sqlite3_stmt*pStmt);
112341 const char * (*column_database_name)(sqlite3_stmt*,int);
112342 const void * (*column_database_name16)(sqlite3_stmt*,int);
112343 const char * (*column_decltype)(sqlite3_stmt*,int i);
112344 const void * (*column_decltype16)(sqlite3_stmt*,int);
112345 double (*column_double)(sqlite3_stmt*,int iCol);
112346 int (*column_int)(sqlite3_stmt*,int iCol);
112347 sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
112348 const char * (*column_name)(sqlite3_stmt*,int);
112349 const void * (*column_name16)(sqlite3_stmt*,int);
112350 const char * (*column_origin_name)(sqlite3_stmt*,int);
112351 const void * (*column_origin_name16)(sqlite3_stmt*,int);
112352 const char * (*column_table_name)(sqlite3_stmt*,int);
112353 const void * (*column_table_name16)(sqlite3_stmt*,int);
112354 const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
112355 const void * (*column_text16)(sqlite3_stmt*,int iCol);
112356 int (*column_type)(sqlite3_stmt*,int iCol);
112357 sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
112358 void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
112359 int (*complete)(const char*sql);
112360 int (*complete16)(const void*sql);
112361 int (*create_collation)(sqlite3*,const char*,int,void*,
112362 int(*)(void*,int,const void*,int,const void*));
112363 int (*create_collation16)(sqlite3*,const void*,int,void*,
112364 int(*)(void*,int,const void*,int,const void*));
112365 int (*create_function)(sqlite3*,const char*,int,int,void*,
112366 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112367 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112368 void (*xFinal)(sqlite3_context*));
112369 int (*create_function16)(sqlite3*,const void*,int,int,void*,
112370 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112371 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112372 void (*xFinal)(sqlite3_context*));
112373 int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
112374 int (*data_count)(sqlite3_stmt*pStmt);
112375 sqlite3 * (*db_handle)(sqlite3_stmt*);
112376 int (*declare_vtab)(sqlite3*,const char*);
112377 int (*enable_shared_cache)(int);
112378 int (*errcode)(sqlite3*db);
112379 const char * (*errmsg)(sqlite3*);
112380 const void * (*errmsg16)(sqlite3*);
112381 int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
112382 int (*expired)(sqlite3_stmt*);
112383 int (*finalize)(sqlite3_stmt*pStmt);
112384 void (*free)(void*);
112385 void (*free_table)(char**result);
112386 int (*get_autocommit)(sqlite3*);
112387 void * (*get_auxdata)(sqlite3_context*,int);
112388 int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
112389 int (*global_recover)(void);
112390 void (*interruptx)(sqlite3*);
112391 sqlite_int64 (*last_insert_rowid)(sqlite3*);
112392 const char * (*libversion)(void);
112393 int (*libversion_number)(void);
112394 void *(*malloc)(int);
112395 char * (*mprintf)(const char*,...);
112396 int (*open)(const char*,sqlite3**);
112397 int (*open16)(const void*,sqlite3**);
112398 int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
112399 int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
112400 void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
112401 void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
112402 void *(*realloc)(void*,int);
112403 int (*reset)(sqlite3_stmt*pStmt);
112404 void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
112405 void (*result_double)(sqlite3_context*,double);
112406 void (*result_error)(sqlite3_context*,const char*,int);
112407 void (*result_error16)(sqlite3_context*,const void*,int);
112408 void (*result_int)(sqlite3_context*,int);
112409 void (*result_int64)(sqlite3_context*,sqlite_int64);
112410 void (*result_null)(sqlite3_context*);
112411 void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
112412 void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
112413 void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
112414 void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
112415 void (*result_value)(sqlite3_context*,sqlite3_value*);
112416 void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
112417 int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
112418 const char*,const char*),void*);
112419 void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
112420 char * (*xsnprintf)(int,char*,const char*,...);
112421 int (*step)(sqlite3_stmt*);
112422 int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
112423 char const**,char const**,int*,int*,int*);
112424 void (*thread_cleanup)(void);
112425 int (*total_changes)(sqlite3*);
112426 void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
112427 int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
112428 void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
112429 sqlite_int64),void*);
112430 void * (*user_data)(sqlite3_context*);
112431 const void * (*value_blob)(sqlite3_value*);
112432 int (*value_bytes)(sqlite3_value*);
112433 int (*value_bytes16)(sqlite3_value*);
112434 double (*value_double)(sqlite3_value*);
112435 int (*value_int)(sqlite3_value*);
112436 sqlite_int64 (*value_int64)(sqlite3_value*);
112437 int (*value_numeric_type)(sqlite3_value*);
112438 const unsigned char * (*value_text)(sqlite3_value*);
112439 const void * (*value_text16)(sqlite3_value*);
112440 const void * (*value_text16be)(sqlite3_value*);
112441 const void * (*value_text16le)(sqlite3_value*);
112442 int (*value_type)(sqlite3_value*);
112443 char *(*vmprintf)(const char*,va_list);
112444 /* Added ??? */
112445 int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
112446 /* Added by 3.3.13 */
112447 int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
112448 int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
112449 int (*clear_bindings)(sqlite3_stmt*);
112450 /* Added by 3.4.1 */
112451 int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
112452 void (*xDestroy)(void *));
112453 /* Added by 3.5.0 */
112454 int (*bind_zeroblob)(sqlite3_stmt*,int,int);
112455 int (*blob_bytes)(sqlite3_blob*);
112456 int (*blob_close)(sqlite3_blob*);
112457 int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
112458 int,sqlite3_blob**);
112459 int (*blob_read)(sqlite3_blob*,void*,int,int);
112460 int (*blob_write)(sqlite3_blob*,const void*,int,int);
112461 int (*create_collation_v2)(sqlite3*,const char*,int,void*,
112462 int(*)(void*,int,const void*,int,const void*),
112463 void(*)(void*));
112464 int (*file_control)(sqlite3*,const char*,int,void*);
112465 sqlite3_int64 (*memory_highwater)(int);
112466 sqlite3_int64 (*memory_used)(void);
112467 sqlite3_mutex *(*mutex_alloc)(int);
112468 void (*mutex_enter)(sqlite3_mutex*);
112469 void (*mutex_free)(sqlite3_mutex*);
112470 void (*mutex_leave)(sqlite3_mutex*);
112471 int (*mutex_try)(sqlite3_mutex*);
112472 int (*open_v2)(const char*,sqlite3**,int,const char*);
112473 int (*release_memory)(int);
112474 void (*result_error_nomem)(sqlite3_context*);
112475 void (*result_error_toobig)(sqlite3_context*);
112476 int (*sleep)(int);
112477 void (*soft_heap_limit)(int);
112478 sqlite3_vfs *(*vfs_find)(const char*);
112479 int (*vfs_register)(sqlite3_vfs*,int);
112480 int (*vfs_unregister)(sqlite3_vfs*);
112481 int (*xthreadsafe)(void);
112482 void (*result_zeroblob)(sqlite3_context*,int);
112483 void (*result_error_code)(sqlite3_context*,int);
112484 int (*test_control)(int, ...);
112485 void (*randomness)(int,void*);
112486 sqlite3 *(*context_db_handle)(sqlite3_context*);
112487 int (*extended_result_codes)(sqlite3*,int);
112488 int (*limit)(sqlite3*,int,int);
112489 sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
112490 const char *(*sql)(sqlite3_stmt*);
112491 int (*status)(int,int*,int*,int);
112492 int (*backup_finish)(sqlite3_backup*);
112493 sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
112494 int (*backup_pagecount)(sqlite3_backup*);
112495 int (*backup_remaining)(sqlite3_backup*);
112496 int (*backup_step)(sqlite3_backup*,int);
112497 const char *(*compileoption_get)(int);
112498 int (*compileoption_used)(const char*);
112499 int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
112500 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112501 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112502 void (*xFinal)(sqlite3_context*),
112503 void(*xDestroy)(void*));
112504 int (*db_config)(sqlite3*,int,...);
112505 sqlite3_mutex *(*db_mutex)(sqlite3*);
112506 int (*db_status)(sqlite3*,int,int*,int*,int);
112507 int (*extended_errcode)(sqlite3*);
112508 void (*log)(int,const char*,...);
112509 sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
112510 const char *(*sourceid)(void);
112511 int (*stmt_status)(sqlite3_stmt*,int,int);
112512 int (*strnicmp)(const char*,const char*,int);
112513 int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
112514 int (*wal_autocheckpoint)(sqlite3*,int);
112515 int (*wal_checkpoint)(sqlite3*,const char*);
112516 void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
112517 int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
112518 int (*vtab_config)(sqlite3*,int op,...);
112519 int (*vtab_on_conflict)(sqlite3*);
112520 /* Version 3.7.16 and later */
112521 int (*close_v2)(sqlite3*);
112522 const char *(*db_filename)(sqlite3*,const char*);
112523 int (*db_readonly)(sqlite3*,const char*);
112524 int (*db_release_memory)(sqlite3*);
112525 const char *(*errstr)(int);
112526 int (*stmt_busy)(sqlite3_stmt*);
112527 int (*stmt_readonly)(sqlite3_stmt*);
112528 int (*stricmp)(const char*,const char*);
112529 int (*uri_boolean)(const char*,const char*,int);
112530 sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
112531 const char *(*uri_parameter)(const char*,const char*);
112532 char *(*xvsnprintf)(int,char*,const char*,va_list);
112533 int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
112534 /* Version 3.8.7 and later */
112535 int (*auto_extension)(void(*)(void));
112536 int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
112537 void(*)(void*));
112538 int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
112539 void(*)(void*),unsigned char);
112540 int (*cancel_auto_extension)(void(*)(void));
112541 int (*load_extension)(sqlite3*,const char*,const char*,char**);
112542 void *(*malloc64)(sqlite3_uint64);
112543 sqlite3_uint64 (*msize)(void*);
112544 void *(*realloc64)(void*,sqlite3_uint64);
112545 void (*reset_auto_extension)(void);
112546 void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
112547 void(*)(void*));
112548 void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
112549 void(*)(void*), unsigned char);
112550 int (*strglob)(const char*,const char*);
112551 /* Version 3.8.11 and later */
112552 sqlite3_value *(*value_dup)(const sqlite3_value*);
112553 void (*value_free)(sqlite3_value*);
112554 int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
112555 int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
112556 /* Version 3.9.0 and later */
112557 unsigned int (*value_subtype)(sqlite3_value*);
112558 void (*result_subtype)(sqlite3_context*,unsigned int);
112559 /* Version 3.10.0 and later */
112560 int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
112561 int (*strlike)(const char*,const char*,unsigned int);
112562 int (*db_cacheflush)(sqlite3*);
112563 /* Version 3.12.0 and later */
112564 int (*system_errno)(sqlite3*);
112565 /* Version 3.14.0 and later */
112566 int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
112567 char *(*expanded_sql)(sqlite3_stmt*);
112568 /* Version 3.18.0 and later */
112569 void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
112570 /* Version 3.20.0 and later */
112571 int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
112572 sqlite3_stmt**,const char**);
112573 int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
112574 sqlite3_stmt**,const void**);
112575 int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
112576 void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
112577 void *(*value_pointer)(sqlite3_value*,const char*);
112581 ** This is the function signature used for all extension entry points. It
112582 ** is also defined in the file "loadext.c".
112584 typedef int (*sqlite3_loadext_entry)(
112585 sqlite3 *db, /* Handle to the database. */
112586 char **pzErrMsg, /* Used to set error string on failure. */
112587 const sqlite3_api_routines *pThunk /* Extension API function pointers. */
112591 ** The following macros redefine the API routines so that they are
112592 ** redirected through the global sqlite3_api structure.
112594 ** This header file is also used by the loadext.c source file
112595 ** (part of the main SQLite library - not an extension) so that
112596 ** it can get access to the sqlite3_api_routines structure
112597 ** definition. But the main library does not want to redefine
112598 ** the API. So the redefinition macros are only valid if the
112599 ** SQLITE_CORE macros is undefined.
112601 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
112602 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
112603 #ifndef SQLITE_OMIT_DEPRECATED
112604 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
112605 #endif
112606 #define sqlite3_bind_blob sqlite3_api->bind_blob
112607 #define sqlite3_bind_double sqlite3_api->bind_double
112608 #define sqlite3_bind_int sqlite3_api->bind_int
112609 #define sqlite3_bind_int64 sqlite3_api->bind_int64
112610 #define sqlite3_bind_null sqlite3_api->bind_null
112611 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
112612 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
112613 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
112614 #define sqlite3_bind_text sqlite3_api->bind_text
112615 #define sqlite3_bind_text16 sqlite3_api->bind_text16
112616 #define sqlite3_bind_value sqlite3_api->bind_value
112617 #define sqlite3_busy_handler sqlite3_api->busy_handler
112618 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
112619 #define sqlite3_changes sqlite3_api->changes
112620 #define sqlite3_close sqlite3_api->close
112621 #define sqlite3_collation_needed sqlite3_api->collation_needed
112622 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
112623 #define sqlite3_column_blob sqlite3_api->column_blob
112624 #define sqlite3_column_bytes sqlite3_api->column_bytes
112625 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
112626 #define sqlite3_column_count sqlite3_api->column_count
112627 #define sqlite3_column_database_name sqlite3_api->column_database_name
112628 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
112629 #define sqlite3_column_decltype sqlite3_api->column_decltype
112630 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
112631 #define sqlite3_column_double sqlite3_api->column_double
112632 #define sqlite3_column_int sqlite3_api->column_int
112633 #define sqlite3_column_int64 sqlite3_api->column_int64
112634 #define sqlite3_column_name sqlite3_api->column_name
112635 #define sqlite3_column_name16 sqlite3_api->column_name16
112636 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
112637 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
112638 #define sqlite3_column_table_name sqlite3_api->column_table_name
112639 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
112640 #define sqlite3_column_text sqlite3_api->column_text
112641 #define sqlite3_column_text16 sqlite3_api->column_text16
112642 #define sqlite3_column_type sqlite3_api->column_type
112643 #define sqlite3_column_value sqlite3_api->column_value
112644 #define sqlite3_commit_hook sqlite3_api->commit_hook
112645 #define sqlite3_complete sqlite3_api->complete
112646 #define sqlite3_complete16 sqlite3_api->complete16
112647 #define sqlite3_create_collation sqlite3_api->create_collation
112648 #define sqlite3_create_collation16 sqlite3_api->create_collation16
112649 #define sqlite3_create_function sqlite3_api->create_function
112650 #define sqlite3_create_function16 sqlite3_api->create_function16
112651 #define sqlite3_create_module sqlite3_api->create_module
112652 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
112653 #define sqlite3_data_count sqlite3_api->data_count
112654 #define sqlite3_db_handle sqlite3_api->db_handle
112655 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
112656 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
112657 #define sqlite3_errcode sqlite3_api->errcode
112658 #define sqlite3_errmsg sqlite3_api->errmsg
112659 #define sqlite3_errmsg16 sqlite3_api->errmsg16
112660 #define sqlite3_exec sqlite3_api->exec
112661 #ifndef SQLITE_OMIT_DEPRECATED
112662 #define sqlite3_expired sqlite3_api->expired
112663 #endif
112664 #define sqlite3_finalize sqlite3_api->finalize
112665 #define sqlite3_free sqlite3_api->free
112666 #define sqlite3_free_table sqlite3_api->free_table
112667 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
112668 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
112669 #define sqlite3_get_table sqlite3_api->get_table
112670 #ifndef SQLITE_OMIT_DEPRECATED
112671 #define sqlite3_global_recover sqlite3_api->global_recover
112672 #endif
112673 #define sqlite3_interrupt sqlite3_api->interruptx
112674 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
112675 #define sqlite3_libversion sqlite3_api->libversion
112676 #define sqlite3_libversion_number sqlite3_api->libversion_number
112677 #define sqlite3_malloc sqlite3_api->malloc
112678 #define sqlite3_mprintf sqlite3_api->mprintf
112679 #define sqlite3_open sqlite3_api->open
112680 #define sqlite3_open16 sqlite3_api->open16
112681 #define sqlite3_prepare sqlite3_api->prepare
112682 #define sqlite3_prepare16 sqlite3_api->prepare16
112683 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
112684 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
112685 #define sqlite3_profile sqlite3_api->profile
112686 #define sqlite3_progress_handler sqlite3_api->progress_handler
112687 #define sqlite3_realloc sqlite3_api->realloc
112688 #define sqlite3_reset sqlite3_api->reset
112689 #define sqlite3_result_blob sqlite3_api->result_blob
112690 #define sqlite3_result_double sqlite3_api->result_double
112691 #define sqlite3_result_error sqlite3_api->result_error
112692 #define sqlite3_result_error16 sqlite3_api->result_error16
112693 #define sqlite3_result_int sqlite3_api->result_int
112694 #define sqlite3_result_int64 sqlite3_api->result_int64
112695 #define sqlite3_result_null sqlite3_api->result_null
112696 #define sqlite3_result_text sqlite3_api->result_text
112697 #define sqlite3_result_text16 sqlite3_api->result_text16
112698 #define sqlite3_result_text16be sqlite3_api->result_text16be
112699 #define sqlite3_result_text16le sqlite3_api->result_text16le
112700 #define sqlite3_result_value sqlite3_api->result_value
112701 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
112702 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
112703 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
112704 #define sqlite3_snprintf sqlite3_api->xsnprintf
112705 #define sqlite3_step sqlite3_api->step
112706 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
112707 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
112708 #define sqlite3_total_changes sqlite3_api->total_changes
112709 #define sqlite3_trace sqlite3_api->trace
112710 #ifndef SQLITE_OMIT_DEPRECATED
112711 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
112712 #endif
112713 #define sqlite3_update_hook sqlite3_api->update_hook
112714 #define sqlite3_user_data sqlite3_api->user_data
112715 #define sqlite3_value_blob sqlite3_api->value_blob
112716 #define sqlite3_value_bytes sqlite3_api->value_bytes
112717 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
112718 #define sqlite3_value_double sqlite3_api->value_double
112719 #define sqlite3_value_int sqlite3_api->value_int
112720 #define sqlite3_value_int64 sqlite3_api->value_int64
112721 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
112722 #define sqlite3_value_text sqlite3_api->value_text
112723 #define sqlite3_value_text16 sqlite3_api->value_text16
112724 #define sqlite3_value_text16be sqlite3_api->value_text16be
112725 #define sqlite3_value_text16le sqlite3_api->value_text16le
112726 #define sqlite3_value_type sqlite3_api->value_type
112727 #define sqlite3_vmprintf sqlite3_api->vmprintf
112728 #define sqlite3_vsnprintf sqlite3_api->xvsnprintf
112729 #define sqlite3_overload_function sqlite3_api->overload_function
112730 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
112731 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
112732 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
112733 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
112734 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
112735 #define sqlite3_blob_close sqlite3_api->blob_close
112736 #define sqlite3_blob_open sqlite3_api->blob_open
112737 #define sqlite3_blob_read sqlite3_api->blob_read
112738 #define sqlite3_blob_write sqlite3_api->blob_write
112739 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
112740 #define sqlite3_file_control sqlite3_api->file_control
112741 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
112742 #define sqlite3_memory_used sqlite3_api->memory_used
112743 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
112744 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
112745 #define sqlite3_mutex_free sqlite3_api->mutex_free
112746 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
112747 #define sqlite3_mutex_try sqlite3_api->mutex_try
112748 #define sqlite3_open_v2 sqlite3_api->open_v2
112749 #define sqlite3_release_memory sqlite3_api->release_memory
112750 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
112751 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
112752 #define sqlite3_sleep sqlite3_api->sleep
112753 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
112754 #define sqlite3_vfs_find sqlite3_api->vfs_find
112755 #define sqlite3_vfs_register sqlite3_api->vfs_register
112756 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
112757 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
112758 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
112759 #define sqlite3_result_error_code sqlite3_api->result_error_code
112760 #define sqlite3_test_control sqlite3_api->test_control
112761 #define sqlite3_randomness sqlite3_api->randomness
112762 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
112763 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
112764 #define sqlite3_limit sqlite3_api->limit
112765 #define sqlite3_next_stmt sqlite3_api->next_stmt
112766 #define sqlite3_sql sqlite3_api->sql
112767 #define sqlite3_status sqlite3_api->status
112768 #define sqlite3_backup_finish sqlite3_api->backup_finish
112769 #define sqlite3_backup_init sqlite3_api->backup_init
112770 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
112771 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
112772 #define sqlite3_backup_step sqlite3_api->backup_step
112773 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
112774 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
112775 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
112776 #define sqlite3_db_config sqlite3_api->db_config
112777 #define sqlite3_db_mutex sqlite3_api->db_mutex
112778 #define sqlite3_db_status sqlite3_api->db_status
112779 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
112780 #define sqlite3_log sqlite3_api->log
112781 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
112782 #define sqlite3_sourceid sqlite3_api->sourceid
112783 #define sqlite3_stmt_status sqlite3_api->stmt_status
112784 #define sqlite3_strnicmp sqlite3_api->strnicmp
112785 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
112786 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
112787 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
112788 #define sqlite3_wal_hook sqlite3_api->wal_hook
112789 #define sqlite3_blob_reopen sqlite3_api->blob_reopen
112790 #define sqlite3_vtab_config sqlite3_api->vtab_config
112791 #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
112792 /* Version 3.7.16 and later */
112793 #define sqlite3_close_v2 sqlite3_api->close_v2
112794 #define sqlite3_db_filename sqlite3_api->db_filename
112795 #define sqlite3_db_readonly sqlite3_api->db_readonly
112796 #define sqlite3_db_release_memory sqlite3_api->db_release_memory
112797 #define sqlite3_errstr sqlite3_api->errstr
112798 #define sqlite3_stmt_busy sqlite3_api->stmt_busy
112799 #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
112800 #define sqlite3_stricmp sqlite3_api->stricmp
112801 #define sqlite3_uri_boolean sqlite3_api->uri_boolean
112802 #define sqlite3_uri_int64 sqlite3_api->uri_int64
112803 #define sqlite3_uri_parameter sqlite3_api->uri_parameter
112804 #define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
112805 #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
112806 /* Version 3.8.7 and later */
112807 #define sqlite3_auto_extension sqlite3_api->auto_extension
112808 #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
112809 #define sqlite3_bind_text64 sqlite3_api->bind_text64
112810 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
112811 #define sqlite3_load_extension sqlite3_api->load_extension
112812 #define sqlite3_malloc64 sqlite3_api->malloc64
112813 #define sqlite3_msize sqlite3_api->msize
112814 #define sqlite3_realloc64 sqlite3_api->realloc64
112815 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
112816 #define sqlite3_result_blob64 sqlite3_api->result_blob64
112817 #define sqlite3_result_text64 sqlite3_api->result_text64
112818 #define sqlite3_strglob sqlite3_api->strglob
112819 /* Version 3.8.11 and later */
112820 #define sqlite3_value_dup sqlite3_api->value_dup
112821 #define sqlite3_value_free sqlite3_api->value_free
112822 #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
112823 #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
112824 /* Version 3.9.0 and later */
112825 #define sqlite3_value_subtype sqlite3_api->value_subtype
112826 #define sqlite3_result_subtype sqlite3_api->result_subtype
112827 /* Version 3.10.0 and later */
112828 #define sqlite3_status64 sqlite3_api->status64
112829 #define sqlite3_strlike sqlite3_api->strlike
112830 #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
112831 /* Version 3.12.0 and later */
112832 #define sqlite3_system_errno sqlite3_api->system_errno
112833 /* Version 3.14.0 and later */
112834 #define sqlite3_trace_v2 sqlite3_api->trace_v2
112835 #define sqlite3_expanded_sql sqlite3_api->expanded_sql
112836 /* Version 3.18.0 and later */
112837 #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
112838 /* Version 3.20.0 and later */
112839 #define sqlite3_prepare_v3 sqlite3_api->prepare_v3
112840 #define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
112841 #define sqlite3_bind_pointer sqlite3_api->bind_pointer
112842 #define sqlite3_result_pointer sqlite3_api->result_pointer
112843 #define sqlite3_value_pointer sqlite3_api->value_pointer
112844 #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
112846 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
112847 /* This case when the file really is being compiled as a loadable
112848 ** extension */
112849 # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
112850 # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
112851 # define SQLITE_EXTENSION_INIT3 \
112852 extern const sqlite3_api_routines *sqlite3_api;
112853 #else
112854 /* This case when the file is being statically linked into the
112855 ** application */
112856 # define SQLITE_EXTENSION_INIT1 /*no-op*/
112857 # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
112858 # define SQLITE_EXTENSION_INIT3 /*no-op*/
112859 #endif
112861 #endif /* SQLITE3EXT_H */
112863 /************** End of sqlite3ext.h ******************************************/
112864 /************** Continuing where we left off in loadext.c ********************/
112865 /* #include "sqliteInt.h" */
112867 #ifndef SQLITE_OMIT_LOAD_EXTENSION
112869 ** Some API routines are omitted when various features are
112870 ** excluded from a build of SQLite. Substitute a NULL pointer
112871 ** for any missing APIs.
112873 #ifndef SQLITE_ENABLE_COLUMN_METADATA
112874 # define sqlite3_column_database_name 0
112875 # define sqlite3_column_database_name16 0
112876 # define sqlite3_column_table_name 0
112877 # define sqlite3_column_table_name16 0
112878 # define sqlite3_column_origin_name 0
112879 # define sqlite3_column_origin_name16 0
112880 #endif
112882 #ifdef SQLITE_OMIT_AUTHORIZATION
112883 # define sqlite3_set_authorizer 0
112884 #endif
112886 #ifdef SQLITE_OMIT_UTF16
112887 # define sqlite3_bind_text16 0
112888 # define sqlite3_collation_needed16 0
112889 # define sqlite3_column_decltype16 0
112890 # define sqlite3_column_name16 0
112891 # define sqlite3_column_text16 0
112892 # define sqlite3_complete16 0
112893 # define sqlite3_create_collation16 0
112894 # define sqlite3_create_function16 0
112895 # define sqlite3_errmsg16 0
112896 # define sqlite3_open16 0
112897 # define sqlite3_prepare16 0
112898 # define sqlite3_prepare16_v2 0
112899 # define sqlite3_prepare16_v3 0
112900 # define sqlite3_result_error16 0
112901 # define sqlite3_result_text16 0
112902 # define sqlite3_result_text16be 0
112903 # define sqlite3_result_text16le 0
112904 # define sqlite3_value_text16 0
112905 # define sqlite3_value_text16be 0
112906 # define sqlite3_value_text16le 0
112907 # define sqlite3_column_database_name16 0
112908 # define sqlite3_column_table_name16 0
112909 # define sqlite3_column_origin_name16 0
112910 #endif
112912 #ifdef SQLITE_OMIT_COMPLETE
112913 # define sqlite3_complete 0
112914 # define sqlite3_complete16 0
112915 #endif
112917 #ifdef SQLITE_OMIT_DECLTYPE
112918 # define sqlite3_column_decltype16 0
112919 # define sqlite3_column_decltype 0
112920 #endif
112922 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
112923 # define sqlite3_progress_handler 0
112924 #endif
112926 #ifdef SQLITE_OMIT_VIRTUALTABLE
112927 # define sqlite3_create_module 0
112928 # define sqlite3_create_module_v2 0
112929 # define sqlite3_declare_vtab 0
112930 # define sqlite3_vtab_config 0
112931 # define sqlite3_vtab_on_conflict 0
112932 #endif
112934 #ifdef SQLITE_OMIT_SHARED_CACHE
112935 # define sqlite3_enable_shared_cache 0
112936 #endif
112938 #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
112939 # define sqlite3_profile 0
112940 # define sqlite3_trace 0
112941 #endif
112943 #ifdef SQLITE_OMIT_GET_TABLE
112944 # define sqlite3_free_table 0
112945 # define sqlite3_get_table 0
112946 #endif
112948 #ifdef SQLITE_OMIT_INCRBLOB
112949 #define sqlite3_bind_zeroblob 0
112950 #define sqlite3_blob_bytes 0
112951 #define sqlite3_blob_close 0
112952 #define sqlite3_blob_open 0
112953 #define sqlite3_blob_read 0
112954 #define sqlite3_blob_write 0
112955 #define sqlite3_blob_reopen 0
112956 #endif
112958 #if defined(SQLITE_OMIT_TRACE)
112959 # define sqlite3_trace_v2 0
112960 #endif
112963 ** The following structure contains pointers to all SQLite API routines.
112964 ** A pointer to this structure is passed into extensions when they are
112965 ** loaded so that the extension can make calls back into the SQLite
112966 ** library.
112968 ** When adding new APIs, add them to the bottom of this structure
112969 ** in order to preserve backwards compatibility.
112971 ** Extensions that use newer APIs should first call the
112972 ** sqlite3_libversion_number() to make sure that the API they
112973 ** intend to use is supported by the library. Extensions should
112974 ** also check to make sure that the pointer to the function is
112975 ** not NULL before calling it.
112977 static const sqlite3_api_routines sqlite3Apis = {
112978 sqlite3_aggregate_context,
112979 #ifndef SQLITE_OMIT_DEPRECATED
112980 sqlite3_aggregate_count,
112981 #else
112983 #endif
112984 sqlite3_bind_blob,
112985 sqlite3_bind_double,
112986 sqlite3_bind_int,
112987 sqlite3_bind_int64,
112988 sqlite3_bind_null,
112989 sqlite3_bind_parameter_count,
112990 sqlite3_bind_parameter_index,
112991 sqlite3_bind_parameter_name,
112992 sqlite3_bind_text,
112993 sqlite3_bind_text16,
112994 sqlite3_bind_value,
112995 sqlite3_busy_handler,
112996 sqlite3_busy_timeout,
112997 sqlite3_changes,
112998 sqlite3_close,
112999 sqlite3_collation_needed,
113000 sqlite3_collation_needed16,
113001 sqlite3_column_blob,
113002 sqlite3_column_bytes,
113003 sqlite3_column_bytes16,
113004 sqlite3_column_count,
113005 sqlite3_column_database_name,
113006 sqlite3_column_database_name16,
113007 sqlite3_column_decltype,
113008 sqlite3_column_decltype16,
113009 sqlite3_column_double,
113010 sqlite3_column_int,
113011 sqlite3_column_int64,
113012 sqlite3_column_name,
113013 sqlite3_column_name16,
113014 sqlite3_column_origin_name,
113015 sqlite3_column_origin_name16,
113016 sqlite3_column_table_name,
113017 sqlite3_column_table_name16,
113018 sqlite3_column_text,
113019 sqlite3_column_text16,
113020 sqlite3_column_type,
113021 sqlite3_column_value,
113022 sqlite3_commit_hook,
113023 sqlite3_complete,
113024 sqlite3_complete16,
113025 sqlite3_create_collation,
113026 sqlite3_create_collation16,
113027 sqlite3_create_function,
113028 sqlite3_create_function16,
113029 sqlite3_create_module,
113030 sqlite3_data_count,
113031 sqlite3_db_handle,
113032 sqlite3_declare_vtab,
113033 sqlite3_enable_shared_cache,
113034 sqlite3_errcode,
113035 sqlite3_errmsg,
113036 sqlite3_errmsg16,
113037 sqlite3_exec,
113038 #ifndef SQLITE_OMIT_DEPRECATED
113039 sqlite3_expired,
113040 #else
113042 #endif
113043 sqlite3_finalize,
113044 sqlite3_free,
113045 sqlite3_free_table,
113046 sqlite3_get_autocommit,
113047 sqlite3_get_auxdata,
113048 sqlite3_get_table,
113049 0, /* Was sqlite3_global_recover(), but that function is deprecated */
113050 sqlite3_interrupt,
113051 sqlite3_last_insert_rowid,
113052 sqlite3_libversion,
113053 sqlite3_libversion_number,
113054 sqlite3_malloc,
113055 sqlite3_mprintf,
113056 sqlite3_open,
113057 sqlite3_open16,
113058 sqlite3_prepare,
113059 sqlite3_prepare16,
113060 sqlite3_profile,
113061 sqlite3_progress_handler,
113062 sqlite3_realloc,
113063 sqlite3_reset,
113064 sqlite3_result_blob,
113065 sqlite3_result_double,
113066 sqlite3_result_error,
113067 sqlite3_result_error16,
113068 sqlite3_result_int,
113069 sqlite3_result_int64,
113070 sqlite3_result_null,
113071 sqlite3_result_text,
113072 sqlite3_result_text16,
113073 sqlite3_result_text16be,
113074 sqlite3_result_text16le,
113075 sqlite3_result_value,
113076 sqlite3_rollback_hook,
113077 sqlite3_set_authorizer,
113078 sqlite3_set_auxdata,
113079 sqlite3_snprintf,
113080 sqlite3_step,
113081 sqlite3_table_column_metadata,
113082 #ifndef SQLITE_OMIT_DEPRECATED
113083 sqlite3_thread_cleanup,
113084 #else
113086 #endif
113087 sqlite3_total_changes,
113088 sqlite3_trace,
113089 #ifndef SQLITE_OMIT_DEPRECATED
113090 sqlite3_transfer_bindings,
113091 #else
113093 #endif
113094 sqlite3_update_hook,
113095 sqlite3_user_data,
113096 sqlite3_value_blob,
113097 sqlite3_value_bytes,
113098 sqlite3_value_bytes16,
113099 sqlite3_value_double,
113100 sqlite3_value_int,
113101 sqlite3_value_int64,
113102 sqlite3_value_numeric_type,
113103 sqlite3_value_text,
113104 sqlite3_value_text16,
113105 sqlite3_value_text16be,
113106 sqlite3_value_text16le,
113107 sqlite3_value_type,
113108 sqlite3_vmprintf,
113110 ** The original API set ends here. All extensions can call any
113111 ** of the APIs above provided that the pointer is not NULL. But
113112 ** before calling APIs that follow, extension should check the
113113 ** sqlite3_libversion_number() to make sure they are dealing with
113114 ** a library that is new enough to support that API.
113115 *************************************************************************
113117 sqlite3_overload_function,
113120 ** Added after 3.3.13
113122 sqlite3_prepare_v2,
113123 sqlite3_prepare16_v2,
113124 sqlite3_clear_bindings,
113127 ** Added for 3.4.1
113129 sqlite3_create_module_v2,
113132 ** Added for 3.5.0
113134 sqlite3_bind_zeroblob,
113135 sqlite3_blob_bytes,
113136 sqlite3_blob_close,
113137 sqlite3_blob_open,
113138 sqlite3_blob_read,
113139 sqlite3_blob_write,
113140 sqlite3_create_collation_v2,
113141 sqlite3_file_control,
113142 sqlite3_memory_highwater,
113143 sqlite3_memory_used,
113144 #ifdef SQLITE_MUTEX_OMIT
113150 #else
113151 sqlite3_mutex_alloc,
113152 sqlite3_mutex_enter,
113153 sqlite3_mutex_free,
113154 sqlite3_mutex_leave,
113155 sqlite3_mutex_try,
113156 #endif
113157 sqlite3_open_v2,
113158 sqlite3_release_memory,
113159 sqlite3_result_error_nomem,
113160 sqlite3_result_error_toobig,
113161 sqlite3_sleep,
113162 sqlite3_soft_heap_limit,
113163 sqlite3_vfs_find,
113164 sqlite3_vfs_register,
113165 sqlite3_vfs_unregister,
113168 ** Added for 3.5.8
113170 sqlite3_threadsafe,
113171 sqlite3_result_zeroblob,
113172 sqlite3_result_error_code,
113173 sqlite3_test_control,
113174 sqlite3_randomness,
113175 sqlite3_context_db_handle,
113178 ** Added for 3.6.0
113180 sqlite3_extended_result_codes,
113181 sqlite3_limit,
113182 sqlite3_next_stmt,
113183 sqlite3_sql,
113184 sqlite3_status,
113187 ** Added for 3.7.4
113189 sqlite3_backup_finish,
113190 sqlite3_backup_init,
113191 sqlite3_backup_pagecount,
113192 sqlite3_backup_remaining,
113193 sqlite3_backup_step,
113194 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
113195 sqlite3_compileoption_get,
113196 sqlite3_compileoption_used,
113197 #else
113200 #endif
113201 sqlite3_create_function_v2,
113202 sqlite3_db_config,
113203 sqlite3_db_mutex,
113204 sqlite3_db_status,
113205 sqlite3_extended_errcode,
113206 sqlite3_log,
113207 sqlite3_soft_heap_limit64,
113208 sqlite3_sourceid,
113209 sqlite3_stmt_status,
113210 sqlite3_strnicmp,
113211 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
113212 sqlite3_unlock_notify,
113213 #else
113215 #endif
113216 #ifndef SQLITE_OMIT_WAL
113217 sqlite3_wal_autocheckpoint,
113218 sqlite3_wal_checkpoint,
113219 sqlite3_wal_hook,
113220 #else
113224 #endif
113225 sqlite3_blob_reopen,
113226 sqlite3_vtab_config,
113227 sqlite3_vtab_on_conflict,
113228 sqlite3_close_v2,
113229 sqlite3_db_filename,
113230 sqlite3_db_readonly,
113231 sqlite3_db_release_memory,
113232 sqlite3_errstr,
113233 sqlite3_stmt_busy,
113234 sqlite3_stmt_readonly,
113235 sqlite3_stricmp,
113236 sqlite3_uri_boolean,
113237 sqlite3_uri_int64,
113238 sqlite3_uri_parameter,
113239 sqlite3_vsnprintf,
113240 sqlite3_wal_checkpoint_v2,
113241 /* Version 3.8.7 and later */
113242 sqlite3_auto_extension,
113243 sqlite3_bind_blob64,
113244 sqlite3_bind_text64,
113245 sqlite3_cancel_auto_extension,
113246 sqlite3_load_extension,
113247 sqlite3_malloc64,
113248 sqlite3_msize,
113249 sqlite3_realloc64,
113250 sqlite3_reset_auto_extension,
113251 sqlite3_result_blob64,
113252 sqlite3_result_text64,
113253 sqlite3_strglob,
113254 /* Version 3.8.11 and later */
113255 (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
113256 sqlite3_value_free,
113257 sqlite3_result_zeroblob64,
113258 sqlite3_bind_zeroblob64,
113259 /* Version 3.9.0 and later */
113260 sqlite3_value_subtype,
113261 sqlite3_result_subtype,
113262 /* Version 3.10.0 and later */
113263 sqlite3_status64,
113264 sqlite3_strlike,
113265 sqlite3_db_cacheflush,
113266 /* Version 3.12.0 and later */
113267 sqlite3_system_errno,
113268 /* Version 3.14.0 and later */
113269 sqlite3_trace_v2,
113270 sqlite3_expanded_sql,
113271 /* Version 3.18.0 and later */
113272 sqlite3_set_last_insert_rowid,
113273 /* Version 3.20.0 and later */
113274 sqlite3_prepare_v3,
113275 sqlite3_prepare16_v3,
113276 sqlite3_bind_pointer,
113277 sqlite3_result_pointer,
113278 sqlite3_value_pointer
113282 ** Attempt to load an SQLite extension library contained in the file
113283 ** zFile. The entry point is zProc. zProc may be 0 in which case a
113284 ** default entry point name (sqlite3_extension_init) is used. Use
113285 ** of the default name is recommended.
113287 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
113289 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
113290 ** error message text. The calling function should free this memory
113291 ** by calling sqlite3DbFree(db, ).
113293 static int sqlite3LoadExtension(
113294 sqlite3 *db, /* Load the extension into this database connection */
113295 const char *zFile, /* Name of the shared library containing extension */
113296 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
113297 char **pzErrMsg /* Put error message here if not 0 */
113299 sqlite3_vfs *pVfs = db->pVfs;
113300 void *handle;
113301 sqlite3_loadext_entry xInit;
113302 char *zErrmsg = 0;
113303 const char *zEntry;
113304 char *zAltEntry = 0;
113305 void **aHandle;
113306 u64 nMsg = 300 + sqlite3Strlen30(zFile);
113307 int ii;
113308 int rc;
113310 /* Shared library endings to try if zFile cannot be loaded as written */
113311 static const char *azEndings[] = {
113312 #if SQLITE_OS_WIN
113313 "dll"
113314 #elif defined(__APPLE__)
113315 "dylib"
113316 #else
113318 #endif
113322 if( pzErrMsg ) *pzErrMsg = 0;
113324 /* Ticket #1863. To avoid a creating security problems for older
113325 ** applications that relink against newer versions of SQLite, the
113326 ** ability to run load_extension is turned off by default. One
113327 ** must call either sqlite3_enable_load_extension(db) or
113328 ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
113329 ** to turn on extension loading.
113331 if( (db->flags & SQLITE_LoadExtension)==0 ){
113332 if( pzErrMsg ){
113333 *pzErrMsg = sqlite3_mprintf("not authorized");
113335 return SQLITE_ERROR;
113338 zEntry = zProc ? zProc : "sqlite3_extension_init";
113340 handle = sqlite3OsDlOpen(pVfs, zFile);
113341 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
113342 for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
113343 char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
113344 if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
113345 handle = sqlite3OsDlOpen(pVfs, zAltFile);
113346 sqlite3_free(zAltFile);
113348 #endif
113349 if( handle==0 ){
113350 if( pzErrMsg ){
113351 *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
113352 if( zErrmsg ){
113353 sqlite3_snprintf(nMsg, zErrmsg,
113354 "unable to open shared library [%s]", zFile);
113355 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
113358 return SQLITE_ERROR;
113360 xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
113362 /* If no entry point was specified and the default legacy
113363 ** entry point name "sqlite3_extension_init" was not found, then
113364 ** construct an entry point name "sqlite3_X_init" where the X is
113365 ** replaced by the lowercase value of every ASCII alphabetic
113366 ** character in the filename after the last "/" upto the first ".",
113367 ** and eliding the first three characters if they are "lib".
113368 ** Examples:
113370 ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
113371 ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
113373 if( xInit==0 && zProc==0 ){
113374 int iFile, iEntry, c;
113375 int ncFile = sqlite3Strlen30(zFile);
113376 zAltEntry = sqlite3_malloc64(ncFile+30);
113377 if( zAltEntry==0 ){
113378 sqlite3OsDlClose(pVfs, handle);
113379 return SQLITE_NOMEM_BKPT;
113381 memcpy(zAltEntry, "sqlite3_", 8);
113382 for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
113383 iFile++;
113384 if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
113385 for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
113386 if( sqlite3Isalpha(c) ){
113387 zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
113390 memcpy(zAltEntry+iEntry, "_init", 6);
113391 zEntry = zAltEntry;
113392 xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
113394 if( xInit==0 ){
113395 if( pzErrMsg ){
113396 nMsg += sqlite3Strlen30(zEntry);
113397 *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
113398 if( zErrmsg ){
113399 sqlite3_snprintf(nMsg, zErrmsg,
113400 "no entry point [%s] in shared library [%s]", zEntry, zFile);
113401 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
113404 sqlite3OsDlClose(pVfs, handle);
113405 sqlite3_free(zAltEntry);
113406 return SQLITE_ERROR;
113408 sqlite3_free(zAltEntry);
113409 rc = xInit(db, &zErrmsg, &sqlite3Apis);
113410 if( rc ){
113411 if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
113412 if( pzErrMsg ){
113413 *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
113415 sqlite3_free(zErrmsg);
113416 sqlite3OsDlClose(pVfs, handle);
113417 return SQLITE_ERROR;
113420 /* Append the new shared library handle to the db->aExtension array. */
113421 aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
113422 if( aHandle==0 ){
113423 return SQLITE_NOMEM_BKPT;
113425 if( db->nExtension>0 ){
113426 memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
113428 sqlite3DbFree(db, db->aExtension);
113429 db->aExtension = aHandle;
113431 db->aExtension[db->nExtension++] = handle;
113432 return SQLITE_OK;
113434 SQLITE_API int sqlite3_load_extension(
113435 sqlite3 *db, /* Load the extension into this database connection */
113436 const char *zFile, /* Name of the shared library containing extension */
113437 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
113438 char **pzErrMsg /* Put error message here if not 0 */
113440 int rc;
113441 sqlite3_mutex_enter(db->mutex);
113442 rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
113443 rc = sqlite3ApiExit(db, rc);
113444 sqlite3_mutex_leave(db->mutex);
113445 return rc;
113449 ** Call this routine when the database connection is closing in order
113450 ** to clean up loaded extensions
113452 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
113453 int i;
113454 assert( sqlite3_mutex_held(db->mutex) );
113455 for(i=0; i<db->nExtension; i++){
113456 sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
113458 sqlite3DbFree(db, db->aExtension);
113462 ** Enable or disable extension loading. Extension loading is disabled by
113463 ** default so as not to open security holes in older applications.
113465 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
113466 sqlite3_mutex_enter(db->mutex);
113467 if( onoff ){
113468 db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
113469 }else{
113470 db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
113472 sqlite3_mutex_leave(db->mutex);
113473 return SQLITE_OK;
113476 #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
113479 ** The following object holds the list of automatically loaded
113480 ** extensions.
113482 ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
113483 ** mutex must be held while accessing this list.
113485 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
113486 static SQLITE_WSD struct sqlite3AutoExtList {
113487 u32 nExt; /* Number of entries in aExt[] */
113488 void (**aExt)(void); /* Pointers to the extension init functions */
113489 } sqlite3Autoext = { 0, 0 };
113491 /* The "wsdAutoext" macro will resolve to the autoextension
113492 ** state vector. If writable static data is unsupported on the target,
113493 ** we have to locate the state vector at run-time. In the more common
113494 ** case where writable static data is supported, wsdStat can refer directly
113495 ** to the "sqlite3Autoext" state vector declared above.
113497 #ifdef SQLITE_OMIT_WSD
113498 # define wsdAutoextInit \
113499 sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
113500 # define wsdAutoext x[0]
113501 #else
113502 # define wsdAutoextInit
113503 # define wsdAutoext sqlite3Autoext
113504 #endif
113508 ** Register a statically linked extension that is automatically
113509 ** loaded by every new database connection.
113511 SQLITE_API int sqlite3_auto_extension(
113512 void (*xInit)(void)
113514 int rc = SQLITE_OK;
113515 #ifndef SQLITE_OMIT_AUTOINIT
113516 rc = sqlite3_initialize();
113517 if( rc ){
113518 return rc;
113519 }else
113520 #endif
113522 u32 i;
113523 #if SQLITE_THREADSAFE
113524 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113525 #endif
113526 wsdAutoextInit;
113527 sqlite3_mutex_enter(mutex);
113528 for(i=0; i<wsdAutoext.nExt; i++){
113529 if( wsdAutoext.aExt[i]==xInit ) break;
113531 if( i==wsdAutoext.nExt ){
113532 u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
113533 void (**aNew)(void);
113534 aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
113535 if( aNew==0 ){
113536 rc = SQLITE_NOMEM_BKPT;
113537 }else{
113538 wsdAutoext.aExt = aNew;
113539 wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
113540 wsdAutoext.nExt++;
113543 sqlite3_mutex_leave(mutex);
113544 assert( (rc&0xff)==rc );
113545 return rc;
113550 ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
113551 ** set of routines that is invoked for each new database connection, if it
113552 ** is currently on the list. If xInit is not on the list, then this
113553 ** routine is a no-op.
113555 ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
113556 ** was not on the list.
113558 SQLITE_API int sqlite3_cancel_auto_extension(
113559 void (*xInit)(void)
113561 #if SQLITE_THREADSAFE
113562 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113563 #endif
113564 int i;
113565 int n = 0;
113566 wsdAutoextInit;
113567 sqlite3_mutex_enter(mutex);
113568 for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
113569 if( wsdAutoext.aExt[i]==xInit ){
113570 wsdAutoext.nExt--;
113571 wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
113573 break;
113576 sqlite3_mutex_leave(mutex);
113577 return n;
113581 ** Reset the automatic extension loading mechanism.
113583 SQLITE_API void sqlite3_reset_auto_extension(void){
113584 #ifndef SQLITE_OMIT_AUTOINIT
113585 if( sqlite3_initialize()==SQLITE_OK )
113586 #endif
113588 #if SQLITE_THREADSAFE
113589 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113590 #endif
113591 wsdAutoextInit;
113592 sqlite3_mutex_enter(mutex);
113593 sqlite3_free(wsdAutoext.aExt);
113594 wsdAutoext.aExt = 0;
113595 wsdAutoext.nExt = 0;
113596 sqlite3_mutex_leave(mutex);
113601 ** Load all automatic extensions.
113603 ** If anything goes wrong, set an error in the database connection.
113605 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
113606 u32 i;
113607 int go = 1;
113608 int rc;
113609 sqlite3_loadext_entry xInit;
113611 wsdAutoextInit;
113612 if( wsdAutoext.nExt==0 ){
113613 /* Common case: early out without every having to acquire a mutex */
113614 return;
113616 for(i=0; go; i++){
113617 char *zErrmsg;
113618 #if SQLITE_THREADSAFE
113619 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113620 #endif
113621 #ifdef SQLITE_OMIT_LOAD_EXTENSION
113622 const sqlite3_api_routines *pThunk = 0;
113623 #else
113624 const sqlite3_api_routines *pThunk = &sqlite3Apis;
113625 #endif
113626 sqlite3_mutex_enter(mutex);
113627 if( i>=wsdAutoext.nExt ){
113628 xInit = 0;
113629 go = 0;
113630 }else{
113631 xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
113633 sqlite3_mutex_leave(mutex);
113634 zErrmsg = 0;
113635 if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
113636 sqlite3ErrorWithMsg(db, rc,
113637 "automatic extension loading failed: %s", zErrmsg);
113638 go = 0;
113640 sqlite3_free(zErrmsg);
113644 /************** End of loadext.c *********************************************/
113645 /************** Begin file pragma.c ******************************************/
113647 ** 2003 April 6
113649 ** The author disclaims copyright to this source code. In place of
113650 ** a legal notice, here is a blessing:
113652 ** May you do good and not evil.
113653 ** May you find forgiveness for yourself and forgive others.
113654 ** May you share freely, never taking more than you give.
113656 *************************************************************************
113657 ** This file contains code used to implement the PRAGMA command.
113659 /* #include "sqliteInt.h" */
113661 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
113662 # if defined(__APPLE__)
113663 # define SQLITE_ENABLE_LOCKING_STYLE 1
113664 # else
113665 # define SQLITE_ENABLE_LOCKING_STYLE 0
113666 # endif
113667 #endif
113669 /***************************************************************************
113670 ** The "pragma.h" include file is an automatically generated file that
113671 ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
113672 ** object. This ensures that the aPragmaName[] table is arranged in
113673 ** lexicographical order to facility a binary search of the pragma name.
113674 ** Do not edit pragma.h directly. Edit and rerun the script in at
113675 ** ../tool/mkpragmatab.tcl. */
113676 /************** Include pragma.h in the middle of pragma.c *******************/
113677 /************** Begin file pragma.h ******************************************/
113678 /* DO NOT EDIT!
113679 ** This file is automatically generated by the script at
113680 ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
113681 ** that script and rerun it.
113684 /* The various pragma types */
113685 #define PragTyp_HEADER_VALUE 0
113686 #define PragTyp_AUTO_VACUUM 1
113687 #define PragTyp_FLAG 2
113688 #define PragTyp_BUSY_TIMEOUT 3
113689 #define PragTyp_CACHE_SIZE 4
113690 #define PragTyp_CACHE_SPILL 5
113691 #define PragTyp_CASE_SENSITIVE_LIKE 6
113692 #define PragTyp_COLLATION_LIST 7
113693 #define PragTyp_COMPILE_OPTIONS 8
113694 #define PragTyp_DATA_STORE_DIRECTORY 9
113695 #define PragTyp_DATABASE_LIST 10
113696 #define PragTyp_DEFAULT_CACHE_SIZE 11
113697 #define PragTyp_ENCODING 12
113698 #define PragTyp_FOREIGN_KEY_CHECK 13
113699 #define PragTyp_FOREIGN_KEY_LIST 14
113700 #define PragTyp_FUNCTION_LIST 15
113701 #define PragTyp_INCREMENTAL_VACUUM 16
113702 #define PragTyp_INDEX_INFO 17
113703 #define PragTyp_INDEX_LIST 18
113704 #define PragTyp_INTEGRITY_CHECK 19
113705 #define PragTyp_JOURNAL_MODE 20
113706 #define PragTyp_JOURNAL_SIZE_LIMIT 21
113707 #define PragTyp_LOCK_PROXY_FILE 22
113708 #define PragTyp_LOCKING_MODE 23
113709 #define PragTyp_PAGE_COUNT 24
113710 #define PragTyp_MMAP_SIZE 25
113711 #define PragTyp_MODULE_LIST 26
113712 #define PragTyp_OPTIMIZE 27
113713 #define PragTyp_PAGE_SIZE 28
113714 #define PragTyp_PRAGMA_LIST 29
113715 #define PragTyp_SECURE_DELETE 30
113716 #define PragTyp_SHRINK_MEMORY 31
113717 #define PragTyp_SOFT_HEAP_LIMIT 32
113718 #define PragTyp_SYNCHRONOUS 33
113719 #define PragTyp_TABLE_INFO 34
113720 #define PragTyp_TEMP_STORE 35
113721 #define PragTyp_TEMP_STORE_DIRECTORY 36
113722 #define PragTyp_THREADS 37
113723 #define PragTyp_WAL_AUTOCHECKPOINT 38
113724 #define PragTyp_WAL_CHECKPOINT 39
113725 #define PragTyp_ACTIVATE_EXTENSIONS 40
113726 #define PragTyp_HEXKEY 41
113727 #define PragTyp_KEY 42
113728 #define PragTyp_REKEY 43
113729 #define PragTyp_LOCK_STATUS 44
113730 #define PragTyp_PARSER_TRACE 45
113731 #define PragTyp_STATS 46
113733 /* Property flags associated with various pragma. */
113734 #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
113735 #define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */
113736 #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
113737 #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
113738 #define PragFlg_Result0 0x10 /* Acts as query when no argument */
113739 #define PragFlg_Result1 0x20 /* Acts as query when has one argument */
113740 #define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */
113741 #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
113743 /* Names of columns for pragmas that return multi-column result
113744 ** or that return single-column results where the name of the
113745 ** result column is different from the name of the pragma
113747 static const char *const pragCName[] = {
113748 /* 0 */ "cache_size", /* Used by: default_cache_size */
113749 /* 1 */ "cid", /* Used by: table_info */
113750 /* 2 */ "name",
113751 /* 3 */ "type",
113752 /* 4 */ "notnull",
113753 /* 5 */ "dflt_value",
113754 /* 6 */ "pk",
113755 /* 7 */ "tbl", /* Used by: stats */
113756 /* 8 */ "idx",
113757 /* 9 */ "wdth",
113758 /* 10 */ "hght",
113759 /* 11 */ "flgs",
113760 /* 12 */ "seqno", /* Used by: index_info */
113761 /* 13 */ "cid",
113762 /* 14 */ "name",
113763 /* 15 */ "seqno", /* Used by: index_xinfo */
113764 /* 16 */ "cid",
113765 /* 17 */ "name",
113766 /* 18 */ "desc",
113767 /* 19 */ "coll",
113768 /* 20 */ "key",
113769 /* 21 */ "seq", /* Used by: index_list */
113770 /* 22 */ "name",
113771 /* 23 */ "unique",
113772 /* 24 */ "origin",
113773 /* 25 */ "partial",
113774 /* 26 */ "seq", /* Used by: database_list */
113775 /* 27 */ "name",
113776 /* 28 */ "file",
113777 /* 29 */ "name", /* Used by: function_list */
113778 /* 30 */ "builtin",
113779 /* 31 */ "name", /* Used by: module_list pragma_list */
113780 /* 32 */ "seq", /* Used by: collation_list */
113781 /* 33 */ "name",
113782 /* 34 */ "id", /* Used by: foreign_key_list */
113783 /* 35 */ "seq",
113784 /* 36 */ "table",
113785 /* 37 */ "from",
113786 /* 38 */ "to",
113787 /* 39 */ "on_update",
113788 /* 40 */ "on_delete",
113789 /* 41 */ "match",
113790 /* 42 */ "table", /* Used by: foreign_key_check */
113791 /* 43 */ "rowid",
113792 /* 44 */ "parent",
113793 /* 45 */ "fkid",
113794 /* 46 */ "busy", /* Used by: wal_checkpoint */
113795 /* 47 */ "log",
113796 /* 48 */ "checkpointed",
113797 /* 49 */ "timeout", /* Used by: busy_timeout */
113798 /* 50 */ "database", /* Used by: lock_status */
113799 /* 51 */ "status",
113802 /* Definitions of all built-in pragmas */
113803 typedef struct PragmaName {
113804 const char *const zName; /* Name of pragma */
113805 u8 ePragTyp; /* PragTyp_XXX value */
113806 u8 mPragFlg; /* Zero or more PragFlg_XXX values */
113807 u8 iPragCName; /* Start of column names in pragCName[] */
113808 u8 nPragCName; /* Num of col names. 0 means use pragma name */
113809 u32 iArg; /* Extra argument */
113810 } PragmaName;
113811 static const PragmaName aPragmaName[] = {
113812 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
113813 {/* zName: */ "activate_extensions",
113814 /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
113815 /* ePragFlg: */ 0,
113816 /* ColNames: */ 0, 0,
113817 /* iArg: */ 0 },
113818 #endif
113819 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
113820 {/* zName: */ "application_id",
113821 /* ePragTyp: */ PragTyp_HEADER_VALUE,
113822 /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
113823 /* ColNames: */ 0, 0,
113824 /* iArg: */ BTREE_APPLICATION_ID },
113825 #endif
113826 #if !defined(SQLITE_OMIT_AUTOVACUUM)
113827 {/* zName: */ "auto_vacuum",
113828 /* ePragTyp: */ PragTyp_AUTO_VACUUM,
113829 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113830 /* ColNames: */ 0, 0,
113831 /* iArg: */ 0 },
113832 #endif
113833 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113834 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
113835 {/* zName: */ "automatic_index",
113836 /* ePragTyp: */ PragTyp_FLAG,
113837 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
113838 /* ColNames: */ 0, 0,
113839 /* iArg: */ SQLITE_AutoIndex },
113840 #endif
113841 #endif
113842 {/* zName: */ "busy_timeout",
113843 /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
113844 /* ePragFlg: */ PragFlg_Result0,
113845 /* ColNames: */ 49, 1,
113846 /* iArg: */ 0 },
113847 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
113848 {/* zName: */ "cache_size",
113849 /* ePragTyp: */ PragTyp_CACHE_SIZE,
113850 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113851 /* ColNames: */ 0, 0,
113852 /* iArg: */ 0 },
113853 #endif
113854 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113855 {/* zName: */ "cache_spill",
113856 /* ePragTyp: */ PragTyp_CACHE_SPILL,
113857 /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113858 /* ColNames: */ 0, 0,
113859 /* iArg: */ 0 },
113860 #endif
113861 {/* zName: */ "case_sensitive_like",
113862 /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
113863 /* ePragFlg: */ PragFlg_NoColumns,
113864 /* ColNames: */ 0, 0,
113865 /* iArg: */ 0 },
113866 {/* zName: */ "cell_size_check",
113867 /* ePragTyp: */ PragTyp_FLAG,
113868 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
113869 /* ColNames: */ 0, 0,
113870 /* iArg: */ SQLITE_CellSizeCk },
113871 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113872 {/* zName: */ "checkpoint_fullfsync",
113873 /* ePragTyp: */ PragTyp_FLAG,
113874 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
113875 /* ColNames: */ 0, 0,
113876 /* iArg: */ SQLITE_CkptFullFSync },
113877 #endif
113878 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113879 {/* zName: */ "collation_list",
113880 /* ePragTyp: */ PragTyp_COLLATION_LIST,
113881 /* ePragFlg: */ PragFlg_Result0,
113882 /* ColNames: */ 32, 2,
113883 /* iArg: */ 0 },
113884 #endif
113885 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
113886 {/* zName: */ "compile_options",
113887 /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
113888 /* ePragFlg: */ PragFlg_Result0,
113889 /* ColNames: */ 0, 0,
113890 /* iArg: */ 0 },
113891 #endif
113892 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113893 {/* zName: */ "count_changes",
113894 /* ePragTyp: */ PragTyp_FLAG,
113895 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
113896 /* ColNames: */ 0, 0,
113897 /* iArg: */ SQLITE_CountRows },
113898 #endif
113899 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
113900 {/* zName: */ "data_store_directory",
113901 /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
113902 /* ePragFlg: */ PragFlg_NoColumns1,
113903 /* ColNames: */ 0, 0,
113904 /* iArg: */ 0 },
113905 #endif
113906 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
113907 {/* zName: */ "data_version",
113908 /* ePragTyp: */ PragTyp_HEADER_VALUE,
113909 /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
113910 /* ColNames: */ 0, 0,
113911 /* iArg: */ BTREE_DATA_VERSION },
113912 #endif
113913 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113914 {/* zName: */ "database_list",
113915 /* ePragTyp: */ PragTyp_DATABASE_LIST,
113916 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
113917 /* ColNames: */ 26, 3,
113918 /* iArg: */ 0 },
113919 #endif
113920 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
113921 {/* zName: */ "default_cache_size",
113922 /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
113923 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113924 /* ColNames: */ 0, 1,
113925 /* iArg: */ 0 },
113926 #endif
113927 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113928 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
113929 {/* zName: */ "defer_foreign_keys",
113930 /* ePragTyp: */ PragTyp_FLAG,
113931 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
113932 /* ColNames: */ 0, 0,
113933 /* iArg: */ SQLITE_DeferFKs },
113934 #endif
113935 #endif
113936 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113937 {/* zName: */ "empty_result_callbacks",
113938 /* ePragTyp: */ PragTyp_FLAG,
113939 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
113940 /* ColNames: */ 0, 0,
113941 /* iArg: */ SQLITE_NullCallback },
113942 #endif
113943 #if !defined(SQLITE_OMIT_UTF16)
113944 {/* zName: */ "encoding",
113945 /* ePragTyp: */ PragTyp_ENCODING,
113946 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
113947 /* ColNames: */ 0, 0,
113948 /* iArg: */ 0 },
113949 #endif
113950 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
113951 {/* zName: */ "foreign_key_check",
113952 /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
113953 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
113954 /* ColNames: */ 42, 4,
113955 /* iArg: */ 0 },
113956 #endif
113957 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
113958 {/* zName: */ "foreign_key_list",
113959 /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
113960 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
113961 /* ColNames: */ 34, 8,
113962 /* iArg: */ 0 },
113963 #endif
113964 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113965 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
113966 {/* zName: */ "foreign_keys",
113967 /* ePragTyp: */ PragTyp_FLAG,
113968 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
113969 /* ColNames: */ 0, 0,
113970 /* iArg: */ SQLITE_ForeignKeys },
113971 #endif
113972 #endif
113973 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
113974 {/* zName: */ "freelist_count",
113975 /* ePragTyp: */ PragTyp_HEADER_VALUE,
113976 /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
113977 /* ColNames: */ 0, 0,
113978 /* iArg: */ BTREE_FREE_PAGE_COUNT },
113979 #endif
113980 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113981 {/* zName: */ "full_column_names",
113982 /* ePragTyp: */ PragTyp_FLAG,
113983 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
113984 /* ColNames: */ 0, 0,
113985 /* iArg: */ SQLITE_FullColNames },
113986 {/* zName: */ "fullfsync",
113987 /* ePragTyp: */ PragTyp_FLAG,
113988 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
113989 /* ColNames: */ 0, 0,
113990 /* iArg: */ SQLITE_FullFSync },
113991 #endif
113992 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113993 #if defined(SQLITE_INTROSPECTION_PRAGMAS)
113994 {/* zName: */ "function_list",
113995 /* ePragTyp: */ PragTyp_FUNCTION_LIST,
113996 /* ePragFlg: */ PragFlg_Result0,
113997 /* ColNames: */ 29, 2,
113998 /* iArg: */ 0 },
113999 #endif
114000 #endif
114001 #if defined(SQLITE_HAS_CODEC)
114002 {/* zName: */ "hexkey",
114003 /* ePragTyp: */ PragTyp_HEXKEY,
114004 /* ePragFlg: */ 0,
114005 /* ColNames: */ 0, 0,
114006 /* iArg: */ 0 },
114007 {/* zName: */ "hexrekey",
114008 /* ePragTyp: */ PragTyp_HEXKEY,
114009 /* ePragFlg: */ 0,
114010 /* ColNames: */ 0, 0,
114011 /* iArg: */ 0 },
114012 #endif
114013 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114014 #if !defined(SQLITE_OMIT_CHECK)
114015 {/* zName: */ "ignore_check_constraints",
114016 /* ePragTyp: */ PragTyp_FLAG,
114017 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114018 /* ColNames: */ 0, 0,
114019 /* iArg: */ SQLITE_IgnoreChecks },
114020 #endif
114021 #endif
114022 #if !defined(SQLITE_OMIT_AUTOVACUUM)
114023 {/* zName: */ "incremental_vacuum",
114024 /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
114025 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns,
114026 /* ColNames: */ 0, 0,
114027 /* iArg: */ 0 },
114028 #endif
114029 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
114030 {/* zName: */ "index_info",
114031 /* ePragTyp: */ PragTyp_INDEX_INFO,
114032 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
114033 /* ColNames: */ 12, 3,
114034 /* iArg: */ 0 },
114035 {/* zName: */ "index_list",
114036 /* ePragTyp: */ PragTyp_INDEX_LIST,
114037 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
114038 /* ColNames: */ 21, 5,
114039 /* iArg: */ 0 },
114040 {/* zName: */ "index_xinfo",
114041 /* ePragTyp: */ PragTyp_INDEX_INFO,
114042 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
114043 /* ColNames: */ 15, 6,
114044 /* iArg: */ 1 },
114045 #endif
114046 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
114047 {/* zName: */ "integrity_check",
114048 /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
114049 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
114050 /* ColNames: */ 0, 0,
114051 /* iArg: */ 0 },
114052 #endif
114053 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114054 {/* zName: */ "journal_mode",
114055 /* ePragTyp: */ PragTyp_JOURNAL_MODE,
114056 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
114057 /* ColNames: */ 0, 0,
114058 /* iArg: */ 0 },
114059 {/* zName: */ "journal_size_limit",
114060 /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
114061 /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
114062 /* ColNames: */ 0, 0,
114063 /* iArg: */ 0 },
114064 #endif
114065 #if defined(SQLITE_HAS_CODEC)
114066 {/* zName: */ "key",
114067 /* ePragTyp: */ PragTyp_KEY,
114068 /* ePragFlg: */ 0,
114069 /* ColNames: */ 0, 0,
114070 /* iArg: */ 0 },
114071 #endif
114072 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114073 {/* zName: */ "legacy_file_format",
114074 /* ePragTyp: */ PragTyp_FLAG,
114075 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114076 /* ColNames: */ 0, 0,
114077 /* iArg: */ SQLITE_LegacyFileFmt },
114078 #endif
114079 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
114080 {/* zName: */ "lock_proxy_file",
114081 /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
114082 /* ePragFlg: */ PragFlg_NoColumns1,
114083 /* ColNames: */ 0, 0,
114084 /* iArg: */ 0 },
114085 #endif
114086 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
114087 {/* zName: */ "lock_status",
114088 /* ePragTyp: */ PragTyp_LOCK_STATUS,
114089 /* ePragFlg: */ PragFlg_Result0,
114090 /* ColNames: */ 50, 2,
114091 /* iArg: */ 0 },
114092 #endif
114093 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114094 {/* zName: */ "locking_mode",
114095 /* ePragTyp: */ PragTyp_LOCKING_MODE,
114096 /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
114097 /* ColNames: */ 0, 0,
114098 /* iArg: */ 0 },
114099 {/* zName: */ "max_page_count",
114100 /* ePragTyp: */ PragTyp_PAGE_COUNT,
114101 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
114102 /* ColNames: */ 0, 0,
114103 /* iArg: */ 0 },
114104 {/* zName: */ "mmap_size",
114105 /* ePragTyp: */ PragTyp_MMAP_SIZE,
114106 /* ePragFlg: */ 0,
114107 /* ColNames: */ 0, 0,
114108 /* iArg: */ 0 },
114109 #endif
114110 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
114111 #if !defined(SQLITE_OMIT_VIRTUALTABLE)
114112 #if defined(SQLITE_INTROSPECTION_PRAGMAS)
114113 {/* zName: */ "module_list",
114114 /* ePragTyp: */ PragTyp_MODULE_LIST,
114115 /* ePragFlg: */ PragFlg_Result0,
114116 /* ColNames: */ 31, 1,
114117 /* iArg: */ 0 },
114118 #endif
114119 #endif
114120 #endif
114121 {/* zName: */ "optimize",
114122 /* ePragTyp: */ PragTyp_OPTIMIZE,
114123 /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema,
114124 /* ColNames: */ 0, 0,
114125 /* iArg: */ 0 },
114126 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114127 {/* zName: */ "page_count",
114128 /* ePragTyp: */ PragTyp_PAGE_COUNT,
114129 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
114130 /* ColNames: */ 0, 0,
114131 /* iArg: */ 0 },
114132 {/* zName: */ "page_size",
114133 /* ePragTyp: */ PragTyp_PAGE_SIZE,
114134 /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
114135 /* ColNames: */ 0, 0,
114136 /* iArg: */ 0 },
114137 #endif
114138 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
114139 {/* zName: */ "parser_trace",
114140 /* ePragTyp: */ PragTyp_PARSER_TRACE,
114141 /* ePragFlg: */ 0,
114142 /* ColNames: */ 0, 0,
114143 /* iArg: */ 0 },
114144 #endif
114145 #if defined(SQLITE_INTROSPECTION_PRAGMAS)
114146 {/* zName: */ "pragma_list",
114147 /* ePragTyp: */ PragTyp_PRAGMA_LIST,
114148 /* ePragFlg: */ PragFlg_Result0,
114149 /* ColNames: */ 31, 1,
114150 /* iArg: */ 0 },
114151 #endif
114152 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114153 {/* zName: */ "query_only",
114154 /* ePragTyp: */ PragTyp_FLAG,
114155 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114156 /* ColNames: */ 0, 0,
114157 /* iArg: */ SQLITE_QueryOnly },
114158 #endif
114159 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
114160 {/* zName: */ "quick_check",
114161 /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
114162 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
114163 /* ColNames: */ 0, 0,
114164 /* iArg: */ 0 },
114165 #endif
114166 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114167 {/* zName: */ "read_uncommitted",
114168 /* ePragTyp: */ PragTyp_FLAG,
114169 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114170 /* ColNames: */ 0, 0,
114171 /* iArg: */ SQLITE_ReadUncommit },
114172 {/* zName: */ "recursive_triggers",
114173 /* ePragTyp: */ PragTyp_FLAG,
114174 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114175 /* ColNames: */ 0, 0,
114176 /* iArg: */ SQLITE_RecTriggers },
114177 #endif
114178 #if defined(SQLITE_HAS_CODEC)
114179 {/* zName: */ "rekey",
114180 /* ePragTyp: */ PragTyp_REKEY,
114181 /* ePragFlg: */ 0,
114182 /* ColNames: */ 0, 0,
114183 /* iArg: */ 0 },
114184 #endif
114185 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114186 {/* zName: */ "reverse_unordered_selects",
114187 /* ePragTyp: */ PragTyp_FLAG,
114188 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114189 /* ColNames: */ 0, 0,
114190 /* iArg: */ SQLITE_ReverseOrder },
114191 #endif
114192 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
114193 {/* zName: */ "schema_version",
114194 /* ePragTyp: */ PragTyp_HEADER_VALUE,
114195 /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
114196 /* ColNames: */ 0, 0,
114197 /* iArg: */ BTREE_SCHEMA_VERSION },
114198 #endif
114199 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114200 {/* zName: */ "secure_delete",
114201 /* ePragTyp: */ PragTyp_SECURE_DELETE,
114202 /* ePragFlg: */ PragFlg_Result0,
114203 /* ColNames: */ 0, 0,
114204 /* iArg: */ 0 },
114205 #endif
114206 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114207 {/* zName: */ "short_column_names",
114208 /* ePragTyp: */ PragTyp_FLAG,
114209 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114210 /* ColNames: */ 0, 0,
114211 /* iArg: */ SQLITE_ShortColNames },
114212 #endif
114213 {/* zName: */ "shrink_memory",
114214 /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
114215 /* ePragFlg: */ PragFlg_NoColumns,
114216 /* ColNames: */ 0, 0,
114217 /* iArg: */ 0 },
114218 {/* zName: */ "soft_heap_limit",
114219 /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
114220 /* ePragFlg: */ PragFlg_Result0,
114221 /* ColNames: */ 0, 0,
114222 /* iArg: */ 0 },
114223 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114224 #if defined(SQLITE_DEBUG)
114225 {/* zName: */ "sql_trace",
114226 /* ePragTyp: */ PragTyp_FLAG,
114227 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114228 /* ColNames: */ 0, 0,
114229 /* iArg: */ SQLITE_SqlTrace },
114230 #endif
114231 #endif
114232 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
114233 {/* zName: */ "stats",
114234 /* ePragTyp: */ PragTyp_STATS,
114235 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
114236 /* ColNames: */ 7, 5,
114237 /* iArg: */ 0 },
114238 #endif
114239 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114240 {/* zName: */ "synchronous",
114241 /* ePragTyp: */ PragTyp_SYNCHRONOUS,
114242 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
114243 /* ColNames: */ 0, 0,
114244 /* iArg: */ 0 },
114245 #endif
114246 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
114247 {/* zName: */ "table_info",
114248 /* ePragTyp: */ PragTyp_TABLE_INFO,
114249 /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
114250 /* ColNames: */ 1, 6,
114251 /* iArg: */ 0 },
114252 #endif
114253 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114254 {/* zName: */ "temp_store",
114255 /* ePragTyp: */ PragTyp_TEMP_STORE,
114256 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114257 /* ColNames: */ 0, 0,
114258 /* iArg: */ 0 },
114259 {/* zName: */ "temp_store_directory",
114260 /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
114261 /* ePragFlg: */ PragFlg_NoColumns1,
114262 /* ColNames: */ 0, 0,
114263 /* iArg: */ 0 },
114264 #endif
114265 {/* zName: */ "threads",
114266 /* ePragTyp: */ PragTyp_THREADS,
114267 /* ePragFlg: */ PragFlg_Result0,
114268 /* ColNames: */ 0, 0,
114269 /* iArg: */ 0 },
114270 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
114271 {/* zName: */ "user_version",
114272 /* ePragTyp: */ PragTyp_HEADER_VALUE,
114273 /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
114274 /* ColNames: */ 0, 0,
114275 /* iArg: */ BTREE_USER_VERSION },
114276 #endif
114277 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114278 #if defined(SQLITE_DEBUG)
114279 {/* zName: */ "vdbe_addoptrace",
114280 /* ePragTyp: */ PragTyp_FLAG,
114281 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114282 /* ColNames: */ 0, 0,
114283 /* iArg: */ SQLITE_VdbeAddopTrace },
114284 {/* zName: */ "vdbe_debug",
114285 /* ePragTyp: */ PragTyp_FLAG,
114286 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114287 /* ColNames: */ 0, 0,
114288 /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
114289 {/* zName: */ "vdbe_eqp",
114290 /* ePragTyp: */ PragTyp_FLAG,
114291 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114292 /* ColNames: */ 0, 0,
114293 /* iArg: */ SQLITE_VdbeEQP },
114294 {/* zName: */ "vdbe_listing",
114295 /* ePragTyp: */ PragTyp_FLAG,
114296 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114297 /* ColNames: */ 0, 0,
114298 /* iArg: */ SQLITE_VdbeListing },
114299 {/* zName: */ "vdbe_trace",
114300 /* ePragTyp: */ PragTyp_FLAG,
114301 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114302 /* ColNames: */ 0, 0,
114303 /* iArg: */ SQLITE_VdbeTrace },
114304 #endif
114305 #endif
114306 #if !defined(SQLITE_OMIT_WAL)
114307 {/* zName: */ "wal_autocheckpoint",
114308 /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
114309 /* ePragFlg: */ 0,
114310 /* ColNames: */ 0, 0,
114311 /* iArg: */ 0 },
114312 {/* zName: */ "wal_checkpoint",
114313 /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
114314 /* ePragFlg: */ PragFlg_NeedSchema,
114315 /* ColNames: */ 46, 3,
114316 /* iArg: */ 0 },
114317 #endif
114318 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114319 {/* zName: */ "writable_schema",
114320 /* ePragTyp: */ PragTyp_FLAG,
114321 /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
114322 /* ColNames: */ 0, 0,
114323 /* iArg: */ SQLITE_WriteSchema },
114324 #endif
114326 /* Number of pragmas: 60 on by default, 77 total. */
114328 /************** End of pragma.h **********************************************/
114329 /************** Continuing where we left off in pragma.c *********************/
114332 ** Interpret the given string as a safety level. Return 0 for OFF,
114333 ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
114334 ** unrecognized string argument. The FULL and EXTRA option is disallowed
114335 ** if the omitFull parameter it 1.
114337 ** Note that the values returned are one less that the values that
114338 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
114339 ** to support legacy SQL code. The safety level used to be boolean
114340 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
114342 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
114343 /* 123456789 123456789 123 */
114344 static const char zText[] = "onoffalseyestruextrafull";
114345 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
114346 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
114347 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
114348 /* on no off false yes true extra full */
114349 int i, n;
114350 if( sqlite3Isdigit(*z) ){
114351 return (u8)sqlite3Atoi(z);
114353 n = sqlite3Strlen30(z);
114354 for(i=0; i<ArraySize(iLength); i++){
114355 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
114356 && (!omitFull || iValue[i]<=1)
114358 return iValue[i];
114361 return dflt;
114365 ** Interpret the given string as a boolean value.
114367 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
114368 return getSafetyLevel(z,1,dflt)!=0;
114371 /* The sqlite3GetBoolean() function is used by other modules but the
114372 ** remainder of this file is specific to PRAGMA processing. So omit
114373 ** the rest of the file if PRAGMAs are omitted from the build.
114375 #if !defined(SQLITE_OMIT_PRAGMA)
114378 ** Interpret the given string as a locking mode value.
114380 static int getLockingMode(const char *z){
114381 if( z ){
114382 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
114383 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
114385 return PAGER_LOCKINGMODE_QUERY;
114388 #ifndef SQLITE_OMIT_AUTOVACUUM
114390 ** Interpret the given string as an auto-vacuum mode value.
114392 ** The following strings, "none", "full" and "incremental" are
114393 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
114395 static int getAutoVacuum(const char *z){
114396 int i;
114397 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
114398 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
114399 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
114400 i = sqlite3Atoi(z);
114401 return (u8)((i>=0&&i<=2)?i:0);
114403 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
114405 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
114407 ** Interpret the given string as a temp db location. Return 1 for file
114408 ** backed temporary databases, 2 for the Red-Black tree in memory database
114409 ** and 0 to use the compile-time default.
114411 static int getTempStore(const char *z){
114412 if( z[0]>='0' && z[0]<='2' ){
114413 return z[0] - '0';
114414 }else if( sqlite3StrICmp(z, "file")==0 ){
114415 return 1;
114416 }else if( sqlite3StrICmp(z, "memory")==0 ){
114417 return 2;
114418 }else{
114419 return 0;
114422 #endif /* SQLITE_PAGER_PRAGMAS */
114424 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
114426 ** Invalidate temp storage, either when the temp storage is changed
114427 ** from default, or when 'file' and the temp_store_directory has changed
114429 static int invalidateTempStorage(Parse *pParse){
114430 sqlite3 *db = pParse->db;
114431 if( db->aDb[1].pBt!=0 ){
114432 if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
114433 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
114434 "from within a transaction");
114435 return SQLITE_ERROR;
114437 sqlite3BtreeClose(db->aDb[1].pBt);
114438 db->aDb[1].pBt = 0;
114439 sqlite3ResetAllSchemasOfConnection(db);
114441 return SQLITE_OK;
114443 #endif /* SQLITE_PAGER_PRAGMAS */
114445 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
114447 ** If the TEMP database is open, close it and mark the database schema
114448 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
114449 ** or DEFAULT_TEMP_STORE pragmas.
114451 static int changeTempStorage(Parse *pParse, const char *zStorageType){
114452 int ts = getTempStore(zStorageType);
114453 sqlite3 *db = pParse->db;
114454 if( db->temp_store==ts ) return SQLITE_OK;
114455 if( invalidateTempStorage( pParse ) != SQLITE_OK ){
114456 return SQLITE_ERROR;
114458 db->temp_store = (u8)ts;
114459 return SQLITE_OK;
114461 #endif /* SQLITE_PAGER_PRAGMAS */
114464 ** Set result column names for a pragma.
114466 static void setPragmaResultColumnNames(
114467 Vdbe *v, /* The query under construction */
114468 const PragmaName *pPragma /* The pragma */
114470 u8 n = pPragma->nPragCName;
114471 sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
114472 if( n==0 ){
114473 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
114474 }else{
114475 int i, j;
114476 for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
114477 sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
114483 ** Generate code to return a single integer value.
114485 static void returnSingleInt(Vdbe *v, i64 value){
114486 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
114487 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
114491 ** Generate code to return a single text value.
114493 static void returnSingleText(
114494 Vdbe *v, /* Prepared statement under construction */
114495 const char *zValue /* Value to be returned */
114497 if( zValue ){
114498 sqlite3VdbeLoadString(v, 1, (const char*)zValue);
114499 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
114505 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
114506 ** set these values for all pagers.
114508 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
114509 static void setAllPagerFlags(sqlite3 *db){
114510 if( db->autoCommit ){
114511 Db *pDb = db->aDb;
114512 int n = db->nDb;
114513 assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
114514 assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
114515 assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
114516 assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
114517 == PAGER_FLAGS_MASK );
114518 assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
114519 while( (n--) > 0 ){
114520 if( pDb->pBt ){
114521 sqlite3BtreeSetPagerFlags(pDb->pBt,
114522 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
114524 pDb++;
114528 #else
114529 # define setAllPagerFlags(X) /* no-op */
114530 #endif
114534 ** Return a human-readable name for a constraint resolution action.
114536 #ifndef SQLITE_OMIT_FOREIGN_KEY
114537 static const char *actionName(u8 action){
114538 const char *zName;
114539 switch( action ){
114540 case OE_SetNull: zName = "SET NULL"; break;
114541 case OE_SetDflt: zName = "SET DEFAULT"; break;
114542 case OE_Cascade: zName = "CASCADE"; break;
114543 case OE_Restrict: zName = "RESTRICT"; break;
114544 default: zName = "NO ACTION";
114545 assert( action==OE_None ); break;
114547 return zName;
114549 #endif
114553 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
114554 ** defined in pager.h. This function returns the associated lowercase
114555 ** journal-mode name.
114557 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
114558 static char * const azModeName[] = {
114559 "delete", "persist", "off", "truncate", "memory"
114560 #ifndef SQLITE_OMIT_WAL
114561 , "wal"
114562 #endif
114564 assert( PAGER_JOURNALMODE_DELETE==0 );
114565 assert( PAGER_JOURNALMODE_PERSIST==1 );
114566 assert( PAGER_JOURNALMODE_OFF==2 );
114567 assert( PAGER_JOURNALMODE_TRUNCATE==3 );
114568 assert( PAGER_JOURNALMODE_MEMORY==4 );
114569 assert( PAGER_JOURNALMODE_WAL==5 );
114570 assert( eMode>=0 && eMode<=ArraySize(azModeName) );
114572 if( eMode==ArraySize(azModeName) ) return 0;
114573 return azModeName[eMode];
114577 ** Locate a pragma in the aPragmaName[] array.
114579 static const PragmaName *pragmaLocate(const char *zName){
114580 int upr, lwr, mid = 0, rc;
114581 lwr = 0;
114582 upr = ArraySize(aPragmaName)-1;
114583 while( lwr<=upr ){
114584 mid = (lwr+upr)/2;
114585 rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
114586 if( rc==0 ) break;
114587 if( rc<0 ){
114588 upr = mid - 1;
114589 }else{
114590 lwr = mid + 1;
114593 return lwr>upr ? 0 : &aPragmaName[mid];
114597 ** Helper subroutine for PRAGMA integrity_check:
114599 ** Generate code to output a single-column result row with a value of the
114600 ** string held in register 3. Decrement the result count in register 1
114601 ** and halt if the maximum number of result rows have been issued.
114603 static int integrityCheckResultRow(Vdbe *v){
114604 int addr;
114605 sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
114606 addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
114607 VdbeCoverage(v);
114608 sqlite3VdbeAddOp0(v, OP_Halt);
114609 return addr;
114613 ** Process a pragma statement.
114615 ** Pragmas are of this form:
114617 ** PRAGMA [schema.]id [= value]
114619 ** The identifier might also be a string. The value is a string, and
114620 ** identifier, or a number. If minusFlag is true, then the value is
114621 ** a number that was preceded by a minus sign.
114623 ** If the left side is "database.id" then pId1 is the database name
114624 ** and pId2 is the id. If the left side is just "id" then pId1 is the
114625 ** id and pId2 is any empty string.
114627 SQLITE_PRIVATE void sqlite3Pragma(
114628 Parse *pParse,
114629 Token *pId1, /* First part of [schema.]id field */
114630 Token *pId2, /* Second part of [schema.]id field, or NULL */
114631 Token *pValue, /* Token for <value>, or NULL */
114632 int minusFlag /* True if a '-' sign preceded <value> */
114634 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
114635 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
114636 const char *zDb = 0; /* The database name */
114637 Token *pId; /* Pointer to <id> token */
114638 char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
114639 int iDb; /* Database index for <database> */
114640 int rc; /* return value form SQLITE_FCNTL_PRAGMA */
114641 sqlite3 *db = pParse->db; /* The database connection */
114642 Db *pDb; /* The specific database being pragmaed */
114643 Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
114644 const PragmaName *pPragma; /* The pragma */
114646 if( v==0 ) return;
114647 sqlite3VdbeRunOnlyOnce(v);
114648 pParse->nMem = 2;
114650 /* Interpret the [schema.] part of the pragma statement. iDb is the
114651 ** index of the database this pragma is being applied to in db.aDb[]. */
114652 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
114653 if( iDb<0 ) return;
114654 pDb = &db->aDb[iDb];
114656 /* If the temp database has been explicitly named as part of the
114657 ** pragma, make sure it is open.
114659 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
114660 return;
114663 zLeft = sqlite3NameFromToken(db, pId);
114664 if( !zLeft ) return;
114665 if( minusFlag ){
114666 zRight = sqlite3MPrintf(db, "-%T", pValue);
114667 }else{
114668 zRight = sqlite3NameFromToken(db, pValue);
114671 assert( pId2 );
114672 zDb = pId2->n>0 ? pDb->zDbSName : 0;
114673 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
114674 goto pragma_out;
114677 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
114678 ** connection. If it returns SQLITE_OK, then assume that the VFS
114679 ** handled the pragma and generate a no-op prepared statement.
114681 ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
114682 ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
114683 ** object corresponding to the database file to which the pragma
114684 ** statement refers.
114686 ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
114687 ** file control is an array of pointers to strings (char**) in which the
114688 ** second element of the array is the name of the pragma and the third
114689 ** element is the argument to the pragma or NULL if the pragma has no
114690 ** argument.
114692 aFcntl[0] = 0;
114693 aFcntl[1] = zLeft;
114694 aFcntl[2] = zRight;
114695 aFcntl[3] = 0;
114696 db->busyHandler.nBusy = 0;
114697 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
114698 if( rc==SQLITE_OK ){
114699 sqlite3VdbeSetNumCols(v, 1);
114700 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
114701 returnSingleText(v, aFcntl[0]);
114702 sqlite3_free(aFcntl[0]);
114703 goto pragma_out;
114705 if( rc!=SQLITE_NOTFOUND ){
114706 if( aFcntl[0] ){
114707 sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
114708 sqlite3_free(aFcntl[0]);
114710 pParse->nErr++;
114711 pParse->rc = rc;
114712 goto pragma_out;
114715 /* Locate the pragma in the lookup table */
114716 pPragma = pragmaLocate(zLeft);
114717 if( pPragma==0 ) goto pragma_out;
114719 /* Make sure the database schema is loaded if the pragma requires that */
114720 if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
114721 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
114724 /* Register the result column names for pragmas that return results */
114725 if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
114726 && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
114728 setPragmaResultColumnNames(v, pPragma);
114731 /* Jump to the appropriate pragma handler */
114732 switch( pPragma->ePragTyp ){
114734 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
114736 ** PRAGMA [schema.]default_cache_size
114737 ** PRAGMA [schema.]default_cache_size=N
114739 ** The first form reports the current persistent setting for the
114740 ** page cache size. The value returned is the maximum number of
114741 ** pages in the page cache. The second form sets both the current
114742 ** page cache size value and the persistent page cache size value
114743 ** stored in the database file.
114745 ** Older versions of SQLite would set the default cache size to a
114746 ** negative number to indicate synchronous=OFF. These days, synchronous
114747 ** is always on by default regardless of the sign of the default cache
114748 ** size. But continue to take the absolute value of the default cache
114749 ** size of historical compatibility.
114751 case PragTyp_DEFAULT_CACHE_SIZE: {
114752 static const int iLn = VDBE_OFFSET_LINENO(2);
114753 static const VdbeOpList getCacheSize[] = {
114754 { OP_Transaction, 0, 0, 0}, /* 0 */
114755 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
114756 { OP_IfPos, 1, 8, 0},
114757 { OP_Integer, 0, 2, 0},
114758 { OP_Subtract, 1, 2, 1},
114759 { OP_IfPos, 1, 8, 0},
114760 { OP_Integer, 0, 1, 0}, /* 6 */
114761 { OP_Noop, 0, 0, 0},
114762 { OP_ResultRow, 1, 1, 0},
114764 VdbeOp *aOp;
114765 sqlite3VdbeUsesBtree(v, iDb);
114766 if( !zRight ){
114767 pParse->nMem += 2;
114768 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
114769 aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
114770 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
114771 aOp[0].p1 = iDb;
114772 aOp[1].p1 = iDb;
114773 aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
114774 }else{
114775 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
114776 sqlite3BeginWriteOperation(pParse, 0, iDb);
114777 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
114778 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114779 pDb->pSchema->cache_size = size;
114780 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
114782 break;
114784 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
114786 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114788 ** PRAGMA [schema.]page_size
114789 ** PRAGMA [schema.]page_size=N
114791 ** The first form reports the current setting for the
114792 ** database page size in bytes. The second form sets the
114793 ** database page size value. The value can only be set if
114794 ** the database has not yet been created.
114796 case PragTyp_PAGE_SIZE: {
114797 Btree *pBt = pDb->pBt;
114798 assert( pBt!=0 );
114799 if( !zRight ){
114800 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
114801 returnSingleInt(v, size);
114802 }else{
114803 /* Malloc may fail when setting the page-size, as there is an internal
114804 ** buffer that the pager module resizes using sqlite3_realloc().
114806 db->nextPagesize = sqlite3Atoi(zRight);
114807 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
114808 sqlite3OomFault(db);
114811 break;
114815 ** PRAGMA [schema.]secure_delete
114816 ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
114818 ** The first form reports the current setting for the
114819 ** secure_delete flag. The second form changes the secure_delete
114820 ** flag setting and reports the new value.
114822 case PragTyp_SECURE_DELETE: {
114823 Btree *pBt = pDb->pBt;
114824 int b = -1;
114825 assert( pBt!=0 );
114826 if( zRight ){
114827 if( sqlite3_stricmp(zRight, "fast")==0 ){
114828 b = 2;
114829 }else{
114830 b = sqlite3GetBoolean(zRight, 0);
114833 if( pId2->n==0 && b>=0 ){
114834 int ii;
114835 for(ii=0; ii<db->nDb; ii++){
114836 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
114839 b = sqlite3BtreeSecureDelete(pBt, b);
114840 returnSingleInt(v, b);
114841 break;
114845 ** PRAGMA [schema.]max_page_count
114846 ** PRAGMA [schema.]max_page_count=N
114848 ** The first form reports the current setting for the
114849 ** maximum number of pages in the database file. The
114850 ** second form attempts to change this setting. Both
114851 ** forms return the current setting.
114853 ** The absolute value of N is used. This is undocumented and might
114854 ** change. The only purpose is to provide an easy way to test
114855 ** the sqlite3AbsInt32() function.
114857 ** PRAGMA [schema.]page_count
114859 ** Return the number of pages in the specified database.
114861 case PragTyp_PAGE_COUNT: {
114862 int iReg;
114863 sqlite3CodeVerifySchema(pParse, iDb);
114864 iReg = ++pParse->nMem;
114865 if( sqlite3Tolower(zLeft[0])=='p' ){
114866 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
114867 }else{
114868 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
114869 sqlite3AbsInt32(sqlite3Atoi(zRight)));
114871 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
114872 break;
114876 ** PRAGMA [schema.]locking_mode
114877 ** PRAGMA [schema.]locking_mode = (normal|exclusive)
114879 case PragTyp_LOCKING_MODE: {
114880 const char *zRet = "normal";
114881 int eMode = getLockingMode(zRight);
114883 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
114884 /* Simple "PRAGMA locking_mode;" statement. This is a query for
114885 ** the current default locking mode (which may be different to
114886 ** the locking-mode of the main database).
114888 eMode = db->dfltLockMode;
114889 }else{
114890 Pager *pPager;
114891 if( pId2->n==0 ){
114892 /* This indicates that no database name was specified as part
114893 ** of the PRAGMA command. In this case the locking-mode must be
114894 ** set on all attached databases, as well as the main db file.
114896 ** Also, the sqlite3.dfltLockMode variable is set so that
114897 ** any subsequently attached databases also use the specified
114898 ** locking mode.
114900 int ii;
114901 assert(pDb==&db->aDb[0]);
114902 for(ii=2; ii<db->nDb; ii++){
114903 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
114904 sqlite3PagerLockingMode(pPager, eMode);
114906 db->dfltLockMode = (u8)eMode;
114908 pPager = sqlite3BtreePager(pDb->pBt);
114909 eMode = sqlite3PagerLockingMode(pPager, eMode);
114912 assert( eMode==PAGER_LOCKINGMODE_NORMAL
114913 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
114914 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
114915 zRet = "exclusive";
114917 returnSingleText(v, zRet);
114918 break;
114922 ** PRAGMA [schema.]journal_mode
114923 ** PRAGMA [schema.]journal_mode =
114924 ** (delete|persist|off|truncate|memory|wal|off)
114926 case PragTyp_JOURNAL_MODE: {
114927 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
114928 int ii; /* Loop counter */
114930 if( zRight==0 ){
114931 /* If there is no "=MODE" part of the pragma, do a query for the
114932 ** current mode */
114933 eMode = PAGER_JOURNALMODE_QUERY;
114934 }else{
114935 const char *zMode;
114936 int n = sqlite3Strlen30(zRight);
114937 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
114938 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
114940 if( !zMode ){
114941 /* If the "=MODE" part does not match any known journal mode,
114942 ** then do a query */
114943 eMode = PAGER_JOURNALMODE_QUERY;
114946 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
114947 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
114948 iDb = 0;
114949 pId2->n = 1;
114951 for(ii=db->nDb-1; ii>=0; ii--){
114952 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
114953 sqlite3VdbeUsesBtree(v, ii);
114954 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
114957 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
114958 break;
114962 ** PRAGMA [schema.]journal_size_limit
114963 ** PRAGMA [schema.]journal_size_limit=N
114965 ** Get or set the size limit on rollback journal files.
114967 case PragTyp_JOURNAL_SIZE_LIMIT: {
114968 Pager *pPager = sqlite3BtreePager(pDb->pBt);
114969 i64 iLimit = -2;
114970 if( zRight ){
114971 sqlite3DecOrHexToI64(zRight, &iLimit);
114972 if( iLimit<-1 ) iLimit = -1;
114974 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
114975 returnSingleInt(v, iLimit);
114976 break;
114979 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
114982 ** PRAGMA [schema.]auto_vacuum
114983 ** PRAGMA [schema.]auto_vacuum=N
114985 ** Get or set the value of the database 'auto-vacuum' parameter.
114986 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
114988 #ifndef SQLITE_OMIT_AUTOVACUUM
114989 case PragTyp_AUTO_VACUUM: {
114990 Btree *pBt = pDb->pBt;
114991 assert( pBt!=0 );
114992 if( !zRight ){
114993 returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
114994 }else{
114995 int eAuto = getAutoVacuum(zRight);
114996 assert( eAuto>=0 && eAuto<=2 );
114997 db->nextAutovac = (u8)eAuto;
114998 /* Call SetAutoVacuum() to set initialize the internal auto and
114999 ** incr-vacuum flags. This is required in case this connection
115000 ** creates the database file. It is important that it is created
115001 ** as an auto-vacuum capable db.
115003 rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
115004 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
115005 /* When setting the auto_vacuum mode to either "full" or
115006 ** "incremental", write the value of meta[6] in the database
115007 ** file. Before writing to meta[6], check that meta[3] indicates
115008 ** that this really is an auto-vacuum capable database.
115010 static const int iLn = VDBE_OFFSET_LINENO(2);
115011 static const VdbeOpList setMeta6[] = {
115012 { OP_Transaction, 0, 1, 0}, /* 0 */
115013 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
115014 { OP_If, 1, 0, 0}, /* 2 */
115015 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
115016 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
115018 VdbeOp *aOp;
115019 int iAddr = sqlite3VdbeCurrentAddr(v);
115020 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
115021 aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
115022 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
115023 aOp[0].p1 = iDb;
115024 aOp[1].p1 = iDb;
115025 aOp[2].p2 = iAddr+4;
115026 aOp[4].p1 = iDb;
115027 aOp[4].p3 = eAuto - 1;
115028 sqlite3VdbeUsesBtree(v, iDb);
115031 break;
115033 #endif
115036 ** PRAGMA [schema.]incremental_vacuum(N)
115038 ** Do N steps of incremental vacuuming on a database.
115040 #ifndef SQLITE_OMIT_AUTOVACUUM
115041 case PragTyp_INCREMENTAL_VACUUM: {
115042 int iLimit, addr;
115043 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
115044 iLimit = 0x7fffffff;
115046 sqlite3BeginWriteOperation(pParse, 0, iDb);
115047 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
115048 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
115049 sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
115050 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
115051 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
115052 sqlite3VdbeJumpHere(v, addr);
115053 break;
115055 #endif
115057 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
115059 ** PRAGMA [schema.]cache_size
115060 ** PRAGMA [schema.]cache_size=N
115062 ** The first form reports the current local setting for the
115063 ** page cache size. The second form sets the local
115064 ** page cache size value. If N is positive then that is the
115065 ** number of pages in the cache. If N is negative, then the
115066 ** number of pages is adjusted so that the cache uses -N kibibytes
115067 ** of memory.
115069 case PragTyp_CACHE_SIZE: {
115070 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
115071 if( !zRight ){
115072 returnSingleInt(v, pDb->pSchema->cache_size);
115073 }else{
115074 int size = sqlite3Atoi(zRight);
115075 pDb->pSchema->cache_size = size;
115076 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
115078 break;
115082 ** PRAGMA [schema.]cache_spill
115083 ** PRAGMA cache_spill=BOOLEAN
115084 ** PRAGMA [schema.]cache_spill=N
115086 ** The first form reports the current local setting for the
115087 ** page cache spill size. The second form turns cache spill on
115088 ** or off. When turnning cache spill on, the size is set to the
115089 ** current cache_size. The third form sets a spill size that
115090 ** may be different form the cache size.
115091 ** If N is positive then that is the
115092 ** number of pages in the cache. If N is negative, then the
115093 ** number of pages is adjusted so that the cache uses -N kibibytes
115094 ** of memory.
115096 ** If the number of cache_spill pages is less then the number of
115097 ** cache_size pages, no spilling occurs until the page count exceeds
115098 ** the number of cache_size pages.
115100 ** The cache_spill=BOOLEAN setting applies to all attached schemas,
115101 ** not just the schema specified.
115103 case PragTyp_CACHE_SPILL: {
115104 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
115105 if( !zRight ){
115106 returnSingleInt(v,
115107 (db->flags & SQLITE_CacheSpill)==0 ? 0 :
115108 sqlite3BtreeSetSpillSize(pDb->pBt,0));
115109 }else{
115110 int size = 1;
115111 if( sqlite3GetInt32(zRight, &size) ){
115112 sqlite3BtreeSetSpillSize(pDb->pBt, size);
115114 if( sqlite3GetBoolean(zRight, size!=0) ){
115115 db->flags |= SQLITE_CacheSpill;
115116 }else{
115117 db->flags &= ~SQLITE_CacheSpill;
115119 setAllPagerFlags(db);
115121 break;
115125 ** PRAGMA [schema.]mmap_size(N)
115127 ** Used to set mapping size limit. The mapping size limit is
115128 ** used to limit the aggregate size of all memory mapped regions of the
115129 ** database file. If this parameter is set to zero, then memory mapping
115130 ** is not used at all. If N is negative, then the default memory map
115131 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
115132 ** The parameter N is measured in bytes.
115134 ** This value is advisory. The underlying VFS is free to memory map
115135 ** as little or as much as it wants. Except, if N is set to 0 then the
115136 ** upper layers will never invoke the xFetch interfaces to the VFS.
115138 case PragTyp_MMAP_SIZE: {
115139 sqlite3_int64 sz;
115140 #if SQLITE_MAX_MMAP_SIZE>0
115141 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
115142 if( zRight ){
115143 int ii;
115144 sqlite3DecOrHexToI64(zRight, &sz);
115145 if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
115146 if( pId2->n==0 ) db->szMmap = sz;
115147 for(ii=db->nDb-1; ii>=0; ii--){
115148 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
115149 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
115153 sz = -1;
115154 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
115155 #else
115156 sz = 0;
115157 rc = SQLITE_OK;
115158 #endif
115159 if( rc==SQLITE_OK ){
115160 returnSingleInt(v, sz);
115161 }else if( rc!=SQLITE_NOTFOUND ){
115162 pParse->nErr++;
115163 pParse->rc = rc;
115165 break;
115169 ** PRAGMA temp_store
115170 ** PRAGMA temp_store = "default"|"memory"|"file"
115172 ** Return or set the local value of the temp_store flag. Changing
115173 ** the local value does not make changes to the disk file and the default
115174 ** value will be restored the next time the database is opened.
115176 ** Note that it is possible for the library compile-time options to
115177 ** override this setting
115179 case PragTyp_TEMP_STORE: {
115180 if( !zRight ){
115181 returnSingleInt(v, db->temp_store);
115182 }else{
115183 changeTempStorage(pParse, zRight);
115185 break;
115189 ** PRAGMA temp_store_directory
115190 ** PRAGMA temp_store_directory = ""|"directory_name"
115192 ** Return or set the local value of the temp_store_directory flag. Changing
115193 ** the value sets a specific directory to be used for temporary files.
115194 ** Setting to a null string reverts to the default temporary directory search.
115195 ** If temporary directory is changed, then invalidateTempStorage.
115198 case PragTyp_TEMP_STORE_DIRECTORY: {
115199 if( !zRight ){
115200 returnSingleText(v, sqlite3_temp_directory);
115201 }else{
115202 #ifndef SQLITE_OMIT_WSD
115203 if( zRight[0] ){
115204 int res;
115205 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
115206 if( rc!=SQLITE_OK || res==0 ){
115207 sqlite3ErrorMsg(pParse, "not a writable directory");
115208 goto pragma_out;
115211 if( SQLITE_TEMP_STORE==0
115212 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
115213 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
115215 invalidateTempStorage(pParse);
115217 sqlite3_free(sqlite3_temp_directory);
115218 if( zRight[0] ){
115219 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
115220 }else{
115221 sqlite3_temp_directory = 0;
115223 #endif /* SQLITE_OMIT_WSD */
115225 break;
115228 #if SQLITE_OS_WIN
115230 ** PRAGMA data_store_directory
115231 ** PRAGMA data_store_directory = ""|"directory_name"
115233 ** Return or set the local value of the data_store_directory flag. Changing
115234 ** the value sets a specific directory to be used for database files that
115235 ** were specified with a relative pathname. Setting to a null string reverts
115236 ** to the default database directory, which for database files specified with
115237 ** a relative path will probably be based on the current directory for the
115238 ** process. Database file specified with an absolute path are not impacted
115239 ** by this setting, regardless of its value.
115242 case PragTyp_DATA_STORE_DIRECTORY: {
115243 if( !zRight ){
115244 returnSingleText(v, sqlite3_data_directory);
115245 }else{
115246 #ifndef SQLITE_OMIT_WSD
115247 if( zRight[0] ){
115248 int res;
115249 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
115250 if( rc!=SQLITE_OK || res==0 ){
115251 sqlite3ErrorMsg(pParse, "not a writable directory");
115252 goto pragma_out;
115255 sqlite3_free(sqlite3_data_directory);
115256 if( zRight[0] ){
115257 sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
115258 }else{
115259 sqlite3_data_directory = 0;
115261 #endif /* SQLITE_OMIT_WSD */
115263 break;
115265 #endif
115267 #if SQLITE_ENABLE_LOCKING_STYLE
115269 ** PRAGMA [schema.]lock_proxy_file
115270 ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
115272 ** Return or set the value of the lock_proxy_file flag. Changing
115273 ** the value sets a specific file to be used for database access locks.
115276 case PragTyp_LOCK_PROXY_FILE: {
115277 if( !zRight ){
115278 Pager *pPager = sqlite3BtreePager(pDb->pBt);
115279 char *proxy_file_path = NULL;
115280 sqlite3_file *pFile = sqlite3PagerFile(pPager);
115281 sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
115282 &proxy_file_path);
115283 returnSingleText(v, proxy_file_path);
115284 }else{
115285 Pager *pPager = sqlite3BtreePager(pDb->pBt);
115286 sqlite3_file *pFile = sqlite3PagerFile(pPager);
115287 int res;
115288 if( zRight[0] ){
115289 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
115290 zRight);
115291 } else {
115292 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
115293 NULL);
115295 if( res!=SQLITE_OK ){
115296 sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
115297 goto pragma_out;
115300 break;
115302 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
115305 ** PRAGMA [schema.]synchronous
115306 ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
115308 ** Return or set the local value of the synchronous flag. Changing
115309 ** the local value does not make changes to the disk file and the
115310 ** default value will be restored the next time the database is
115311 ** opened.
115313 case PragTyp_SYNCHRONOUS: {
115314 if( !zRight ){
115315 returnSingleInt(v, pDb->safety_level-1);
115316 }else{
115317 if( !db->autoCommit ){
115318 sqlite3ErrorMsg(pParse,
115319 "Safety level may not be changed inside a transaction");
115320 }else if( iDb!=1 ){
115321 int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
115322 if( iLevel==0 ) iLevel = 1;
115323 pDb->safety_level = iLevel;
115324 pDb->bSyncSet = 1;
115325 setAllPagerFlags(db);
115328 break;
115330 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
115332 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
115333 case PragTyp_FLAG: {
115334 if( zRight==0 ){
115335 setPragmaResultColumnNames(v, pPragma);
115336 returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
115337 }else{
115338 int mask = pPragma->iArg; /* Mask of bits to set or clear. */
115339 if( db->autoCommit==0 ){
115340 /* Foreign key support may not be enabled or disabled while not
115341 ** in auto-commit mode. */
115342 mask &= ~(SQLITE_ForeignKeys);
115344 #if SQLITE_USER_AUTHENTICATION
115345 if( db->auth.authLevel==UAUTH_User ){
115346 /* Do not allow non-admin users to modify the schema arbitrarily */
115347 mask &= ~(SQLITE_WriteSchema);
115349 #endif
115351 if( sqlite3GetBoolean(zRight, 0) ){
115352 db->flags |= mask;
115353 }else{
115354 db->flags &= ~mask;
115355 if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
115358 /* Many of the flag-pragmas modify the code generated by the SQL
115359 ** compiler (eg. count_changes). So add an opcode to expire all
115360 ** compiled SQL statements after modifying a pragma value.
115362 sqlite3VdbeAddOp0(v, OP_Expire);
115363 setAllPagerFlags(db);
115365 break;
115367 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
115369 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
115371 ** PRAGMA table_info(<table>)
115373 ** Return a single row for each column of the named table. The columns of
115374 ** the returned data set are:
115376 ** cid: Column id (numbered from left to right, starting at 0)
115377 ** name: Column name
115378 ** type: Column declaration type.
115379 ** notnull: True if 'NOT NULL' is part of column declaration
115380 ** dflt_value: The default value for the column, if any.
115382 case PragTyp_TABLE_INFO: if( zRight ){
115383 Table *pTab;
115384 pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
115385 if( pTab ){
115386 int i, k;
115387 int nHidden = 0;
115388 Column *pCol;
115389 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
115390 pParse->nMem = 6;
115391 sqlite3CodeVerifySchema(pParse, iDb);
115392 sqlite3ViewGetColumnNames(pParse, pTab);
115393 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
115394 if( IsHiddenColumn(pCol) ){
115395 nHidden++;
115396 continue;
115398 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
115399 k = 0;
115400 }else if( pPk==0 ){
115401 k = 1;
115402 }else{
115403 for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
115405 assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
115406 sqlite3VdbeMultiLoad(v, 1, "issisi",
115407 i-nHidden,
115408 pCol->zName,
115409 sqlite3ColumnType(pCol,""),
115410 pCol->notNull ? 1 : 0,
115411 pCol->pDflt ? pCol->pDflt->u.zToken : 0,
115416 break;
115418 #ifdef SQLITE_DEBUG
115419 case PragTyp_STATS: {
115420 Index *pIdx;
115421 HashElem *i;
115422 pParse->nMem = 5;
115423 sqlite3CodeVerifySchema(pParse, iDb);
115424 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
115425 Table *pTab = sqliteHashData(i);
115426 sqlite3VdbeMultiLoad(v, 1, "ssiii",
115427 pTab->zName,
115429 pTab->szTabRow,
115430 pTab->nRowLogEst,
115431 pTab->tabFlags);
115432 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115433 sqlite3VdbeMultiLoad(v, 2, "siiiX",
115434 pIdx->zName,
115435 pIdx->szIdxRow,
115436 pIdx->aiRowLogEst[0],
115437 pIdx->hasStat1);
115438 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
115442 break;
115443 #endif
115445 case PragTyp_INDEX_INFO: if( zRight ){
115446 Index *pIdx;
115447 Table *pTab;
115448 pIdx = sqlite3FindIndex(db, zRight, zDb);
115449 if( pIdx ){
115450 int i;
115451 int mx;
115452 if( pPragma->iArg ){
115453 /* PRAGMA index_xinfo (newer version with more rows and columns) */
115454 mx = pIdx->nColumn;
115455 pParse->nMem = 6;
115456 }else{
115457 /* PRAGMA index_info (legacy version) */
115458 mx = pIdx->nKeyCol;
115459 pParse->nMem = 3;
115461 pTab = pIdx->pTable;
115462 sqlite3CodeVerifySchema(pParse, iDb);
115463 assert( pParse->nMem<=pPragma->nPragCName );
115464 for(i=0; i<mx; i++){
115465 i16 cnum = pIdx->aiColumn[i];
115466 sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
115467 cnum<0 ? 0 : pTab->aCol[cnum].zName);
115468 if( pPragma->iArg ){
115469 sqlite3VdbeMultiLoad(v, 4, "isiX",
115470 pIdx->aSortOrder[i],
115471 pIdx->azColl[i],
115472 i<pIdx->nKeyCol);
115474 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
115478 break;
115480 case PragTyp_INDEX_LIST: if( zRight ){
115481 Index *pIdx;
115482 Table *pTab;
115483 int i;
115484 pTab = sqlite3FindTable(db, zRight, zDb);
115485 if( pTab ){
115486 pParse->nMem = 5;
115487 sqlite3CodeVerifySchema(pParse, iDb);
115488 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
115489 const char *azOrigin[] = { "c", "u", "pk" };
115490 sqlite3VdbeMultiLoad(v, 1, "isisi",
115492 pIdx->zName,
115493 IsUniqueIndex(pIdx),
115494 azOrigin[pIdx->idxType],
115495 pIdx->pPartIdxWhere!=0);
115499 break;
115501 case PragTyp_DATABASE_LIST: {
115502 int i;
115503 pParse->nMem = 3;
115504 for(i=0; i<db->nDb; i++){
115505 if( db->aDb[i].pBt==0 ) continue;
115506 assert( db->aDb[i].zDbSName!=0 );
115507 sqlite3VdbeMultiLoad(v, 1, "iss",
115509 db->aDb[i].zDbSName,
115510 sqlite3BtreeGetFilename(db->aDb[i].pBt));
115513 break;
115515 case PragTyp_COLLATION_LIST: {
115516 int i = 0;
115517 HashElem *p;
115518 pParse->nMem = 2;
115519 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
115520 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
115521 sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
115524 break;
115526 #ifdef SQLITE_INTROSPECTION_PRAGMAS
115527 case PragTyp_FUNCTION_LIST: {
115528 int i;
115529 HashElem *j;
115530 FuncDef *p;
115531 pParse->nMem = 2;
115532 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
115533 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
115534 sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
115537 for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
115538 p = (FuncDef*)sqliteHashData(j);
115539 sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
115542 break;
115544 #ifndef SQLITE_OMIT_VIRTUALTABLE
115545 case PragTyp_MODULE_LIST: {
115546 HashElem *j;
115547 pParse->nMem = 1;
115548 for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
115549 Module *pMod = (Module*)sqliteHashData(j);
115550 sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
115553 break;
115554 #endif /* SQLITE_OMIT_VIRTUALTABLE */
115556 case PragTyp_PRAGMA_LIST: {
115557 int i;
115558 for(i=0; i<ArraySize(aPragmaName); i++){
115559 sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
115562 break;
115563 #endif /* SQLITE_INTROSPECTION_PRAGMAS */
115565 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
115567 #ifndef SQLITE_OMIT_FOREIGN_KEY
115568 case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
115569 FKey *pFK;
115570 Table *pTab;
115571 pTab = sqlite3FindTable(db, zRight, zDb);
115572 if( pTab ){
115573 pFK = pTab->pFKey;
115574 if( pFK ){
115575 int i = 0;
115576 pParse->nMem = 8;
115577 sqlite3CodeVerifySchema(pParse, iDb);
115578 while(pFK){
115579 int j;
115580 for(j=0; j<pFK->nCol; j++){
115581 sqlite3VdbeMultiLoad(v, 1, "iissssss",
115584 pFK->zTo,
115585 pTab->aCol[pFK->aCol[j].iFrom].zName,
115586 pFK->aCol[j].zCol,
115587 actionName(pFK->aAction[1]), /* ON UPDATE */
115588 actionName(pFK->aAction[0]), /* ON DELETE */
115589 "NONE");
115592 pFK = pFK->pNextFrom;
115597 break;
115598 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
115600 #ifndef SQLITE_OMIT_FOREIGN_KEY
115601 #ifndef SQLITE_OMIT_TRIGGER
115602 case PragTyp_FOREIGN_KEY_CHECK: {
115603 FKey *pFK; /* A foreign key constraint */
115604 Table *pTab; /* Child table contain "REFERENCES" keyword */
115605 Table *pParent; /* Parent table that child points to */
115606 Index *pIdx; /* Index in the parent table */
115607 int i; /* Loop counter: Foreign key number for pTab */
115608 int j; /* Loop counter: Field of the foreign key */
115609 HashElem *k; /* Loop counter: Next table in schema */
115610 int x; /* result variable */
115611 int regResult; /* 3 registers to hold a result row */
115612 int regKey; /* Register to hold key for checking the FK */
115613 int regRow; /* Registers to hold a row from pTab */
115614 int addrTop; /* Top of a loop checking foreign keys */
115615 int addrOk; /* Jump here if the key is OK */
115616 int *aiCols; /* child to parent column mapping */
115618 regResult = pParse->nMem+1;
115619 pParse->nMem += 4;
115620 regKey = ++pParse->nMem;
115621 regRow = ++pParse->nMem;
115622 sqlite3CodeVerifySchema(pParse, iDb);
115623 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
115624 while( k ){
115625 if( zRight ){
115626 pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
115627 k = 0;
115628 }else{
115629 pTab = (Table*)sqliteHashData(k);
115630 k = sqliteHashNext(k);
115632 if( pTab==0 || pTab->pFKey==0 ) continue;
115633 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
115634 if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
115635 sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
115636 sqlite3VdbeLoadString(v, regResult, pTab->zName);
115637 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
115638 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
115639 if( pParent==0 ) continue;
115640 pIdx = 0;
115641 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
115642 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
115643 if( x==0 ){
115644 if( pIdx==0 ){
115645 sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
115646 }else{
115647 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
115648 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
115650 }else{
115651 k = 0;
115652 break;
115655 assert( pParse->nErr>0 || pFK==0 );
115656 if( pFK ) break;
115657 if( pParse->nTab<i ) pParse->nTab = i;
115658 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
115659 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
115660 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
115661 pIdx = 0;
115662 aiCols = 0;
115663 if( pParent ){
115664 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
115665 assert( x==0 );
115667 addrOk = sqlite3VdbeMakeLabel(v);
115669 /* Generate code to read the child key values into registers
115670 ** regRow..regRow+n. If any of the child key values are NULL, this
115671 ** row cannot cause an FK violation. Jump directly to addrOk in
115672 ** this case. */
115673 for(j=0; j<pFK->nCol; j++){
115674 int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
115675 sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
115676 sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
115679 /* Generate code to query the parent index for a matching parent
115680 ** key. If a match is found, jump to addrOk. */
115681 if( pIdx ){
115682 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
115683 sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
115684 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
115685 VdbeCoverage(v);
115686 }else if( pParent ){
115687 int jmp = sqlite3VdbeCurrentAddr(v)+2;
115688 sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
115689 sqlite3VdbeGoto(v, addrOk);
115690 assert( pFK->nCol==1 );
115693 /* Generate code to report an FK violation to the caller. */
115694 if( HasRowid(pTab) ){
115695 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
115696 }else{
115697 sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
115699 sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
115700 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
115701 sqlite3VdbeResolveLabel(v, addrOk);
115702 sqlite3DbFree(db, aiCols);
115704 sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
115705 sqlite3VdbeJumpHere(v, addrTop);
115708 break;
115709 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
115710 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
115712 #ifndef NDEBUG
115713 case PragTyp_PARSER_TRACE: {
115714 if( zRight ){
115715 if( sqlite3GetBoolean(zRight, 0) ){
115716 sqlite3ParserTrace(stdout, "parser: ");
115717 }else{
115718 sqlite3ParserTrace(0, 0);
115722 break;
115723 #endif
115725 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
115726 ** used will be case sensitive or not depending on the RHS.
115728 case PragTyp_CASE_SENSITIVE_LIKE: {
115729 if( zRight ){
115730 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
115733 break;
115735 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
115736 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
115737 #endif
115739 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
115740 /* PRAGMA integrity_check
115741 ** PRAGMA integrity_check(N)
115742 ** PRAGMA quick_check
115743 ** PRAGMA quick_check(N)
115745 ** Verify the integrity of the database.
115747 ** The "quick_check" is reduced version of
115748 ** integrity_check designed to detect most database corruption
115749 ** without the overhead of cross-checking indexes. Quick_check
115750 ** is linear time wherease integrity_check is O(NlogN).
115752 case PragTyp_INTEGRITY_CHECK: {
115753 int i, j, addr, mxErr;
115755 int isQuick = (sqlite3Tolower(zLeft[0])=='q');
115757 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
115758 ** then iDb is set to the index of the database identified by <db>.
115759 ** In this case, the integrity of database iDb only is verified by
115760 ** the VDBE created below.
115762 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
115763 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
115764 ** to -1 here, to indicate that the VDBE should verify the integrity
115765 ** of all attached databases. */
115766 assert( iDb>=0 );
115767 assert( iDb==0 || pId2->z );
115768 if( pId2->z==0 ) iDb = -1;
115770 /* Initialize the VDBE program */
115771 pParse->nMem = 6;
115773 /* Set the maximum error count */
115774 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
115775 if( zRight ){
115776 sqlite3GetInt32(zRight, &mxErr);
115777 if( mxErr<=0 ){
115778 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
115781 sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
115783 /* Do an integrity check on each database file */
115784 for(i=0; i<db->nDb; i++){
115785 HashElem *x; /* For looping over tables in the schema */
115786 Hash *pTbls; /* Set of all tables in the schema */
115787 int *aRoot; /* Array of root page numbers of all btrees */
115788 int cnt = 0; /* Number of entries in aRoot[] */
115789 int mxIdx = 0; /* Maximum number of indexes for any table */
115791 if( OMIT_TEMPDB && i==1 ) continue;
115792 if( iDb>=0 && i!=iDb ) continue;
115794 sqlite3CodeVerifySchema(pParse, i);
115796 /* Do an integrity check of the B-Tree
115798 ** Begin by finding the root pages numbers
115799 ** for all tables and indices in the database.
115801 assert( sqlite3SchemaMutexHeld(db, i, 0) );
115802 pTbls = &db->aDb[i].pSchema->tblHash;
115803 for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
115804 Table *pTab = sqliteHashData(x); /* Current table */
115805 Index *pIdx; /* An index on pTab */
115806 int nIdx; /* Number of indexes on pTab */
115807 if( HasRowid(pTab) ) cnt++;
115808 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
115809 if( nIdx>mxIdx ) mxIdx = nIdx;
115811 aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
115812 if( aRoot==0 ) break;
115813 for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
115814 Table *pTab = sqliteHashData(x);
115815 Index *pIdx;
115816 if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
115817 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115818 aRoot[++cnt] = pIdx->tnum;
115821 aRoot[0] = cnt;
115823 /* Make sure sufficient number of registers have been allocated */
115824 pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
115825 sqlite3ClearTempRegCache(pParse);
115827 /* Do the b-tree integrity checks */
115828 sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
115829 sqlite3VdbeChangeP5(v, (u8)i);
115830 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
115831 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
115832 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
115833 P4_DYNAMIC);
115834 sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
115835 integrityCheckResultRow(v);
115836 sqlite3VdbeJumpHere(v, addr);
115838 /* Make sure all the indices are constructed correctly.
115840 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
115841 Table *pTab = sqliteHashData(x);
115842 Index *pIdx, *pPk;
115843 Index *pPrior = 0;
115844 int loopTop;
115845 int iDataCur, iIdxCur;
115846 int r1 = -1;
115848 if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
115849 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
115850 sqlite3ExprCacheClear(pParse);
115851 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
115852 1, 0, &iDataCur, &iIdxCur);
115853 /* reg[7] counts the number of entries in the table.
115854 ** reg[8+i] counts the number of entries in the i-th index
115856 sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
115857 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
115858 sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
115860 assert( pParse->nMem>=8+j );
115861 assert( sqlite3NoTempsInRange(pParse,1,7+j) );
115862 sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
115863 loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
115864 /* Verify that all NOT NULL columns really are NOT NULL */
115865 for(j=0; j<pTab->nCol; j++){
115866 char *zErr;
115867 int jmp2;
115868 if( j==pTab->iPKey ) continue;
115869 if( pTab->aCol[j].notNull==0 ) continue;
115870 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
115871 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
115872 jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
115873 zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
115874 pTab->aCol[j].zName);
115875 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
115876 integrityCheckResultRow(v);
115877 sqlite3VdbeJumpHere(v, jmp2);
115879 /* Verify CHECK constraints */
115880 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
115881 ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
115882 if( db->mallocFailed==0 ){
115883 int addrCkFault = sqlite3VdbeMakeLabel(v);
115884 int addrCkOk = sqlite3VdbeMakeLabel(v);
115885 char *zErr;
115886 int k;
115887 pParse->iSelfTab = iDataCur + 1;
115888 sqlite3ExprCachePush(pParse);
115889 for(k=pCheck->nExpr-1; k>0; k--){
115890 sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
115892 sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
115893 SQLITE_JUMPIFNULL);
115894 sqlite3VdbeResolveLabel(v, addrCkFault);
115895 pParse->iSelfTab = 0;
115896 zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
115897 pTab->zName);
115898 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
115899 integrityCheckResultRow(v);
115900 sqlite3VdbeResolveLabel(v, addrCkOk);
115901 sqlite3ExprCachePop(pParse);
115903 sqlite3ExprListDelete(db, pCheck);
115905 if( !isQuick ){ /* Omit the remaining tests for quick_check */
115906 /* Sanity check on record header decoding */
115907 sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
115908 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
115909 /* Validate index entries for the current row */
115910 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
115911 int jmp2, jmp3, jmp4, jmp5;
115912 int ckUniq = sqlite3VdbeMakeLabel(v);
115913 if( pPk==pIdx ) continue;
115914 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
115915 pPrior, r1);
115916 pPrior = pIdx;
115917 sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
115918 /* Verify that an index entry exists for the current table row */
115919 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
115920 pIdx->nColumn); VdbeCoverage(v);
115921 sqlite3VdbeLoadString(v, 3, "row ");
115922 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
115923 sqlite3VdbeLoadString(v, 4, " missing from index ");
115924 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
115925 jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
115926 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
115927 jmp4 = integrityCheckResultRow(v);
115928 sqlite3VdbeJumpHere(v, jmp2);
115929 /* For UNIQUE indexes, verify that only one entry exists with the
115930 ** current key. The entry is unique if (1) any column is NULL
115931 ** or (2) the next entry has a different key */
115932 if( IsUniqueIndex(pIdx) ){
115933 int uniqOk = sqlite3VdbeMakeLabel(v);
115934 int jmp6;
115935 int kk;
115936 for(kk=0; kk<pIdx->nKeyCol; kk++){
115937 int iCol = pIdx->aiColumn[kk];
115938 assert( iCol!=XN_ROWID && iCol<pTab->nCol );
115939 if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
115940 sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
115941 VdbeCoverage(v);
115943 jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
115944 sqlite3VdbeGoto(v, uniqOk);
115945 sqlite3VdbeJumpHere(v, jmp6);
115946 sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
115947 pIdx->nKeyCol); VdbeCoverage(v);
115948 sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
115949 sqlite3VdbeGoto(v, jmp5);
115950 sqlite3VdbeResolveLabel(v, uniqOk);
115952 sqlite3VdbeJumpHere(v, jmp4);
115953 sqlite3ResolvePartIdxLabel(pParse, jmp3);
115956 sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
115957 sqlite3VdbeJumpHere(v, loopTop-1);
115958 #ifndef SQLITE_OMIT_BTREECOUNT
115959 if( !isQuick ){
115960 sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
115961 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
115962 if( pPk==pIdx ) continue;
115963 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
115964 addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
115965 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
115966 sqlite3VdbeLoadString(v, 4, pIdx->zName);
115967 sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
115968 integrityCheckResultRow(v);
115969 sqlite3VdbeJumpHere(v, addr);
115972 #endif /* SQLITE_OMIT_BTREECOUNT */
115976 static const int iLn = VDBE_OFFSET_LINENO(2);
115977 static const VdbeOpList endCode[] = {
115978 { OP_AddImm, 1, 0, 0}, /* 0 */
115979 { OP_IfNotZero, 1, 4, 0}, /* 1 */
115980 { OP_String8, 0, 3, 0}, /* 2 */
115981 { OP_ResultRow, 3, 1, 0}, /* 3 */
115982 { OP_Halt, 0, 0, 0}, /* 4 */
115983 { OP_String8, 0, 3, 0}, /* 5 */
115984 { OP_Goto, 0, 3, 0}, /* 6 */
115986 VdbeOp *aOp;
115988 aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
115989 if( aOp ){
115990 aOp[0].p2 = 1-mxErr;
115991 aOp[2].p4type = P4_STATIC;
115992 aOp[2].p4.z = "ok";
115993 aOp[5].p4type = P4_STATIC;
115994 aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
115996 sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
115999 break;
116000 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
116002 #ifndef SQLITE_OMIT_UTF16
116004 ** PRAGMA encoding
116005 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
116007 ** In its first form, this pragma returns the encoding of the main
116008 ** database. If the database is not initialized, it is initialized now.
116010 ** The second form of this pragma is a no-op if the main database file
116011 ** has not already been initialized. In this case it sets the default
116012 ** encoding that will be used for the main database file if a new file
116013 ** is created. If an existing main database file is opened, then the
116014 ** default text encoding for the existing database is used.
116016 ** In all cases new databases created using the ATTACH command are
116017 ** created to use the same default text encoding as the main database. If
116018 ** the main database has not been initialized and/or created when ATTACH
116019 ** is executed, this is done before the ATTACH operation.
116021 ** In the second form this pragma sets the text encoding to be used in
116022 ** new database files created using this database handle. It is only
116023 ** useful if invoked immediately after the main database i
116025 case PragTyp_ENCODING: {
116026 static const struct EncName {
116027 char *zName;
116028 u8 enc;
116029 } encnames[] = {
116030 { "UTF8", SQLITE_UTF8 },
116031 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
116032 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
116033 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
116034 { "UTF16le", SQLITE_UTF16LE },
116035 { "UTF16be", SQLITE_UTF16BE },
116036 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
116037 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
116038 { 0, 0 }
116040 const struct EncName *pEnc;
116041 if( !zRight ){ /* "PRAGMA encoding" */
116042 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
116043 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
116044 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
116045 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
116046 returnSingleText(v, encnames[ENC(pParse->db)].zName);
116047 }else{ /* "PRAGMA encoding = XXX" */
116048 /* Only change the value of sqlite.enc if the database handle is not
116049 ** initialized. If the main database exists, the new sqlite.enc value
116050 ** will be overwritten when the schema is next loaded. If it does not
116051 ** already exists, it will be created to use the new encoding value.
116054 !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
116055 DbHasProperty(db, 0, DB_Empty)
116057 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
116058 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
116059 SCHEMA_ENC(db) = ENC(db) =
116060 pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
116061 break;
116064 if( !pEnc->zName ){
116065 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
116070 break;
116071 #endif /* SQLITE_OMIT_UTF16 */
116073 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
116075 ** PRAGMA [schema.]schema_version
116076 ** PRAGMA [schema.]schema_version = <integer>
116078 ** PRAGMA [schema.]user_version
116079 ** PRAGMA [schema.]user_version = <integer>
116081 ** PRAGMA [schema.]freelist_count
116083 ** PRAGMA [schema.]data_version
116085 ** PRAGMA [schema.]application_id
116086 ** PRAGMA [schema.]application_id = <integer>
116088 ** The pragma's schema_version and user_version are used to set or get
116089 ** the value of the schema-version and user-version, respectively. Both
116090 ** the schema-version and the user-version are 32-bit signed integers
116091 ** stored in the database header.
116093 ** The schema-cookie is usually only manipulated internally by SQLite. It
116094 ** is incremented by SQLite whenever the database schema is modified (by
116095 ** creating or dropping a table or index). The schema version is used by
116096 ** SQLite each time a query is executed to ensure that the internal cache
116097 ** of the schema used when compiling the SQL query matches the schema of
116098 ** the database against which the compiled query is actually executed.
116099 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
116100 ** the schema-version is potentially dangerous and may lead to program
116101 ** crashes or database corruption. Use with caution!
116103 ** The user-version is not used internally by SQLite. It may be used by
116104 ** applications for any purpose.
116106 case PragTyp_HEADER_VALUE: {
116107 int iCookie = pPragma->iArg; /* Which cookie to read or write */
116108 sqlite3VdbeUsesBtree(v, iDb);
116109 if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
116110 /* Write the specified cookie value */
116111 static const VdbeOpList setCookie[] = {
116112 { OP_Transaction, 0, 1, 0}, /* 0 */
116113 { OP_SetCookie, 0, 0, 0}, /* 1 */
116115 VdbeOp *aOp;
116116 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
116117 aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
116118 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
116119 aOp[0].p1 = iDb;
116120 aOp[1].p1 = iDb;
116121 aOp[1].p2 = iCookie;
116122 aOp[1].p3 = sqlite3Atoi(zRight);
116123 }else{
116124 /* Read the specified cookie value */
116125 static const VdbeOpList readCookie[] = {
116126 { OP_Transaction, 0, 0, 0}, /* 0 */
116127 { OP_ReadCookie, 0, 1, 0}, /* 1 */
116128 { OP_ResultRow, 1, 1, 0}
116130 VdbeOp *aOp;
116131 sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
116132 aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
116133 if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
116134 aOp[0].p1 = iDb;
116135 aOp[1].p1 = iDb;
116136 aOp[1].p3 = iCookie;
116137 sqlite3VdbeReusable(v);
116140 break;
116141 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
116143 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
116145 ** PRAGMA compile_options
116147 ** Return the names of all compile-time options used in this build,
116148 ** one option per row.
116150 case PragTyp_COMPILE_OPTIONS: {
116151 int i = 0;
116152 const char *zOpt;
116153 pParse->nMem = 1;
116154 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
116155 sqlite3VdbeLoadString(v, 1, zOpt);
116156 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
116158 sqlite3VdbeReusable(v);
116160 break;
116161 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
116163 #ifndef SQLITE_OMIT_WAL
116165 ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
116167 ** Checkpoint the database.
116169 case PragTyp_WAL_CHECKPOINT: {
116170 int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
116171 int eMode = SQLITE_CHECKPOINT_PASSIVE;
116172 if( zRight ){
116173 if( sqlite3StrICmp(zRight, "full")==0 ){
116174 eMode = SQLITE_CHECKPOINT_FULL;
116175 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
116176 eMode = SQLITE_CHECKPOINT_RESTART;
116177 }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
116178 eMode = SQLITE_CHECKPOINT_TRUNCATE;
116181 pParse->nMem = 3;
116182 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
116183 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
116185 break;
116188 ** PRAGMA wal_autocheckpoint
116189 ** PRAGMA wal_autocheckpoint = N
116191 ** Configure a database connection to automatically checkpoint a database
116192 ** after accumulating N frames in the log. Or query for the current value
116193 ** of N.
116195 case PragTyp_WAL_AUTOCHECKPOINT: {
116196 if( zRight ){
116197 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
116199 returnSingleInt(v,
116200 db->xWalCallback==sqlite3WalDefaultHook ?
116201 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
116203 break;
116204 #endif
116207 ** PRAGMA shrink_memory
116209 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
116210 ** connection on which it is invoked to free up as much memory as it
116211 ** can, by calling sqlite3_db_release_memory().
116213 case PragTyp_SHRINK_MEMORY: {
116214 sqlite3_db_release_memory(db);
116215 break;
116219 ** PRAGMA optimize
116220 ** PRAGMA optimize(MASK)
116221 ** PRAGMA schema.optimize
116222 ** PRAGMA schema.optimize(MASK)
116224 ** Attempt to optimize the database. All schemas are optimized in the first
116225 ** two forms, and only the specified schema is optimized in the latter two.
116227 ** The details of optimizations performed by this pragma are expected
116228 ** to change and improve over time. Applications should anticipate that
116229 ** this pragma will perform new optimizations in future releases.
116231 ** The optional argument is a bitmask of optimizations to perform:
116233 ** 0x0001 Debugging mode. Do not actually perform any optimizations
116234 ** but instead return one line of text for each optimization
116235 ** that would have been done. Off by default.
116237 ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
116238 ** See below for additional information.
116240 ** 0x0004 (Not yet implemented) Record usage and performance
116241 ** information from the current session in the
116242 ** database file so that it will be available to "optimize"
116243 ** pragmas run by future database connections.
116245 ** 0x0008 (Not yet implemented) Create indexes that might have
116246 ** been helpful to recent queries
116248 ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
116249 ** of the optimizations listed above except Debug Mode, including new
116250 ** optimizations that have not yet been invented. If new optimizations are
116251 ** ever added that should be off by default, those off-by-default
116252 ** optimizations will have bitmasks of 0x10000 or larger.
116254 ** DETERMINATION OF WHEN TO RUN ANALYZE
116256 ** In the current implementation, a table is analyzed if only if all of
116257 ** the following are true:
116259 ** (1) MASK bit 0x02 is set.
116261 ** (2) The query planner used sqlite_stat1-style statistics for one or
116262 ** more indexes of the table at some point during the lifetime of
116263 ** the current connection.
116265 ** (3) One or more indexes of the table are currently unanalyzed OR
116266 ** the number of rows in the table has increased by 25 times or more
116267 ** since the last time ANALYZE was run.
116269 ** The rules for when tables are analyzed are likely to change in
116270 ** future releases.
116272 case PragTyp_OPTIMIZE: {
116273 int iDbLast; /* Loop termination point for the schema loop */
116274 int iTabCur; /* Cursor for a table whose size needs checking */
116275 HashElem *k; /* Loop over tables of a schema */
116276 Schema *pSchema; /* The current schema */
116277 Table *pTab; /* A table in the schema */
116278 Index *pIdx; /* An index of the table */
116279 LogEst szThreshold; /* Size threshold above which reanalysis is needd */
116280 char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
116281 u32 opMask; /* Mask of operations to perform */
116283 if( zRight ){
116284 opMask = (u32)sqlite3Atoi(zRight);
116285 if( (opMask & 0x02)==0 ) break;
116286 }else{
116287 opMask = 0xfffe;
116289 iTabCur = pParse->nTab++;
116290 for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
116291 if( iDb==1 ) continue;
116292 sqlite3CodeVerifySchema(pParse, iDb);
116293 pSchema = db->aDb[iDb].pSchema;
116294 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
116295 pTab = (Table*)sqliteHashData(k);
116297 /* If table pTab has not been used in a way that would benefit from
116298 ** having analysis statistics during the current session, then skip it.
116299 ** This also has the effect of skipping virtual tables and views */
116300 if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
116302 /* Reanalyze if the table is 25 times larger than the last analysis */
116303 szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
116304 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
116305 if( !pIdx->hasStat1 ){
116306 szThreshold = 0; /* Always analyze if any index lacks statistics */
116307 break;
116310 if( szThreshold ){
116311 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
116312 sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
116313 sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
116314 VdbeCoverage(v);
116316 zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
116317 db->aDb[iDb].zDbSName, pTab->zName);
116318 if( opMask & 0x01 ){
116319 int r1 = sqlite3GetTempReg(pParse);
116320 sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
116321 sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
116322 }else{
116323 sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
116327 sqlite3VdbeAddOp0(v, OP_Expire);
116328 break;
116332 ** PRAGMA busy_timeout
116333 ** PRAGMA busy_timeout = N
116335 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
116336 ** if one is set. If no busy handler or a different busy handler is set
116337 ** then 0 is returned. Setting the busy_timeout to 0 or negative
116338 ** disables the timeout.
116340 /*case PragTyp_BUSY_TIMEOUT*/ default: {
116341 assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
116342 if( zRight ){
116343 sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
116345 returnSingleInt(v, db->busyTimeout);
116346 break;
116350 ** PRAGMA soft_heap_limit
116351 ** PRAGMA soft_heap_limit = N
116353 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
116354 ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
116355 ** specified and is a non-negative integer.
116356 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
116357 ** returns the same integer that would be returned by the
116358 ** sqlite3_soft_heap_limit64(-1) C-language function.
116360 case PragTyp_SOFT_HEAP_LIMIT: {
116361 sqlite3_int64 N;
116362 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
116363 sqlite3_soft_heap_limit64(N);
116365 returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
116366 break;
116370 ** PRAGMA threads
116371 ** PRAGMA threads = N
116373 ** Configure the maximum number of worker threads. Return the new
116374 ** maximum, which might be less than requested.
116376 case PragTyp_THREADS: {
116377 sqlite3_int64 N;
116378 if( zRight
116379 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
116380 && N>=0
116382 sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
116384 returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
116385 break;
116388 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
116390 ** Report the current state of file logs for all databases
116392 case PragTyp_LOCK_STATUS: {
116393 static const char *const azLockName[] = {
116394 "unlocked", "shared", "reserved", "pending", "exclusive"
116396 int i;
116397 pParse->nMem = 2;
116398 for(i=0; i<db->nDb; i++){
116399 Btree *pBt;
116400 const char *zState = "unknown";
116401 int j;
116402 if( db->aDb[i].zDbSName==0 ) continue;
116403 pBt = db->aDb[i].pBt;
116404 if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
116405 zState = "closed";
116406 }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
116407 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
116408 zState = azLockName[j];
116410 sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
116412 break;
116414 #endif
116416 #ifdef SQLITE_HAS_CODEC
116417 case PragTyp_KEY: {
116418 if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
116419 break;
116421 case PragTyp_REKEY: {
116422 if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
116423 break;
116425 case PragTyp_HEXKEY: {
116426 if( zRight ){
116427 u8 iByte;
116428 int i;
116429 char zKey[40];
116430 for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
116431 iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
116432 if( (i&1)!=0 ) zKey[i/2] = iByte;
116434 if( (zLeft[3] & 0xf)==0xb ){
116435 sqlite3_key_v2(db, zDb, zKey, i/2);
116436 }else{
116437 sqlite3_rekey_v2(db, zDb, zKey, i/2);
116440 break;
116442 #endif
116443 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
116444 case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
116445 #ifdef SQLITE_HAS_CODEC
116446 if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
116447 sqlite3_activate_see(&zRight[4]);
116449 #endif
116450 #ifdef SQLITE_ENABLE_CEROD
116451 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
116452 sqlite3_activate_cerod(&zRight[6]);
116454 #endif
116456 break;
116457 #endif
116459 } /* End of the PRAGMA switch */
116461 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
116462 ** purpose is to execute assert() statements to verify that if the
116463 ** PragFlg_NoColumns1 flag is set and the caller specified an argument
116464 ** to the PRAGMA, the implementation has not added any OP_ResultRow
116465 ** instructions to the VM. */
116466 if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
116467 sqlite3VdbeVerifyNoResultRow(v);
116470 pragma_out:
116471 sqlite3DbFree(db, zLeft);
116472 sqlite3DbFree(db, zRight);
116474 #ifndef SQLITE_OMIT_VIRTUALTABLE
116475 /*****************************************************************************
116476 ** Implementation of an eponymous virtual table that runs a pragma.
116479 typedef struct PragmaVtab PragmaVtab;
116480 typedef struct PragmaVtabCursor PragmaVtabCursor;
116481 struct PragmaVtab {
116482 sqlite3_vtab base; /* Base class. Must be first */
116483 sqlite3 *db; /* The database connection to which it belongs */
116484 const PragmaName *pName; /* Name of the pragma */
116485 u8 nHidden; /* Number of hidden columns */
116486 u8 iHidden; /* Index of the first hidden column */
116488 struct PragmaVtabCursor {
116489 sqlite3_vtab_cursor base; /* Base class. Must be first */
116490 sqlite3_stmt *pPragma; /* The pragma statement to run */
116491 sqlite_int64 iRowid; /* Current rowid */
116492 char *azArg[2]; /* Value of the argument and schema */
116496 ** Pragma virtual table module xConnect method.
116498 static int pragmaVtabConnect(
116499 sqlite3 *db,
116500 void *pAux,
116501 int argc, const char *const*argv,
116502 sqlite3_vtab **ppVtab,
116503 char **pzErr
116505 const PragmaName *pPragma = (const PragmaName*)pAux;
116506 PragmaVtab *pTab = 0;
116507 int rc;
116508 int i, j;
116509 char cSep = '(';
116510 StrAccum acc;
116511 char zBuf[200];
116513 UNUSED_PARAMETER(argc);
116514 UNUSED_PARAMETER(argv);
116515 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
116516 sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
116517 for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
116518 sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
116519 cSep = ',';
116521 if( i==0 ){
116522 sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
116523 cSep = ',';
116526 j = 0;
116527 if( pPragma->mPragFlg & PragFlg_Result1 ){
116528 sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
116531 if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
116532 sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
116535 sqlite3StrAccumAppend(&acc, ")", 1);
116536 sqlite3StrAccumFinish(&acc);
116537 assert( strlen(zBuf) < sizeof(zBuf)-1 );
116538 rc = sqlite3_declare_vtab(db, zBuf);
116539 if( rc==SQLITE_OK ){
116540 pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
116541 if( pTab==0 ){
116542 rc = SQLITE_NOMEM;
116543 }else{
116544 memset(pTab, 0, sizeof(PragmaVtab));
116545 pTab->pName = pPragma;
116546 pTab->db = db;
116547 pTab->iHidden = i;
116548 pTab->nHidden = j;
116550 }else{
116551 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
116554 *ppVtab = (sqlite3_vtab*)pTab;
116555 return rc;
116559 ** Pragma virtual table module xDisconnect method.
116561 static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
116562 PragmaVtab *pTab = (PragmaVtab*)pVtab;
116563 sqlite3_free(pTab);
116564 return SQLITE_OK;
116567 /* Figure out the best index to use to search a pragma virtual table.
116569 ** There are not really any index choices. But we want to encourage the
116570 ** query planner to give == constraints on as many hidden parameters as
116571 ** possible, and especially on the first hidden parameter. So return a
116572 ** high cost if hidden parameters are unconstrained.
116574 static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
116575 PragmaVtab *pTab = (PragmaVtab*)tab;
116576 const struct sqlite3_index_constraint *pConstraint;
116577 int i, j;
116578 int seen[2];
116580 pIdxInfo->estimatedCost = (double)1;
116581 if( pTab->nHidden==0 ){ return SQLITE_OK; }
116582 pConstraint = pIdxInfo->aConstraint;
116583 seen[0] = 0;
116584 seen[1] = 0;
116585 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
116586 if( pConstraint->usable==0 ) continue;
116587 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
116588 if( pConstraint->iColumn < pTab->iHidden ) continue;
116589 j = pConstraint->iColumn - pTab->iHidden;
116590 assert( j < 2 );
116591 seen[j] = i+1;
116593 if( seen[0]==0 ){
116594 pIdxInfo->estimatedCost = (double)2147483647;
116595 pIdxInfo->estimatedRows = 2147483647;
116596 return SQLITE_OK;
116598 j = seen[0]-1;
116599 pIdxInfo->aConstraintUsage[j].argvIndex = 1;
116600 pIdxInfo->aConstraintUsage[j].omit = 1;
116601 if( seen[1]==0 ) return SQLITE_OK;
116602 pIdxInfo->estimatedCost = (double)20;
116603 pIdxInfo->estimatedRows = 20;
116604 j = seen[1]-1;
116605 pIdxInfo->aConstraintUsage[j].argvIndex = 2;
116606 pIdxInfo->aConstraintUsage[j].omit = 1;
116607 return SQLITE_OK;
116610 /* Create a new cursor for the pragma virtual table */
116611 static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
116612 PragmaVtabCursor *pCsr;
116613 pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
116614 if( pCsr==0 ) return SQLITE_NOMEM;
116615 memset(pCsr, 0, sizeof(PragmaVtabCursor));
116616 pCsr->base.pVtab = pVtab;
116617 *ppCursor = &pCsr->base;
116618 return SQLITE_OK;
116621 /* Clear all content from pragma virtual table cursor. */
116622 static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
116623 int i;
116624 sqlite3_finalize(pCsr->pPragma);
116625 pCsr->pPragma = 0;
116626 for(i=0; i<ArraySize(pCsr->azArg); i++){
116627 sqlite3_free(pCsr->azArg[i]);
116628 pCsr->azArg[i] = 0;
116632 /* Close a pragma virtual table cursor */
116633 static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
116634 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
116635 pragmaVtabCursorClear(pCsr);
116636 sqlite3_free(pCsr);
116637 return SQLITE_OK;
116640 /* Advance the pragma virtual table cursor to the next row */
116641 static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
116642 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116643 int rc = SQLITE_OK;
116645 /* Increment the xRowid value */
116646 pCsr->iRowid++;
116647 assert( pCsr->pPragma );
116648 if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
116649 rc = sqlite3_finalize(pCsr->pPragma);
116650 pCsr->pPragma = 0;
116651 pragmaVtabCursorClear(pCsr);
116653 return rc;
116657 ** Pragma virtual table module xFilter method.
116659 static int pragmaVtabFilter(
116660 sqlite3_vtab_cursor *pVtabCursor,
116661 int idxNum, const char *idxStr,
116662 int argc, sqlite3_value **argv
116664 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116665 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
116666 int rc;
116667 int i, j;
116668 StrAccum acc;
116669 char *zSql;
116671 UNUSED_PARAMETER(idxNum);
116672 UNUSED_PARAMETER(idxStr);
116673 pragmaVtabCursorClear(pCsr);
116674 j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
116675 for(i=0; i<argc; i++, j++){
116676 const char *zText = (const char*)sqlite3_value_text(argv[i]);
116677 assert( j<ArraySize(pCsr->azArg) );
116678 assert( pCsr->azArg[j]==0 );
116679 if( zText ){
116680 pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
116681 if( pCsr->azArg[j]==0 ){
116682 return SQLITE_NOMEM;
116686 sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
116687 sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
116688 if( pCsr->azArg[1] ){
116689 sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
116691 sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
116692 if( pCsr->azArg[0] ){
116693 sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
116695 zSql = sqlite3StrAccumFinish(&acc);
116696 if( zSql==0 ) return SQLITE_NOMEM;
116697 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
116698 sqlite3_free(zSql);
116699 if( rc!=SQLITE_OK ){
116700 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
116701 return rc;
116703 return pragmaVtabNext(pVtabCursor);
116707 ** Pragma virtual table module xEof method.
116709 static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
116710 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116711 return (pCsr->pPragma==0);
116714 /* The xColumn method simply returns the corresponding column from
116715 ** the PRAGMA.
116717 static int pragmaVtabColumn(
116718 sqlite3_vtab_cursor *pVtabCursor,
116719 sqlite3_context *ctx,
116720 int i
116722 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116723 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
116724 if( i<pTab->iHidden ){
116725 sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
116726 }else{
116727 sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
116729 return SQLITE_OK;
116733 ** Pragma virtual table module xRowid method.
116735 static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
116736 PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116737 *p = pCsr->iRowid;
116738 return SQLITE_OK;
116741 /* The pragma virtual table object */
116742 static const sqlite3_module pragmaVtabModule = {
116743 0, /* iVersion */
116744 0, /* xCreate - create a table */
116745 pragmaVtabConnect, /* xConnect - connect to an existing table */
116746 pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
116747 pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
116748 0, /* xDestroy - Drop a table */
116749 pragmaVtabOpen, /* xOpen - open a cursor */
116750 pragmaVtabClose, /* xClose - close a cursor */
116751 pragmaVtabFilter, /* xFilter - configure scan constraints */
116752 pragmaVtabNext, /* xNext - advance a cursor */
116753 pragmaVtabEof, /* xEof */
116754 pragmaVtabColumn, /* xColumn - read data */
116755 pragmaVtabRowid, /* xRowid - read data */
116756 0, /* xUpdate - write data */
116757 0, /* xBegin - begin transaction */
116758 0, /* xSync - sync transaction */
116759 0, /* xCommit - commit transaction */
116760 0, /* xRollback - rollback transaction */
116761 0, /* xFindFunction - function overloading */
116762 0, /* xRename - rename the table */
116763 0, /* xSavepoint */
116764 0, /* xRelease */
116765 0 /* xRollbackTo */
116769 ** Check to see if zTabName is really the name of a pragma. If it is,
116770 ** then register an eponymous virtual table for that pragma and return
116771 ** a pointer to the Module object for the new virtual table.
116773 SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
116774 const PragmaName *pName;
116775 assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
116776 pName = pragmaLocate(zName+7);
116777 if( pName==0 ) return 0;
116778 if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
116779 assert( sqlite3HashFind(&db->aModule, zName)==0 );
116780 return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
116783 #endif /* SQLITE_OMIT_VIRTUALTABLE */
116785 #endif /* SQLITE_OMIT_PRAGMA */
116787 /************** End of pragma.c **********************************************/
116788 /************** Begin file prepare.c *****************************************/
116790 ** 2005 May 25
116792 ** The author disclaims copyright to this source code. In place of
116793 ** a legal notice, here is a blessing:
116795 ** May you do good and not evil.
116796 ** May you find forgiveness for yourself and forgive others.
116797 ** May you share freely, never taking more than you give.
116799 *************************************************************************
116800 ** This file contains the implementation of the sqlite3_prepare()
116801 ** interface, and routines that contribute to loading the database schema
116802 ** from disk.
116804 /* #include "sqliteInt.h" */
116807 ** Fill the InitData structure with an error message that indicates
116808 ** that the database is corrupt.
116810 static void corruptSchema(
116811 InitData *pData, /* Initialization context */
116812 const char *zObj, /* Object being parsed at the point of error */
116813 const char *zExtra /* Error information */
116815 sqlite3 *db = pData->db;
116816 if( !db->mallocFailed && (db->flags & SQLITE_WriteSchema)==0 ){
116817 char *z;
116818 if( zObj==0 ) zObj = "?";
116819 z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
116820 if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
116821 sqlite3DbFree(db, *pData->pzErrMsg);
116822 *pData->pzErrMsg = z;
116824 pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
116828 ** This is the callback routine for the code that initializes the
116829 ** database. See sqlite3Init() below for additional information.
116830 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
116832 ** Each callback contains the following information:
116834 ** argv[0] = name of thing being created
116835 ** argv[1] = root page number for table or index. 0 for trigger or view.
116836 ** argv[2] = SQL text for the CREATE statement.
116839 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
116840 InitData *pData = (InitData*)pInit;
116841 sqlite3 *db = pData->db;
116842 int iDb = pData->iDb;
116844 assert( argc==3 );
116845 UNUSED_PARAMETER2(NotUsed, argc);
116846 assert( sqlite3_mutex_held(db->mutex) );
116847 DbClearProperty(db, iDb, DB_Empty);
116848 if( db->mallocFailed ){
116849 corruptSchema(pData, argv[0], 0);
116850 return 1;
116853 assert( iDb>=0 && iDb<db->nDb );
116854 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
116855 if( argv[1]==0 ){
116856 corruptSchema(pData, argv[0], 0);
116857 }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
116858 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
116859 ** But because db->init.busy is set to 1, no VDBE code is generated
116860 ** or executed. All the parser does is build the internal data
116861 ** structures that describe the table, index, or view.
116863 int rc;
116864 u8 saved_iDb = db->init.iDb;
116865 sqlite3_stmt *pStmt;
116866 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
116868 assert( db->init.busy );
116869 db->init.iDb = iDb;
116870 db->init.newTnum = sqlite3Atoi(argv[1]);
116871 db->init.orphanTrigger = 0;
116872 TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
116873 rc = db->errCode;
116874 assert( (rc&0xFF)==(rcp&0xFF) );
116875 db->init.iDb = saved_iDb;
116876 assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 );
116877 if( SQLITE_OK!=rc ){
116878 if( db->init.orphanTrigger ){
116879 assert( iDb==1 );
116880 }else{
116881 pData->rc = rc;
116882 if( rc==SQLITE_NOMEM ){
116883 sqlite3OomFault(db);
116884 }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
116885 corruptSchema(pData, argv[0], sqlite3_errmsg(db));
116889 sqlite3_finalize(pStmt);
116890 }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
116891 corruptSchema(pData, argv[0], 0);
116892 }else{
116893 /* If the SQL column is blank it means this is an index that
116894 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
116895 ** constraint for a CREATE TABLE. The index should have already
116896 ** been created when we processed the CREATE TABLE. All we have
116897 ** to do here is record the root page number for that index.
116899 Index *pIndex;
116900 pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
116901 if( pIndex==0 ){
116902 /* This can occur if there exists an index on a TEMP table which
116903 ** has the same name as another index on a permanent index. Since
116904 ** the permanent table is hidden by the TEMP table, we can also
116905 ** safely ignore the index on the permanent table.
116907 /* Do Nothing */;
116908 }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
116909 corruptSchema(pData, argv[0], "invalid rootpage");
116912 return 0;
116916 ** Attempt to read the database schema and initialize internal
116917 ** data structures for a single database file. The index of the
116918 ** database file is given by iDb. iDb==0 is used for the main
116919 ** database. iDb==1 should never be used. iDb>=2 is used for
116920 ** auxiliary databases. Return one of the SQLITE_ error codes to
116921 ** indicate success or failure.
116923 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
116924 int rc;
116925 int i;
116926 #ifndef SQLITE_OMIT_DEPRECATED
116927 int size;
116928 #endif
116929 Db *pDb;
116930 char const *azArg[4];
116931 int meta[5];
116932 InitData initData;
116933 const char *zMasterName;
116934 int openedTransaction = 0;
116936 assert( iDb>=0 && iDb<db->nDb );
116937 assert( db->aDb[iDb].pSchema );
116938 assert( sqlite3_mutex_held(db->mutex) );
116939 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
116941 db->init.busy = 1;
116943 /* Construct the in-memory representation schema tables (sqlite_master or
116944 ** sqlite_temp_master) by invoking the parser directly. The appropriate
116945 ** table name will be inserted automatically by the parser so we can just
116946 ** use the abbreviation "x" here. The parser will also automatically tag
116947 ** the schema table as read-only. */
116948 azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
116949 azArg[1] = "1";
116950 azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
116951 "rootpage int,sql text)";
116952 azArg[3] = 0;
116953 initData.db = db;
116954 initData.iDb = iDb;
116955 initData.rc = SQLITE_OK;
116956 initData.pzErrMsg = pzErrMsg;
116957 sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
116958 if( initData.rc ){
116959 rc = initData.rc;
116960 goto error_out;
116963 /* Create a cursor to hold the database open
116965 pDb = &db->aDb[iDb];
116966 if( pDb->pBt==0 ){
116967 assert( iDb==1 );
116968 DbSetProperty(db, 1, DB_SchemaLoaded);
116969 rc = SQLITE_OK;
116970 goto error_out;
116973 /* If there is not already a read-only (or read-write) transaction opened
116974 ** on the b-tree database, open one now. If a transaction is opened, it
116975 ** will be closed before this function returns. */
116976 sqlite3BtreeEnter(pDb->pBt);
116977 if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
116978 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
116979 if( rc!=SQLITE_OK ){
116980 sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
116981 goto initone_error_out;
116983 openedTransaction = 1;
116986 /* Get the database meta information.
116988 ** Meta values are as follows:
116989 ** meta[0] Schema cookie. Changes with each schema change.
116990 ** meta[1] File format of schema layer.
116991 ** meta[2] Size of the page cache.
116992 ** meta[3] Largest rootpage (auto/incr_vacuum mode)
116993 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
116994 ** meta[5] User version
116995 ** meta[6] Incremental vacuum mode
116996 ** meta[7] unused
116997 ** meta[8] unused
116998 ** meta[9] unused
117000 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
117001 ** the possible values of meta[4].
117003 for(i=0; i<ArraySize(meta); i++){
117004 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
117006 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
117008 /* If opening a non-empty database, check the text encoding. For the
117009 ** main database, set sqlite3.enc to the encoding of the main database.
117010 ** For an attached db, it is an error if the encoding is not the same
117011 ** as sqlite3.enc.
117013 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
117014 if( iDb==0 ){
117015 #ifndef SQLITE_OMIT_UTF16
117016 u8 encoding;
117017 /* If opening the main database, set ENC(db). */
117018 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
117019 if( encoding==0 ) encoding = SQLITE_UTF8;
117020 ENC(db) = encoding;
117021 #else
117022 ENC(db) = SQLITE_UTF8;
117023 #endif
117024 }else{
117025 /* If opening an attached database, the encoding much match ENC(db) */
117026 if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
117027 sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
117028 " text encoding as main database");
117029 rc = SQLITE_ERROR;
117030 goto initone_error_out;
117033 }else{
117034 DbSetProperty(db, iDb, DB_Empty);
117036 pDb->pSchema->enc = ENC(db);
117038 if( pDb->pSchema->cache_size==0 ){
117039 #ifndef SQLITE_OMIT_DEPRECATED
117040 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
117041 if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
117042 pDb->pSchema->cache_size = size;
117043 #else
117044 pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
117045 #endif
117046 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
117050 ** file_format==1 Version 3.0.0.
117051 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
117052 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
117053 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
117055 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
117056 if( pDb->pSchema->file_format==0 ){
117057 pDb->pSchema->file_format = 1;
117059 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
117060 sqlite3SetString(pzErrMsg, db, "unsupported file format");
117061 rc = SQLITE_ERROR;
117062 goto initone_error_out;
117065 /* Ticket #2804: When we open a database in the newer file format,
117066 ** clear the legacy_file_format pragma flag so that a VACUUM will
117067 ** not downgrade the database and thus invalidate any descending
117068 ** indices that the user might have created.
117070 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
117071 db->flags &= ~SQLITE_LegacyFileFmt;
117074 /* Read the schema information out of the schema tables
117076 assert( db->init.busy );
117078 char *zSql;
117079 zSql = sqlite3MPrintf(db,
117080 "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
117081 db->aDb[iDb].zDbSName, zMasterName);
117082 #ifndef SQLITE_OMIT_AUTHORIZATION
117084 sqlite3_xauth xAuth;
117085 xAuth = db->xAuth;
117086 db->xAuth = 0;
117087 #endif
117088 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
117089 #ifndef SQLITE_OMIT_AUTHORIZATION
117090 db->xAuth = xAuth;
117092 #endif
117093 if( rc==SQLITE_OK ) rc = initData.rc;
117094 sqlite3DbFree(db, zSql);
117095 #ifndef SQLITE_OMIT_ANALYZE
117096 if( rc==SQLITE_OK ){
117097 sqlite3AnalysisLoad(db, iDb);
117099 #endif
117101 if( db->mallocFailed ){
117102 rc = SQLITE_NOMEM_BKPT;
117103 sqlite3ResetAllSchemasOfConnection(db);
117105 if( rc==SQLITE_OK || (db->flags&SQLITE_WriteSchema)){
117106 /* Black magic: If the SQLITE_WriteSchema flag is set, then consider
117107 ** the schema loaded, even if errors occurred. In this situation the
117108 ** current sqlite3_prepare() operation will fail, but the following one
117109 ** will attempt to compile the supplied statement against whatever subset
117110 ** of the schema was loaded before the error occurred. The primary
117111 ** purpose of this is to allow access to the sqlite_master table
117112 ** even when its contents have been corrupted.
117114 DbSetProperty(db, iDb, DB_SchemaLoaded);
117115 rc = SQLITE_OK;
117118 /* Jump here for an error that occurs after successfully allocating
117119 ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
117120 ** before that point, jump to error_out.
117122 initone_error_out:
117123 if( openedTransaction ){
117124 sqlite3BtreeCommit(pDb->pBt);
117126 sqlite3BtreeLeave(pDb->pBt);
117128 error_out:
117129 if( rc ){
117130 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
117131 sqlite3OomFault(db);
117133 sqlite3ResetOneSchema(db, iDb);
117135 db->init.busy = 0;
117136 return rc;
117140 ** Initialize all database files - the main database file, the file
117141 ** used to store temporary tables, and any additional database files
117142 ** created using ATTACH statements. Return a success code. If an
117143 ** error occurs, write an error message into *pzErrMsg.
117145 ** After a database is initialized, the DB_SchemaLoaded bit is set
117146 ** bit is set in the flags field of the Db structure. If the database
117147 ** file was of zero-length, then the DB_Empty flag is also set.
117149 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
117150 int i, rc;
117151 int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
117153 assert( sqlite3_mutex_held(db->mutex) );
117154 assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
117155 assert( db->init.busy==0 );
117156 ENC(db) = SCHEMA_ENC(db);
117157 assert( db->nDb>0 );
117158 /* Do the main schema first */
117159 if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
117160 rc = sqlite3InitOne(db, 0, pzErrMsg);
117161 if( rc ) return rc;
117163 /* All other schemas after the main schema. The "temp" schema must be last */
117164 for(i=db->nDb-1; i>0; i--){
117165 if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
117166 rc = sqlite3InitOne(db, i, pzErrMsg);
117167 if( rc ) return rc;
117170 if( commit_internal ){
117171 sqlite3CommitInternalChanges(db);
117173 return SQLITE_OK;
117177 ** This routine is a no-op if the database schema is already initialized.
117178 ** Otherwise, the schema is loaded. An error code is returned.
117180 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
117181 int rc = SQLITE_OK;
117182 sqlite3 *db = pParse->db;
117183 assert( sqlite3_mutex_held(db->mutex) );
117184 if( !db->init.busy ){
117185 rc = sqlite3Init(db, &pParse->zErrMsg);
117187 if( rc!=SQLITE_OK ){
117188 pParse->rc = rc;
117189 pParse->nErr++;
117191 return rc;
117196 ** Check schema cookies in all databases. If any cookie is out
117197 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
117198 ** make no changes to pParse->rc.
117200 static void schemaIsValid(Parse *pParse){
117201 sqlite3 *db = pParse->db;
117202 int iDb;
117203 int rc;
117204 int cookie;
117206 assert( pParse->checkSchema );
117207 assert( sqlite3_mutex_held(db->mutex) );
117208 for(iDb=0; iDb<db->nDb; iDb++){
117209 int openedTransaction = 0; /* True if a transaction is opened */
117210 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
117211 if( pBt==0 ) continue;
117213 /* If there is not already a read-only (or read-write) transaction opened
117214 ** on the b-tree database, open one now. If a transaction is opened, it
117215 ** will be closed immediately after reading the meta-value. */
117216 if( !sqlite3BtreeIsInReadTrans(pBt) ){
117217 rc = sqlite3BtreeBeginTrans(pBt, 0);
117218 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
117219 sqlite3OomFault(db);
117221 if( rc!=SQLITE_OK ) return;
117222 openedTransaction = 1;
117225 /* Read the schema cookie from the database. If it does not match the
117226 ** value stored as part of the in-memory schema representation,
117227 ** set Parse.rc to SQLITE_SCHEMA. */
117228 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
117229 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
117230 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
117231 sqlite3ResetOneSchema(db, iDb);
117232 pParse->rc = SQLITE_SCHEMA;
117235 /* Close the transaction, if one was opened. */
117236 if( openedTransaction ){
117237 sqlite3BtreeCommit(pBt);
117243 ** Convert a schema pointer into the iDb index that indicates
117244 ** which database file in db->aDb[] the schema refers to.
117246 ** If the same database is attached more than once, the first
117247 ** attached database is returned.
117249 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
117250 int i = -1000000;
117252 /* If pSchema is NULL, then return -1000000. This happens when code in
117253 ** expr.c is trying to resolve a reference to a transient table (i.e. one
117254 ** created by a sub-select). In this case the return value of this
117255 ** function should never be used.
117257 ** We return -1000000 instead of the more usual -1 simply because using
117258 ** -1000000 as the incorrect index into db->aDb[] is much
117259 ** more likely to cause a segfault than -1 (of course there are assert()
117260 ** statements too, but it never hurts to play the odds).
117262 assert( sqlite3_mutex_held(db->mutex) );
117263 if( pSchema ){
117264 for(i=0; ALWAYS(i<db->nDb); i++){
117265 if( db->aDb[i].pSchema==pSchema ){
117266 break;
117269 assert( i>=0 && i<db->nDb );
117271 return i;
117275 ** Free all memory allocations in the pParse object
117277 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
117278 sqlite3 *db = pParse->db;
117279 sqlite3DbFree(db, pParse->aLabel);
117280 sqlite3ExprListDelete(db, pParse->pConstExpr);
117281 if( db ){
117282 assert( db->lookaside.bDisable >= pParse->disableLookaside );
117283 db->lookaside.bDisable -= pParse->disableLookaside;
117285 pParse->disableLookaside = 0;
117289 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
117291 static int sqlite3Prepare(
117292 sqlite3 *db, /* Database handle. */
117293 const char *zSql, /* UTF-8 encoded SQL statement. */
117294 int nBytes, /* Length of zSql in bytes. */
117295 u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
117296 Vdbe *pReprepare, /* VM being reprepared */
117297 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
117298 const char **pzTail /* OUT: End of parsed string */
117300 char *zErrMsg = 0; /* Error message */
117301 int rc = SQLITE_OK; /* Result code */
117302 int i; /* Loop counter */
117303 Parse sParse; /* Parsing context */
117305 memset(&sParse, 0, PARSE_HDR_SZ);
117306 memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
117307 sParse.pReprepare = pReprepare;
117308 assert( ppStmt && *ppStmt==0 );
117309 /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
117310 assert( sqlite3_mutex_held(db->mutex) );
117312 /* For a long-term use prepared statement avoid the use of
117313 ** lookaside memory.
117315 if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
117316 sParse.disableLookaside++;
117317 db->lookaside.bDisable++;
117320 /* Check to verify that it is possible to get a read lock on all
117321 ** database schemas. The inability to get a read lock indicates that
117322 ** some other database connection is holding a write-lock, which in
117323 ** turn means that the other connection has made uncommitted changes
117324 ** to the schema.
117326 ** Were we to proceed and prepare the statement against the uncommitted
117327 ** schema changes and if those schema changes are subsequently rolled
117328 ** back and different changes are made in their place, then when this
117329 ** prepared statement goes to run the schema cookie would fail to detect
117330 ** the schema change. Disaster would follow.
117332 ** This thread is currently holding mutexes on all Btrees (because
117333 ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
117334 ** is not possible for another thread to start a new schema change
117335 ** while this routine is running. Hence, we do not need to hold
117336 ** locks on the schema, we just need to make sure nobody else is
117337 ** holding them.
117339 ** Note that setting READ_UNCOMMITTED overrides most lock detection,
117340 ** but it does *not* override schema lock detection, so this all still
117341 ** works even if READ_UNCOMMITTED is set.
117343 for(i=0; i<db->nDb; i++) {
117344 Btree *pBt = db->aDb[i].pBt;
117345 if( pBt ){
117346 assert( sqlite3BtreeHoldsMutex(pBt) );
117347 rc = sqlite3BtreeSchemaLocked(pBt);
117348 if( rc ){
117349 const char *zDb = db->aDb[i].zDbSName;
117350 sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
117351 testcase( db->flags & SQLITE_ReadUncommit );
117352 goto end_prepare;
117357 sqlite3VtabUnlockList(db);
117359 sParse.db = db;
117360 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
117361 char *zSqlCopy;
117362 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
117363 testcase( nBytes==mxLen );
117364 testcase( nBytes==mxLen+1 );
117365 if( nBytes>mxLen ){
117366 sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
117367 rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
117368 goto end_prepare;
117370 zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
117371 if( zSqlCopy ){
117372 sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
117373 sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
117374 sqlite3DbFree(db, zSqlCopy);
117375 }else{
117376 sParse.zTail = &zSql[nBytes];
117378 }else{
117379 sqlite3RunParser(&sParse, zSql, &zErrMsg);
117381 assert( 0==sParse.nQueryLoop );
117383 if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
117384 if( sParse.checkSchema ){
117385 schemaIsValid(&sParse);
117387 if( db->mallocFailed ){
117388 sParse.rc = SQLITE_NOMEM_BKPT;
117390 if( pzTail ){
117391 *pzTail = sParse.zTail;
117393 rc = sParse.rc;
117395 #ifndef SQLITE_OMIT_EXPLAIN
117396 if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
117397 static const char * const azColName[] = {
117398 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
117399 "selectid", "order", "from", "detail"
117401 int iFirst, mx;
117402 if( sParse.explain==2 ){
117403 sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
117404 iFirst = 8;
117405 mx = 12;
117406 }else{
117407 sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
117408 iFirst = 0;
117409 mx = 8;
117411 for(i=iFirst; i<mx; i++){
117412 sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
117413 azColName[i], SQLITE_STATIC);
117416 #endif
117418 if( db->init.busy==0 ){
117419 sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
117421 if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
117422 sqlite3VdbeFinalize(sParse.pVdbe);
117423 assert(!(*ppStmt));
117424 }else{
117425 *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
117428 if( zErrMsg ){
117429 sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
117430 sqlite3DbFree(db, zErrMsg);
117431 }else{
117432 sqlite3Error(db, rc);
117435 /* Delete any TriggerPrg structures allocated while parsing this statement. */
117436 while( sParse.pTriggerPrg ){
117437 TriggerPrg *pT = sParse.pTriggerPrg;
117438 sParse.pTriggerPrg = pT->pNext;
117439 sqlite3DbFree(db, pT);
117442 end_prepare:
117444 sqlite3ParserReset(&sParse);
117445 rc = sqlite3ApiExit(db, rc);
117446 assert( (rc&db->errMask)==rc );
117447 return rc;
117449 static int sqlite3LockAndPrepare(
117450 sqlite3 *db, /* Database handle. */
117451 const char *zSql, /* UTF-8 encoded SQL statement. */
117452 int nBytes, /* Length of zSql in bytes. */
117453 u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
117454 Vdbe *pOld, /* VM being reprepared */
117455 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
117456 const char **pzTail /* OUT: End of parsed string */
117458 int rc;
117460 #ifdef SQLITE_ENABLE_API_ARMOR
117461 if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
117462 #endif
117463 *ppStmt = 0;
117464 if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
117465 return SQLITE_MISUSE_BKPT;
117467 sqlite3_mutex_enter(db->mutex);
117468 sqlite3BtreeEnterAll(db);
117469 rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
117470 if( rc==SQLITE_SCHEMA ){
117471 sqlite3ResetOneSchema(db, -1);
117472 sqlite3_finalize(*ppStmt);
117473 rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
117475 sqlite3BtreeLeaveAll(db);
117476 sqlite3_mutex_leave(db->mutex);
117477 assert( rc==SQLITE_OK || *ppStmt==0 );
117478 return rc;
117482 ** Rerun the compilation of a statement after a schema change.
117484 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
117485 ** if the statement cannot be recompiled because another connection has
117486 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
117487 ** occurs, return SQLITE_SCHEMA.
117489 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
117490 int rc;
117491 sqlite3_stmt *pNew;
117492 const char *zSql;
117493 sqlite3 *db;
117494 u8 prepFlags;
117496 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
117497 zSql = sqlite3_sql((sqlite3_stmt *)p);
117498 assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
117499 db = sqlite3VdbeDb(p);
117500 assert( sqlite3_mutex_held(db->mutex) );
117501 prepFlags = sqlite3VdbePrepareFlags(p);
117502 rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
117503 if( rc ){
117504 if( rc==SQLITE_NOMEM ){
117505 sqlite3OomFault(db);
117507 assert( pNew==0 );
117508 return rc;
117509 }else{
117510 assert( pNew!=0 );
117512 sqlite3VdbeSwap((Vdbe*)pNew, p);
117513 sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
117514 sqlite3VdbeResetStepResult((Vdbe*)pNew);
117515 sqlite3VdbeFinalize((Vdbe*)pNew);
117516 return SQLITE_OK;
117521 ** Two versions of the official API. Legacy and new use. In the legacy
117522 ** version, the original SQL text is not saved in the prepared statement
117523 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
117524 ** sqlite3_step(). In the new version, the original SQL text is retained
117525 ** and the statement is automatically recompiled if an schema change
117526 ** occurs.
117528 SQLITE_API int sqlite3_prepare(
117529 sqlite3 *db, /* Database handle. */
117530 const char *zSql, /* UTF-8 encoded SQL statement. */
117531 int nBytes, /* Length of zSql in bytes. */
117532 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
117533 const char **pzTail /* OUT: End of parsed string */
117535 int rc;
117536 rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
117537 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
117538 return rc;
117540 SQLITE_API int sqlite3_prepare_v2(
117541 sqlite3 *db, /* Database handle. */
117542 const char *zSql, /* UTF-8 encoded SQL statement. */
117543 int nBytes, /* Length of zSql in bytes. */
117544 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
117545 const char **pzTail /* OUT: End of parsed string */
117547 int rc;
117548 /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
117549 ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
117550 ** parameter.
117552 ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
117553 rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
117554 ppStmt,pzTail);
117555 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
117556 return rc;
117558 SQLITE_API int sqlite3_prepare_v3(
117559 sqlite3 *db, /* Database handle. */
117560 const char *zSql, /* UTF-8 encoded SQL statement. */
117561 int nBytes, /* Length of zSql in bytes. */
117562 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
117563 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
117564 const char **pzTail /* OUT: End of parsed string */
117566 int rc;
117567 /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
117568 ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
117569 ** which is a bit array consisting of zero or more of the
117570 ** SQLITE_PREPARE_* flags.
117572 ** Proof by comparison to the implementation of sqlite3_prepare_v2()
117573 ** directly above. */
117574 rc = sqlite3LockAndPrepare(db,zSql,nBytes,
117575 SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
117576 0,ppStmt,pzTail);
117577 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
117578 return rc;
117582 #ifndef SQLITE_OMIT_UTF16
117584 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
117586 static int sqlite3Prepare16(
117587 sqlite3 *db, /* Database handle. */
117588 const void *zSql, /* UTF-16 encoded SQL statement. */
117589 int nBytes, /* Length of zSql in bytes. */
117590 u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
117591 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
117592 const void **pzTail /* OUT: End of parsed string */
117594 /* This function currently works by first transforming the UTF-16
117595 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
117596 ** tricky bit is figuring out the pointer to return in *pzTail.
117598 char *zSql8;
117599 const char *zTail8 = 0;
117600 int rc = SQLITE_OK;
117602 #ifdef SQLITE_ENABLE_API_ARMOR
117603 if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
117604 #endif
117605 *ppStmt = 0;
117606 if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
117607 return SQLITE_MISUSE_BKPT;
117609 if( nBytes>=0 ){
117610 int sz;
117611 const char *z = (const char*)zSql;
117612 for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
117613 nBytes = sz;
117615 sqlite3_mutex_enter(db->mutex);
117616 zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
117617 if( zSql8 ){
117618 rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
117621 if( zTail8 && pzTail ){
117622 /* If sqlite3_prepare returns a tail pointer, we calculate the
117623 ** equivalent pointer into the UTF-16 string by counting the unicode
117624 ** characters between zSql8 and zTail8, and then returning a pointer
117625 ** the same number of characters into the UTF-16 string.
117627 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
117628 *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
117630 sqlite3DbFree(db, zSql8);
117631 rc = sqlite3ApiExit(db, rc);
117632 sqlite3_mutex_leave(db->mutex);
117633 return rc;
117637 ** Two versions of the official API. Legacy and new use. In the legacy
117638 ** version, the original SQL text is not saved in the prepared statement
117639 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
117640 ** sqlite3_step(). In the new version, the original SQL text is retained
117641 ** and the statement is automatically recompiled if an schema change
117642 ** occurs.
117644 SQLITE_API int sqlite3_prepare16(
117645 sqlite3 *db, /* Database handle. */
117646 const void *zSql, /* UTF-16 encoded SQL statement. */
117647 int nBytes, /* Length of zSql in bytes. */
117648 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
117649 const void **pzTail /* OUT: End of parsed string */
117651 int rc;
117652 rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
117653 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
117654 return rc;
117656 SQLITE_API int sqlite3_prepare16_v2(
117657 sqlite3 *db, /* Database handle. */
117658 const void *zSql, /* UTF-16 encoded SQL statement. */
117659 int nBytes, /* Length of zSql in bytes. */
117660 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
117661 const void **pzTail /* OUT: End of parsed string */
117663 int rc;
117664 rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
117665 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
117666 return rc;
117668 SQLITE_API int sqlite3_prepare16_v3(
117669 sqlite3 *db, /* Database handle. */
117670 const void *zSql, /* UTF-16 encoded SQL statement. */
117671 int nBytes, /* Length of zSql in bytes. */
117672 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
117673 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
117674 const void **pzTail /* OUT: End of parsed string */
117676 int rc;
117677 rc = sqlite3Prepare16(db,zSql,nBytes,
117678 SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
117679 ppStmt,pzTail);
117680 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
117681 return rc;
117684 #endif /* SQLITE_OMIT_UTF16 */
117686 /************** End of prepare.c *********************************************/
117687 /************** Begin file select.c ******************************************/
117689 ** 2001 September 15
117691 ** The author disclaims copyright to this source code. In place of
117692 ** a legal notice, here is a blessing:
117694 ** May you do good and not evil.
117695 ** May you find forgiveness for yourself and forgive others.
117696 ** May you share freely, never taking more than you give.
117698 *************************************************************************
117699 ** This file contains C code routines that are called by the parser
117700 ** to handle SELECT statements in SQLite.
117702 /* #include "sqliteInt.h" */
117705 ** Trace output macros
117707 #if SELECTTRACE_ENABLED
117708 /***/ int sqlite3SelectTrace = 0;
117709 # define SELECTTRACE(K,P,S,X) \
117710 if(sqlite3SelectTrace&(K)) \
117711 sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
117712 (S)->zSelName,(S)),\
117713 sqlite3DebugPrintf X
117714 #else
117715 # define SELECTTRACE(K,P,S,X)
117716 #endif
117720 ** An instance of the following object is used to record information about
117721 ** how to process the DISTINCT keyword, to simplify passing that information
117722 ** into the selectInnerLoop() routine.
117724 typedef struct DistinctCtx DistinctCtx;
117725 struct DistinctCtx {
117726 u8 isTnct; /* True if the DISTINCT keyword is present */
117727 u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
117728 int tabTnct; /* Ephemeral table used for DISTINCT processing */
117729 int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
117733 ** An instance of the following object is used to record information about
117734 ** the ORDER BY (or GROUP BY) clause of query is being coded.
117736 typedef struct SortCtx SortCtx;
117737 struct SortCtx {
117738 ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
117739 int nOBSat; /* Number of ORDER BY terms satisfied by indices */
117740 int iECursor; /* Cursor number for the sorter */
117741 int regReturn; /* Register holding block-output return address */
117742 int labelBkOut; /* Start label for the block-output subroutine */
117743 int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
117744 int labelDone; /* Jump here when done, ex: LIMIT reached */
117745 u8 sortFlags; /* Zero or more SORTFLAG_* bits */
117746 u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
117748 #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
117751 ** Delete all the content of a Select structure. Deallocate the structure
117752 ** itself only if bFree is true.
117754 static void clearSelect(sqlite3 *db, Select *p, int bFree){
117755 while( p ){
117756 Select *pPrior = p->pPrior;
117757 sqlite3ExprListDelete(db, p->pEList);
117758 sqlite3SrcListDelete(db, p->pSrc);
117759 sqlite3ExprDelete(db, p->pWhere);
117760 sqlite3ExprListDelete(db, p->pGroupBy);
117761 sqlite3ExprDelete(db, p->pHaving);
117762 sqlite3ExprListDelete(db, p->pOrderBy);
117763 sqlite3ExprDelete(db, p->pLimit);
117764 sqlite3ExprDelete(db, p->pOffset);
117765 if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
117766 if( bFree ) sqlite3DbFreeNN(db, p);
117767 p = pPrior;
117768 bFree = 1;
117773 ** Initialize a SelectDest structure.
117775 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
117776 pDest->eDest = (u8)eDest;
117777 pDest->iSDParm = iParm;
117778 pDest->zAffSdst = 0;
117779 pDest->iSdst = 0;
117780 pDest->nSdst = 0;
117785 ** Allocate a new Select structure and return a pointer to that
117786 ** structure.
117788 SQLITE_PRIVATE Select *sqlite3SelectNew(
117789 Parse *pParse, /* Parsing context */
117790 ExprList *pEList, /* which columns to include in the result */
117791 SrcList *pSrc, /* the FROM clause -- which tables to scan */
117792 Expr *pWhere, /* the WHERE clause */
117793 ExprList *pGroupBy, /* the GROUP BY clause */
117794 Expr *pHaving, /* the HAVING clause */
117795 ExprList *pOrderBy, /* the ORDER BY clause */
117796 u32 selFlags, /* Flag parameters, such as SF_Distinct */
117797 Expr *pLimit, /* LIMIT value. NULL means not used */
117798 Expr *pOffset /* OFFSET value. NULL means no offset */
117800 Select *pNew;
117801 Select standin;
117802 pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
117803 if( pNew==0 ){
117804 assert( pParse->db->mallocFailed );
117805 pNew = &standin;
117807 if( pEList==0 ){
117808 pEList = sqlite3ExprListAppend(pParse, 0,
117809 sqlite3Expr(pParse->db,TK_ASTERISK,0));
117811 pNew->pEList = pEList;
117812 pNew->op = TK_SELECT;
117813 pNew->selFlags = selFlags;
117814 pNew->iLimit = 0;
117815 pNew->iOffset = 0;
117816 #if SELECTTRACE_ENABLED
117817 pNew->zSelName[0] = 0;
117818 #endif
117819 pNew->addrOpenEphm[0] = -1;
117820 pNew->addrOpenEphm[1] = -1;
117821 pNew->nSelectRow = 0;
117822 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
117823 pNew->pSrc = pSrc;
117824 pNew->pWhere = pWhere;
117825 pNew->pGroupBy = pGroupBy;
117826 pNew->pHaving = pHaving;
117827 pNew->pOrderBy = pOrderBy;
117828 pNew->pPrior = 0;
117829 pNew->pNext = 0;
117830 pNew->pLimit = pLimit;
117831 pNew->pOffset = pOffset;
117832 pNew->pWith = 0;
117833 assert( pOffset==0 || pLimit!=0 || pParse->nErr>0
117834 || pParse->db->mallocFailed!=0 );
117835 if( pParse->db->mallocFailed ) {
117836 clearSelect(pParse->db, pNew, pNew!=&standin);
117837 pNew = 0;
117838 }else{
117839 assert( pNew->pSrc!=0 || pParse->nErr>0 );
117841 assert( pNew!=&standin );
117842 return pNew;
117845 #if SELECTTRACE_ENABLED
117847 ** Set the name of a Select object
117849 SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
117850 if( p && zName ){
117851 sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
117854 #endif
117858 ** Delete the given Select structure and all of its substructures.
117860 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
117861 if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
117865 ** Return a pointer to the right-most SELECT statement in a compound.
117867 static Select *findRightmost(Select *p){
117868 while( p->pNext ) p = p->pNext;
117869 return p;
117873 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
117874 ** type of join. Return an integer constant that expresses that type
117875 ** in terms of the following bit values:
117877 ** JT_INNER
117878 ** JT_CROSS
117879 ** JT_OUTER
117880 ** JT_NATURAL
117881 ** JT_LEFT
117882 ** JT_RIGHT
117884 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
117886 ** If an illegal or unsupported join type is seen, then still return
117887 ** a join type, but put an error in the pParse structure.
117889 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
117890 int jointype = 0;
117891 Token *apAll[3];
117892 Token *p;
117893 /* 0123456789 123456789 123456789 123 */
117894 static const char zKeyText[] = "naturaleftouterightfullinnercross";
117895 static const struct {
117896 u8 i; /* Beginning of keyword text in zKeyText[] */
117897 u8 nChar; /* Length of the keyword in characters */
117898 u8 code; /* Join type mask */
117899 } aKeyword[] = {
117900 /* natural */ { 0, 7, JT_NATURAL },
117901 /* left */ { 6, 4, JT_LEFT|JT_OUTER },
117902 /* outer */ { 10, 5, JT_OUTER },
117903 /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
117904 /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
117905 /* inner */ { 23, 5, JT_INNER },
117906 /* cross */ { 28, 5, JT_INNER|JT_CROSS },
117908 int i, j;
117909 apAll[0] = pA;
117910 apAll[1] = pB;
117911 apAll[2] = pC;
117912 for(i=0; i<3 && apAll[i]; i++){
117913 p = apAll[i];
117914 for(j=0; j<ArraySize(aKeyword); j++){
117915 if( p->n==aKeyword[j].nChar
117916 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
117917 jointype |= aKeyword[j].code;
117918 break;
117921 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
117922 if( j>=ArraySize(aKeyword) ){
117923 jointype |= JT_ERROR;
117924 break;
117928 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
117929 (jointype & JT_ERROR)!=0
117931 const char *zSp = " ";
117932 assert( pB!=0 );
117933 if( pC==0 ){ zSp++; }
117934 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
117935 "%T %T%s%T", pA, pB, zSp, pC);
117936 jointype = JT_INNER;
117937 }else if( (jointype & JT_OUTER)!=0
117938 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
117939 sqlite3ErrorMsg(pParse,
117940 "RIGHT and FULL OUTER JOINs are not currently supported");
117941 jointype = JT_INNER;
117943 return jointype;
117947 ** Return the index of a column in a table. Return -1 if the column
117948 ** is not contained in the table.
117950 static int columnIndex(Table *pTab, const char *zCol){
117951 int i;
117952 for(i=0; i<pTab->nCol; i++){
117953 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
117955 return -1;
117959 ** Search the first N tables in pSrc, from left to right, looking for a
117960 ** table that has a column named zCol.
117962 ** When found, set *piTab and *piCol to the table index and column index
117963 ** of the matching column and return TRUE.
117965 ** If not found, return FALSE.
117967 static int tableAndColumnIndex(
117968 SrcList *pSrc, /* Array of tables to search */
117969 int N, /* Number of tables in pSrc->a[] to search */
117970 const char *zCol, /* Name of the column we are looking for */
117971 int *piTab, /* Write index of pSrc->a[] here */
117972 int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
117974 int i; /* For looping over tables in pSrc */
117975 int iCol; /* Index of column matching zCol */
117977 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
117978 for(i=0; i<N; i++){
117979 iCol = columnIndex(pSrc->a[i].pTab, zCol);
117980 if( iCol>=0 ){
117981 if( piTab ){
117982 *piTab = i;
117983 *piCol = iCol;
117985 return 1;
117988 return 0;
117992 ** This function is used to add terms implied by JOIN syntax to the
117993 ** WHERE clause expression of a SELECT statement. The new term, which
117994 ** is ANDed with the existing WHERE clause, is of the form:
117996 ** (tab1.col1 = tab2.col2)
117998 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
117999 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
118000 ** column iColRight of tab2.
118002 static void addWhereTerm(
118003 Parse *pParse, /* Parsing context */
118004 SrcList *pSrc, /* List of tables in FROM clause */
118005 int iLeft, /* Index of first table to join in pSrc */
118006 int iColLeft, /* Index of column in first table */
118007 int iRight, /* Index of second table in pSrc */
118008 int iColRight, /* Index of column in second table */
118009 int isOuterJoin, /* True if this is an OUTER join */
118010 Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
118012 sqlite3 *db = pParse->db;
118013 Expr *pE1;
118014 Expr *pE2;
118015 Expr *pEq;
118017 assert( iLeft<iRight );
118018 assert( pSrc->nSrc>iRight );
118019 assert( pSrc->a[iLeft].pTab );
118020 assert( pSrc->a[iRight].pTab );
118022 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
118023 pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
118025 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
118026 if( pEq && isOuterJoin ){
118027 ExprSetProperty(pEq, EP_FromJoin);
118028 assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
118029 ExprSetVVAProperty(pEq, EP_NoReduce);
118030 pEq->iRightJoinTable = (i16)pE2->iTable;
118032 *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
118036 ** Set the EP_FromJoin property on all terms of the given expression.
118037 ** And set the Expr.iRightJoinTable to iTable for every term in the
118038 ** expression.
118040 ** The EP_FromJoin property is used on terms of an expression to tell
118041 ** the LEFT OUTER JOIN processing logic that this term is part of the
118042 ** join restriction specified in the ON or USING clause and not a part
118043 ** of the more general WHERE clause. These terms are moved over to the
118044 ** WHERE clause during join processing but we need to remember that they
118045 ** originated in the ON or USING clause.
118047 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
118048 ** expression depends on table iRightJoinTable even if that table is not
118049 ** explicitly mentioned in the expression. That information is needed
118050 ** for cases like this:
118052 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
118054 ** The where clause needs to defer the handling of the t1.x=5
118055 ** term until after the t2 loop of the join. In that way, a
118056 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
118057 ** defer the handling of t1.x=5, it will be processed immediately
118058 ** after the t1 loop and rows with t1.x!=5 will never appear in
118059 ** the output, which is incorrect.
118061 static void setJoinExpr(Expr *p, int iTable){
118062 while( p ){
118063 ExprSetProperty(p, EP_FromJoin);
118064 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
118065 ExprSetVVAProperty(p, EP_NoReduce);
118066 p->iRightJoinTable = (i16)iTable;
118067 if( p->op==TK_FUNCTION && p->x.pList ){
118068 int i;
118069 for(i=0; i<p->x.pList->nExpr; i++){
118070 setJoinExpr(p->x.pList->a[i].pExpr, iTable);
118073 setJoinExpr(p->pLeft, iTable);
118074 p = p->pRight;
118079 ** This routine processes the join information for a SELECT statement.
118080 ** ON and USING clauses are converted into extra terms of the WHERE clause.
118081 ** NATURAL joins also create extra WHERE clause terms.
118083 ** The terms of a FROM clause are contained in the Select.pSrc structure.
118084 ** The left most table is the first entry in Select.pSrc. The right-most
118085 ** table is the last entry. The join operator is held in the entry to
118086 ** the left. Thus entry 0 contains the join operator for the join between
118087 ** entries 0 and 1. Any ON or USING clauses associated with the join are
118088 ** also attached to the left entry.
118090 ** This routine returns the number of errors encountered.
118092 static int sqliteProcessJoin(Parse *pParse, Select *p){
118093 SrcList *pSrc; /* All tables in the FROM clause */
118094 int i, j; /* Loop counters */
118095 struct SrcList_item *pLeft; /* Left table being joined */
118096 struct SrcList_item *pRight; /* Right table being joined */
118098 pSrc = p->pSrc;
118099 pLeft = &pSrc->a[0];
118100 pRight = &pLeft[1];
118101 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
118102 Table *pRightTab = pRight->pTab;
118103 int isOuter;
118105 if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
118106 isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
118108 /* When the NATURAL keyword is present, add WHERE clause terms for
118109 ** every column that the two tables have in common.
118111 if( pRight->fg.jointype & JT_NATURAL ){
118112 if( pRight->pOn || pRight->pUsing ){
118113 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
118114 "an ON or USING clause", 0);
118115 return 1;
118117 for(j=0; j<pRightTab->nCol; j++){
118118 char *zName; /* Name of column in the right table */
118119 int iLeft; /* Matching left table */
118120 int iLeftCol; /* Matching column in the left table */
118122 zName = pRightTab->aCol[j].zName;
118123 if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
118124 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
118125 isOuter, &p->pWhere);
118130 /* Disallow both ON and USING clauses in the same join
118132 if( pRight->pOn && pRight->pUsing ){
118133 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
118134 "clauses in the same join");
118135 return 1;
118138 /* Add the ON clause to the end of the WHERE clause, connected by
118139 ** an AND operator.
118141 if( pRight->pOn ){
118142 if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
118143 p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
118144 pRight->pOn = 0;
118147 /* Create extra terms on the WHERE clause for each column named
118148 ** in the USING clause. Example: If the two tables to be joined are
118149 ** A and B and the USING clause names X, Y, and Z, then add this
118150 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
118151 ** Report an error if any column mentioned in the USING clause is
118152 ** not contained in both tables to be joined.
118154 if( pRight->pUsing ){
118155 IdList *pList = pRight->pUsing;
118156 for(j=0; j<pList->nId; j++){
118157 char *zName; /* Name of the term in the USING clause */
118158 int iLeft; /* Table on the left with matching column name */
118159 int iLeftCol; /* Column number of matching column on the left */
118160 int iRightCol; /* Column number of matching column on the right */
118162 zName = pList->a[j].zName;
118163 iRightCol = columnIndex(pRightTab, zName);
118164 if( iRightCol<0
118165 || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
118167 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
118168 "not present in both tables", zName);
118169 return 1;
118171 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
118172 isOuter, &p->pWhere);
118176 return 0;
118179 /* Forward reference */
118180 static KeyInfo *keyInfoFromExprList(
118181 Parse *pParse, /* Parsing context */
118182 ExprList *pList, /* Form the KeyInfo object from this ExprList */
118183 int iStart, /* Begin with this column of pList */
118184 int nExtra /* Add this many extra columns to the end */
118188 ** Generate code that will push the record in registers regData
118189 ** through regData+nData-1 onto the sorter.
118191 static void pushOntoSorter(
118192 Parse *pParse, /* Parser context */
118193 SortCtx *pSort, /* Information about the ORDER BY clause */
118194 Select *pSelect, /* The whole SELECT statement */
118195 int regData, /* First register holding data to be sorted */
118196 int regOrigData, /* First register holding data before packing */
118197 int nData, /* Number of elements in the data array */
118198 int nPrefixReg /* No. of reg prior to regData available for use */
118200 Vdbe *v = pParse->pVdbe; /* Stmt under construction */
118201 int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
118202 int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
118203 int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
118204 int regBase; /* Regs for sorter record */
118205 int regRecord = ++pParse->nMem; /* Assembled sorter record */
118206 int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
118207 int op; /* Opcode to add sorter record to sorter */
118208 int iLimit; /* LIMIT counter */
118210 assert( bSeq==0 || bSeq==1 );
118211 assert( nData==1 || regData==regOrigData || regOrigData==0 );
118212 if( nPrefixReg ){
118213 assert( nPrefixReg==nExpr+bSeq );
118214 regBase = regData - nExpr - bSeq;
118215 }else{
118216 regBase = pParse->nMem + 1;
118217 pParse->nMem += nBase;
118219 assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
118220 iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
118221 pSort->labelDone = sqlite3VdbeMakeLabel(v);
118222 sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
118223 SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
118224 if( bSeq ){
118225 sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
118227 if( nPrefixReg==0 && nData>0 ){
118228 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
118230 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
118231 if( nOBSat>0 ){
118232 int regPrevKey; /* The first nOBSat columns of the previous row */
118233 int addrFirst; /* Address of the OP_IfNot opcode */
118234 int addrJmp; /* Address of the OP_Jump opcode */
118235 VdbeOp *pOp; /* Opcode that opens the sorter */
118236 int nKey; /* Number of sorting key columns, including OP_Sequence */
118237 KeyInfo *pKI; /* Original KeyInfo on the sorter table */
118239 regPrevKey = pParse->nMem+1;
118240 pParse->nMem += pSort->nOBSat;
118241 nKey = nExpr - pSort->nOBSat + bSeq;
118242 if( bSeq ){
118243 addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
118244 }else{
118245 addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
118247 VdbeCoverage(v);
118248 sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
118249 pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
118250 if( pParse->db->mallocFailed ) return;
118251 pOp->p2 = nKey + nData;
118252 pKI = pOp->p4.pKeyInfo;
118253 memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */
118254 sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
118255 testcase( pKI->nAllField > pKI->nKeyField+2 );
118256 pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
118257 pKI->nAllField-pKI->nKeyField-1);
118258 addrJmp = sqlite3VdbeCurrentAddr(v);
118259 sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
118260 pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
118261 pSort->regReturn = ++pParse->nMem;
118262 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
118263 sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
118264 if( iLimit ){
118265 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
118266 VdbeCoverage(v);
118268 sqlite3VdbeJumpHere(v, addrFirst);
118269 sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
118270 sqlite3VdbeJumpHere(v, addrJmp);
118272 if( pSort->sortFlags & SORTFLAG_UseSorter ){
118273 op = OP_SorterInsert;
118274 }else{
118275 op = OP_IdxInsert;
118277 sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
118278 regBase+nOBSat, nBase-nOBSat);
118279 if( iLimit ){
118280 int addr;
118281 int r1 = 0;
118282 /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit
118283 ** register is initialized with value of LIMIT+OFFSET.) After the sorter
118284 ** fills up, delete the least entry in the sorter after each insert.
118285 ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
118286 addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v);
118287 sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
118288 if( pSort->bOrderedInnerLoop ){
118289 r1 = ++pParse->nMem;
118290 sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
118291 VdbeComment((v, "seq"));
118293 sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
118294 if( pSort->bOrderedInnerLoop ){
118295 /* If the inner loop is driven by an index such that values from
118296 ** the same iteration of the inner loop are in sorted order, then
118297 ** immediately jump to the next iteration of an inner loop if the
118298 ** entry from the current iteration does not fit into the top
118299 ** LIMIT+OFFSET entries of the sorter. */
118300 int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
118301 sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
118302 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
118303 VdbeCoverage(v);
118305 sqlite3VdbeJumpHere(v, addr);
118310 ** Add code to implement the OFFSET
118312 static void codeOffset(
118313 Vdbe *v, /* Generate code into this VM */
118314 int iOffset, /* Register holding the offset counter */
118315 int iContinue /* Jump here to skip the current record */
118317 if( iOffset>0 ){
118318 sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
118319 VdbeComment((v, "OFFSET"));
118324 ** Add code that will check to make sure the N registers starting at iMem
118325 ** form a distinct entry. iTab is a sorting index that holds previously
118326 ** seen combinations of the N values. A new entry is made in iTab
118327 ** if the current N values are new.
118329 ** A jump to addrRepeat is made and the N+1 values are popped from the
118330 ** stack if the top N elements are not distinct.
118332 static void codeDistinct(
118333 Parse *pParse, /* Parsing and code generating context */
118334 int iTab, /* A sorting index used to test for distinctness */
118335 int addrRepeat, /* Jump to here if not distinct */
118336 int N, /* Number of elements */
118337 int iMem /* First element */
118339 Vdbe *v;
118340 int r1;
118342 v = pParse->pVdbe;
118343 r1 = sqlite3GetTempReg(pParse);
118344 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
118345 sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
118346 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
118347 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
118348 sqlite3ReleaseTempReg(pParse, r1);
118352 ** This routine generates the code for the inside of the inner loop
118353 ** of a SELECT.
118355 ** If srcTab is negative, then the p->pEList expressions
118356 ** are evaluated in order to get the data for this row. If srcTab is
118357 ** zero or more, then data is pulled from srcTab and p->pEList is used only
118358 ** to get the number of columns and the collation sequence for each column.
118360 static void selectInnerLoop(
118361 Parse *pParse, /* The parser context */
118362 Select *p, /* The complete select statement being coded */
118363 int srcTab, /* Pull data from this table if non-negative */
118364 SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
118365 DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
118366 SelectDest *pDest, /* How to dispose of the results */
118367 int iContinue, /* Jump here to continue with next row */
118368 int iBreak /* Jump here to break out of the inner loop */
118370 Vdbe *v = pParse->pVdbe;
118371 int i;
118372 int hasDistinct; /* True if the DISTINCT keyword is present */
118373 int eDest = pDest->eDest; /* How to dispose of results */
118374 int iParm = pDest->iSDParm; /* First argument to disposal method */
118375 int nResultCol; /* Number of result columns */
118376 int nPrefixReg = 0; /* Number of extra registers before regResult */
118378 /* Usually, regResult is the first cell in an array of memory cells
118379 ** containing the current result row. In this case regOrig is set to the
118380 ** same value. However, if the results are being sent to the sorter, the
118381 ** values for any expressions that are also part of the sort-key are omitted
118382 ** from this array. In this case regOrig is set to zero. */
118383 int regResult; /* Start of memory holding current results */
118384 int regOrig; /* Start of memory holding full result (or 0) */
118386 assert( v );
118387 assert( p->pEList!=0 );
118388 hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
118389 if( pSort && pSort->pOrderBy==0 ) pSort = 0;
118390 if( pSort==0 && !hasDistinct ){
118391 assert( iContinue!=0 );
118392 codeOffset(v, p->iOffset, iContinue);
118395 /* Pull the requested columns.
118397 nResultCol = p->pEList->nExpr;
118399 if( pDest->iSdst==0 ){
118400 if( pSort ){
118401 nPrefixReg = pSort->pOrderBy->nExpr;
118402 if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
118403 pParse->nMem += nPrefixReg;
118405 pDest->iSdst = pParse->nMem+1;
118406 pParse->nMem += nResultCol;
118407 }else if( pDest->iSdst+nResultCol > pParse->nMem ){
118408 /* This is an error condition that can result, for example, when a SELECT
118409 ** on the right-hand side of an INSERT contains more result columns than
118410 ** there are columns in the table on the left. The error will be caught
118411 ** and reported later. But we need to make sure enough memory is allocated
118412 ** to avoid other spurious errors in the meantime. */
118413 pParse->nMem += nResultCol;
118415 pDest->nSdst = nResultCol;
118416 regOrig = regResult = pDest->iSdst;
118417 if( srcTab>=0 ){
118418 for(i=0; i<nResultCol; i++){
118419 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
118420 VdbeComment((v, "%s", p->pEList->a[i].zName));
118422 }else if( eDest!=SRT_Exists ){
118423 /* If the destination is an EXISTS(...) expression, the actual
118424 ** values returned by the SELECT are not required.
118426 u8 ecelFlags;
118427 if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
118428 ecelFlags = SQLITE_ECEL_DUP;
118429 }else{
118430 ecelFlags = 0;
118432 if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
118433 /* For each expression in p->pEList that is a copy of an expression in
118434 ** the ORDER BY clause (pSort->pOrderBy), set the associated
118435 ** iOrderByCol value to one more than the index of the ORDER BY
118436 ** expression within the sort-key that pushOntoSorter() will generate.
118437 ** This allows the p->pEList field to be omitted from the sorted record,
118438 ** saving space and CPU cycles. */
118439 ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
118440 for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
118441 int j;
118442 if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
118443 p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
118446 regOrig = 0;
118447 assert( eDest==SRT_Set || eDest==SRT_Mem
118448 || eDest==SRT_Coroutine || eDest==SRT_Output );
118450 nResultCol = sqlite3ExprCodeExprList(pParse,p->pEList,regResult,
118451 0,ecelFlags);
118454 /* If the DISTINCT keyword was present on the SELECT statement
118455 ** and this row has been seen before, then do not make this row
118456 ** part of the result.
118458 if( hasDistinct ){
118459 switch( pDistinct->eTnctType ){
118460 case WHERE_DISTINCT_ORDERED: {
118461 VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
118462 int iJump; /* Jump destination */
118463 int regPrev; /* Previous row content */
118465 /* Allocate space for the previous row */
118466 regPrev = pParse->nMem+1;
118467 pParse->nMem += nResultCol;
118469 /* Change the OP_OpenEphemeral coded earlier to an OP_Null
118470 ** sets the MEM_Cleared bit on the first register of the
118471 ** previous value. This will cause the OP_Ne below to always
118472 ** fail on the first iteration of the loop even if the first
118473 ** row is all NULLs.
118475 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
118476 pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
118477 pOp->opcode = OP_Null;
118478 pOp->p1 = 1;
118479 pOp->p2 = regPrev;
118481 iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
118482 for(i=0; i<nResultCol; i++){
118483 CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
118484 if( i<nResultCol-1 ){
118485 sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
118486 VdbeCoverage(v);
118487 }else{
118488 sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
118489 VdbeCoverage(v);
118491 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
118492 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
118494 assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
118495 sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
118496 break;
118499 case WHERE_DISTINCT_UNIQUE: {
118500 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
118501 break;
118504 default: {
118505 assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
118506 codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
118507 regResult);
118508 break;
118511 if( pSort==0 ){
118512 codeOffset(v, p->iOffset, iContinue);
118516 switch( eDest ){
118517 /* In this mode, write each query result to the key of the temporary
118518 ** table iParm.
118520 #ifndef SQLITE_OMIT_COMPOUND_SELECT
118521 case SRT_Union: {
118522 int r1;
118523 r1 = sqlite3GetTempReg(pParse);
118524 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
118525 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
118526 sqlite3ReleaseTempReg(pParse, r1);
118527 break;
118530 /* Construct a record from the query result, but instead of
118531 ** saving that record, use it as a key to delete elements from
118532 ** the temporary table iParm.
118534 case SRT_Except: {
118535 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
118536 break;
118538 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
118540 /* Store the result as data using a unique key.
118542 case SRT_Fifo:
118543 case SRT_DistFifo:
118544 case SRT_Table:
118545 case SRT_EphemTab: {
118546 int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
118547 testcase( eDest==SRT_Table );
118548 testcase( eDest==SRT_EphemTab );
118549 testcase( eDest==SRT_Fifo );
118550 testcase( eDest==SRT_DistFifo );
118551 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
118552 #ifndef SQLITE_OMIT_CTE
118553 if( eDest==SRT_DistFifo ){
118554 /* If the destination is DistFifo, then cursor (iParm+1) is open
118555 ** on an ephemeral index. If the current row is already present
118556 ** in the index, do not write it to the output. If not, add the
118557 ** current row to the index and proceed with writing it to the
118558 ** output table as well. */
118559 int addr = sqlite3VdbeCurrentAddr(v) + 4;
118560 sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
118561 VdbeCoverage(v);
118562 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
118563 assert( pSort==0 );
118565 #endif
118566 if( pSort ){
118567 pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
118568 }else{
118569 int r2 = sqlite3GetTempReg(pParse);
118570 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
118571 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
118572 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
118573 sqlite3ReleaseTempReg(pParse, r2);
118575 sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
118576 break;
118579 #ifndef SQLITE_OMIT_SUBQUERY
118580 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
118581 ** then there should be a single item on the stack. Write this
118582 ** item into the set table with bogus data.
118584 case SRT_Set: {
118585 if( pSort ){
118586 /* At first glance you would think we could optimize out the
118587 ** ORDER BY in this case since the order of entries in the set
118588 ** does not matter. But there might be a LIMIT clause, in which
118589 ** case the order does matter */
118590 pushOntoSorter(
118591 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
118592 }else{
118593 int r1 = sqlite3GetTempReg(pParse);
118594 assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
118595 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
118596 r1, pDest->zAffSdst, nResultCol);
118597 sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
118598 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
118599 sqlite3ReleaseTempReg(pParse, r1);
118601 break;
118604 /* If any row exist in the result set, record that fact and abort.
118606 case SRT_Exists: {
118607 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
118608 /* The LIMIT clause will terminate the loop for us */
118609 break;
118612 /* If this is a scalar select that is part of an expression, then
118613 ** store the results in the appropriate memory cell or array of
118614 ** memory cells and break out of the scan loop.
118616 case SRT_Mem: {
118617 if( pSort ){
118618 assert( nResultCol<=pDest->nSdst );
118619 pushOntoSorter(
118620 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
118621 }else{
118622 assert( nResultCol==pDest->nSdst );
118623 assert( regResult==iParm );
118624 /* The LIMIT clause will jump out of the loop for us */
118626 break;
118628 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
118630 case SRT_Coroutine: /* Send data to a co-routine */
118631 case SRT_Output: { /* Return the results */
118632 testcase( eDest==SRT_Coroutine );
118633 testcase( eDest==SRT_Output );
118634 if( pSort ){
118635 pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
118636 nPrefixReg);
118637 }else if( eDest==SRT_Coroutine ){
118638 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
118639 }else{
118640 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
118641 sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
118643 break;
118646 #ifndef SQLITE_OMIT_CTE
118647 /* Write the results into a priority queue that is order according to
118648 ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
118649 ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
118650 ** pSO->nExpr columns, then make sure all keys are unique by adding a
118651 ** final OP_Sequence column. The last column is the record as a blob.
118653 case SRT_DistQueue:
118654 case SRT_Queue: {
118655 int nKey;
118656 int r1, r2, r3;
118657 int addrTest = 0;
118658 ExprList *pSO;
118659 pSO = pDest->pOrderBy;
118660 assert( pSO );
118661 nKey = pSO->nExpr;
118662 r1 = sqlite3GetTempReg(pParse);
118663 r2 = sqlite3GetTempRange(pParse, nKey+2);
118664 r3 = r2+nKey+1;
118665 if( eDest==SRT_DistQueue ){
118666 /* If the destination is DistQueue, then cursor (iParm+1) is open
118667 ** on a second ephemeral index that holds all values every previously
118668 ** added to the queue. */
118669 addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
118670 regResult, nResultCol);
118671 VdbeCoverage(v);
118673 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
118674 if( eDest==SRT_DistQueue ){
118675 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
118676 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
118678 for(i=0; i<nKey; i++){
118679 sqlite3VdbeAddOp2(v, OP_SCopy,
118680 regResult + pSO->a[i].u.x.iOrderByCol - 1,
118681 r2+i);
118683 sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
118684 sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
118685 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
118686 if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
118687 sqlite3ReleaseTempReg(pParse, r1);
118688 sqlite3ReleaseTempRange(pParse, r2, nKey+2);
118689 break;
118691 #endif /* SQLITE_OMIT_CTE */
118695 #if !defined(SQLITE_OMIT_TRIGGER)
118696 /* Discard the results. This is used for SELECT statements inside
118697 ** the body of a TRIGGER. The purpose of such selects is to call
118698 ** user-defined functions that have side effects. We do not care
118699 ** about the actual results of the select.
118701 default: {
118702 assert( eDest==SRT_Discard );
118703 break;
118705 #endif
118708 /* Jump to the end of the loop if the LIMIT is reached. Except, if
118709 ** there is a sorter, in which case the sorter has already limited
118710 ** the output for us.
118712 if( pSort==0 && p->iLimit ){
118713 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
118718 ** Allocate a KeyInfo object sufficient for an index of N key columns and
118719 ** X extra columns.
118721 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
118722 int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
118723 KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
118724 if( p ){
118725 p->aSortOrder = (u8*)&p->aColl[N+X];
118726 p->nKeyField = (u16)N;
118727 p->nAllField = (u16)(N+X);
118728 p->enc = ENC(db);
118729 p->db = db;
118730 p->nRef = 1;
118731 memset(&p[1], 0, nExtra);
118732 }else{
118733 sqlite3OomFault(db);
118735 return p;
118739 ** Deallocate a KeyInfo object
118741 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
118742 if( p ){
118743 assert( p->nRef>0 );
118744 p->nRef--;
118745 if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
118750 ** Make a new pointer to a KeyInfo object
118752 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
118753 if( p ){
118754 assert( p->nRef>0 );
118755 p->nRef++;
118757 return p;
118760 #ifdef SQLITE_DEBUG
118762 ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
118763 ** can only be changed if this is just a single reference to the object.
118765 ** This routine is used only inside of assert() statements.
118767 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
118768 #endif /* SQLITE_DEBUG */
118771 ** Given an expression list, generate a KeyInfo structure that records
118772 ** the collating sequence for each expression in that expression list.
118774 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
118775 ** KeyInfo structure is appropriate for initializing a virtual index to
118776 ** implement that clause. If the ExprList is the result set of a SELECT
118777 ** then the KeyInfo structure is appropriate for initializing a virtual
118778 ** index to implement a DISTINCT test.
118780 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
118781 ** function is responsible for seeing that this structure is eventually
118782 ** freed.
118784 static KeyInfo *keyInfoFromExprList(
118785 Parse *pParse, /* Parsing context */
118786 ExprList *pList, /* Form the KeyInfo object from this ExprList */
118787 int iStart, /* Begin with this column of pList */
118788 int nExtra /* Add this many extra columns to the end */
118790 int nExpr;
118791 KeyInfo *pInfo;
118792 struct ExprList_item *pItem;
118793 sqlite3 *db = pParse->db;
118794 int i;
118796 nExpr = pList->nExpr;
118797 pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
118798 if( pInfo ){
118799 assert( sqlite3KeyInfoIsWriteable(pInfo) );
118800 for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
118801 pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
118802 pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
118805 return pInfo;
118809 ** Name of the connection operator, used for error messages.
118811 static const char *selectOpName(int id){
118812 char *z;
118813 switch( id ){
118814 case TK_ALL: z = "UNION ALL"; break;
118815 case TK_INTERSECT: z = "INTERSECT"; break;
118816 case TK_EXCEPT: z = "EXCEPT"; break;
118817 default: z = "UNION"; break;
118819 return z;
118822 #ifndef SQLITE_OMIT_EXPLAIN
118824 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
118825 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
118826 ** where the caption is of the form:
118828 ** "USE TEMP B-TREE FOR xxx"
118830 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
118831 ** is determined by the zUsage argument.
118833 static void explainTempTable(Parse *pParse, const char *zUsage){
118834 if( pParse->explain==2 ){
118835 Vdbe *v = pParse->pVdbe;
118836 char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
118837 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
118842 ** Assign expression b to lvalue a. A second, no-op, version of this macro
118843 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
118844 ** in sqlite3Select() to assign values to structure member variables that
118845 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
118846 ** code with #ifndef directives.
118848 # define explainSetInteger(a, b) a = b
118850 #else
118851 /* No-op versions of the explainXXX() functions and macros. */
118852 # define explainTempTable(y,z)
118853 # define explainSetInteger(y,z)
118854 #endif
118856 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
118858 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
118859 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
118860 ** where the caption is of one of the two forms:
118862 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
118863 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
118865 ** where iSub1 and iSub2 are the integers passed as the corresponding
118866 ** function parameters, and op is the text representation of the parameter
118867 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
118868 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
118869 ** false, or the second form if it is true.
118871 static void explainComposite(
118872 Parse *pParse, /* Parse context */
118873 int op, /* One of TK_UNION, TK_EXCEPT etc. */
118874 int iSub1, /* Subquery id 1 */
118875 int iSub2, /* Subquery id 2 */
118876 int bUseTmp /* True if a temp table was used */
118878 assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
118879 if( pParse->explain==2 ){
118880 Vdbe *v = pParse->pVdbe;
118881 char *zMsg = sqlite3MPrintf(
118882 pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
118883 bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
118885 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
118888 #else
118889 /* No-op versions of the explainXXX() functions and macros. */
118890 # define explainComposite(v,w,x,y,z)
118891 #endif
118894 ** If the inner loop was generated using a non-null pOrderBy argument,
118895 ** then the results were placed in a sorter. After the loop is terminated
118896 ** we need to run the sorter and output the results. The following
118897 ** routine generates the code needed to do that.
118899 static void generateSortTail(
118900 Parse *pParse, /* Parsing context */
118901 Select *p, /* The SELECT statement */
118902 SortCtx *pSort, /* Information on the ORDER BY clause */
118903 int nColumn, /* Number of columns of data */
118904 SelectDest *pDest /* Write the sorted results here */
118906 Vdbe *v = pParse->pVdbe; /* The prepared statement */
118907 int addrBreak = pSort->labelDone; /* Jump here to exit loop */
118908 int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
118909 int addr;
118910 int addrOnce = 0;
118911 int iTab;
118912 ExprList *pOrderBy = pSort->pOrderBy;
118913 int eDest = pDest->eDest;
118914 int iParm = pDest->iSDParm;
118915 int regRow;
118916 int regRowid;
118917 int iCol;
118918 int nKey;
118919 int iSortTab; /* Sorter cursor to read from */
118920 int nSortData; /* Trailing values to read from sorter */
118921 int i;
118922 int bSeq; /* True if sorter record includes seq. no. */
118923 struct ExprList_item *aOutEx = p->pEList->a;
118925 assert( addrBreak<0 );
118926 if( pSort->labelBkOut ){
118927 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
118928 sqlite3VdbeGoto(v, addrBreak);
118929 sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
118931 iTab = pSort->iECursor;
118932 if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
118933 regRowid = 0;
118934 regRow = pDest->iSdst;
118935 nSortData = nColumn;
118936 }else{
118937 regRowid = sqlite3GetTempReg(pParse);
118938 regRow = sqlite3GetTempRange(pParse, nColumn);
118939 nSortData = nColumn;
118941 nKey = pOrderBy->nExpr - pSort->nOBSat;
118942 if( pSort->sortFlags & SORTFLAG_UseSorter ){
118943 int regSortOut = ++pParse->nMem;
118944 iSortTab = pParse->nTab++;
118945 if( pSort->labelBkOut ){
118946 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
118948 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
118949 if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
118950 addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
118951 VdbeCoverage(v);
118952 codeOffset(v, p->iOffset, addrContinue);
118953 sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
118954 bSeq = 0;
118955 }else{
118956 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
118957 codeOffset(v, p->iOffset, addrContinue);
118958 iSortTab = iTab;
118959 bSeq = 1;
118961 for(i=0, iCol=nKey+bSeq; i<nSortData; i++){
118962 int iRead;
118963 if( aOutEx[i].u.x.iOrderByCol ){
118964 iRead = aOutEx[i].u.x.iOrderByCol-1;
118965 }else{
118966 iRead = iCol++;
118968 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
118969 VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
118971 switch( eDest ){
118972 case SRT_Table:
118973 case SRT_EphemTab: {
118974 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
118975 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
118976 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
118977 break;
118979 #ifndef SQLITE_OMIT_SUBQUERY
118980 case SRT_Set: {
118981 assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
118982 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
118983 pDest->zAffSdst, nColumn);
118984 sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
118985 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
118986 break;
118988 case SRT_Mem: {
118989 /* The LIMIT clause will terminate the loop for us */
118990 break;
118992 #endif
118993 default: {
118994 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
118995 testcase( eDest==SRT_Output );
118996 testcase( eDest==SRT_Coroutine );
118997 if( eDest==SRT_Output ){
118998 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
118999 sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
119000 }else{
119001 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
119003 break;
119006 if( regRowid ){
119007 if( eDest==SRT_Set ){
119008 sqlite3ReleaseTempRange(pParse, regRow, nColumn);
119009 }else{
119010 sqlite3ReleaseTempReg(pParse, regRow);
119012 sqlite3ReleaseTempReg(pParse, regRowid);
119014 /* The bottom of the loop
119016 sqlite3VdbeResolveLabel(v, addrContinue);
119017 if( pSort->sortFlags & SORTFLAG_UseSorter ){
119018 sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
119019 }else{
119020 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
119022 if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
119023 sqlite3VdbeResolveLabel(v, addrBreak);
119027 ** Return a pointer to a string containing the 'declaration type' of the
119028 ** expression pExpr. The string may be treated as static by the caller.
119030 ** Also try to estimate the size of the returned value and return that
119031 ** result in *pEstWidth.
119033 ** The declaration type is the exact datatype definition extracted from the
119034 ** original CREATE TABLE statement if the expression is a column. The
119035 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
119036 ** is considered a column can be complex in the presence of subqueries. The
119037 ** result-set expression in all of the following SELECT statements is
119038 ** considered a column by this function.
119040 ** SELECT col FROM tbl;
119041 ** SELECT (SELECT col FROM tbl;
119042 ** SELECT (SELECT col FROM tbl);
119043 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
119045 ** The declaration type for any expression other than a column is NULL.
119047 ** This routine has either 3 or 6 parameters depending on whether or not
119048 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
119050 #ifdef SQLITE_ENABLE_COLUMN_METADATA
119051 # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
119052 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
119053 # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
119054 #endif
119055 static const char *columnTypeImpl(
119056 NameContext *pNC,
119057 #ifndef SQLITE_ENABLE_COLUMN_METADATA
119058 Expr *pExpr
119059 #else
119060 Expr *pExpr,
119061 const char **pzOrigDb,
119062 const char **pzOrigTab,
119063 const char **pzOrigCol
119064 #endif
119066 char const *zType = 0;
119067 int j;
119068 #ifdef SQLITE_ENABLE_COLUMN_METADATA
119069 char const *zOrigDb = 0;
119070 char const *zOrigTab = 0;
119071 char const *zOrigCol = 0;
119072 #endif
119074 assert( pExpr!=0 );
119075 assert( pNC->pSrcList!=0 );
119076 switch( pExpr->op ){
119077 case TK_AGG_COLUMN:
119078 case TK_COLUMN: {
119079 /* The expression is a column. Locate the table the column is being
119080 ** extracted from in NameContext.pSrcList. This table may be real
119081 ** database table or a subquery.
119083 Table *pTab = 0; /* Table structure column is extracted from */
119084 Select *pS = 0; /* Select the column is extracted from */
119085 int iCol = pExpr->iColumn; /* Index of column in pTab */
119086 testcase( pExpr->op==TK_AGG_COLUMN );
119087 testcase( pExpr->op==TK_COLUMN );
119088 while( pNC && !pTab ){
119089 SrcList *pTabList = pNC->pSrcList;
119090 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
119091 if( j<pTabList->nSrc ){
119092 pTab = pTabList->a[j].pTab;
119093 pS = pTabList->a[j].pSelect;
119094 }else{
119095 pNC = pNC->pNext;
119099 if( pTab==0 ){
119100 /* At one time, code such as "SELECT new.x" within a trigger would
119101 ** cause this condition to run. Since then, we have restructured how
119102 ** trigger code is generated and so this condition is no longer
119103 ** possible. However, it can still be true for statements like
119104 ** the following:
119106 ** CREATE TABLE t1(col INTEGER);
119107 ** SELECT (SELECT t1.col) FROM FROM t1;
119109 ** when columnType() is called on the expression "t1.col" in the
119110 ** sub-select. In this case, set the column type to NULL, even
119111 ** though it should really be "INTEGER".
119113 ** This is not a problem, as the column type of "t1.col" is never
119114 ** used. When columnType() is called on the expression
119115 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
119116 ** branch below. */
119117 break;
119120 assert( pTab && pExpr->pTab==pTab );
119121 if( pS ){
119122 /* The "table" is actually a sub-select or a view in the FROM clause
119123 ** of the SELECT statement. Return the declaration type and origin
119124 ** data for the result-set column of the sub-select.
119126 if( iCol>=0 && iCol<pS->pEList->nExpr ){
119127 /* If iCol is less than zero, then the expression requests the
119128 ** rowid of the sub-select or view. This expression is legal (see
119129 ** test case misc2.2.2) - it always evaluates to NULL.
119131 NameContext sNC;
119132 Expr *p = pS->pEList->a[iCol].pExpr;
119133 sNC.pSrcList = pS->pSrc;
119134 sNC.pNext = pNC;
119135 sNC.pParse = pNC->pParse;
119136 zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
119138 }else{
119139 /* A real table or a CTE table */
119140 assert( !pS );
119141 #ifdef SQLITE_ENABLE_COLUMN_METADATA
119142 if( iCol<0 ) iCol = pTab->iPKey;
119143 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
119144 if( iCol<0 ){
119145 zType = "INTEGER";
119146 zOrigCol = "rowid";
119147 }else{
119148 zOrigCol = pTab->aCol[iCol].zName;
119149 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
119151 zOrigTab = pTab->zName;
119152 if( pNC->pParse && pTab->pSchema ){
119153 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
119154 zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
119156 #else
119157 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
119158 if( iCol<0 ){
119159 zType = "INTEGER";
119160 }else{
119161 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
119163 #endif
119165 break;
119167 #ifndef SQLITE_OMIT_SUBQUERY
119168 case TK_SELECT: {
119169 /* The expression is a sub-select. Return the declaration type and
119170 ** origin info for the single column in the result set of the SELECT
119171 ** statement.
119173 NameContext sNC;
119174 Select *pS = pExpr->x.pSelect;
119175 Expr *p = pS->pEList->a[0].pExpr;
119176 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
119177 sNC.pSrcList = pS->pSrc;
119178 sNC.pNext = pNC;
119179 sNC.pParse = pNC->pParse;
119180 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
119181 break;
119183 #endif
119186 #ifdef SQLITE_ENABLE_COLUMN_METADATA
119187 if( pzOrigDb ){
119188 assert( pzOrigTab && pzOrigCol );
119189 *pzOrigDb = zOrigDb;
119190 *pzOrigTab = zOrigTab;
119191 *pzOrigCol = zOrigCol;
119193 #endif
119194 return zType;
119198 ** Generate code that will tell the VDBE the declaration types of columns
119199 ** in the result set.
119201 static void generateColumnTypes(
119202 Parse *pParse, /* Parser context */
119203 SrcList *pTabList, /* List of tables */
119204 ExprList *pEList /* Expressions defining the result set */
119206 #ifndef SQLITE_OMIT_DECLTYPE
119207 Vdbe *v = pParse->pVdbe;
119208 int i;
119209 NameContext sNC;
119210 sNC.pSrcList = pTabList;
119211 sNC.pParse = pParse;
119212 sNC.pNext = 0;
119213 for(i=0; i<pEList->nExpr; i++){
119214 Expr *p = pEList->a[i].pExpr;
119215 const char *zType;
119216 #ifdef SQLITE_ENABLE_COLUMN_METADATA
119217 const char *zOrigDb = 0;
119218 const char *zOrigTab = 0;
119219 const char *zOrigCol = 0;
119220 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
119222 /* The vdbe must make its own copy of the column-type and other
119223 ** column specific strings, in case the schema is reset before this
119224 ** virtual machine is deleted.
119226 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
119227 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
119228 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
119229 #else
119230 zType = columnType(&sNC, p, 0, 0, 0);
119231 #endif
119232 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
119234 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
119239 ** Compute the column names for a SELECT statement.
119241 ** The only guarantee that SQLite makes about column names is that if the
119242 ** column has an AS clause assigning it a name, that will be the name used.
119243 ** That is the only documented guarantee. However, countless applications
119244 ** developed over the years have made baseless assumptions about column names
119245 ** and will break if those assumptions changes. Hence, use extreme caution
119246 ** when modifying this routine to avoid breaking legacy.
119248 ** See Also: sqlite3ColumnsFromExprList()
119250 ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
119251 ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
119252 ** applications should operate this way. Nevertheless, we need to support the
119253 ** other modes for legacy:
119255 ** short=OFF, full=OFF: Column name is the text of the expression has it
119256 ** originally appears in the SELECT statement. In
119257 ** other words, the zSpan of the result expression.
119259 ** short=ON, full=OFF: (This is the default setting). If the result
119260 ** refers directly to a table column, then the
119261 ** result column name is just the table column
119262 ** name: COLUMN. Otherwise use zSpan.
119264 ** full=ON, short=ANY: If the result refers directly to a table column,
119265 ** then the result column name with the table name
119266 ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
119268 static void generateColumnNames(
119269 Parse *pParse, /* Parser context */
119270 Select *pSelect /* Generate column names for this SELECT statement */
119272 Vdbe *v = pParse->pVdbe;
119273 int i;
119274 Table *pTab;
119275 SrcList *pTabList;
119276 ExprList *pEList;
119277 sqlite3 *db = pParse->db;
119278 int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
119279 int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
119281 #ifndef SQLITE_OMIT_EXPLAIN
119282 /* If this is an EXPLAIN, skip this step */
119283 if( pParse->explain ){
119284 return;
119286 #endif
119288 if( pParse->colNamesSet || db->mallocFailed ) return;
119289 /* Column names are determined by the left-most term of a compound select */
119290 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
119291 pTabList = pSelect->pSrc;
119292 pEList = pSelect->pEList;
119293 assert( v!=0 );
119294 assert( pTabList!=0 );
119295 pParse->colNamesSet = 1;
119296 fullName = (db->flags & SQLITE_FullColNames)!=0;
119297 srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
119298 sqlite3VdbeSetNumCols(v, pEList->nExpr);
119299 for(i=0; i<pEList->nExpr; i++){
119300 Expr *p = pEList->a[i].pExpr;
119302 assert( p!=0 );
119303 assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
119304 assert( p->op!=TK_COLUMN || p->pTab!=0 ); /* Covering idx not yet coded */
119305 if( pEList->a[i].zName ){
119306 /* An AS clause always takes first priority */
119307 char *zName = pEList->a[i].zName;
119308 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
119309 }else if( srcName && p->op==TK_COLUMN ){
119310 char *zCol;
119311 int iCol = p->iColumn;
119312 pTab = p->pTab;
119313 assert( pTab!=0 );
119314 if( iCol<0 ) iCol = pTab->iPKey;
119315 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
119316 if( iCol<0 ){
119317 zCol = "rowid";
119318 }else{
119319 zCol = pTab->aCol[iCol].zName;
119321 if( fullName ){
119322 char *zName = 0;
119323 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
119324 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
119325 }else{
119326 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
119328 }else{
119329 const char *z = pEList->a[i].zSpan;
119330 z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
119331 sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
119334 generateColumnTypes(pParse, pTabList, pEList);
119338 ** Given an expression list (which is really the list of expressions
119339 ** that form the result set of a SELECT statement) compute appropriate
119340 ** column names for a table that would hold the expression list.
119342 ** All column names will be unique.
119344 ** Only the column names are computed. Column.zType, Column.zColl,
119345 ** and other fields of Column are zeroed.
119347 ** Return SQLITE_OK on success. If a memory allocation error occurs,
119348 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
119350 ** The only guarantee that SQLite makes about column names is that if the
119351 ** column has an AS clause assigning it a name, that will be the name used.
119352 ** That is the only documented guarantee. However, countless applications
119353 ** developed over the years have made baseless assumptions about column names
119354 ** and will break if those assumptions changes. Hence, use extreme caution
119355 ** when modifying this routine to avoid breaking legacy.
119357 ** See Also: generateColumnNames()
119359 SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
119360 Parse *pParse, /* Parsing context */
119361 ExprList *pEList, /* Expr list from which to derive column names */
119362 i16 *pnCol, /* Write the number of columns here */
119363 Column **paCol /* Write the new column list here */
119365 sqlite3 *db = pParse->db; /* Database connection */
119366 int i, j; /* Loop counters */
119367 u32 cnt; /* Index added to make the name unique */
119368 Column *aCol, *pCol; /* For looping over result columns */
119369 int nCol; /* Number of columns in the result set */
119370 char *zName; /* Column name */
119371 int nName; /* Size of name in zName[] */
119372 Hash ht; /* Hash table of column names */
119374 sqlite3HashInit(&ht);
119375 if( pEList ){
119376 nCol = pEList->nExpr;
119377 aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
119378 testcase( aCol==0 );
119379 if( nCol>32767 ) nCol = 32767;
119380 }else{
119381 nCol = 0;
119382 aCol = 0;
119384 assert( nCol==(i16)nCol );
119385 *pnCol = nCol;
119386 *paCol = aCol;
119388 for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
119389 /* Get an appropriate name for the column
119391 if( (zName = pEList->a[i].zName)!=0 ){
119392 /* If the column contains an "AS <name>" phrase, use <name> as the name */
119393 }else{
119394 Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
119395 while( pColExpr->op==TK_DOT ){
119396 pColExpr = pColExpr->pRight;
119397 assert( pColExpr!=0 );
119399 if( (pColExpr->op==TK_COLUMN || pColExpr->op==TK_AGG_COLUMN)
119400 && pColExpr->pTab!=0
119402 /* For columns use the column name name */
119403 int iCol = pColExpr->iColumn;
119404 Table *pTab = pColExpr->pTab;
119405 if( iCol<0 ) iCol = pTab->iPKey;
119406 zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
119407 }else if( pColExpr->op==TK_ID ){
119408 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
119409 zName = pColExpr->u.zToken;
119410 }else{
119411 /* Use the original text of the column expression as its name */
119412 zName = pEList->a[i].zSpan;
119415 if( zName ){
119416 zName = sqlite3DbStrDup(db, zName);
119417 }else{
119418 zName = sqlite3MPrintf(db,"column%d",i+1);
119421 /* Make sure the column name is unique. If the name is not unique,
119422 ** append an integer to the name so that it becomes unique.
119424 cnt = 0;
119425 while( zName && sqlite3HashFind(&ht, zName)!=0 ){
119426 nName = sqlite3Strlen30(zName);
119427 if( nName>0 ){
119428 for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
119429 if( zName[j]==':' ) nName = j;
119431 zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
119432 if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
119434 pCol->zName = zName;
119435 sqlite3ColumnPropertiesFromName(0, pCol);
119436 if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
119437 sqlite3OomFault(db);
119440 sqlite3HashClear(&ht);
119441 if( db->mallocFailed ){
119442 for(j=0; j<i; j++){
119443 sqlite3DbFree(db, aCol[j].zName);
119445 sqlite3DbFree(db, aCol);
119446 *paCol = 0;
119447 *pnCol = 0;
119448 return SQLITE_NOMEM_BKPT;
119450 return SQLITE_OK;
119454 ** Add type and collation information to a column list based on
119455 ** a SELECT statement.
119457 ** The column list presumably came from selectColumnNamesFromExprList().
119458 ** The column list has only names, not types or collations. This
119459 ** routine goes through and adds the types and collations.
119461 ** This routine requires that all identifiers in the SELECT
119462 ** statement be resolved.
119464 SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
119465 Parse *pParse, /* Parsing contexts */
119466 Table *pTab, /* Add column type information to this table */
119467 Select *pSelect /* SELECT used to determine types and collations */
119469 sqlite3 *db = pParse->db;
119470 NameContext sNC;
119471 Column *pCol;
119472 CollSeq *pColl;
119473 int i;
119474 Expr *p;
119475 struct ExprList_item *a;
119477 assert( pSelect!=0 );
119478 assert( (pSelect->selFlags & SF_Resolved)!=0 );
119479 assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
119480 if( db->mallocFailed ) return;
119481 memset(&sNC, 0, sizeof(sNC));
119482 sNC.pSrcList = pSelect->pSrc;
119483 a = pSelect->pEList->a;
119484 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
119485 const char *zType;
119486 int n, m;
119487 p = a[i].pExpr;
119488 zType = columnType(&sNC, p, 0, 0, 0);
119489 /* pCol->szEst = ... // Column size est for SELECT tables never used */
119490 pCol->affinity = sqlite3ExprAffinity(p);
119491 if( zType ){
119492 m = sqlite3Strlen30(zType);
119493 n = sqlite3Strlen30(pCol->zName);
119494 pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
119495 if( pCol->zName ){
119496 memcpy(&pCol->zName[n+1], zType, m+1);
119497 pCol->colFlags |= COLFLAG_HASTYPE;
119500 if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
119501 pColl = sqlite3ExprCollSeq(pParse, p);
119502 if( pColl && pCol->zColl==0 ){
119503 pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
119506 pTab->szTabRow = 1; /* Any non-zero value works */
119510 ** Given a SELECT statement, generate a Table structure that describes
119511 ** the result set of that SELECT.
119513 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
119514 Table *pTab;
119515 sqlite3 *db = pParse->db;
119516 int savedFlags;
119518 savedFlags = db->flags;
119519 db->flags &= ~SQLITE_FullColNames;
119520 db->flags |= SQLITE_ShortColNames;
119521 sqlite3SelectPrep(pParse, pSelect, 0);
119522 if( pParse->nErr ) return 0;
119523 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
119524 db->flags = savedFlags;
119525 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
119526 if( pTab==0 ){
119527 return 0;
119529 /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
119530 ** is disabled */
119531 assert( db->lookaside.bDisable );
119532 pTab->nTabRef = 1;
119533 pTab->zName = 0;
119534 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
119535 sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
119536 sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
119537 pTab->iPKey = -1;
119538 if( db->mallocFailed ){
119539 sqlite3DeleteTable(db, pTab);
119540 return 0;
119542 return pTab;
119546 ** Get a VDBE for the given parser context. Create a new one if necessary.
119547 ** If an error occurs, return NULL and leave a message in pParse.
119549 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
119550 if( pParse->pVdbe ){
119551 return pParse->pVdbe;
119553 if( pParse->pToplevel==0
119554 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
119556 pParse->okConstFactor = 1;
119558 return sqlite3VdbeCreate(pParse);
119563 ** Compute the iLimit and iOffset fields of the SELECT based on the
119564 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
119565 ** that appear in the original SQL statement after the LIMIT and OFFSET
119566 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
119567 ** are the integer memory register numbers for counters used to compute
119568 ** the limit and offset. If there is no limit and/or offset, then
119569 ** iLimit and iOffset are negative.
119571 ** This routine changes the values of iLimit and iOffset only if
119572 ** a limit or offset is defined by pLimit and pOffset. iLimit and
119573 ** iOffset should have been preset to appropriate default values (zero)
119574 ** prior to calling this routine.
119576 ** The iOffset register (if it exists) is initialized to the value
119577 ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
119578 ** iOffset+1 is initialized to LIMIT+OFFSET.
119580 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
119581 ** redefined. The UNION ALL operator uses this property to force
119582 ** the reuse of the same limit and offset registers across multiple
119583 ** SELECT statements.
119585 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
119586 Vdbe *v = 0;
119587 int iLimit = 0;
119588 int iOffset;
119589 int n;
119590 if( p->iLimit ) return;
119593 ** "LIMIT -1" always shows all rows. There is some
119594 ** controversy about what the correct behavior should be.
119595 ** The current implementation interprets "LIMIT 0" to mean
119596 ** no rows.
119598 sqlite3ExprCacheClear(pParse);
119599 assert( p->pOffset==0 || p->pLimit!=0 );
119600 if( p->pLimit ){
119601 p->iLimit = iLimit = ++pParse->nMem;
119602 v = sqlite3GetVdbe(pParse);
119603 assert( v!=0 );
119604 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
119605 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
119606 VdbeComment((v, "LIMIT counter"));
119607 if( n==0 ){
119608 sqlite3VdbeGoto(v, iBreak);
119609 }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
119610 p->nSelectRow = sqlite3LogEst((u64)n);
119611 p->selFlags |= SF_FixedLimit;
119613 }else{
119614 sqlite3ExprCode(pParse, p->pLimit, iLimit);
119615 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
119616 VdbeComment((v, "LIMIT counter"));
119617 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
119619 if( p->pOffset ){
119620 p->iOffset = iOffset = ++pParse->nMem;
119621 pParse->nMem++; /* Allocate an extra register for limit+offset */
119622 sqlite3ExprCode(pParse, p->pOffset, iOffset);
119623 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
119624 VdbeComment((v, "OFFSET counter"));
119625 sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
119626 VdbeComment((v, "LIMIT+OFFSET"));
119631 #ifndef SQLITE_OMIT_COMPOUND_SELECT
119633 ** Return the appropriate collating sequence for the iCol-th column of
119634 ** the result set for the compound-select statement "p". Return NULL if
119635 ** the column has no default collating sequence.
119637 ** The collating sequence for the compound select is taken from the
119638 ** left-most term of the select that has a collating sequence.
119640 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
119641 CollSeq *pRet;
119642 if( p->pPrior ){
119643 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
119644 }else{
119645 pRet = 0;
119647 assert( iCol>=0 );
119648 /* iCol must be less than p->pEList->nExpr. Otherwise an error would
119649 ** have been thrown during name resolution and we would not have gotten
119650 ** this far */
119651 if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
119652 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
119654 return pRet;
119658 ** The select statement passed as the second parameter is a compound SELECT
119659 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
119660 ** structure suitable for implementing the ORDER BY.
119662 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
119663 ** function is responsible for ensuring that this structure is eventually
119664 ** freed.
119666 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
119667 ExprList *pOrderBy = p->pOrderBy;
119668 int nOrderBy = p->pOrderBy->nExpr;
119669 sqlite3 *db = pParse->db;
119670 KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
119671 if( pRet ){
119672 int i;
119673 for(i=0; i<nOrderBy; i++){
119674 struct ExprList_item *pItem = &pOrderBy->a[i];
119675 Expr *pTerm = pItem->pExpr;
119676 CollSeq *pColl;
119678 if( pTerm->flags & EP_Collate ){
119679 pColl = sqlite3ExprCollSeq(pParse, pTerm);
119680 }else{
119681 pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
119682 if( pColl==0 ) pColl = db->pDfltColl;
119683 pOrderBy->a[i].pExpr =
119684 sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
119686 assert( sqlite3KeyInfoIsWriteable(pRet) );
119687 pRet->aColl[i] = pColl;
119688 pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
119692 return pRet;
119695 #ifndef SQLITE_OMIT_CTE
119697 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
119698 ** query of the form:
119700 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
119701 ** \___________/ \_______________/
119702 ** p->pPrior p
119705 ** There is exactly one reference to the recursive-table in the FROM clause
119706 ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
119708 ** The setup-query runs once to generate an initial set of rows that go
119709 ** into a Queue table. Rows are extracted from the Queue table one by
119710 ** one. Each row extracted from Queue is output to pDest. Then the single
119711 ** extracted row (now in the iCurrent table) becomes the content of the
119712 ** recursive-table for a recursive-query run. The output of the recursive-query
119713 ** is added back into the Queue table. Then another row is extracted from Queue
119714 ** and the iteration continues until the Queue table is empty.
119716 ** If the compound query operator is UNION then no duplicate rows are ever
119717 ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
119718 ** that have ever been inserted into Queue and causes duplicates to be
119719 ** discarded. If the operator is UNION ALL, then duplicates are allowed.
119721 ** If the query has an ORDER BY, then entries in the Queue table are kept in
119722 ** ORDER BY order and the first entry is extracted for each cycle. Without
119723 ** an ORDER BY, the Queue table is just a FIFO.
119725 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
119726 ** have been output to pDest. A LIMIT of zero means to output no rows and a
119727 ** negative LIMIT means to output all rows. If there is also an OFFSET clause
119728 ** with a positive value, then the first OFFSET outputs are discarded rather
119729 ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
119730 ** rows have been skipped.
119732 static void generateWithRecursiveQuery(
119733 Parse *pParse, /* Parsing context */
119734 Select *p, /* The recursive SELECT to be coded */
119735 SelectDest *pDest /* What to do with query results */
119737 SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
119738 int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
119739 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
119740 Select *pSetup = p->pPrior; /* The setup query */
119741 int addrTop; /* Top of the loop */
119742 int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
119743 int iCurrent = 0; /* The Current table */
119744 int regCurrent; /* Register holding Current table */
119745 int iQueue; /* The Queue table */
119746 int iDistinct = 0; /* To ensure unique results if UNION */
119747 int eDest = SRT_Fifo; /* How to write to Queue */
119748 SelectDest destQueue; /* SelectDest targetting the Queue table */
119749 int i; /* Loop counter */
119750 int rc; /* Result code */
119751 ExprList *pOrderBy; /* The ORDER BY clause */
119752 Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
119753 int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
119755 /* Obtain authorization to do a recursive query */
119756 if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
119758 /* Process the LIMIT and OFFSET clauses, if they exist */
119759 addrBreak = sqlite3VdbeMakeLabel(v);
119760 p->nSelectRow = 320; /* 4 billion rows */
119761 computeLimitRegisters(pParse, p, addrBreak);
119762 pLimit = p->pLimit;
119763 pOffset = p->pOffset;
119764 regLimit = p->iLimit;
119765 regOffset = p->iOffset;
119766 p->pLimit = p->pOffset = 0;
119767 p->iLimit = p->iOffset = 0;
119768 pOrderBy = p->pOrderBy;
119770 /* Locate the cursor number of the Current table */
119771 for(i=0; ALWAYS(i<pSrc->nSrc); i++){
119772 if( pSrc->a[i].fg.isRecursive ){
119773 iCurrent = pSrc->a[i].iCursor;
119774 break;
119778 /* Allocate cursors numbers for Queue and Distinct. The cursor number for
119779 ** the Distinct table must be exactly one greater than Queue in order
119780 ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
119781 iQueue = pParse->nTab++;
119782 if( p->op==TK_UNION ){
119783 eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
119784 iDistinct = pParse->nTab++;
119785 }else{
119786 eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
119788 sqlite3SelectDestInit(&destQueue, eDest, iQueue);
119790 /* Allocate cursors for Current, Queue, and Distinct. */
119791 regCurrent = ++pParse->nMem;
119792 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
119793 if( pOrderBy ){
119794 KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
119795 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
119796 (char*)pKeyInfo, P4_KEYINFO);
119797 destQueue.pOrderBy = pOrderBy;
119798 }else{
119799 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
119801 VdbeComment((v, "Queue table"));
119802 if( iDistinct ){
119803 p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
119804 p->selFlags |= SF_UsesEphemeral;
119807 /* Detach the ORDER BY clause from the compound SELECT */
119808 p->pOrderBy = 0;
119810 /* Store the results of the setup-query in Queue. */
119811 pSetup->pNext = 0;
119812 rc = sqlite3Select(pParse, pSetup, &destQueue);
119813 pSetup->pNext = p;
119814 if( rc ) goto end_of_recursive_query;
119816 /* Find the next row in the Queue and output that row */
119817 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
119819 /* Transfer the next row in Queue over to Current */
119820 sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
119821 if( pOrderBy ){
119822 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
119823 }else{
119824 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
119826 sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
119828 /* Output the single row in Current */
119829 addrCont = sqlite3VdbeMakeLabel(v);
119830 codeOffset(v, regOffset, addrCont);
119831 selectInnerLoop(pParse, p, iCurrent,
119832 0, 0, pDest, addrCont, addrBreak);
119833 if( regLimit ){
119834 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
119835 VdbeCoverage(v);
119837 sqlite3VdbeResolveLabel(v, addrCont);
119839 /* Execute the recursive SELECT taking the single row in Current as
119840 ** the value for the recursive-table. Store the results in the Queue.
119842 if( p->selFlags & SF_Aggregate ){
119843 sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
119844 }else{
119845 p->pPrior = 0;
119846 sqlite3Select(pParse, p, &destQueue);
119847 assert( p->pPrior==0 );
119848 p->pPrior = pSetup;
119851 /* Keep running the loop until the Queue is empty */
119852 sqlite3VdbeGoto(v, addrTop);
119853 sqlite3VdbeResolveLabel(v, addrBreak);
119855 end_of_recursive_query:
119856 sqlite3ExprListDelete(pParse->db, p->pOrderBy);
119857 p->pOrderBy = pOrderBy;
119858 p->pLimit = pLimit;
119859 p->pOffset = pOffset;
119860 return;
119862 #endif /* SQLITE_OMIT_CTE */
119864 /* Forward references */
119865 static int multiSelectOrderBy(
119866 Parse *pParse, /* Parsing context */
119867 Select *p, /* The right-most of SELECTs to be coded */
119868 SelectDest *pDest /* What to do with query results */
119872 ** Handle the special case of a compound-select that originates from a
119873 ** VALUES clause. By handling this as a special case, we avoid deep
119874 ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
119875 ** on a VALUES clause.
119877 ** Because the Select object originates from a VALUES clause:
119878 ** (1) It has no LIMIT or OFFSET
119879 ** (2) All terms are UNION ALL
119880 ** (3) There is no ORDER BY clause
119882 static int multiSelectValues(
119883 Parse *pParse, /* Parsing context */
119884 Select *p, /* The right-most of SELECTs to be coded */
119885 SelectDest *pDest /* What to do with query results */
119887 Select *pPrior;
119888 int nRow = 1;
119889 int rc = 0;
119890 assert( p->selFlags & SF_MultiValue );
119892 assert( p->selFlags & SF_Values );
119893 assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
119894 assert( p->pLimit==0 );
119895 assert( p->pOffset==0 );
119896 assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
119897 if( p->pPrior==0 ) break;
119898 assert( p->pPrior->pNext==p );
119899 p = p->pPrior;
119900 nRow++;
119901 }while(1);
119902 while( p ){
119903 pPrior = p->pPrior;
119904 p->pPrior = 0;
119905 rc = sqlite3Select(pParse, p, pDest);
119906 p->pPrior = pPrior;
119907 if( rc ) break;
119908 p->nSelectRow = nRow;
119909 p = p->pNext;
119911 return rc;
119915 ** This routine is called to process a compound query form from
119916 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
119917 ** INTERSECT
119919 ** "p" points to the right-most of the two queries. the query on the
119920 ** left is p->pPrior. The left query could also be a compound query
119921 ** in which case this routine will be called recursively.
119923 ** The results of the total query are to be written into a destination
119924 ** of type eDest with parameter iParm.
119926 ** Example 1: Consider a three-way compound SQL statement.
119928 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
119930 ** This statement is parsed up as follows:
119932 ** SELECT c FROM t3
119934 ** `-----> SELECT b FROM t2
119936 ** `------> SELECT a FROM t1
119938 ** The arrows in the diagram above represent the Select.pPrior pointer.
119939 ** So if this routine is called with p equal to the t3 query, then
119940 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
119942 ** Notice that because of the way SQLite parses compound SELECTs, the
119943 ** individual selects always group from left to right.
119945 static int multiSelect(
119946 Parse *pParse, /* Parsing context */
119947 Select *p, /* The right-most of SELECTs to be coded */
119948 SelectDest *pDest /* What to do with query results */
119950 int rc = SQLITE_OK; /* Success code from a subroutine */
119951 Select *pPrior; /* Another SELECT immediately to our left */
119952 Vdbe *v; /* Generate code to this VDBE */
119953 SelectDest dest; /* Alternative data destination */
119954 Select *pDelete = 0; /* Chain of simple selects to delete */
119955 sqlite3 *db; /* Database connection */
119956 #ifndef SQLITE_OMIT_EXPLAIN
119957 int iSub1 = 0; /* EQP id of left-hand query */
119958 int iSub2 = 0; /* EQP id of right-hand query */
119959 #endif
119961 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
119962 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
119964 assert( p && p->pPrior ); /* Calling function guarantees this much */
119965 assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
119966 db = pParse->db;
119967 pPrior = p->pPrior;
119968 dest = *pDest;
119969 if( pPrior->pOrderBy || pPrior->pLimit ){
119970 sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
119971 pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
119972 rc = 1;
119973 goto multi_select_end;
119976 v = sqlite3GetVdbe(pParse);
119977 assert( v!=0 ); /* The VDBE already created by calling function */
119979 /* Create the destination temporary table if necessary
119981 if( dest.eDest==SRT_EphemTab ){
119982 assert( p->pEList );
119983 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
119984 dest.eDest = SRT_Table;
119987 /* Special handling for a compound-select that originates as a VALUES clause.
119989 if( p->selFlags & SF_MultiValue ){
119990 rc = multiSelectValues(pParse, p, &dest);
119991 goto multi_select_end;
119994 /* Make sure all SELECTs in the statement have the same number of elements
119995 ** in their result sets.
119997 assert( p->pEList && pPrior->pEList );
119998 assert( p->pEList->nExpr==pPrior->pEList->nExpr );
120000 #ifndef SQLITE_OMIT_CTE
120001 if( p->selFlags & SF_Recursive ){
120002 generateWithRecursiveQuery(pParse, p, &dest);
120003 }else
120004 #endif
120006 /* Compound SELECTs that have an ORDER BY clause are handled separately.
120008 if( p->pOrderBy ){
120009 return multiSelectOrderBy(pParse, p, pDest);
120010 }else
120012 /* Generate code for the left and right SELECT statements.
120014 switch( p->op ){
120015 case TK_ALL: {
120016 int addr = 0;
120017 int nLimit;
120018 assert( !pPrior->pLimit );
120019 pPrior->iLimit = p->iLimit;
120020 pPrior->iOffset = p->iOffset;
120021 pPrior->pLimit = p->pLimit;
120022 pPrior->pOffset = p->pOffset;
120023 explainSetInteger(iSub1, pParse->iNextSelectId);
120024 rc = sqlite3Select(pParse, pPrior, &dest);
120025 p->pLimit = 0;
120026 p->pOffset = 0;
120027 if( rc ){
120028 goto multi_select_end;
120030 p->pPrior = 0;
120031 p->iLimit = pPrior->iLimit;
120032 p->iOffset = pPrior->iOffset;
120033 if( p->iLimit ){
120034 addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
120035 VdbeComment((v, "Jump ahead if LIMIT reached"));
120036 if( p->iOffset ){
120037 sqlite3VdbeAddOp3(v, OP_OffsetLimit,
120038 p->iLimit, p->iOffset+1, p->iOffset);
120041 explainSetInteger(iSub2, pParse->iNextSelectId);
120042 rc = sqlite3Select(pParse, p, &dest);
120043 testcase( rc!=SQLITE_OK );
120044 pDelete = p->pPrior;
120045 p->pPrior = pPrior;
120046 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
120047 if( pPrior->pLimit
120048 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
120049 && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
120051 p->nSelectRow = sqlite3LogEst((u64)nLimit);
120053 if( addr ){
120054 sqlite3VdbeJumpHere(v, addr);
120056 break;
120058 case TK_EXCEPT:
120059 case TK_UNION: {
120060 int unionTab; /* Cursor number of the temporary table holding result */
120061 u8 op = 0; /* One of the SRT_ operations to apply to self */
120062 int priorOp; /* The SRT_ operation to apply to prior selects */
120063 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
120064 int addr;
120065 SelectDest uniondest;
120067 testcase( p->op==TK_EXCEPT );
120068 testcase( p->op==TK_UNION );
120069 priorOp = SRT_Union;
120070 if( dest.eDest==priorOp ){
120071 /* We can reuse a temporary table generated by a SELECT to our
120072 ** right.
120074 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
120075 assert( p->pOffset==0 ); /* Not allowed on leftward elements */
120076 unionTab = dest.iSDParm;
120077 }else{
120078 /* We will need to create our own temporary table to hold the
120079 ** intermediate results.
120081 unionTab = pParse->nTab++;
120082 assert( p->pOrderBy==0 );
120083 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
120084 assert( p->addrOpenEphm[0] == -1 );
120085 p->addrOpenEphm[0] = addr;
120086 findRightmost(p)->selFlags |= SF_UsesEphemeral;
120087 assert( p->pEList );
120090 /* Code the SELECT statements to our left
120092 assert( !pPrior->pOrderBy );
120093 sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
120094 explainSetInteger(iSub1, pParse->iNextSelectId);
120095 rc = sqlite3Select(pParse, pPrior, &uniondest);
120096 if( rc ){
120097 goto multi_select_end;
120100 /* Code the current SELECT statement
120102 if( p->op==TK_EXCEPT ){
120103 op = SRT_Except;
120104 }else{
120105 assert( p->op==TK_UNION );
120106 op = SRT_Union;
120108 p->pPrior = 0;
120109 pLimit = p->pLimit;
120110 p->pLimit = 0;
120111 pOffset = p->pOffset;
120112 p->pOffset = 0;
120113 uniondest.eDest = op;
120114 explainSetInteger(iSub2, pParse->iNextSelectId);
120115 rc = sqlite3Select(pParse, p, &uniondest);
120116 testcase( rc!=SQLITE_OK );
120117 /* Query flattening in sqlite3Select() might refill p->pOrderBy.
120118 ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
120119 sqlite3ExprListDelete(db, p->pOrderBy);
120120 pDelete = p->pPrior;
120121 p->pPrior = pPrior;
120122 p->pOrderBy = 0;
120123 if( p->op==TK_UNION ){
120124 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
120126 sqlite3ExprDelete(db, p->pLimit);
120127 p->pLimit = pLimit;
120128 p->pOffset = pOffset;
120129 p->iLimit = 0;
120130 p->iOffset = 0;
120132 /* Convert the data in the temporary table into whatever form
120133 ** it is that we currently need.
120135 assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
120136 if( dest.eDest!=priorOp ){
120137 int iCont, iBreak, iStart;
120138 assert( p->pEList );
120139 iBreak = sqlite3VdbeMakeLabel(v);
120140 iCont = sqlite3VdbeMakeLabel(v);
120141 computeLimitRegisters(pParse, p, iBreak);
120142 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
120143 iStart = sqlite3VdbeCurrentAddr(v);
120144 selectInnerLoop(pParse, p, unionTab,
120145 0, 0, &dest, iCont, iBreak);
120146 sqlite3VdbeResolveLabel(v, iCont);
120147 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
120148 sqlite3VdbeResolveLabel(v, iBreak);
120149 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
120151 break;
120153 default: assert( p->op==TK_INTERSECT ); {
120154 int tab1, tab2;
120155 int iCont, iBreak, iStart;
120156 Expr *pLimit, *pOffset;
120157 int addr;
120158 SelectDest intersectdest;
120159 int r1;
120161 /* INTERSECT is different from the others since it requires
120162 ** two temporary tables. Hence it has its own case. Begin
120163 ** by allocating the tables we will need.
120165 tab1 = pParse->nTab++;
120166 tab2 = pParse->nTab++;
120167 assert( p->pOrderBy==0 );
120169 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
120170 assert( p->addrOpenEphm[0] == -1 );
120171 p->addrOpenEphm[0] = addr;
120172 findRightmost(p)->selFlags |= SF_UsesEphemeral;
120173 assert( p->pEList );
120175 /* Code the SELECTs to our left into temporary table "tab1".
120177 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
120178 explainSetInteger(iSub1, pParse->iNextSelectId);
120179 rc = sqlite3Select(pParse, pPrior, &intersectdest);
120180 if( rc ){
120181 goto multi_select_end;
120184 /* Code the current SELECT into temporary table "tab2"
120186 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
120187 assert( p->addrOpenEphm[1] == -1 );
120188 p->addrOpenEphm[1] = addr;
120189 p->pPrior = 0;
120190 pLimit = p->pLimit;
120191 p->pLimit = 0;
120192 pOffset = p->pOffset;
120193 p->pOffset = 0;
120194 intersectdest.iSDParm = tab2;
120195 explainSetInteger(iSub2, pParse->iNextSelectId);
120196 rc = sqlite3Select(pParse, p, &intersectdest);
120197 testcase( rc!=SQLITE_OK );
120198 pDelete = p->pPrior;
120199 p->pPrior = pPrior;
120200 if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
120201 sqlite3ExprDelete(db, p->pLimit);
120202 p->pLimit = pLimit;
120203 p->pOffset = pOffset;
120205 /* Generate code to take the intersection of the two temporary
120206 ** tables.
120208 assert( p->pEList );
120209 iBreak = sqlite3VdbeMakeLabel(v);
120210 iCont = sqlite3VdbeMakeLabel(v);
120211 computeLimitRegisters(pParse, p, iBreak);
120212 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
120213 r1 = sqlite3GetTempReg(pParse);
120214 iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
120215 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
120216 sqlite3ReleaseTempReg(pParse, r1);
120217 selectInnerLoop(pParse, p, tab1,
120218 0, 0, &dest, iCont, iBreak);
120219 sqlite3VdbeResolveLabel(v, iCont);
120220 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
120221 sqlite3VdbeResolveLabel(v, iBreak);
120222 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
120223 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
120224 break;
120228 explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
120230 /* Compute collating sequences used by
120231 ** temporary tables needed to implement the compound select.
120232 ** Attach the KeyInfo structure to all temporary tables.
120234 ** This section is run by the right-most SELECT statement only.
120235 ** SELECT statements to the left always skip this part. The right-most
120236 ** SELECT might also skip this part if it has no ORDER BY clause and
120237 ** no temp tables are required.
120239 if( p->selFlags & SF_UsesEphemeral ){
120240 int i; /* Loop counter */
120241 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
120242 Select *pLoop; /* For looping through SELECT statements */
120243 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
120244 int nCol; /* Number of columns in result set */
120246 assert( p->pNext==0 );
120247 nCol = p->pEList->nExpr;
120248 pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
120249 if( !pKeyInfo ){
120250 rc = SQLITE_NOMEM_BKPT;
120251 goto multi_select_end;
120253 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
120254 *apColl = multiSelectCollSeq(pParse, p, i);
120255 if( 0==*apColl ){
120256 *apColl = db->pDfltColl;
120260 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
120261 for(i=0; i<2; i++){
120262 int addr = pLoop->addrOpenEphm[i];
120263 if( addr<0 ){
120264 /* If [0] is unused then [1] is also unused. So we can
120265 ** always safely abort as soon as the first unused slot is found */
120266 assert( pLoop->addrOpenEphm[1]<0 );
120267 break;
120269 sqlite3VdbeChangeP2(v, addr, nCol);
120270 sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
120271 P4_KEYINFO);
120272 pLoop->addrOpenEphm[i] = -1;
120275 sqlite3KeyInfoUnref(pKeyInfo);
120278 multi_select_end:
120279 pDest->iSdst = dest.iSdst;
120280 pDest->nSdst = dest.nSdst;
120281 sqlite3SelectDelete(db, pDelete);
120282 return rc;
120284 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
120287 ** Error message for when two or more terms of a compound select have different
120288 ** size result sets.
120290 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
120291 if( p->selFlags & SF_Values ){
120292 sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
120293 }else{
120294 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
120295 " do not have the same number of result columns", selectOpName(p->op));
120300 ** Code an output subroutine for a coroutine implementation of a
120301 ** SELECT statment.
120303 ** The data to be output is contained in pIn->iSdst. There are
120304 ** pIn->nSdst columns to be output. pDest is where the output should
120305 ** be sent.
120307 ** regReturn is the number of the register holding the subroutine
120308 ** return address.
120310 ** If regPrev>0 then it is the first register in a vector that
120311 ** records the previous output. mem[regPrev] is a flag that is false
120312 ** if there has been no previous output. If regPrev>0 then code is
120313 ** generated to suppress duplicates. pKeyInfo is used for comparing
120314 ** keys.
120316 ** If the LIMIT found in p->iLimit is reached, jump immediately to
120317 ** iBreak.
120319 static int generateOutputSubroutine(
120320 Parse *pParse, /* Parsing context */
120321 Select *p, /* The SELECT statement */
120322 SelectDest *pIn, /* Coroutine supplying data */
120323 SelectDest *pDest, /* Where to send the data */
120324 int regReturn, /* The return address register */
120325 int regPrev, /* Previous result register. No uniqueness if 0 */
120326 KeyInfo *pKeyInfo, /* For comparing with previous entry */
120327 int iBreak /* Jump here if we hit the LIMIT */
120329 Vdbe *v = pParse->pVdbe;
120330 int iContinue;
120331 int addr;
120333 addr = sqlite3VdbeCurrentAddr(v);
120334 iContinue = sqlite3VdbeMakeLabel(v);
120336 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
120338 if( regPrev ){
120339 int addr1, addr2;
120340 addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
120341 addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
120342 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
120343 sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
120344 sqlite3VdbeJumpHere(v, addr1);
120345 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
120346 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
120348 if( pParse->db->mallocFailed ) return 0;
120350 /* Suppress the first OFFSET entries if there is an OFFSET clause
120352 codeOffset(v, p->iOffset, iContinue);
120354 assert( pDest->eDest!=SRT_Exists );
120355 assert( pDest->eDest!=SRT_Table );
120356 switch( pDest->eDest ){
120357 /* Store the result as data using a unique key.
120359 case SRT_EphemTab: {
120360 int r1 = sqlite3GetTempReg(pParse);
120361 int r2 = sqlite3GetTempReg(pParse);
120362 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
120363 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
120364 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
120365 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
120366 sqlite3ReleaseTempReg(pParse, r2);
120367 sqlite3ReleaseTempReg(pParse, r1);
120368 break;
120371 #ifndef SQLITE_OMIT_SUBQUERY
120372 /* If we are creating a set for an "expr IN (SELECT ...)".
120374 case SRT_Set: {
120375 int r1;
120376 testcase( pIn->nSdst>1 );
120377 r1 = sqlite3GetTempReg(pParse);
120378 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
120379 r1, pDest->zAffSdst, pIn->nSdst);
120380 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
120381 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
120382 pIn->iSdst, pIn->nSdst);
120383 sqlite3ReleaseTempReg(pParse, r1);
120384 break;
120387 /* If this is a scalar select that is part of an expression, then
120388 ** store the results in the appropriate memory cell and break out
120389 ** of the scan loop.
120391 case SRT_Mem: {
120392 assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
120393 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
120394 /* The LIMIT clause will jump out of the loop for us */
120395 break;
120397 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
120399 /* The results are stored in a sequence of registers
120400 ** starting at pDest->iSdst. Then the co-routine yields.
120402 case SRT_Coroutine: {
120403 if( pDest->iSdst==0 ){
120404 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
120405 pDest->nSdst = pIn->nSdst;
120407 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
120408 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
120409 break;
120412 /* If none of the above, then the result destination must be
120413 ** SRT_Output. This routine is never called with any other
120414 ** destination other than the ones handled above or SRT_Output.
120416 ** For SRT_Output, results are stored in a sequence of registers.
120417 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
120418 ** return the next row of result.
120420 default: {
120421 assert( pDest->eDest==SRT_Output );
120422 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
120423 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
120424 break;
120428 /* Jump to the end of the loop if the LIMIT is reached.
120430 if( p->iLimit ){
120431 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
120434 /* Generate the subroutine return
120436 sqlite3VdbeResolveLabel(v, iContinue);
120437 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
120439 return addr;
120443 ** Alternative compound select code generator for cases when there
120444 ** is an ORDER BY clause.
120446 ** We assume a query of the following form:
120448 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
120450 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
120451 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
120452 ** co-routines. Then run the co-routines in parallel and merge the results
120453 ** into the output. In addition to the two coroutines (called selectA and
120454 ** selectB) there are 7 subroutines:
120456 ** outA: Move the output of the selectA coroutine into the output
120457 ** of the compound query.
120459 ** outB: Move the output of the selectB coroutine into the output
120460 ** of the compound query. (Only generated for UNION and
120461 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
120462 ** appears only in B.)
120464 ** AltB: Called when there is data from both coroutines and A<B.
120466 ** AeqB: Called when there is data from both coroutines and A==B.
120468 ** AgtB: Called when there is data from both coroutines and A>B.
120470 ** EofA: Called when data is exhausted from selectA.
120472 ** EofB: Called when data is exhausted from selectB.
120474 ** The implementation of the latter five subroutines depend on which
120475 ** <operator> is used:
120478 ** UNION ALL UNION EXCEPT INTERSECT
120479 ** ------------- ----------------- -------------- -----------------
120480 ** AltB: outA, nextA outA, nextA outA, nextA nextA
120482 ** AeqB: outA, nextA nextA nextA outA, nextA
120484 ** AgtB: outB, nextB outB, nextB nextB nextB
120486 ** EofA: outB, nextB outB, nextB halt halt
120488 ** EofB: outA, nextA outA, nextA outA, nextA halt
120490 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
120491 ** causes an immediate jump to EofA and an EOF on B following nextB causes
120492 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
120493 ** following nextX causes a jump to the end of the select processing.
120495 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
120496 ** within the output subroutine. The regPrev register set holds the previously
120497 ** output value. A comparison is made against this value and the output
120498 ** is skipped if the next results would be the same as the previous.
120500 ** The implementation plan is to implement the two coroutines and seven
120501 ** subroutines first, then put the control logic at the bottom. Like this:
120503 ** goto Init
120504 ** coA: coroutine for left query (A)
120505 ** coB: coroutine for right query (B)
120506 ** outA: output one row of A
120507 ** outB: output one row of B (UNION and UNION ALL only)
120508 ** EofA: ...
120509 ** EofB: ...
120510 ** AltB: ...
120511 ** AeqB: ...
120512 ** AgtB: ...
120513 ** Init: initialize coroutine registers
120514 ** yield coA
120515 ** if eof(A) goto EofA
120516 ** yield coB
120517 ** if eof(B) goto EofB
120518 ** Cmpr: Compare A, B
120519 ** Jump AltB, AeqB, AgtB
120520 ** End: ...
120522 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
120523 ** actually called using Gosub and they do not Return. EofA and EofB loop
120524 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
120525 ** and AgtB jump to either L2 or to one of EofA or EofB.
120527 #ifndef SQLITE_OMIT_COMPOUND_SELECT
120528 static int multiSelectOrderBy(
120529 Parse *pParse, /* Parsing context */
120530 Select *p, /* The right-most of SELECTs to be coded */
120531 SelectDest *pDest /* What to do with query results */
120533 int i, j; /* Loop counters */
120534 Select *pPrior; /* Another SELECT immediately to our left */
120535 Vdbe *v; /* Generate code to this VDBE */
120536 SelectDest destA; /* Destination for coroutine A */
120537 SelectDest destB; /* Destination for coroutine B */
120538 int regAddrA; /* Address register for select-A coroutine */
120539 int regAddrB; /* Address register for select-B coroutine */
120540 int addrSelectA; /* Address of the select-A coroutine */
120541 int addrSelectB; /* Address of the select-B coroutine */
120542 int regOutA; /* Address register for the output-A subroutine */
120543 int regOutB; /* Address register for the output-B subroutine */
120544 int addrOutA; /* Address of the output-A subroutine */
120545 int addrOutB = 0; /* Address of the output-B subroutine */
120546 int addrEofA; /* Address of the select-A-exhausted subroutine */
120547 int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
120548 int addrEofB; /* Address of the select-B-exhausted subroutine */
120549 int addrAltB; /* Address of the A<B subroutine */
120550 int addrAeqB; /* Address of the A==B subroutine */
120551 int addrAgtB; /* Address of the A>B subroutine */
120552 int regLimitA; /* Limit register for select-A */
120553 int regLimitB; /* Limit register for select-A */
120554 int regPrev; /* A range of registers to hold previous output */
120555 int savedLimit; /* Saved value of p->iLimit */
120556 int savedOffset; /* Saved value of p->iOffset */
120557 int labelCmpr; /* Label for the start of the merge algorithm */
120558 int labelEnd; /* Label for the end of the overall SELECT stmt */
120559 int addr1; /* Jump instructions that get retargetted */
120560 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
120561 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
120562 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
120563 sqlite3 *db; /* Database connection */
120564 ExprList *pOrderBy; /* The ORDER BY clause */
120565 int nOrderBy; /* Number of terms in the ORDER BY clause */
120566 int *aPermute; /* Mapping from ORDER BY terms to result set columns */
120567 #ifndef SQLITE_OMIT_EXPLAIN
120568 int iSub1; /* EQP id of left-hand query */
120569 int iSub2; /* EQP id of right-hand query */
120570 #endif
120572 assert( p->pOrderBy!=0 );
120573 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
120574 db = pParse->db;
120575 v = pParse->pVdbe;
120576 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
120577 labelEnd = sqlite3VdbeMakeLabel(v);
120578 labelCmpr = sqlite3VdbeMakeLabel(v);
120581 /* Patch up the ORDER BY clause
120583 op = p->op;
120584 pPrior = p->pPrior;
120585 assert( pPrior->pOrderBy==0 );
120586 pOrderBy = p->pOrderBy;
120587 assert( pOrderBy );
120588 nOrderBy = pOrderBy->nExpr;
120590 /* For operators other than UNION ALL we have to make sure that
120591 ** the ORDER BY clause covers every term of the result set. Add
120592 ** terms to the ORDER BY clause as necessary.
120594 if( op!=TK_ALL ){
120595 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
120596 struct ExprList_item *pItem;
120597 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
120598 assert( pItem->u.x.iOrderByCol>0 );
120599 if( pItem->u.x.iOrderByCol==i ) break;
120601 if( j==nOrderBy ){
120602 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
120603 if( pNew==0 ) return SQLITE_NOMEM_BKPT;
120604 pNew->flags |= EP_IntValue;
120605 pNew->u.iValue = i;
120606 p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
120607 if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
120612 /* Compute the comparison permutation and keyinfo that is used with
120613 ** the permutation used to determine if the next
120614 ** row of results comes from selectA or selectB. Also add explicit
120615 ** collations to the ORDER BY clause terms so that when the subqueries
120616 ** to the right and the left are evaluated, they use the correct
120617 ** collation.
120619 aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
120620 if( aPermute ){
120621 struct ExprList_item *pItem;
120622 aPermute[0] = nOrderBy;
120623 for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
120624 assert( pItem->u.x.iOrderByCol>0 );
120625 assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
120626 aPermute[i] = pItem->u.x.iOrderByCol - 1;
120628 pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
120629 }else{
120630 pKeyMerge = 0;
120633 /* Reattach the ORDER BY clause to the query.
120635 p->pOrderBy = pOrderBy;
120636 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
120638 /* Allocate a range of temporary registers and the KeyInfo needed
120639 ** for the logic that removes duplicate result rows when the
120640 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
120642 if( op==TK_ALL ){
120643 regPrev = 0;
120644 }else{
120645 int nExpr = p->pEList->nExpr;
120646 assert( nOrderBy>=nExpr || db->mallocFailed );
120647 regPrev = pParse->nMem+1;
120648 pParse->nMem += nExpr+1;
120649 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
120650 pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
120651 if( pKeyDup ){
120652 assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
120653 for(i=0; i<nExpr; i++){
120654 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
120655 pKeyDup->aSortOrder[i] = 0;
120660 /* Separate the left and the right query from one another
120662 p->pPrior = 0;
120663 pPrior->pNext = 0;
120664 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
120665 if( pPrior->pPrior==0 ){
120666 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
120669 /* Compute the limit registers */
120670 computeLimitRegisters(pParse, p, labelEnd);
120671 if( p->iLimit && op==TK_ALL ){
120672 regLimitA = ++pParse->nMem;
120673 regLimitB = ++pParse->nMem;
120674 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
120675 regLimitA);
120676 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
120677 }else{
120678 regLimitA = regLimitB = 0;
120680 sqlite3ExprDelete(db, p->pLimit);
120681 p->pLimit = 0;
120682 sqlite3ExprDelete(db, p->pOffset);
120683 p->pOffset = 0;
120685 regAddrA = ++pParse->nMem;
120686 regAddrB = ++pParse->nMem;
120687 regOutA = ++pParse->nMem;
120688 regOutB = ++pParse->nMem;
120689 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
120690 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
120692 /* Generate a coroutine to evaluate the SELECT statement to the
120693 ** left of the compound operator - the "A" select.
120695 addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
120696 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
120697 VdbeComment((v, "left SELECT"));
120698 pPrior->iLimit = regLimitA;
120699 explainSetInteger(iSub1, pParse->iNextSelectId);
120700 sqlite3Select(pParse, pPrior, &destA);
120701 sqlite3VdbeEndCoroutine(v, regAddrA);
120702 sqlite3VdbeJumpHere(v, addr1);
120704 /* Generate a coroutine to evaluate the SELECT statement on
120705 ** the right - the "B" select
120707 addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
120708 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
120709 VdbeComment((v, "right SELECT"));
120710 savedLimit = p->iLimit;
120711 savedOffset = p->iOffset;
120712 p->iLimit = regLimitB;
120713 p->iOffset = 0;
120714 explainSetInteger(iSub2, pParse->iNextSelectId);
120715 sqlite3Select(pParse, p, &destB);
120716 p->iLimit = savedLimit;
120717 p->iOffset = savedOffset;
120718 sqlite3VdbeEndCoroutine(v, regAddrB);
120720 /* Generate a subroutine that outputs the current row of the A
120721 ** select as the next output row of the compound select.
120723 VdbeNoopComment((v, "Output routine for A"));
120724 addrOutA = generateOutputSubroutine(pParse,
120725 p, &destA, pDest, regOutA,
120726 regPrev, pKeyDup, labelEnd);
120728 /* Generate a subroutine that outputs the current row of the B
120729 ** select as the next output row of the compound select.
120731 if( op==TK_ALL || op==TK_UNION ){
120732 VdbeNoopComment((v, "Output routine for B"));
120733 addrOutB = generateOutputSubroutine(pParse,
120734 p, &destB, pDest, regOutB,
120735 regPrev, pKeyDup, labelEnd);
120737 sqlite3KeyInfoUnref(pKeyDup);
120739 /* Generate a subroutine to run when the results from select A
120740 ** are exhausted and only data in select B remains.
120742 if( op==TK_EXCEPT || op==TK_INTERSECT ){
120743 addrEofA_noB = addrEofA = labelEnd;
120744 }else{
120745 VdbeNoopComment((v, "eof-A subroutine"));
120746 addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
120747 addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
120748 VdbeCoverage(v);
120749 sqlite3VdbeGoto(v, addrEofA);
120750 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
120753 /* Generate a subroutine to run when the results from select B
120754 ** are exhausted and only data in select A remains.
120756 if( op==TK_INTERSECT ){
120757 addrEofB = addrEofA;
120758 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
120759 }else{
120760 VdbeNoopComment((v, "eof-B subroutine"));
120761 addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
120762 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
120763 sqlite3VdbeGoto(v, addrEofB);
120766 /* Generate code to handle the case of A<B
120768 VdbeNoopComment((v, "A-lt-B subroutine"));
120769 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
120770 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
120771 sqlite3VdbeGoto(v, labelCmpr);
120773 /* Generate code to handle the case of A==B
120775 if( op==TK_ALL ){
120776 addrAeqB = addrAltB;
120777 }else if( op==TK_INTERSECT ){
120778 addrAeqB = addrAltB;
120779 addrAltB++;
120780 }else{
120781 VdbeNoopComment((v, "A-eq-B subroutine"));
120782 addrAeqB =
120783 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
120784 sqlite3VdbeGoto(v, labelCmpr);
120787 /* Generate code to handle the case of A>B
120789 VdbeNoopComment((v, "A-gt-B subroutine"));
120790 addrAgtB = sqlite3VdbeCurrentAddr(v);
120791 if( op==TK_ALL || op==TK_UNION ){
120792 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
120794 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
120795 sqlite3VdbeGoto(v, labelCmpr);
120797 /* This code runs once to initialize everything.
120799 sqlite3VdbeJumpHere(v, addr1);
120800 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
120801 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
120803 /* Implement the main merge loop
120805 sqlite3VdbeResolveLabel(v, labelCmpr);
120806 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
120807 sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
120808 (char*)pKeyMerge, P4_KEYINFO);
120809 sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
120810 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
120812 /* Jump to the this point in order to terminate the query.
120814 sqlite3VdbeResolveLabel(v, labelEnd);
120816 /* Reassembly the compound query so that it will be freed correctly
120817 ** by the calling function */
120818 if( p->pPrior ){
120819 sqlite3SelectDelete(db, p->pPrior);
120821 p->pPrior = pPrior;
120822 pPrior->pNext = p;
120824 /*** TBD: Insert subroutine calls to close cursors on incomplete
120825 **** subqueries ****/
120826 explainComposite(pParse, p->op, iSub1, iSub2, 0);
120827 return pParse->nErr!=0;
120829 #endif
120831 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
120833 /* An instance of the SubstContext object describes an substitution edit
120834 ** to be performed on a parse tree.
120836 ** All references to columns in table iTable are to be replaced by corresponding
120837 ** expressions in pEList.
120839 typedef struct SubstContext {
120840 Parse *pParse; /* The parsing context */
120841 int iTable; /* Replace references to this table */
120842 int iNewTable; /* New table number */
120843 int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
120844 ExprList *pEList; /* Replacement expressions */
120845 } SubstContext;
120847 /* Forward Declarations */
120848 static void substExprList(SubstContext*, ExprList*);
120849 static void substSelect(SubstContext*, Select*, int);
120852 ** Scan through the expression pExpr. Replace every reference to
120853 ** a column in table number iTable with a copy of the iColumn-th
120854 ** entry in pEList. (But leave references to the ROWID column
120855 ** unchanged.)
120857 ** This routine is part of the flattening procedure. A subquery
120858 ** whose result set is defined by pEList appears as entry in the
120859 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
120860 ** FORM clause entry is iTable. This routine makes the necessary
120861 ** changes to pExpr so that it refers directly to the source table
120862 ** of the subquery rather the result set of the subquery.
120864 static Expr *substExpr(
120865 SubstContext *pSubst, /* Description of the substitution */
120866 Expr *pExpr /* Expr in which substitution occurs */
120868 if( pExpr==0 ) return 0;
120869 if( ExprHasProperty(pExpr, EP_FromJoin)
120870 && pExpr->iRightJoinTable==pSubst->iTable
120872 pExpr->iRightJoinTable = pSubst->iNewTable;
120874 if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
120875 if( pExpr->iColumn<0 ){
120876 pExpr->op = TK_NULL;
120877 }else{
120878 Expr *pNew;
120879 Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
120880 Expr ifNullRow;
120881 assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
120882 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
120883 if( sqlite3ExprIsVector(pCopy) ){
120884 sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
120885 }else{
120886 sqlite3 *db = pSubst->pParse->db;
120887 if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
120888 memset(&ifNullRow, 0, sizeof(ifNullRow));
120889 ifNullRow.op = TK_IF_NULL_ROW;
120890 ifNullRow.pLeft = pCopy;
120891 ifNullRow.iTable = pSubst->iNewTable;
120892 pCopy = &ifNullRow;
120894 pNew = sqlite3ExprDup(db, pCopy, 0);
120895 if( pNew && pSubst->isLeftJoin ){
120896 ExprSetProperty(pNew, EP_CanBeNull);
120898 if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
120899 pNew->iRightJoinTable = pExpr->iRightJoinTable;
120900 ExprSetProperty(pNew, EP_FromJoin);
120902 sqlite3ExprDelete(db, pExpr);
120903 pExpr = pNew;
120906 }else{
120907 if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
120908 pExpr->iTable = pSubst->iNewTable;
120910 pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
120911 pExpr->pRight = substExpr(pSubst, pExpr->pRight);
120912 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
120913 substSelect(pSubst, pExpr->x.pSelect, 1);
120914 }else{
120915 substExprList(pSubst, pExpr->x.pList);
120918 return pExpr;
120920 static void substExprList(
120921 SubstContext *pSubst, /* Description of the substitution */
120922 ExprList *pList /* List to scan and in which to make substitutes */
120924 int i;
120925 if( pList==0 ) return;
120926 for(i=0; i<pList->nExpr; i++){
120927 pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
120930 static void substSelect(
120931 SubstContext *pSubst, /* Description of the substitution */
120932 Select *p, /* SELECT statement in which to make substitutions */
120933 int doPrior /* Do substitutes on p->pPrior too */
120935 SrcList *pSrc;
120936 struct SrcList_item *pItem;
120937 int i;
120938 if( !p ) return;
120940 substExprList(pSubst, p->pEList);
120941 substExprList(pSubst, p->pGroupBy);
120942 substExprList(pSubst, p->pOrderBy);
120943 p->pHaving = substExpr(pSubst, p->pHaving);
120944 p->pWhere = substExpr(pSubst, p->pWhere);
120945 pSrc = p->pSrc;
120946 assert( pSrc!=0 );
120947 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
120948 substSelect(pSubst, pItem->pSelect, 1);
120949 if( pItem->fg.isTabFunc ){
120950 substExprList(pSubst, pItem->u1.pFuncArg);
120953 }while( doPrior && (p = p->pPrior)!=0 );
120955 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
120957 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
120959 ** This routine attempts to flatten subqueries as a performance optimization.
120960 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
120962 ** To understand the concept of flattening, consider the following
120963 ** query:
120965 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
120967 ** The default way of implementing this query is to execute the
120968 ** subquery first and store the results in a temporary table, then
120969 ** run the outer query on that temporary table. This requires two
120970 ** passes over the data. Furthermore, because the temporary table
120971 ** has no indices, the WHERE clause on the outer query cannot be
120972 ** optimized.
120974 ** This routine attempts to rewrite queries such as the above into
120975 ** a single flat select, like this:
120977 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
120979 ** The code generated for this simplification gives the same result
120980 ** but only has to scan the data once. And because indices might
120981 ** exist on the table t1, a complete scan of the data might be
120982 ** avoided.
120984 ** Flattening is subject to the following constraints:
120986 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
120987 ** The subquery and the outer query cannot both be aggregates.
120989 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
120990 ** (2) If the subquery is an aggregate then
120991 ** (2a) the outer query must not be a join and
120992 ** (2b) the outer query must not use subqueries
120993 ** other than the one FROM-clause subquery that is a candidate
120994 ** for flattening. (This is due to ticket [2f7170d73bf9abf80]
120995 ** from 2015-02-09.)
120997 ** (3) If the subquery is the right operand of a LEFT JOIN then
120998 ** (3a) the subquery may not be a join and
120999 ** (3b) the FROM clause of the subquery may not contain a virtual
121000 ** table and
121001 ** (3c) the outer query may not be an aggregate.
121003 ** (4) The subquery can not be DISTINCT.
121005 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
121006 ** sub-queries that were excluded from this optimization. Restriction
121007 ** (4) has since been expanded to exclude all DISTINCT subqueries.
121009 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
121010 ** If the subquery is aggregate, the outer query may not be DISTINCT.
121012 ** (7) The subquery must have a FROM clause. TODO: For subqueries without
121013 ** A FROM clause, consider adding a FROM clause with the special
121014 ** table sqlite_once that consists of a single row containing a
121015 ** single NULL.
121017 ** (8) If the subquery uses LIMIT then the outer query may not be a join.
121019 ** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
121021 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
121022 ** accidently carried the comment forward until 2014-09-15. Original
121023 ** constraint: "If the subquery is aggregate then the outer query
121024 ** may not use LIMIT."
121026 ** (11) The subquery and the outer query may not both have ORDER BY clauses.
121028 ** (**) Not implemented. Subsumed into restriction (3). Was previously
121029 ** a separate restriction deriving from ticket #350.
121031 ** (13) The subquery and outer query may not both use LIMIT.
121033 ** (14) The subquery may not use OFFSET.
121035 ** (15) If the outer query is part of a compound select, then the
121036 ** subquery may not use LIMIT.
121037 ** (See ticket #2339 and ticket [02a8e81d44]).
121039 ** (16) If the outer query is aggregate, then the subquery may not
121040 ** use ORDER BY. (Ticket #2942) This used to not matter
121041 ** until we introduced the group_concat() function.
121043 ** (17) If the subquery is a compound select, then
121044 ** (17a) all compound operators must be a UNION ALL, and
121045 ** (17b) no terms within the subquery compound may be aggregate
121046 ** or DISTINCT, and
121047 ** (17c) every term within the subquery compound must have a FROM clause
121048 ** (17d) the outer query may not be
121049 ** (17d1) aggregate, or
121050 ** (17d2) DISTINCT, or
121051 ** (17d3) a join.
121053 ** The parent and sub-query may contain WHERE clauses. Subject to
121054 ** rules (11), (13) and (14), they may also contain ORDER BY,
121055 ** LIMIT and OFFSET clauses. The subquery cannot use any compound
121056 ** operator other than UNION ALL because all the other compound
121057 ** operators have an implied DISTINCT which is disallowed by
121058 ** restriction (4).
121060 ** Also, each component of the sub-query must return the same number
121061 ** of result columns. This is actually a requirement for any compound
121062 ** SELECT statement, but all the code here does is make sure that no
121063 ** such (illegal) sub-query is flattened. The caller will detect the
121064 ** syntax error and return a detailed message.
121066 ** (18) If the sub-query is a compound select, then all terms of the
121067 ** ORDER BY clause of the parent must be simple references to
121068 ** columns of the sub-query.
121070 ** (19) If the subquery uses LIMIT then the outer query may not
121071 ** have a WHERE clause.
121073 ** (**) Subsumed into (17d3). Was: If the sub-query is a compound select,
121074 ** then it must not use an ORDER BY clause - Ticket #3773. Because
121075 ** of (17d3), then only way to have a compound subquery is if it is
121076 ** the only term in the FROM clause of the outer query. But if the
121077 ** only term in the FROM clause has an ORDER BY, then it will be
121078 ** implemented as a co-routine and the flattener will never be called.
121080 ** (21) If the subquery uses LIMIT then the outer query may not be
121081 ** DISTINCT. (See ticket [752e1646fc]).
121083 ** (22) The subquery may not be a recursive CTE.
121085 ** (**) Subsumed into restriction (17d3). Was: If the outer query is
121086 ** a recursive CTE, then the sub-query may not be a compound query.
121087 ** This restriction is because transforming the
121088 ** parent to a compound query confuses the code that handles
121089 ** recursive queries in multiSelect().
121091 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
121092 ** The subquery may not be an aggregate that uses the built-in min() or
121093 ** or max() functions. (Without this restriction, a query like:
121094 ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
121095 ** return the value X for which Y was maximal.)
121098 ** In this routine, the "p" parameter is a pointer to the outer query.
121099 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
121100 ** uses aggregates.
121102 ** If flattening is not attempted, this routine is a no-op and returns 0.
121103 ** If flattening is attempted this routine returns 1.
121105 ** All of the expression analysis must occur on both the outer query and
121106 ** the subquery before this routine runs.
121108 static int flattenSubquery(
121109 Parse *pParse, /* Parsing context */
121110 Select *p, /* The parent or outer SELECT statement */
121111 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
121112 int isAgg /* True if outer SELECT uses aggregate functions */
121114 const char *zSavedAuthContext = pParse->zAuthContext;
121115 Select *pParent; /* Current UNION ALL term of the other query */
121116 Select *pSub; /* The inner query or "subquery" */
121117 Select *pSub1; /* Pointer to the rightmost select in sub-query */
121118 SrcList *pSrc; /* The FROM clause of the outer query */
121119 SrcList *pSubSrc; /* The FROM clause of the subquery */
121120 int iParent; /* VDBE cursor number of the pSub result set temp table */
121121 int iNewParent = -1;/* Replacement table for iParent */
121122 int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
121123 int i; /* Loop counter */
121124 Expr *pWhere; /* The WHERE clause */
121125 struct SrcList_item *pSubitem; /* The subquery */
121126 sqlite3 *db = pParse->db;
121128 /* Check to see if flattening is permitted. Return 0 if not.
121130 assert( p!=0 );
121131 assert( p->pPrior==0 );
121132 if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
121133 pSrc = p->pSrc;
121134 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
121135 pSubitem = &pSrc->a[iFrom];
121136 iParent = pSubitem->iCursor;
121137 pSub = pSubitem->pSelect;
121138 assert( pSub!=0 );
121140 pSubSrc = pSub->pSrc;
121141 assert( pSubSrc );
121142 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
121143 ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
121144 ** because they could be computed at compile-time. But when LIMIT and OFFSET
121145 ** became arbitrary expressions, we were forced to add restrictions (13)
121146 ** and (14). */
121147 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
121148 if( pSub->pOffset ) return 0; /* Restriction (14) */
121149 if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
121150 return 0; /* Restriction (15) */
121152 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
121153 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
121154 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
121155 return 0; /* Restrictions (8)(9) */
121157 if( p->pOrderBy && pSub->pOrderBy ){
121158 return 0; /* Restriction (11) */
121160 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
121161 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
121162 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
121163 return 0; /* Restriction (21) */
121165 if( pSub->selFlags & (SF_Recursive) ){
121166 return 0; /* Restrictions (22) */
121170 ** If the subquery is the right operand of a LEFT JOIN, then the
121171 ** subquery may not be a join itself (3a). Example of why this is not
121172 ** allowed:
121174 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
121176 ** If we flatten the above, we would get
121178 ** (t1 LEFT OUTER JOIN t2) JOIN t3
121180 ** which is not at all the same thing.
121182 ** If the subquery is the right operand of a LEFT JOIN, then the outer
121183 ** query cannot be an aggregate. (3c) This is an artifact of the way
121184 ** aggregates are processed - there is no mechanism to determine if
121185 ** the LEFT JOIN table should be all-NULL.
121187 ** See also tickets #306, #350, and #3300.
121189 if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
121190 isLeftJoin = 1;
121191 if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
121192 /* (3a) (3c) (3b) */
121193 return 0;
121196 #ifdef SQLITE_EXTRA_IFNULLROW
121197 else if( iFrom>0 && !isAgg ){
121198 /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
121199 ** every reference to any result column from subquery in a join, even
121200 ** though they are not necessary. This will stress-test the OP_IfNullRow
121201 ** opcode. */
121202 isLeftJoin = -1;
121204 #endif
121206 /* Restriction (17): If the sub-query is a compound SELECT, then it must
121207 ** use only the UNION ALL operator. And none of the simple select queries
121208 ** that make up the compound SELECT are allowed to be aggregate or distinct
121209 ** queries.
121211 if( pSub->pPrior ){
121212 if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
121213 return 0; /* (17d1), (17d2), or (17d3) */
121215 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
121216 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
121217 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
121218 assert( pSub->pSrc!=0 );
121219 assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
121220 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
121221 || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
121222 || pSub1->pSrc->nSrc<1 /* (17c) */
121224 return 0;
121226 testcase( pSub1->pSrc->nSrc>1 );
121229 /* Restriction (18). */
121230 if( p->pOrderBy ){
121231 int ii;
121232 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
121233 if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
121238 /* Ex-restriction (23):
121239 ** The only way that the recursive part of a CTE can contain a compound
121240 ** subquery is for the subquery to be one term of a join. But if the
121241 ** subquery is a join, then the flattening has already been stopped by
121242 ** restriction (17d3)
121244 assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
121246 /* Ex-restriction (20):
121247 ** A compound subquery must be the only term in the FROM clause of the
121248 ** outer query by restriction (17d3). But if that term also has an
121249 ** ORDER BY clause, then the subquery will be implemented by co-routine
121250 ** and so the flattener will never be invoked. Hence, it is not possible
121251 ** for the subquery to be a compound and have an ORDER BY clause.
121253 assert( pSub->pPrior==0 || pSub->pOrderBy==0 );
121255 /***** If we reach this point, flattening is permitted. *****/
121256 SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
121257 pSub->zSelName, pSub, iFrom));
121259 /* Authorize the subquery */
121260 pParse->zAuthContext = pSubitem->zName;
121261 TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
121262 testcase( i==SQLITE_DENY );
121263 pParse->zAuthContext = zSavedAuthContext;
121265 /* If the sub-query is a compound SELECT statement, then (by restrictions
121266 ** 17 and 18 above) it must be a UNION ALL and the parent query must
121267 ** be of the form:
121269 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
121271 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
121272 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
121273 ** OFFSET clauses and joins them to the left-hand-side of the original
121274 ** using UNION ALL operators. In this case N is the number of simple
121275 ** select statements in the compound sub-query.
121277 ** Example:
121279 ** SELECT a+1 FROM (
121280 ** SELECT x FROM tab
121281 ** UNION ALL
121282 ** SELECT y FROM tab
121283 ** UNION ALL
121284 ** SELECT abs(z*2) FROM tab2
121285 ** ) WHERE a!=5 ORDER BY 1
121287 ** Transformed into:
121289 ** SELECT x+1 FROM tab WHERE x+1!=5
121290 ** UNION ALL
121291 ** SELECT y+1 FROM tab WHERE y+1!=5
121292 ** UNION ALL
121293 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
121294 ** ORDER BY 1
121296 ** We call this the "compound-subquery flattening".
121298 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
121299 Select *pNew;
121300 ExprList *pOrderBy = p->pOrderBy;
121301 Expr *pLimit = p->pLimit;
121302 Expr *pOffset = p->pOffset;
121303 Select *pPrior = p->pPrior;
121304 p->pOrderBy = 0;
121305 p->pSrc = 0;
121306 p->pPrior = 0;
121307 p->pLimit = 0;
121308 p->pOffset = 0;
121309 pNew = sqlite3SelectDup(db, p, 0);
121310 sqlite3SelectSetName(pNew, pSub->zSelName);
121311 p->pOffset = pOffset;
121312 p->pLimit = pLimit;
121313 p->pOrderBy = pOrderBy;
121314 p->pSrc = pSrc;
121315 p->op = TK_ALL;
121316 if( pNew==0 ){
121317 p->pPrior = pPrior;
121318 }else{
121319 pNew->pPrior = pPrior;
121320 if( pPrior ) pPrior->pNext = pNew;
121321 pNew->pNext = p;
121322 p->pPrior = pNew;
121323 SELECTTRACE(2,pParse,p,
121324 ("compound-subquery flattener creates %s.%p as peer\n",
121325 pNew->zSelName, pNew));
121327 if( db->mallocFailed ) return 1;
121330 /* Begin flattening the iFrom-th entry of the FROM clause
121331 ** in the outer query.
121333 pSub = pSub1 = pSubitem->pSelect;
121335 /* Delete the transient table structure associated with the
121336 ** subquery
121338 sqlite3DbFree(db, pSubitem->zDatabase);
121339 sqlite3DbFree(db, pSubitem->zName);
121340 sqlite3DbFree(db, pSubitem->zAlias);
121341 pSubitem->zDatabase = 0;
121342 pSubitem->zName = 0;
121343 pSubitem->zAlias = 0;
121344 pSubitem->pSelect = 0;
121346 /* Defer deleting the Table object associated with the
121347 ** subquery until code generation is
121348 ** complete, since there may still exist Expr.pTab entries that
121349 ** refer to the subquery even after flattening. Ticket #3346.
121351 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
121353 if( ALWAYS(pSubitem->pTab!=0) ){
121354 Table *pTabToDel = pSubitem->pTab;
121355 if( pTabToDel->nTabRef==1 ){
121356 Parse *pToplevel = sqlite3ParseToplevel(pParse);
121357 pTabToDel->pNextZombie = pToplevel->pZombieTab;
121358 pToplevel->pZombieTab = pTabToDel;
121359 }else{
121360 pTabToDel->nTabRef--;
121362 pSubitem->pTab = 0;
121365 /* The following loop runs once for each term in a compound-subquery
121366 ** flattening (as described above). If we are doing a different kind
121367 ** of flattening - a flattening other than a compound-subquery flattening -
121368 ** then this loop only runs once.
121370 ** This loop moves all of the FROM elements of the subquery into the
121371 ** the FROM clause of the outer query. Before doing this, remember
121372 ** the cursor number for the original outer query FROM element in
121373 ** iParent. The iParent cursor will never be used. Subsequent code
121374 ** will scan expressions looking for iParent references and replace
121375 ** those references with expressions that resolve to the subquery FROM
121376 ** elements we are now copying in.
121378 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
121379 int nSubSrc;
121380 u8 jointype = 0;
121381 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
121382 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
121383 pSrc = pParent->pSrc; /* FROM clause of the outer query */
121385 if( pSrc ){
121386 assert( pParent==p ); /* First time through the loop */
121387 jointype = pSubitem->fg.jointype;
121388 }else{
121389 assert( pParent!=p ); /* 2nd and subsequent times through the loop */
121390 pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
121391 if( pSrc==0 ){
121392 assert( db->mallocFailed );
121393 break;
121397 /* The subquery uses a single slot of the FROM clause of the outer
121398 ** query. If the subquery has more than one element in its FROM clause,
121399 ** then expand the outer query to make space for it to hold all elements
121400 ** of the subquery.
121402 ** Example:
121404 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
121406 ** The outer query has 3 slots in its FROM clause. One slot of the
121407 ** outer query (the middle slot) is used by the subquery. The next
121408 ** block of code will expand the outer query FROM clause to 4 slots.
121409 ** The middle slot is expanded to two slots in order to make space
121410 ** for the two elements in the FROM clause of the subquery.
121412 if( nSubSrc>1 ){
121413 pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
121414 if( db->mallocFailed ){
121415 break;
121419 /* Transfer the FROM clause terms from the subquery into the
121420 ** outer query.
121422 for(i=0; i<nSubSrc; i++){
121423 sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
121424 assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
121425 pSrc->a[i+iFrom] = pSubSrc->a[i];
121426 iNewParent = pSubSrc->a[i].iCursor;
121427 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
121429 pSrc->a[iFrom].fg.jointype = jointype;
121431 /* Now begin substituting subquery result set expressions for
121432 ** references to the iParent in the outer query.
121434 ** Example:
121436 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
121437 ** \ \_____________ subquery __________/ /
121438 ** \_____________________ outer query ______________________________/
121440 ** We look at every expression in the outer query and every place we see
121441 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
121443 if( pSub->pOrderBy ){
121444 /* At this point, any non-zero iOrderByCol values indicate that the
121445 ** ORDER BY column expression is identical to the iOrderByCol'th
121446 ** expression returned by SELECT statement pSub. Since these values
121447 ** do not necessarily correspond to columns in SELECT statement pParent,
121448 ** zero them before transfering the ORDER BY clause.
121450 ** Not doing this may cause an error if a subsequent call to this
121451 ** function attempts to flatten a compound sub-query into pParent
121452 ** (the only way this can happen is if the compound sub-query is
121453 ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
121454 ExprList *pOrderBy = pSub->pOrderBy;
121455 for(i=0; i<pOrderBy->nExpr; i++){
121456 pOrderBy->a[i].u.x.iOrderByCol = 0;
121458 assert( pParent->pOrderBy==0 );
121459 assert( pSub->pPrior==0 );
121460 pParent->pOrderBy = pOrderBy;
121461 pSub->pOrderBy = 0;
121463 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
121464 if( isLeftJoin>0 ){
121465 setJoinExpr(pWhere, iNewParent);
121467 pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
121468 if( db->mallocFailed==0 ){
121469 SubstContext x;
121470 x.pParse = pParse;
121471 x.iTable = iParent;
121472 x.iNewTable = iNewParent;
121473 x.isLeftJoin = isLeftJoin;
121474 x.pEList = pSub->pEList;
121475 substSelect(&x, pParent, 0);
121478 /* The flattened query is distinct if either the inner or the
121479 ** outer query is distinct.
121481 pParent->selFlags |= pSub->selFlags & SF_Distinct;
121484 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
121486 ** One is tempted to try to add a and b to combine the limits. But this
121487 ** does not work if either limit is negative.
121489 if( pSub->pLimit ){
121490 pParent->pLimit = pSub->pLimit;
121491 pSub->pLimit = 0;
121495 /* Finially, delete what is left of the subquery and return
121496 ** success.
121498 sqlite3SelectDelete(db, pSub1);
121500 #if SELECTTRACE_ENABLED
121501 if( sqlite3SelectTrace & 0x100 ){
121502 SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
121503 sqlite3TreeViewSelect(0, p, 0);
121505 #endif
121507 return 1;
121509 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
121513 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
121515 ** Make copies of relevant WHERE clause terms of the outer query into
121516 ** the WHERE clause of subquery. Example:
121518 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
121520 ** Transformed into:
121522 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
121523 ** WHERE x=5 AND y=10;
121525 ** The hope is that the terms added to the inner query will make it more
121526 ** efficient.
121528 ** Do not attempt this optimization if:
121530 ** (1) (** This restriction was removed on 2017-09-29. We used to
121531 ** disallow this optimization for aggregate subqueries, but now
121532 ** it is allowed by putting the extra terms on the HAVING clause.
121533 ** The added HAVING clause is pointless if the subquery lacks
121534 ** a GROUP BY clause. But such a HAVING clause is also harmless
121535 ** so there does not appear to be any reason to add extra logic
121536 ** to suppress it. **)
121538 ** (2) The inner query is the recursive part of a common table expression.
121540 ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
121541 ** close would change the meaning of the LIMIT).
121543 ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
121544 ** enforces this restriction since this routine does not have enough
121545 ** information to know.)
121547 ** (5) The WHERE clause expression originates in the ON or USING clause
121548 ** of a LEFT JOIN.
121550 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
121551 ** terms are duplicated into the subquery.
121553 static int pushDownWhereTerms(
121554 Parse *pParse, /* Parse context (for malloc() and error reporting) */
121555 Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
121556 Expr *pWhere, /* The WHERE clause of the outer query */
121557 int iCursor /* Cursor number of the subquery */
121559 Expr *pNew;
121560 int nChng = 0;
121561 if( pWhere==0 ) return 0;
121562 if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
121564 #ifdef SQLITE_DEBUG
121565 /* Only the first term of a compound can have a WITH clause. But make
121566 ** sure no other terms are marked SF_Recursive in case something changes
121567 ** in the future.
121570 Select *pX;
121571 for(pX=pSubq; pX; pX=pX->pPrior){
121572 assert( (pX->selFlags & (SF_Recursive))==0 );
121575 #endif
121577 if( pSubq->pLimit!=0 ){
121578 return 0; /* restriction (3) */
121580 while( pWhere->op==TK_AND ){
121581 nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor);
121582 pWhere = pWhere->pLeft;
121584 if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction (5) */
121585 if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
121586 nChng++;
121587 while( pSubq ){
121588 SubstContext x;
121589 pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
121590 x.pParse = pParse;
121591 x.iTable = iCursor;
121592 x.iNewTable = iCursor;
121593 x.isLeftJoin = 0;
121594 x.pEList = pSubq->pEList;
121595 pNew = substExpr(&x, pNew);
121596 if( pSubq->selFlags & SF_Aggregate ){
121597 pSubq->pHaving = sqlite3ExprAnd(pParse->db, pSubq->pHaving, pNew);
121598 }else{
121599 pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
121601 pSubq = pSubq->pPrior;
121604 return nChng;
121606 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
121609 ** Based on the contents of the AggInfo structure indicated by the first
121610 ** argument, this function checks if the following are true:
121612 ** * the query contains just a single aggregate function,
121613 ** * the aggregate function is either min() or max(), and
121614 ** * the argument to the aggregate function is a column value.
121616 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
121617 ** is returned as appropriate. Also, *ppMinMax is set to point to the
121618 ** list of arguments passed to the aggregate before returning.
121620 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
121621 ** WHERE_ORDERBY_NORMAL is returned.
121623 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
121624 int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
121626 *ppMinMax = 0;
121627 if( pAggInfo->nFunc==1 ){
121628 Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
121629 ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
121631 assert( pExpr->op==TK_AGG_FUNCTION );
121632 if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
121633 const char *zFunc = pExpr->u.zToken;
121634 if( sqlite3StrICmp(zFunc, "min")==0 ){
121635 eRet = WHERE_ORDERBY_MIN;
121636 *ppMinMax = pEList;
121637 }else if( sqlite3StrICmp(zFunc, "max")==0 ){
121638 eRet = WHERE_ORDERBY_MAX;
121639 *ppMinMax = pEList;
121644 assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
121645 return eRet;
121649 ** The select statement passed as the first argument is an aggregate query.
121650 ** The second argument is the associated aggregate-info object. This
121651 ** function tests if the SELECT is of the form:
121653 ** SELECT count(*) FROM <tbl>
121655 ** where table is a database table, not a sub-select or view. If the query
121656 ** does match this pattern, then a pointer to the Table object representing
121657 ** <tbl> is returned. Otherwise, 0 is returned.
121659 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
121660 Table *pTab;
121661 Expr *pExpr;
121663 assert( !p->pGroupBy );
121665 if( p->pWhere || p->pEList->nExpr!=1
121666 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
121668 return 0;
121670 pTab = p->pSrc->a[0].pTab;
121671 pExpr = p->pEList->a[0].pExpr;
121672 assert( pTab && !pTab->pSelect && pExpr );
121674 if( IsVirtual(pTab) ) return 0;
121675 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
121676 if( NEVER(pAggInfo->nFunc==0) ) return 0;
121677 if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
121678 if( pExpr->flags&EP_Distinct ) return 0;
121680 return pTab;
121684 ** If the source-list item passed as an argument was augmented with an
121685 ** INDEXED BY clause, then try to locate the specified index. If there
121686 ** was such a clause and the named index cannot be found, return
121687 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
121688 ** pFrom->pIndex and return SQLITE_OK.
121690 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
121691 if( pFrom->pTab && pFrom->fg.isIndexedBy ){
121692 Table *pTab = pFrom->pTab;
121693 char *zIndexedBy = pFrom->u1.zIndexedBy;
121694 Index *pIdx;
121695 for(pIdx=pTab->pIndex;
121696 pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
121697 pIdx=pIdx->pNext
121699 if( !pIdx ){
121700 sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
121701 pParse->checkSchema = 1;
121702 return SQLITE_ERROR;
121704 pFrom->pIBIndex = pIdx;
121706 return SQLITE_OK;
121709 ** Detect compound SELECT statements that use an ORDER BY clause with
121710 ** an alternative collating sequence.
121712 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
121714 ** These are rewritten as a subquery:
121716 ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
121717 ** ORDER BY ... COLLATE ...
121719 ** This transformation is necessary because the multiSelectOrderBy() routine
121720 ** above that generates the code for a compound SELECT with an ORDER BY clause
121721 ** uses a merge algorithm that requires the same collating sequence on the
121722 ** result columns as on the ORDER BY clause. See ticket
121723 ** http://www.sqlite.org/src/info/6709574d2a
121725 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
121726 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
121727 ** there are COLLATE terms in the ORDER BY.
121729 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
121730 int i;
121731 Select *pNew;
121732 Select *pX;
121733 sqlite3 *db;
121734 struct ExprList_item *a;
121735 SrcList *pNewSrc;
121736 Parse *pParse;
121737 Token dummy;
121739 if( p->pPrior==0 ) return WRC_Continue;
121740 if( p->pOrderBy==0 ) return WRC_Continue;
121741 for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
121742 if( pX==0 ) return WRC_Continue;
121743 a = p->pOrderBy->a;
121744 for(i=p->pOrderBy->nExpr-1; i>=0; i--){
121745 if( a[i].pExpr->flags & EP_Collate ) break;
121747 if( i<0 ) return WRC_Continue;
121749 /* If we reach this point, that means the transformation is required. */
121751 pParse = pWalker->pParse;
121752 db = pParse->db;
121753 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
121754 if( pNew==0 ) return WRC_Abort;
121755 memset(&dummy, 0, sizeof(dummy));
121756 pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
121757 if( pNewSrc==0 ) return WRC_Abort;
121758 *pNew = *p;
121759 p->pSrc = pNewSrc;
121760 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
121761 p->op = TK_SELECT;
121762 p->pWhere = 0;
121763 pNew->pGroupBy = 0;
121764 pNew->pHaving = 0;
121765 pNew->pOrderBy = 0;
121766 p->pPrior = 0;
121767 p->pNext = 0;
121768 p->pWith = 0;
121769 p->selFlags &= ~SF_Compound;
121770 assert( (p->selFlags & SF_Converted)==0 );
121771 p->selFlags |= SF_Converted;
121772 assert( pNew->pPrior!=0 );
121773 pNew->pPrior->pNext = pNew;
121774 pNew->pLimit = 0;
121775 pNew->pOffset = 0;
121776 return WRC_Continue;
121780 ** Check to see if the FROM clause term pFrom has table-valued function
121781 ** arguments. If it does, leave an error message in pParse and return
121782 ** non-zero, since pFrom is not allowed to be a table-valued function.
121784 static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
121785 if( pFrom->fg.isTabFunc ){
121786 sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
121787 return 1;
121789 return 0;
121792 #ifndef SQLITE_OMIT_CTE
121794 ** Argument pWith (which may be NULL) points to a linked list of nested
121795 ** WITH contexts, from inner to outermost. If the table identified by
121796 ** FROM clause element pItem is really a common-table-expression (CTE)
121797 ** then return a pointer to the CTE definition for that table. Otherwise
121798 ** return NULL.
121800 ** If a non-NULL value is returned, set *ppContext to point to the With
121801 ** object that the returned CTE belongs to.
121803 static struct Cte *searchWith(
121804 With *pWith, /* Current innermost WITH clause */
121805 struct SrcList_item *pItem, /* FROM clause element to resolve */
121806 With **ppContext /* OUT: WITH clause return value belongs to */
121808 const char *zName;
121809 if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
121810 With *p;
121811 for(p=pWith; p; p=p->pOuter){
121812 int i;
121813 for(i=0; i<p->nCte; i++){
121814 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
121815 *ppContext = p;
121816 return &p->a[i];
121821 return 0;
121824 /* The code generator maintains a stack of active WITH clauses
121825 ** with the inner-most WITH clause being at the top of the stack.
121827 ** This routine pushes the WITH clause passed as the second argument
121828 ** onto the top of the stack. If argument bFree is true, then this
121829 ** WITH clause will never be popped from the stack. In this case it
121830 ** should be freed along with the Parse object. In other cases, when
121831 ** bFree==0, the With object will be freed along with the SELECT
121832 ** statement with which it is associated.
121834 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
121835 assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
121836 if( pWith ){
121837 assert( pParse->pWith!=pWith );
121838 pWith->pOuter = pParse->pWith;
121839 pParse->pWith = pWith;
121840 if( bFree ) pParse->pWithToFree = pWith;
121845 ** This function checks if argument pFrom refers to a CTE declared by
121846 ** a WITH clause on the stack currently maintained by the parser. And,
121847 ** if currently processing a CTE expression, if it is a recursive
121848 ** reference to the current CTE.
121850 ** If pFrom falls into either of the two categories above, pFrom->pTab
121851 ** and other fields are populated accordingly. The caller should check
121852 ** (pFrom->pTab!=0) to determine whether or not a successful match
121853 ** was found.
121855 ** Whether or not a match is found, SQLITE_OK is returned if no error
121856 ** occurs. If an error does occur, an error message is stored in the
121857 ** parser and some error code other than SQLITE_OK returned.
121859 static int withExpand(
121860 Walker *pWalker,
121861 struct SrcList_item *pFrom
121863 Parse *pParse = pWalker->pParse;
121864 sqlite3 *db = pParse->db;
121865 struct Cte *pCte; /* Matched CTE (or NULL if no match) */
121866 With *pWith; /* WITH clause that pCte belongs to */
121868 assert( pFrom->pTab==0 );
121870 pCte = searchWith(pParse->pWith, pFrom, &pWith);
121871 if( pCte ){
121872 Table *pTab;
121873 ExprList *pEList;
121874 Select *pSel;
121875 Select *pLeft; /* Left-most SELECT statement */
121876 int bMayRecursive; /* True if compound joined by UNION [ALL] */
121877 With *pSavedWith; /* Initial value of pParse->pWith */
121879 /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
121880 ** recursive reference to CTE pCte. Leave an error in pParse and return
121881 ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
121882 ** In this case, proceed. */
121883 if( pCte->zCteErr ){
121884 sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
121885 return SQLITE_ERROR;
121887 if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
121889 assert( pFrom->pTab==0 );
121890 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
121891 if( pTab==0 ) return WRC_Abort;
121892 pTab->nTabRef = 1;
121893 pTab->zName = sqlite3DbStrDup(db, pCte->zName);
121894 pTab->iPKey = -1;
121895 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
121896 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
121897 pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
121898 if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
121899 assert( pFrom->pSelect );
121901 /* Check if this is a recursive CTE. */
121902 pSel = pFrom->pSelect;
121903 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
121904 if( bMayRecursive ){
121905 int i;
121906 SrcList *pSrc = pFrom->pSelect->pSrc;
121907 for(i=0; i<pSrc->nSrc; i++){
121908 struct SrcList_item *pItem = &pSrc->a[i];
121909 if( pItem->zDatabase==0
121910 && pItem->zName!=0
121911 && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
121913 pItem->pTab = pTab;
121914 pItem->fg.isRecursive = 1;
121915 pTab->nTabRef++;
121916 pSel->selFlags |= SF_Recursive;
121921 /* Only one recursive reference is permitted. */
121922 if( pTab->nTabRef>2 ){
121923 sqlite3ErrorMsg(
121924 pParse, "multiple references to recursive table: %s", pCte->zName
121926 return SQLITE_ERROR;
121928 assert( pTab->nTabRef==1 ||
121929 ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
121931 pCte->zCteErr = "circular reference: %s";
121932 pSavedWith = pParse->pWith;
121933 pParse->pWith = pWith;
121934 if( bMayRecursive ){
121935 Select *pPrior = pSel->pPrior;
121936 assert( pPrior->pWith==0 );
121937 pPrior->pWith = pSel->pWith;
121938 sqlite3WalkSelect(pWalker, pPrior);
121939 pPrior->pWith = 0;
121940 }else{
121941 sqlite3WalkSelect(pWalker, pSel);
121943 pParse->pWith = pWith;
121945 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
121946 pEList = pLeft->pEList;
121947 if( pCte->pCols ){
121948 if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
121949 sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
121950 pCte->zName, pEList->nExpr, pCte->pCols->nExpr
121952 pParse->pWith = pSavedWith;
121953 return SQLITE_ERROR;
121955 pEList = pCte->pCols;
121958 sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
121959 if( bMayRecursive ){
121960 if( pSel->selFlags & SF_Recursive ){
121961 pCte->zCteErr = "multiple recursive references: %s";
121962 }else{
121963 pCte->zCteErr = "recursive reference in a subquery: %s";
121965 sqlite3WalkSelect(pWalker, pSel);
121967 pCte->zCteErr = 0;
121968 pParse->pWith = pSavedWith;
121971 return SQLITE_OK;
121973 #endif
121975 #ifndef SQLITE_OMIT_CTE
121977 ** If the SELECT passed as the second argument has an associated WITH
121978 ** clause, pop it from the stack stored as part of the Parse object.
121980 ** This function is used as the xSelectCallback2() callback by
121981 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
121982 ** names and other FROM clause elements.
121984 static void selectPopWith(Walker *pWalker, Select *p){
121985 Parse *pParse = pWalker->pParse;
121986 if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
121987 With *pWith = findRightmost(p)->pWith;
121988 if( pWith!=0 ){
121989 assert( pParse->pWith==pWith );
121990 pParse->pWith = pWith->pOuter;
121994 #else
121995 #define selectPopWith 0
121996 #endif
121999 ** This routine is a Walker callback for "expanding" a SELECT statement.
122000 ** "Expanding" means to do the following:
122002 ** (1) Make sure VDBE cursor numbers have been assigned to every
122003 ** element of the FROM clause.
122005 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
122006 ** defines FROM clause. When views appear in the FROM clause,
122007 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
122008 ** that implements the view. A copy is made of the view's SELECT
122009 ** statement so that we can freely modify or delete that statement
122010 ** without worrying about messing up the persistent representation
122011 ** of the view.
122013 ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
122014 ** on joins and the ON and USING clause of joins.
122016 ** (4) Scan the list of columns in the result set (pEList) looking
122017 ** for instances of the "*" operator or the TABLE.* operator.
122018 ** If found, expand each "*" to be every column in every table
122019 ** and TABLE.* to be every column in TABLE.
122022 static int selectExpander(Walker *pWalker, Select *p){
122023 Parse *pParse = pWalker->pParse;
122024 int i, j, k;
122025 SrcList *pTabList;
122026 ExprList *pEList;
122027 struct SrcList_item *pFrom;
122028 sqlite3 *db = pParse->db;
122029 Expr *pE, *pRight, *pExpr;
122030 u16 selFlags = p->selFlags;
122032 p->selFlags |= SF_Expanded;
122033 if( db->mallocFailed ){
122034 return WRC_Abort;
122036 if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
122037 return WRC_Prune;
122039 pTabList = p->pSrc;
122040 pEList = p->pEList;
122041 if( OK_IF_ALWAYS_TRUE(p->pWith) ){
122042 sqlite3WithPush(pParse, p->pWith, 0);
122045 /* Make sure cursor numbers have been assigned to all entries in
122046 ** the FROM clause of the SELECT statement.
122048 sqlite3SrcListAssignCursors(pParse, pTabList);
122050 /* Look up every table named in the FROM clause of the select. If
122051 ** an entry of the FROM clause is a subquery instead of a table or view,
122052 ** then create a transient table structure to describe the subquery.
122054 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
122055 Table *pTab;
122056 assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
122057 if( pFrom->fg.isRecursive ) continue;
122058 assert( pFrom->pTab==0 );
122059 #ifndef SQLITE_OMIT_CTE
122060 if( withExpand(pWalker, pFrom) ) return WRC_Abort;
122061 if( pFrom->pTab ) {} else
122062 #endif
122063 if( pFrom->zName==0 ){
122064 #ifndef SQLITE_OMIT_SUBQUERY
122065 Select *pSel = pFrom->pSelect;
122066 /* A sub-query in the FROM clause of a SELECT */
122067 assert( pSel!=0 );
122068 assert( pFrom->pTab==0 );
122069 if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
122070 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
122071 if( pTab==0 ) return WRC_Abort;
122072 pTab->nTabRef = 1;
122073 if( pFrom->zAlias ){
122074 pTab->zName = sqlite3DbStrDup(db, pFrom->zAlias);
122075 }else{
122076 pTab->zName = sqlite3MPrintf(db, "subquery_%p", (void*)pTab);
122078 while( pSel->pPrior ){ pSel = pSel->pPrior; }
122079 sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
122080 pTab->iPKey = -1;
122081 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
122082 pTab->tabFlags |= TF_Ephemeral;
122083 #endif
122084 }else{
122085 /* An ordinary table or view name in the FROM clause */
122086 assert( pFrom->pTab==0 );
122087 pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
122088 if( pTab==0 ) return WRC_Abort;
122089 if( pTab->nTabRef>=0xffff ){
122090 sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
122091 pTab->zName);
122092 pFrom->pTab = 0;
122093 return WRC_Abort;
122095 pTab->nTabRef++;
122096 if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
122097 return WRC_Abort;
122099 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
122100 if( IsVirtual(pTab) || pTab->pSelect ){
122101 i16 nCol;
122102 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
122103 assert( pFrom->pSelect==0 );
122104 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
122105 sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
122106 nCol = pTab->nCol;
122107 pTab->nCol = -1;
122108 sqlite3WalkSelect(pWalker, pFrom->pSelect);
122109 pTab->nCol = nCol;
122111 #endif
122114 /* Locate the index named by the INDEXED BY clause, if any. */
122115 if( sqlite3IndexedByLookup(pParse, pFrom) ){
122116 return WRC_Abort;
122120 /* Process NATURAL keywords, and ON and USING clauses of joins.
122122 if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
122123 return WRC_Abort;
122126 /* For every "*" that occurs in the column list, insert the names of
122127 ** all columns in all tables. And for every TABLE.* insert the names
122128 ** of all columns in TABLE. The parser inserted a special expression
122129 ** with the TK_ASTERISK operator for each "*" that it found in the column
122130 ** list. The following code just has to locate the TK_ASTERISK
122131 ** expressions and expand each one to the list of all columns in
122132 ** all tables.
122134 ** The first loop just checks to see if there are any "*" operators
122135 ** that need expanding.
122137 for(k=0; k<pEList->nExpr; k++){
122138 pE = pEList->a[k].pExpr;
122139 if( pE->op==TK_ASTERISK ) break;
122140 assert( pE->op!=TK_DOT || pE->pRight!=0 );
122141 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
122142 if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
122144 if( k<pEList->nExpr ){
122146 ** If we get here it means the result set contains one or more "*"
122147 ** operators that need to be expanded. Loop through each expression
122148 ** in the result set and expand them one by one.
122150 struct ExprList_item *a = pEList->a;
122151 ExprList *pNew = 0;
122152 int flags = pParse->db->flags;
122153 int longNames = (flags & SQLITE_FullColNames)!=0
122154 && (flags & SQLITE_ShortColNames)==0;
122156 for(k=0; k<pEList->nExpr; k++){
122157 pE = a[k].pExpr;
122158 pRight = pE->pRight;
122159 assert( pE->op!=TK_DOT || pRight!=0 );
122160 if( pE->op!=TK_ASTERISK
122161 && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
122163 /* This particular expression does not need to be expanded.
122165 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
122166 if( pNew ){
122167 pNew->a[pNew->nExpr-1].zName = a[k].zName;
122168 pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
122169 a[k].zName = 0;
122170 a[k].zSpan = 0;
122172 a[k].pExpr = 0;
122173 }else{
122174 /* This expression is a "*" or a "TABLE.*" and needs to be
122175 ** expanded. */
122176 int tableSeen = 0; /* Set to 1 when TABLE matches */
122177 char *zTName = 0; /* text of name of TABLE */
122178 if( pE->op==TK_DOT ){
122179 assert( pE->pLeft!=0 );
122180 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
122181 zTName = pE->pLeft->u.zToken;
122183 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
122184 Table *pTab = pFrom->pTab;
122185 Select *pSub = pFrom->pSelect;
122186 char *zTabName = pFrom->zAlias;
122187 const char *zSchemaName = 0;
122188 int iDb;
122189 if( zTabName==0 ){
122190 zTabName = pTab->zName;
122192 if( db->mallocFailed ) break;
122193 if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
122194 pSub = 0;
122195 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
122196 continue;
122198 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122199 zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
122201 for(j=0; j<pTab->nCol; j++){
122202 char *zName = pTab->aCol[j].zName;
122203 char *zColname; /* The computed column name */
122204 char *zToFree; /* Malloced string that needs to be freed */
122205 Token sColname; /* Computed column name as a token */
122207 assert( zName );
122208 if( zTName && pSub
122209 && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
122211 continue;
122214 /* If a column is marked as 'hidden', omit it from the expanded
122215 ** result-set list unless the SELECT has the SF_IncludeHidden
122216 ** bit set.
122218 if( (p->selFlags & SF_IncludeHidden)==0
122219 && IsHiddenColumn(&pTab->aCol[j])
122221 continue;
122223 tableSeen = 1;
122225 if( i>0 && zTName==0 ){
122226 if( (pFrom->fg.jointype & JT_NATURAL)!=0
122227 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
122229 /* In a NATURAL join, omit the join columns from the
122230 ** table to the right of the join */
122231 continue;
122233 if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
122234 /* In a join with a USING clause, omit columns in the
122235 ** using clause from the table on the right. */
122236 continue;
122239 pRight = sqlite3Expr(db, TK_ID, zName);
122240 zColname = zName;
122241 zToFree = 0;
122242 if( longNames || pTabList->nSrc>1 ){
122243 Expr *pLeft;
122244 pLeft = sqlite3Expr(db, TK_ID, zTabName);
122245 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
122246 if( zSchemaName ){
122247 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
122248 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
122250 if( longNames ){
122251 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
122252 zToFree = zColname;
122254 }else{
122255 pExpr = pRight;
122257 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
122258 sqlite3TokenInit(&sColname, zColname);
122259 sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
122260 if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
122261 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
122262 if( pSub ){
122263 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
122264 testcase( pX->zSpan==0 );
122265 }else{
122266 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
122267 zSchemaName, zTabName, zColname);
122268 testcase( pX->zSpan==0 );
122270 pX->bSpanIsTab = 1;
122272 sqlite3DbFree(db, zToFree);
122275 if( !tableSeen ){
122276 if( zTName ){
122277 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
122278 }else{
122279 sqlite3ErrorMsg(pParse, "no tables specified");
122284 sqlite3ExprListDelete(db, pEList);
122285 p->pEList = pNew;
122287 if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
122288 sqlite3ErrorMsg(pParse, "too many columns in result set");
122289 return WRC_Abort;
122291 return WRC_Continue;
122295 ** No-op routine for the parse-tree walker.
122297 ** When this routine is the Walker.xExprCallback then expression trees
122298 ** are walked without any actions being taken at each node. Presumably,
122299 ** when this routine is used for Walker.xExprCallback then
122300 ** Walker.xSelectCallback is set to do something useful for every
122301 ** subquery in the parser tree.
122303 SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
122304 UNUSED_PARAMETER2(NotUsed, NotUsed2);
122305 return WRC_Continue;
122309 ** No-op routine for the parse-tree walker for SELECT statements.
122310 ** subquery in the parser tree.
122312 SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
122313 UNUSED_PARAMETER2(NotUsed, NotUsed2);
122314 return WRC_Continue;
122317 #if SQLITE_DEBUG
122319 ** Always assert. This xSelectCallback2 implementation proves that the
122320 ** xSelectCallback2 is never invoked.
122322 SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
122323 UNUSED_PARAMETER2(NotUsed, NotUsed2);
122324 assert( 0 );
122326 #endif
122328 ** This routine "expands" a SELECT statement and all of its subqueries.
122329 ** For additional information on what it means to "expand" a SELECT
122330 ** statement, see the comment on the selectExpand worker callback above.
122332 ** Expanding a SELECT statement is the first step in processing a
122333 ** SELECT statement. The SELECT statement must be expanded before
122334 ** name resolution is performed.
122336 ** If anything goes wrong, an error message is written into pParse.
122337 ** The calling function can detect the problem by looking at pParse->nErr
122338 ** and/or pParse->db->mallocFailed.
122340 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
122341 Walker w;
122342 w.xExprCallback = sqlite3ExprWalkNoop;
122343 w.pParse = pParse;
122344 if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
122345 w.xSelectCallback = convertCompoundSelectToSubquery;
122346 w.xSelectCallback2 = 0;
122347 sqlite3WalkSelect(&w, pSelect);
122349 w.xSelectCallback = selectExpander;
122350 w.xSelectCallback2 = selectPopWith;
122351 sqlite3WalkSelect(&w, pSelect);
122355 #ifndef SQLITE_OMIT_SUBQUERY
122357 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
122358 ** interface.
122360 ** For each FROM-clause subquery, add Column.zType and Column.zColl
122361 ** information to the Table structure that represents the result set
122362 ** of that subquery.
122364 ** The Table structure that represents the result set was constructed
122365 ** by selectExpander() but the type and collation information was omitted
122366 ** at that point because identifiers had not yet been resolved. This
122367 ** routine is called after identifier resolution.
122369 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
122370 Parse *pParse;
122371 int i;
122372 SrcList *pTabList;
122373 struct SrcList_item *pFrom;
122375 assert( p->selFlags & SF_Resolved );
122376 assert( (p->selFlags & SF_HasTypeInfo)==0 );
122377 p->selFlags |= SF_HasTypeInfo;
122378 pParse = pWalker->pParse;
122379 pTabList = p->pSrc;
122380 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
122381 Table *pTab = pFrom->pTab;
122382 assert( pTab!=0 );
122383 if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
122384 /* A sub-query in the FROM clause of a SELECT */
122385 Select *pSel = pFrom->pSelect;
122386 if( pSel ){
122387 while( pSel->pPrior ) pSel = pSel->pPrior;
122388 sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
122393 #endif
122397 ** This routine adds datatype and collating sequence information to
122398 ** the Table structures of all FROM-clause subqueries in a
122399 ** SELECT statement.
122401 ** Use this routine after name resolution.
122403 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
122404 #ifndef SQLITE_OMIT_SUBQUERY
122405 Walker w;
122406 w.xSelectCallback = sqlite3SelectWalkNoop;
122407 w.xSelectCallback2 = selectAddSubqueryTypeInfo;
122408 w.xExprCallback = sqlite3ExprWalkNoop;
122409 w.pParse = pParse;
122410 sqlite3WalkSelect(&w, pSelect);
122411 #endif
122416 ** This routine sets up a SELECT statement for processing. The
122417 ** following is accomplished:
122419 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
122420 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
122421 ** * ON and USING clauses are shifted into WHERE statements
122422 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
122423 ** * Identifiers in expression are matched to tables.
122425 ** This routine acts recursively on all subqueries within the SELECT.
122427 SQLITE_PRIVATE void sqlite3SelectPrep(
122428 Parse *pParse, /* The parser context */
122429 Select *p, /* The SELECT statement being coded. */
122430 NameContext *pOuterNC /* Name context for container */
122432 assert( p!=0 || pParse->db->mallocFailed );
122433 if( pParse->db->mallocFailed ) return;
122434 if( p->selFlags & SF_HasTypeInfo ) return;
122435 sqlite3SelectExpand(pParse, p);
122436 if( pParse->nErr || pParse->db->mallocFailed ) return;
122437 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
122438 if( pParse->nErr || pParse->db->mallocFailed ) return;
122439 sqlite3SelectAddTypeInfo(pParse, p);
122443 ** Reset the aggregate accumulator.
122445 ** The aggregate accumulator is a set of memory cells that hold
122446 ** intermediate results while calculating an aggregate. This
122447 ** routine generates code that stores NULLs in all of those memory
122448 ** cells.
122450 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
122451 Vdbe *v = pParse->pVdbe;
122452 int i;
122453 struct AggInfo_func *pFunc;
122454 int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
122455 if( nReg==0 ) return;
122456 #ifdef SQLITE_DEBUG
122457 /* Verify that all AggInfo registers are within the range specified by
122458 ** AggInfo.mnReg..AggInfo.mxReg */
122459 assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
122460 for(i=0; i<pAggInfo->nColumn; i++){
122461 assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
122462 && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
122464 for(i=0; i<pAggInfo->nFunc; i++){
122465 assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
122466 && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
122468 #endif
122469 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
122470 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
122471 if( pFunc->iDistinct>=0 ){
122472 Expr *pE = pFunc->pExpr;
122473 assert( !ExprHasProperty(pE, EP_xIsSelect) );
122474 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
122475 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
122476 "argument");
122477 pFunc->iDistinct = -1;
122478 }else{
122479 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
122480 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
122481 (char*)pKeyInfo, P4_KEYINFO);
122488 ** Invoke the OP_AggFinalize opcode for every aggregate function
122489 ** in the AggInfo structure.
122491 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
122492 Vdbe *v = pParse->pVdbe;
122493 int i;
122494 struct AggInfo_func *pF;
122495 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
122496 ExprList *pList = pF->pExpr->x.pList;
122497 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
122498 sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
122499 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
122504 ** Update the accumulator memory cells for an aggregate based on
122505 ** the current cursor position.
122507 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
122508 Vdbe *v = pParse->pVdbe;
122509 int i;
122510 int regHit = 0;
122511 int addrHitTest = 0;
122512 struct AggInfo_func *pF;
122513 struct AggInfo_col *pC;
122515 pAggInfo->directMode = 1;
122516 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
122517 int nArg;
122518 int addrNext = 0;
122519 int regAgg;
122520 ExprList *pList = pF->pExpr->x.pList;
122521 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
122522 if( pList ){
122523 nArg = pList->nExpr;
122524 regAgg = sqlite3GetTempRange(pParse, nArg);
122525 sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
122526 }else{
122527 nArg = 0;
122528 regAgg = 0;
122530 if( pF->iDistinct>=0 ){
122531 addrNext = sqlite3VdbeMakeLabel(v);
122532 testcase( nArg==0 ); /* Error condition */
122533 testcase( nArg>1 ); /* Also an error */
122534 codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
122536 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
122537 CollSeq *pColl = 0;
122538 struct ExprList_item *pItem;
122539 int j;
122540 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
122541 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
122542 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
122544 if( !pColl ){
122545 pColl = pParse->db->pDfltColl;
122547 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
122548 sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
122550 sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem);
122551 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
122552 sqlite3VdbeChangeP5(v, (u8)nArg);
122553 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
122554 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
122555 if( addrNext ){
122556 sqlite3VdbeResolveLabel(v, addrNext);
122557 sqlite3ExprCacheClear(pParse);
122561 /* Before populating the accumulator registers, clear the column cache.
122562 ** Otherwise, if any of the required column values are already present
122563 ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
122564 ** to pC->iMem. But by the time the value is used, the original register
122565 ** may have been used, invalidating the underlying buffer holding the
122566 ** text or blob value. See ticket [883034dcb5].
122568 ** Another solution would be to change the OP_SCopy used to copy cached
122569 ** values to an OP_Copy.
122571 if( regHit ){
122572 addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
122574 sqlite3ExprCacheClear(pParse);
122575 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
122576 sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
122578 pAggInfo->directMode = 0;
122579 sqlite3ExprCacheClear(pParse);
122580 if( addrHitTest ){
122581 sqlite3VdbeJumpHere(v, addrHitTest);
122586 ** Add a single OP_Explain instruction to the VDBE to explain a simple
122587 ** count(*) query ("SELECT count(*) FROM pTab").
122589 #ifndef SQLITE_OMIT_EXPLAIN
122590 static void explainSimpleCount(
122591 Parse *pParse, /* Parse context */
122592 Table *pTab, /* Table being queried */
122593 Index *pIdx /* Index used to optimize scan, or NULL */
122595 if( pParse->explain==2 ){
122596 int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
122597 char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
122598 pTab->zName,
122599 bCover ? " USING COVERING INDEX " : "",
122600 bCover ? pIdx->zName : ""
122602 sqlite3VdbeAddOp4(
122603 pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
122607 #else
122608 # define explainSimpleCount(a,b,c)
122609 #endif
122612 ** Context object for havingToWhereExprCb().
122614 struct HavingToWhereCtx {
122615 Expr **ppWhere;
122616 ExprList *pGroupBy;
122620 ** sqlite3WalkExpr() callback used by havingToWhere().
122622 ** If the node passed to the callback is a TK_AND node, return
122623 ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
122625 ** Otherwise, return WRC_Prune. In this case, also check if the
122626 ** sub-expression matches the criteria for being moved to the WHERE
122627 ** clause. If so, add it to the WHERE clause and replace the sub-expression
122628 ** within the HAVING expression with a constant "1".
122630 static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
122631 if( pExpr->op!=TK_AND ){
122632 struct HavingToWhereCtx *p = pWalker->u.pHavingCtx;
122633 if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, p->pGroupBy) ){
122634 sqlite3 *db = pWalker->pParse->db;
122635 Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
122636 if( pNew ){
122637 Expr *pWhere = *(p->ppWhere);
122638 SWAP(Expr, *pNew, *pExpr);
122639 pNew = sqlite3ExprAnd(db, pWhere, pNew);
122640 *(p->ppWhere) = pNew;
122643 return WRC_Prune;
122645 return WRC_Continue;
122649 ** Transfer eligible terms from the HAVING clause of a query, which is
122650 ** processed after grouping, to the WHERE clause, which is processed before
122651 ** grouping. For example, the query:
122653 ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
122655 ** can be rewritten as:
122657 ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
122659 ** A term of the HAVING expression is eligible for transfer if it consists
122660 ** entirely of constants and expressions that are also GROUP BY terms that
122661 ** use the "BINARY" collation sequence.
122663 static void havingToWhere(
122664 Parse *pParse,
122665 ExprList *pGroupBy,
122666 Expr *pHaving,
122667 Expr **ppWhere
122669 struct HavingToWhereCtx sCtx;
122670 Walker sWalker;
122672 sCtx.ppWhere = ppWhere;
122673 sCtx.pGroupBy = pGroupBy;
122675 memset(&sWalker, 0, sizeof(sWalker));
122676 sWalker.pParse = pParse;
122677 sWalker.xExprCallback = havingToWhereExprCb;
122678 sWalker.u.pHavingCtx = &sCtx;
122679 sqlite3WalkExpr(&sWalker, pHaving);
122683 ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
122684 ** If it is, then return the SrcList_item for the prior view. If it is not,
122685 ** then return 0.
122687 static struct SrcList_item *isSelfJoinView(
122688 SrcList *pTabList, /* Search for self-joins in this FROM clause */
122689 struct SrcList_item *pThis /* Search for prior reference to this subquery */
122691 struct SrcList_item *pItem;
122692 for(pItem = pTabList->a; pItem<pThis; pItem++){
122693 if( pItem->pSelect==0 ) continue;
122694 if( pItem->fg.viaCoroutine ) continue;
122695 if( pItem->zName==0 ) continue;
122696 if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
122697 if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
122698 if( sqlite3ExprCompare(0,
122699 pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1)
122701 /* The view was modified by some other optimization such as
122702 ** pushDownWhereTerms() */
122703 continue;
122705 return pItem;
122707 return 0;
122710 #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
122712 ** Attempt to transform a query of the form
122714 ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
122716 ** Into this:
122718 ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
122720 ** The transformation only works if all of the following are true:
122722 ** * The subquery is a UNION ALL of two or more terms
122723 ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
122724 ** * The outer query is a simple count(*)
122726 ** Return TRUE if the optimization is undertaken.
122728 static int countOfViewOptimization(Parse *pParse, Select *p){
122729 Select *pSub, *pPrior;
122730 Expr *pExpr;
122731 Expr *pCount;
122732 sqlite3 *db;
122733 if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
122734 if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
122735 pExpr = p->pEList->a[0].pExpr;
122736 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
122737 if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
122738 if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
122739 if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
122740 pSub = p->pSrc->a[0].pSelect;
122741 if( pSub==0 ) return 0; /* The FROM is a subquery */
122742 if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
122744 if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
122745 if( pSub->pWhere ) return 0; /* No WHERE clause */
122746 if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
122747 pSub = pSub->pPrior; /* Repeat over compound */
122748 }while( pSub );
122750 /* If we reach this point then it is OK to perform the transformation */
122752 db = pParse->db;
122753 pCount = pExpr;
122754 pExpr = 0;
122755 pSub = p->pSrc->a[0].pSelect;
122756 p->pSrc->a[0].pSelect = 0;
122757 sqlite3SrcListDelete(db, p->pSrc);
122758 p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
122759 while( pSub ){
122760 Expr *pTerm;
122761 pPrior = pSub->pPrior;
122762 pSub->pPrior = 0;
122763 pSub->pNext = 0;
122764 pSub->selFlags |= SF_Aggregate;
122765 pSub->selFlags &= ~SF_Compound;
122766 pSub->nSelectRow = 0;
122767 sqlite3ExprListDelete(db, pSub->pEList);
122768 pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
122769 pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
122770 pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
122771 sqlite3PExprAddSelect(pParse, pTerm, pSub);
122772 if( pExpr==0 ){
122773 pExpr = pTerm;
122774 }else{
122775 pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
122777 pSub = pPrior;
122779 p->pEList->a[0].pExpr = pExpr;
122780 p->selFlags &= ~SF_Aggregate;
122782 #if SELECTTRACE_ENABLED
122783 if( sqlite3SelectTrace & 0x400 ){
122784 SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
122785 sqlite3TreeViewSelect(0, p, 0);
122787 #endif
122788 return 1;
122790 #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
122793 ** Generate code for the SELECT statement given in the p argument.
122795 ** The results are returned according to the SelectDest structure.
122796 ** See comments in sqliteInt.h for further information.
122798 ** This routine returns the number of errors. If any errors are
122799 ** encountered, then an appropriate error message is left in
122800 ** pParse->zErrMsg.
122802 ** This routine does NOT free the Select structure passed in. The
122803 ** calling function needs to do that.
122805 SQLITE_PRIVATE int sqlite3Select(
122806 Parse *pParse, /* The parser context */
122807 Select *p, /* The SELECT statement being coded. */
122808 SelectDest *pDest /* What to do with the query results */
122810 int i, j; /* Loop counters */
122811 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
122812 Vdbe *v; /* The virtual machine under construction */
122813 int isAgg; /* True for select lists like "count(*)" */
122814 ExprList *pEList = 0; /* List of columns to extract. */
122815 SrcList *pTabList; /* List of tables to select from */
122816 Expr *pWhere; /* The WHERE clause. May be NULL */
122817 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
122818 Expr *pHaving; /* The HAVING clause. May be NULL */
122819 int rc = 1; /* Value to return from this function */
122820 DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
122821 SortCtx sSort; /* Info on how to code the ORDER BY clause */
122822 AggInfo sAggInfo; /* Information used by aggregate queries */
122823 int iEnd; /* Address of the end of the query */
122824 sqlite3 *db; /* The database connection */
122826 #ifndef SQLITE_OMIT_EXPLAIN
122827 int iRestoreSelectId = pParse->iSelectId;
122828 pParse->iSelectId = pParse->iNextSelectId++;
122829 #endif
122831 db = pParse->db;
122832 if( p==0 || db->mallocFailed || pParse->nErr ){
122833 return 1;
122835 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
122836 memset(&sAggInfo, 0, sizeof(sAggInfo));
122837 #if SELECTTRACE_ENABLED
122838 pParse->nSelectIndent++;
122839 SELECTTRACE(1,pParse,p, ("begin processing:\n"));
122840 if( sqlite3SelectTrace & 0x100 ){
122841 sqlite3TreeViewSelect(0, p, 0);
122843 #endif
122845 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
122846 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
122847 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
122848 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
122849 if( IgnorableOrderby(pDest) ){
122850 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
122851 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
122852 pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
122853 pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
122854 /* If ORDER BY makes no difference in the output then neither does
122855 ** DISTINCT so it can be removed too. */
122856 sqlite3ExprListDelete(db, p->pOrderBy);
122857 p->pOrderBy = 0;
122858 p->selFlags &= ~SF_Distinct;
122860 sqlite3SelectPrep(pParse, p, 0);
122861 memset(&sSort, 0, sizeof(sSort));
122862 sSort.pOrderBy = p->pOrderBy;
122863 pTabList = p->pSrc;
122864 if( pParse->nErr || db->mallocFailed ){
122865 goto select_end;
122867 assert( p->pEList!=0 );
122868 isAgg = (p->selFlags & SF_Aggregate)!=0;
122869 #if SELECTTRACE_ENABLED
122870 if( sqlite3SelectTrace & 0x100 ){
122871 SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
122872 sqlite3TreeViewSelect(0, p, 0);
122874 #endif
122876 /* Get a pointer the VDBE under construction, allocating a new VDBE if one
122877 ** does not already exist */
122878 v = sqlite3GetVdbe(pParse);
122879 if( v==0 ) goto select_end;
122880 if( pDest->eDest==SRT_Output ){
122881 generateColumnNames(pParse, p);
122884 /* Try to flatten subqueries in the FROM clause up into the main query
122886 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
122887 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
122888 struct SrcList_item *pItem = &pTabList->a[i];
122889 Select *pSub = pItem->pSelect;
122890 Table *pTab = pItem->pTab;
122891 if( pSub==0 ) continue;
122893 /* Catch mismatch in the declared columns of a view and the number of
122894 ** columns in the SELECT on the RHS */
122895 if( pTab->nCol!=pSub->pEList->nExpr ){
122896 sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
122897 pTab->nCol, pTab->zName, pSub->pEList->nExpr);
122898 goto select_end;
122901 /* Do not try to flatten an aggregate subquery.
122903 ** Flattening an aggregate subquery is only possible if the outer query
122904 ** is not a join. But if the outer query is not a join, then the subquery
122905 ** will be implemented as a co-routine and there is no advantage to
122906 ** flattening in that case.
122908 if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
122909 assert( pSub->pGroupBy==0 );
122911 /* If the subquery contains an ORDER BY clause and if
122912 ** it will be implemented as a co-routine, then do not flatten. This
122913 ** restriction allows SQL constructs like this:
122915 ** SELECT expensive_function(x)
122916 ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
122918 ** The expensive_function() is only computed on the 10 rows that
122919 ** are output, rather than every row of the table.
122921 if( pSub->pOrderBy!=0
122922 && i==0
122923 && (pTabList->nSrc==1
122924 || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
122926 continue;
122929 if( flattenSubquery(pParse, p, i, isAgg) ){
122930 /* This subquery can be absorbed into its parent. */
122931 i = -1;
122933 pTabList = p->pSrc;
122934 if( db->mallocFailed ) goto select_end;
122935 if( !IgnorableOrderby(pDest) ){
122936 sSort.pOrderBy = p->pOrderBy;
122939 #endif
122941 #ifndef SQLITE_OMIT_COMPOUND_SELECT
122942 /* Handle compound SELECT statements using the separate multiSelect()
122943 ** procedure.
122945 if( p->pPrior ){
122946 rc = multiSelect(pParse, p, pDest);
122947 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
122948 #if SELECTTRACE_ENABLED
122949 SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
122950 pParse->nSelectIndent--;
122951 #endif
122952 return rc;
122954 #endif
122956 /* For each term in the FROM clause, do two things:
122957 ** (1) Authorized unreferenced tables
122958 ** (2) Generate code for all sub-queries
122960 for(i=0; i<pTabList->nSrc; i++){
122961 struct SrcList_item *pItem = &pTabList->a[i];
122962 SelectDest dest;
122963 Select *pSub;
122964 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
122965 const char *zSavedAuthContext;
122966 #endif
122968 /* Issue SQLITE_READ authorizations with a fake column name for any
122969 ** tables that are referenced but from which no values are extracted.
122970 ** Examples of where these kinds of null SQLITE_READ authorizations
122971 ** would occur:
122973 ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
122974 ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
122976 ** The fake column name is an empty string. It is possible for a table to
122977 ** have a column named by the empty string, in which case there is no way to
122978 ** distinguish between an unreferenced table and an actual reference to the
122979 ** "" column. The original design was for the fake column name to be a NULL,
122980 ** which would be unambiguous. But legacy authorization callbacks might
122981 ** assume the column name is non-NULL and segfault. The use of an empty
122982 ** string for the fake column name seems safer.
122984 if( pItem->colUsed==0 ){
122985 sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
122988 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
122989 /* Generate code for all sub-queries in the FROM clause
122991 pSub = pItem->pSelect;
122992 if( pSub==0 ) continue;
122994 /* Sometimes the code for a subquery will be generated more than
122995 ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
122996 ** for example. In that case, do not regenerate the code to manifest
122997 ** a view or the co-routine to implement a view. The first instance
122998 ** is sufficient, though the subroutine to manifest the view does need
122999 ** to be invoked again. */
123000 if( pItem->addrFillSub ){
123001 if( pItem->fg.viaCoroutine==0 ){
123002 /* The subroutine that manifests the view might be a one-time routine,
123003 ** or it might need to be rerun on each iteration because it
123004 ** encodes a correlated subquery. */
123005 testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once );
123006 sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
123008 continue;
123011 /* Increment Parse.nHeight by the height of the largest expression
123012 ** tree referred to by this, the parent select. The child select
123013 ** may contain expression trees of at most
123014 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
123015 ** more conservative than necessary, but much easier than enforcing
123016 ** an exact limit.
123018 pParse->nHeight += sqlite3SelectExprHeight(p);
123020 /* Make copies of constant WHERE-clause terms in the outer query down
123021 ** inside the subquery. This can help the subquery to run more efficiently.
123023 if( (pItem->fg.jointype & JT_OUTER)==0
123024 && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor)
123026 #if SELECTTRACE_ENABLED
123027 if( sqlite3SelectTrace & 0x100 ){
123028 SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
123029 sqlite3TreeViewSelect(0, p, 0);
123031 #endif
123034 zSavedAuthContext = pParse->zAuthContext;
123035 pParse->zAuthContext = pItem->zName;
123037 /* Generate code to implement the subquery
123039 ** The subquery is implemented as a co-routine if the subquery is
123040 ** guaranteed to be the outer loop (so that it does not need to be
123041 ** computed more than once)
123043 ** TODO: Are there other reasons beside (1) to use a co-routine
123044 ** implementation?
123046 if( i==0
123047 && (pTabList->nSrc==1
123048 || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
123050 /* Implement a co-routine that will return a single row of the result
123051 ** set on each invocation.
123053 int addrTop = sqlite3VdbeCurrentAddr(v)+1;
123055 pItem->regReturn = ++pParse->nMem;
123056 sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
123057 VdbeComment((v, "%s", pItem->pTab->zName));
123058 pItem->addrFillSub = addrTop;
123059 sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
123060 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
123061 sqlite3Select(pParse, pSub, &dest);
123062 pItem->pTab->nRowLogEst = pSub->nSelectRow;
123063 pItem->fg.viaCoroutine = 1;
123064 pItem->regResult = dest.iSdst;
123065 sqlite3VdbeEndCoroutine(v, pItem->regReturn);
123066 sqlite3VdbeJumpHere(v, addrTop-1);
123067 sqlite3ClearTempRegCache(pParse);
123068 }else{
123069 /* Generate a subroutine that will fill an ephemeral table with
123070 ** the content of this subquery. pItem->addrFillSub will point
123071 ** to the address of the generated subroutine. pItem->regReturn
123072 ** is a register allocated to hold the subroutine return address
123074 int topAddr;
123075 int onceAddr = 0;
123076 int retAddr;
123077 struct SrcList_item *pPrior;
123079 assert( pItem->addrFillSub==0 );
123080 pItem->regReturn = ++pParse->nMem;
123081 topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
123082 pItem->addrFillSub = topAddr+1;
123083 if( pItem->fg.isCorrelated==0 ){
123084 /* If the subquery is not correlated and if we are not inside of
123085 ** a trigger, then we only need to compute the value of the subquery
123086 ** once. */
123087 onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
123088 VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
123089 }else{
123090 VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
123092 pPrior = isSelfJoinView(pTabList, pItem);
123093 if( pPrior ){
123094 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
123095 explainSetInteger(pItem->iSelectId, pPrior->iSelectId);
123096 assert( pPrior->pSelect!=0 );
123097 pSub->nSelectRow = pPrior->pSelect->nSelectRow;
123098 }else{
123099 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
123100 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
123101 sqlite3Select(pParse, pSub, &dest);
123103 pItem->pTab->nRowLogEst = pSub->nSelectRow;
123104 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
123105 retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
123106 VdbeComment((v, "end %s", pItem->pTab->zName));
123107 sqlite3VdbeChangeP1(v, topAddr, retAddr);
123108 sqlite3ClearTempRegCache(pParse);
123110 if( db->mallocFailed ) goto select_end;
123111 pParse->nHeight -= sqlite3SelectExprHeight(p);
123112 pParse->zAuthContext = zSavedAuthContext;
123113 #endif
123116 /* Various elements of the SELECT copied into local variables for
123117 ** convenience */
123118 pEList = p->pEList;
123119 pWhere = p->pWhere;
123120 pGroupBy = p->pGroupBy;
123121 pHaving = p->pHaving;
123122 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
123124 #if SELECTTRACE_ENABLED
123125 if( sqlite3SelectTrace & 0x400 ){
123126 SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
123127 sqlite3TreeViewSelect(0, p, 0);
123129 #endif
123131 #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
123132 if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
123133 && countOfViewOptimization(pParse, p)
123135 if( db->mallocFailed ) goto select_end;
123136 pEList = p->pEList;
123137 pTabList = p->pSrc;
123139 #endif
123141 /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
123142 ** if the select-list is the same as the ORDER BY list, then this query
123143 ** can be rewritten as a GROUP BY. In other words, this:
123145 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
123147 ** is transformed to:
123149 ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
123151 ** The second form is preferred as a single index (or temp-table) may be
123152 ** used for both the ORDER BY and DISTINCT processing. As originally
123153 ** written the query must use a temp-table for at least one of the ORDER
123154 ** BY and DISTINCT, and an index or separate temp-table for the other.
123156 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
123157 && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
123159 p->selFlags &= ~SF_Distinct;
123160 pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
123161 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
123162 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
123163 ** original setting of the SF_Distinct flag, not the current setting */
123164 assert( sDistinct.isTnct );
123166 #if SELECTTRACE_ENABLED
123167 if( sqlite3SelectTrace & 0x400 ){
123168 SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
123169 sqlite3TreeViewSelect(0, p, 0);
123171 #endif
123174 /* If there is an ORDER BY clause, then create an ephemeral index to
123175 ** do the sorting. But this sorting ephemeral index might end up
123176 ** being unused if the data can be extracted in pre-sorted order.
123177 ** If that is the case, then the OP_OpenEphemeral instruction will be
123178 ** changed to an OP_Noop once we figure out that the sorting index is
123179 ** not needed. The sSort.addrSortIndex variable is used to facilitate
123180 ** that change.
123182 if( sSort.pOrderBy ){
123183 KeyInfo *pKeyInfo;
123184 pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
123185 sSort.iECursor = pParse->nTab++;
123186 sSort.addrSortIndex =
123187 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
123188 sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
123189 (char*)pKeyInfo, P4_KEYINFO
123191 }else{
123192 sSort.addrSortIndex = -1;
123195 /* If the output is destined for a temporary table, open that table.
123197 if( pDest->eDest==SRT_EphemTab ){
123198 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
123201 /* Set the limiter.
123203 iEnd = sqlite3VdbeMakeLabel(v);
123204 if( (p->selFlags & SF_FixedLimit)==0 ){
123205 p->nSelectRow = 320; /* 4 billion rows */
123207 computeLimitRegisters(pParse, p, iEnd);
123208 if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
123209 sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
123210 sSort.sortFlags |= SORTFLAG_UseSorter;
123213 /* Open an ephemeral index to use for the distinct set.
123215 if( p->selFlags & SF_Distinct ){
123216 sDistinct.tabTnct = pParse->nTab++;
123217 sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
123218 sDistinct.tabTnct, 0, 0,
123219 (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
123220 P4_KEYINFO);
123221 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
123222 sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
123223 }else{
123224 sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
123227 if( !isAgg && pGroupBy==0 ){
123228 /* No aggregate functions and no GROUP BY clause */
123229 u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
123230 assert( WHERE_USE_LIMIT==SF_FixedLimit );
123231 wctrlFlags |= p->selFlags & SF_FixedLimit;
123233 /* Begin the database scan. */
123234 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
123235 p->pEList, wctrlFlags, p->nSelectRow);
123236 if( pWInfo==0 ) goto select_end;
123237 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
123238 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
123240 if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
123241 sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
123243 if( sSort.pOrderBy ){
123244 sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
123245 sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
123246 if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
123247 sSort.pOrderBy = 0;
123251 /* If sorting index that was created by a prior OP_OpenEphemeral
123252 ** instruction ended up not being needed, then change the OP_OpenEphemeral
123253 ** into an OP_Noop.
123255 if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
123256 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
123259 /* Use the standard inner loop. */
123260 assert( p->pEList==pEList );
123261 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
123262 sqlite3WhereContinueLabel(pWInfo),
123263 sqlite3WhereBreakLabel(pWInfo));
123265 /* End the database scan loop.
123267 sqlite3WhereEnd(pWInfo);
123268 }else{
123269 /* This case when there exist aggregate functions or a GROUP BY clause
123270 ** or both */
123271 NameContext sNC; /* Name context for processing aggregate information */
123272 int iAMem; /* First Mem address for storing current GROUP BY */
123273 int iBMem; /* First Mem address for previous GROUP BY */
123274 int iUseFlag; /* Mem address holding flag indicating that at least
123275 ** one row of the input to the aggregator has been
123276 ** processed */
123277 int iAbortFlag; /* Mem address which causes query abort if positive */
123278 int groupBySort; /* Rows come from source in GROUP BY order */
123279 int addrEnd; /* End of processing for this SELECT */
123280 int sortPTab = 0; /* Pseudotable used to decode sorting results */
123281 int sortOut = 0; /* Output register from the sorter */
123282 int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
123284 /* Remove any and all aliases between the result set and the
123285 ** GROUP BY clause.
123287 if( pGroupBy ){
123288 int k; /* Loop counter */
123289 struct ExprList_item *pItem; /* For looping over expression in a list */
123291 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
123292 pItem->u.x.iAlias = 0;
123294 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
123295 pItem->u.x.iAlias = 0;
123297 assert( 66==sqlite3LogEst(100) );
123298 if( p->nSelectRow>66 ) p->nSelectRow = 66;
123299 }else{
123300 assert( 0==sqlite3LogEst(1) );
123301 p->nSelectRow = 0;
123304 /* If there is both a GROUP BY and an ORDER BY clause and they are
123305 ** identical, then it may be possible to disable the ORDER BY clause
123306 ** on the grounds that the GROUP BY will cause elements to come out
123307 ** in the correct order. It also may not - the GROUP BY might use a
123308 ** database index that causes rows to be grouped together as required
123309 ** but not actually sorted. Either way, record the fact that the
123310 ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
123311 ** variable. */
123312 if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
123313 orderByGrp = 1;
123316 /* Create a label to jump to when we want to abort the query */
123317 addrEnd = sqlite3VdbeMakeLabel(v);
123319 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
123320 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
123321 ** SELECT statement.
123323 memset(&sNC, 0, sizeof(sNC));
123324 sNC.pParse = pParse;
123325 sNC.pSrcList = pTabList;
123326 sNC.pAggInfo = &sAggInfo;
123327 sAggInfo.mnReg = pParse->nMem+1;
123328 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
123329 sAggInfo.pGroupBy = pGroupBy;
123330 sqlite3ExprAnalyzeAggList(&sNC, pEList);
123331 sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
123332 if( pHaving ){
123333 if( pGroupBy ){
123334 assert( pWhere==p->pWhere );
123335 havingToWhere(pParse, pGroupBy, pHaving, &p->pWhere);
123336 pWhere = p->pWhere;
123338 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
123340 sAggInfo.nAccumulator = sAggInfo.nColumn;
123341 for(i=0; i<sAggInfo.nFunc; i++){
123342 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
123343 sNC.ncFlags |= NC_InAggFunc;
123344 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
123345 sNC.ncFlags &= ~NC_InAggFunc;
123347 sAggInfo.mxReg = pParse->nMem;
123348 if( db->mallocFailed ) goto select_end;
123350 /* Processing for aggregates with GROUP BY is very different and
123351 ** much more complex than aggregates without a GROUP BY.
123353 if( pGroupBy ){
123354 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
123355 int addr1; /* A-vs-B comparision jump */
123356 int addrOutputRow; /* Start of subroutine that outputs a result row */
123357 int regOutputRow; /* Return address register for output subroutine */
123358 int addrSetAbort; /* Set the abort flag and return */
123359 int addrTopOfLoop; /* Top of the input loop */
123360 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
123361 int addrReset; /* Subroutine for resetting the accumulator */
123362 int regReset; /* Return address register for reset subroutine */
123364 /* If there is a GROUP BY clause we might need a sorting index to
123365 ** implement it. Allocate that sorting index now. If it turns out
123366 ** that we do not need it after all, the OP_SorterOpen instruction
123367 ** will be converted into a Noop.
123369 sAggInfo.sortingIdx = pParse->nTab++;
123370 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
123371 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
123372 sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
123373 0, (char*)pKeyInfo, P4_KEYINFO);
123375 /* Initialize memory locations used by GROUP BY aggregate processing
123377 iUseFlag = ++pParse->nMem;
123378 iAbortFlag = ++pParse->nMem;
123379 regOutputRow = ++pParse->nMem;
123380 addrOutputRow = sqlite3VdbeMakeLabel(v);
123381 regReset = ++pParse->nMem;
123382 addrReset = sqlite3VdbeMakeLabel(v);
123383 iAMem = pParse->nMem + 1;
123384 pParse->nMem += pGroupBy->nExpr;
123385 iBMem = pParse->nMem + 1;
123386 pParse->nMem += pGroupBy->nExpr;
123387 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
123388 VdbeComment((v, "clear abort flag"));
123389 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
123390 VdbeComment((v, "indicate accumulator empty"));
123391 sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
123393 /* Begin a loop that will extract all source rows in GROUP BY order.
123394 ** This might involve two separate loops with an OP_Sort in between, or
123395 ** it might be a single loop that uses an index to extract information
123396 ** in the right order to begin with.
123398 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
123399 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
123400 WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
123402 if( pWInfo==0 ) goto select_end;
123403 if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
123404 /* The optimizer is able to deliver rows in group by order so
123405 ** we do not have to sort. The OP_OpenEphemeral table will be
123406 ** cancelled later because we still need to use the pKeyInfo
123408 groupBySort = 0;
123409 }else{
123410 /* Rows are coming out in undetermined order. We have to push
123411 ** each row into a sorting index, terminate the first loop,
123412 ** then loop over the sorting index in order to get the output
123413 ** in sorted order
123415 int regBase;
123416 int regRecord;
123417 int nCol;
123418 int nGroupBy;
123420 explainTempTable(pParse,
123421 (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
123422 "DISTINCT" : "GROUP BY");
123424 groupBySort = 1;
123425 nGroupBy = pGroupBy->nExpr;
123426 nCol = nGroupBy;
123427 j = nGroupBy;
123428 for(i=0; i<sAggInfo.nColumn; i++){
123429 if( sAggInfo.aCol[i].iSorterColumn>=j ){
123430 nCol++;
123434 regBase = sqlite3GetTempRange(pParse, nCol);
123435 sqlite3ExprCacheClear(pParse);
123436 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
123437 j = nGroupBy;
123438 for(i=0; i<sAggInfo.nColumn; i++){
123439 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
123440 if( pCol->iSorterColumn>=j ){
123441 int r1 = j + regBase;
123442 sqlite3ExprCodeGetColumnToReg(pParse,
123443 pCol->pTab, pCol->iColumn, pCol->iTable, r1);
123447 regRecord = sqlite3GetTempReg(pParse);
123448 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
123449 sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
123450 sqlite3ReleaseTempReg(pParse, regRecord);
123451 sqlite3ReleaseTempRange(pParse, regBase, nCol);
123452 sqlite3WhereEnd(pWInfo);
123453 sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
123454 sortOut = sqlite3GetTempReg(pParse);
123455 sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
123456 sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
123457 VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
123458 sAggInfo.useSortingIdx = 1;
123459 sqlite3ExprCacheClear(pParse);
123463 /* If the index or temporary table used by the GROUP BY sort
123464 ** will naturally deliver rows in the order required by the ORDER BY
123465 ** clause, cancel the ephemeral table open coded earlier.
123467 ** This is an optimization - the correct answer should result regardless.
123468 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
123469 ** disable this optimization for testing purposes. */
123470 if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
123471 && (groupBySort || sqlite3WhereIsSorted(pWInfo))
123473 sSort.pOrderBy = 0;
123474 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
123477 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
123478 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
123479 ** Then compare the current GROUP BY terms against the GROUP BY terms
123480 ** from the previous row currently stored in a0, a1, a2...
123482 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
123483 sqlite3ExprCacheClear(pParse);
123484 if( groupBySort ){
123485 sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
123486 sortOut, sortPTab);
123488 for(j=0; j<pGroupBy->nExpr; j++){
123489 if( groupBySort ){
123490 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
123491 }else{
123492 sAggInfo.directMode = 1;
123493 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
123496 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
123497 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
123498 addr1 = sqlite3VdbeCurrentAddr(v);
123499 sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
123501 /* Generate code that runs whenever the GROUP BY changes.
123502 ** Changes in the GROUP BY are detected by the previous code
123503 ** block. If there were no changes, this block is skipped.
123505 ** This code copies current group by terms in b0,b1,b2,...
123506 ** over to a0,a1,a2. It then calls the output subroutine
123507 ** and resets the aggregate accumulator registers in preparation
123508 ** for the next GROUP BY batch.
123510 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
123511 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
123512 VdbeComment((v, "output one row"));
123513 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
123514 VdbeComment((v, "check abort flag"));
123515 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
123516 VdbeComment((v, "reset accumulator"));
123518 /* Update the aggregate accumulators based on the content of
123519 ** the current row
123521 sqlite3VdbeJumpHere(v, addr1);
123522 updateAccumulator(pParse, &sAggInfo);
123523 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
123524 VdbeComment((v, "indicate data in accumulator"));
123526 /* End of the loop
123528 if( groupBySort ){
123529 sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
123530 VdbeCoverage(v);
123531 }else{
123532 sqlite3WhereEnd(pWInfo);
123533 sqlite3VdbeChangeToNoop(v, addrSortingIdx);
123536 /* Output the final row of result
123538 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
123539 VdbeComment((v, "output final row"));
123541 /* Jump over the subroutines
123543 sqlite3VdbeGoto(v, addrEnd);
123545 /* Generate a subroutine that outputs a single row of the result
123546 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
123547 ** is less than or equal to zero, the subroutine is a no-op. If
123548 ** the processing calls for the query to abort, this subroutine
123549 ** increments the iAbortFlag memory location before returning in
123550 ** order to signal the caller to abort.
123552 addrSetAbort = sqlite3VdbeCurrentAddr(v);
123553 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
123554 VdbeComment((v, "set abort flag"));
123555 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
123556 sqlite3VdbeResolveLabel(v, addrOutputRow);
123557 addrOutputRow = sqlite3VdbeCurrentAddr(v);
123558 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
123559 VdbeCoverage(v);
123560 VdbeComment((v, "Groupby result generator entry point"));
123561 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
123562 finalizeAggFunctions(pParse, &sAggInfo);
123563 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
123564 selectInnerLoop(pParse, p, -1, &sSort,
123565 &sDistinct, pDest,
123566 addrOutputRow+1, addrSetAbort);
123567 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
123568 VdbeComment((v, "end groupby result generator"));
123570 /* Generate a subroutine that will reset the group-by accumulator
123572 sqlite3VdbeResolveLabel(v, addrReset);
123573 resetAccumulator(pParse, &sAggInfo);
123574 sqlite3VdbeAddOp1(v, OP_Return, regReset);
123576 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
123577 else {
123578 ExprList *pDel = 0;
123579 #ifndef SQLITE_OMIT_BTREECOUNT
123580 Table *pTab;
123581 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
123582 /* If isSimpleCount() returns a pointer to a Table structure, then
123583 ** the SQL statement is of the form:
123585 ** SELECT count(*) FROM <tbl>
123587 ** where the Table structure returned represents table <tbl>.
123589 ** This statement is so common that it is optimized specially. The
123590 ** OP_Count instruction is executed either on the intkey table that
123591 ** contains the data for table <tbl> or on one of its indexes. It
123592 ** is better to execute the op on an index, as indexes are almost
123593 ** always spread across less pages than their corresponding tables.
123595 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
123596 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
123597 Index *pIdx; /* Iterator variable */
123598 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
123599 Index *pBest = 0; /* Best index found so far */
123600 int iRoot = pTab->tnum; /* Root page of scanned b-tree */
123602 sqlite3CodeVerifySchema(pParse, iDb);
123603 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
123605 /* Search for the index that has the lowest scan cost.
123607 ** (2011-04-15) Do not do a full scan of an unordered index.
123609 ** (2013-10-03) Do not count the entries in a partial index.
123611 ** In practice the KeyInfo structure will not be used. It is only
123612 ** passed to keep OP_OpenRead happy.
123614 if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
123615 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
123616 if( pIdx->bUnordered==0
123617 && pIdx->szIdxRow<pTab->szTabRow
123618 && pIdx->pPartIdxWhere==0
123619 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
123621 pBest = pIdx;
123624 if( pBest ){
123625 iRoot = pBest->tnum;
123626 pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
123629 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
123630 sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
123631 if( pKeyInfo ){
123632 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
123634 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
123635 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
123636 explainSimpleCount(pParse, pTab, pBest);
123637 }else
123638 #endif /* SQLITE_OMIT_BTREECOUNT */
123640 /* Check if the query is of one of the following forms:
123642 ** SELECT min(x) FROM ...
123643 ** SELECT max(x) FROM ...
123645 ** If it is, then ask the code in where.c to attempt to sort results
123646 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
123647 ** If where.c is able to produce results sorted in this order, then
123648 ** add vdbe code to break out of the processing loop after the
123649 ** first iteration (since the first iteration of the loop is
123650 ** guaranteed to operate on the row with the minimum or maximum
123651 ** value of x, the only row required).
123653 ** A special flag must be passed to sqlite3WhereBegin() to slightly
123654 ** modify behavior as follows:
123656 ** + If the query is a "SELECT min(x)", then the loop coded by
123657 ** where.c should not iterate over any values with a NULL value
123658 ** for x.
123660 ** + The optimizer code in where.c (the thing that decides which
123661 ** index or indices to use) should place a different priority on
123662 ** satisfying the 'ORDER BY' clause than it does in other cases.
123663 ** Refer to code and comments in where.c for details.
123665 ExprList *pMinMax = 0;
123666 u8 flag = WHERE_ORDERBY_NORMAL;
123668 assert( p->pGroupBy==0 );
123669 assert( flag==0 );
123670 if( p->pHaving==0 ){
123671 flag = minMaxQuery(&sAggInfo, &pMinMax);
123673 assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
123675 if( flag ){
123676 pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
123677 pDel = pMinMax;
123678 assert( db->mallocFailed || pMinMax!=0 );
123679 if( !db->mallocFailed ){
123680 pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
123681 pMinMax->a[0].pExpr->op = TK_COLUMN;
123685 /* This case runs if the aggregate has no GROUP BY clause. The
123686 ** processing is much simpler since there is only a single row
123687 ** of output.
123689 resetAccumulator(pParse, &sAggInfo);
123690 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax, 0,flag,0);
123691 if( pWInfo==0 ){
123692 sqlite3ExprListDelete(db, pDel);
123693 goto select_end;
123695 updateAccumulator(pParse, &sAggInfo);
123696 assert( pMinMax==0 || pMinMax->nExpr==1 );
123697 if( sqlite3WhereIsOrdered(pWInfo)>0 ){
123698 sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
123699 VdbeComment((v, "%s() by index",
123700 (flag==WHERE_ORDERBY_MIN?"min":"max")));
123702 sqlite3WhereEnd(pWInfo);
123703 finalizeAggFunctions(pParse, &sAggInfo);
123706 sSort.pOrderBy = 0;
123707 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
123708 selectInnerLoop(pParse, p, -1, 0, 0,
123709 pDest, addrEnd, addrEnd);
123710 sqlite3ExprListDelete(db, pDel);
123712 sqlite3VdbeResolveLabel(v, addrEnd);
123714 } /* endif aggregate query */
123716 if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
123717 explainTempTable(pParse, "DISTINCT");
123720 /* If there is an ORDER BY clause, then we need to sort the results
123721 ** and send them to the callback one by one.
123723 if( sSort.pOrderBy ){
123724 explainTempTable(pParse,
123725 sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
123726 generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
123729 /* Jump here to skip this query
123731 sqlite3VdbeResolveLabel(v, iEnd);
123733 /* The SELECT has been coded. If there is an error in the Parse structure,
123734 ** set the return code to 1. Otherwise 0. */
123735 rc = (pParse->nErr>0);
123737 /* Control jumps to here if an error is encountered above, or upon
123738 ** successful coding of the SELECT.
123740 select_end:
123741 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
123743 sqlite3DbFree(db, sAggInfo.aCol);
123744 sqlite3DbFree(db, sAggInfo.aFunc);
123745 #if SELECTTRACE_ENABLED
123746 SELECTTRACE(1,pParse,p,("end processing\n"));
123747 pParse->nSelectIndent--;
123748 #endif
123749 return rc;
123752 /************** End of select.c **********************************************/
123753 /************** Begin file table.c *******************************************/
123755 ** 2001 September 15
123757 ** The author disclaims copyright to this source code. In place of
123758 ** a legal notice, here is a blessing:
123760 ** May you do good and not evil.
123761 ** May you find forgiveness for yourself and forgive others.
123762 ** May you share freely, never taking more than you give.
123764 *************************************************************************
123765 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
123766 ** interface routines. These are just wrappers around the main
123767 ** interface routine of sqlite3_exec().
123769 ** These routines are in a separate files so that they will not be linked
123770 ** if they are not used.
123772 /* #include "sqliteInt.h" */
123774 #ifndef SQLITE_OMIT_GET_TABLE
123777 ** This structure is used to pass data from sqlite3_get_table() through
123778 ** to the callback function is uses to build the result.
123780 typedef struct TabResult {
123781 char **azResult; /* Accumulated output */
123782 char *zErrMsg; /* Error message text, if an error occurs */
123783 u32 nAlloc; /* Slots allocated for azResult[] */
123784 u32 nRow; /* Number of rows in the result */
123785 u32 nColumn; /* Number of columns in the result */
123786 u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
123787 int rc; /* Return code from sqlite3_exec() */
123788 } TabResult;
123791 ** This routine is called once for each row in the result table. Its job
123792 ** is to fill in the TabResult structure appropriately, allocating new
123793 ** memory as necessary.
123795 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
123796 TabResult *p = (TabResult*)pArg; /* Result accumulator */
123797 int need; /* Slots needed in p->azResult[] */
123798 int i; /* Loop counter */
123799 char *z; /* A single column of result */
123801 /* Make sure there is enough space in p->azResult to hold everything
123802 ** we need to remember from this invocation of the callback.
123804 if( p->nRow==0 && argv!=0 ){
123805 need = nCol*2;
123806 }else{
123807 need = nCol;
123809 if( p->nData + need > p->nAlloc ){
123810 char **azNew;
123811 p->nAlloc = p->nAlloc*2 + need;
123812 azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
123813 if( azNew==0 ) goto malloc_failed;
123814 p->azResult = azNew;
123817 /* If this is the first row, then generate an extra row containing
123818 ** the names of all columns.
123820 if( p->nRow==0 ){
123821 p->nColumn = nCol;
123822 for(i=0; i<nCol; i++){
123823 z = sqlite3_mprintf("%s", colv[i]);
123824 if( z==0 ) goto malloc_failed;
123825 p->azResult[p->nData++] = z;
123827 }else if( (int)p->nColumn!=nCol ){
123828 sqlite3_free(p->zErrMsg);
123829 p->zErrMsg = sqlite3_mprintf(
123830 "sqlite3_get_table() called with two or more incompatible queries"
123832 p->rc = SQLITE_ERROR;
123833 return 1;
123836 /* Copy over the row data
123838 if( argv!=0 ){
123839 for(i=0; i<nCol; i++){
123840 if( argv[i]==0 ){
123841 z = 0;
123842 }else{
123843 int n = sqlite3Strlen30(argv[i])+1;
123844 z = sqlite3_malloc64( n );
123845 if( z==0 ) goto malloc_failed;
123846 memcpy(z, argv[i], n);
123848 p->azResult[p->nData++] = z;
123850 p->nRow++;
123852 return 0;
123854 malloc_failed:
123855 p->rc = SQLITE_NOMEM_BKPT;
123856 return 1;
123860 ** Query the database. But instead of invoking a callback for each row,
123861 ** malloc() for space to hold the result and return the entire results
123862 ** at the conclusion of the call.
123864 ** The result that is written to ***pazResult is held in memory obtained
123865 ** from malloc(). But the caller cannot free this memory directly.
123866 ** Instead, the entire table should be passed to sqlite3_free_table() when
123867 ** the calling procedure is finished using it.
123869 SQLITE_API int sqlite3_get_table(
123870 sqlite3 *db, /* The database on which the SQL executes */
123871 const char *zSql, /* The SQL to be executed */
123872 char ***pazResult, /* Write the result table here */
123873 int *pnRow, /* Write the number of rows in the result here */
123874 int *pnColumn, /* Write the number of columns of result here */
123875 char **pzErrMsg /* Write error messages here */
123877 int rc;
123878 TabResult res;
123880 #ifdef SQLITE_ENABLE_API_ARMOR
123881 if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
123882 #endif
123883 *pazResult = 0;
123884 if( pnColumn ) *pnColumn = 0;
123885 if( pnRow ) *pnRow = 0;
123886 if( pzErrMsg ) *pzErrMsg = 0;
123887 res.zErrMsg = 0;
123888 res.nRow = 0;
123889 res.nColumn = 0;
123890 res.nData = 1;
123891 res.nAlloc = 20;
123892 res.rc = SQLITE_OK;
123893 res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
123894 if( res.azResult==0 ){
123895 db->errCode = SQLITE_NOMEM;
123896 return SQLITE_NOMEM_BKPT;
123898 res.azResult[0] = 0;
123899 rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
123900 assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
123901 res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
123902 if( (rc&0xff)==SQLITE_ABORT ){
123903 sqlite3_free_table(&res.azResult[1]);
123904 if( res.zErrMsg ){
123905 if( pzErrMsg ){
123906 sqlite3_free(*pzErrMsg);
123907 *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
123909 sqlite3_free(res.zErrMsg);
123911 db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
123912 return res.rc;
123914 sqlite3_free(res.zErrMsg);
123915 if( rc!=SQLITE_OK ){
123916 sqlite3_free_table(&res.azResult[1]);
123917 return rc;
123919 if( res.nAlloc>res.nData ){
123920 char **azNew;
123921 azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
123922 if( azNew==0 ){
123923 sqlite3_free_table(&res.azResult[1]);
123924 db->errCode = SQLITE_NOMEM;
123925 return SQLITE_NOMEM_BKPT;
123927 res.azResult = azNew;
123929 *pazResult = &res.azResult[1];
123930 if( pnColumn ) *pnColumn = res.nColumn;
123931 if( pnRow ) *pnRow = res.nRow;
123932 return rc;
123936 ** This routine frees the space the sqlite3_get_table() malloced.
123938 SQLITE_API void sqlite3_free_table(
123939 char **azResult /* Result returned from sqlite3_get_table() */
123941 if( azResult ){
123942 int i, n;
123943 azResult--;
123944 assert( azResult!=0 );
123945 n = SQLITE_PTR_TO_INT(azResult[0]);
123946 for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
123947 sqlite3_free(azResult);
123951 #endif /* SQLITE_OMIT_GET_TABLE */
123953 /************** End of table.c ***********************************************/
123954 /************** Begin file trigger.c *****************************************/
123957 ** The author disclaims copyright to this source code. In place of
123958 ** a legal notice, here is a blessing:
123960 ** May you do good and not evil.
123961 ** May you find forgiveness for yourself and forgive others.
123962 ** May you share freely, never taking more than you give.
123964 *************************************************************************
123965 ** This file contains the implementation for TRIGGERs
123967 /* #include "sqliteInt.h" */
123969 #ifndef SQLITE_OMIT_TRIGGER
123971 ** Delete a linked list of TriggerStep structures.
123973 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
123974 while( pTriggerStep ){
123975 TriggerStep * pTmp = pTriggerStep;
123976 pTriggerStep = pTriggerStep->pNext;
123978 sqlite3ExprDelete(db, pTmp->pWhere);
123979 sqlite3ExprListDelete(db, pTmp->pExprList);
123980 sqlite3SelectDelete(db, pTmp->pSelect);
123981 sqlite3IdListDelete(db, pTmp->pIdList);
123983 sqlite3DbFree(db, pTmp);
123988 ** Given table pTab, return a list of all the triggers attached to
123989 ** the table. The list is connected by Trigger.pNext pointers.
123991 ** All of the triggers on pTab that are in the same database as pTab
123992 ** are already attached to pTab->pTrigger. But there might be additional
123993 ** triggers on pTab in the TEMP schema. This routine prepends all
123994 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
123995 ** and returns the combined list.
123997 ** To state it another way: This routine returns a list of all triggers
123998 ** that fire off of pTab. The list will include any TEMP triggers on
123999 ** pTab as well as the triggers lised in pTab->pTrigger.
124001 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
124002 Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
124003 Trigger *pList = 0; /* List of triggers to return */
124005 if( pParse->disableTriggers ){
124006 return 0;
124009 if( pTmpSchema!=pTab->pSchema ){
124010 HashElem *p;
124011 assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
124012 for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
124013 Trigger *pTrig = (Trigger *)sqliteHashData(p);
124014 if( pTrig->pTabSchema==pTab->pSchema
124015 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
124017 pTrig->pNext = (pList ? pList : pTab->pTrigger);
124018 pList = pTrig;
124023 return (pList ? pList : pTab->pTrigger);
124027 ** This is called by the parser when it sees a CREATE TRIGGER statement
124028 ** up to the point of the BEGIN before the trigger actions. A Trigger
124029 ** structure is generated based on the information available and stored
124030 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
124031 ** sqlite3FinishTrigger() function is called to complete the trigger
124032 ** construction process.
124034 SQLITE_PRIVATE void sqlite3BeginTrigger(
124035 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
124036 Token *pName1, /* The name of the trigger */
124037 Token *pName2, /* The name of the trigger */
124038 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
124039 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
124040 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
124041 SrcList *pTableName,/* The name of the table/view the trigger applies to */
124042 Expr *pWhen, /* WHEN clause */
124043 int isTemp, /* True if the TEMPORARY keyword is present */
124044 int noErr /* Suppress errors if the trigger already exists */
124046 Trigger *pTrigger = 0; /* The new trigger */
124047 Table *pTab; /* Table that the trigger fires off of */
124048 char *zName = 0; /* Name of the trigger */
124049 sqlite3 *db = pParse->db; /* The database connection */
124050 int iDb; /* The database to store the trigger in */
124051 Token *pName; /* The unqualified db name */
124052 DbFixer sFix; /* State vector for the DB fixer */
124054 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
124055 assert( pName2!=0 );
124056 assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
124057 assert( op>0 && op<0xff );
124058 if( isTemp ){
124059 /* If TEMP was specified, then the trigger name may not be qualified. */
124060 if( pName2->n>0 ){
124061 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
124062 goto trigger_cleanup;
124064 iDb = 1;
124065 pName = pName1;
124066 }else{
124067 /* Figure out the db that the trigger will be created in */
124068 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
124069 if( iDb<0 ){
124070 goto trigger_cleanup;
124073 if( !pTableName || db->mallocFailed ){
124074 goto trigger_cleanup;
124077 /* A long-standing parser bug is that this syntax was allowed:
124079 ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
124080 ** ^^^^^^^^
124082 ** To maintain backwards compatibility, ignore the database
124083 ** name on pTableName if we are reparsing out of SQLITE_MASTER.
124085 if( db->init.busy && iDb!=1 ){
124086 sqlite3DbFree(db, pTableName->a[0].zDatabase);
124087 pTableName->a[0].zDatabase = 0;
124090 /* If the trigger name was unqualified, and the table is a temp table,
124091 ** then set iDb to 1 to create the trigger in the temporary database.
124092 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
124093 ** exist, the error is caught by the block below.
124095 pTab = sqlite3SrcListLookup(pParse, pTableName);
124096 if( db->init.busy==0 && pName2->n==0 && pTab
124097 && pTab->pSchema==db->aDb[1].pSchema ){
124098 iDb = 1;
124101 /* Ensure the table name matches database name and that the table exists */
124102 if( db->mallocFailed ) goto trigger_cleanup;
124103 assert( pTableName->nSrc==1 );
124104 sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
124105 if( sqlite3FixSrcList(&sFix, pTableName) ){
124106 goto trigger_cleanup;
124108 pTab = sqlite3SrcListLookup(pParse, pTableName);
124109 if( !pTab ){
124110 /* The table does not exist. */
124111 if( db->init.iDb==1 ){
124112 /* Ticket #3810.
124113 ** Normally, whenever a table is dropped, all associated triggers are
124114 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
124115 ** and the table is dropped by a different database connection, the
124116 ** trigger is not visible to the database connection that does the
124117 ** drop so the trigger cannot be dropped. This results in an
124118 ** "orphaned trigger" - a trigger whose associated table is missing.
124120 db->init.orphanTrigger = 1;
124122 goto trigger_cleanup;
124124 if( IsVirtual(pTab) ){
124125 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
124126 goto trigger_cleanup;
124129 /* Check that the trigger name is not reserved and that no trigger of the
124130 ** specified name exists */
124131 zName = sqlite3NameFromToken(db, pName);
124132 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
124133 goto trigger_cleanup;
124135 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
124136 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
124137 if( !noErr ){
124138 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
124139 }else{
124140 assert( !db->init.busy );
124141 sqlite3CodeVerifySchema(pParse, iDb);
124143 goto trigger_cleanup;
124146 /* Do not create a trigger on a system table */
124147 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
124148 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
124149 goto trigger_cleanup;
124152 /* INSTEAD of triggers are only for views and views only support INSTEAD
124153 ** of triggers.
124155 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
124156 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
124157 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
124158 goto trigger_cleanup;
124160 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
124161 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
124162 " trigger on table: %S", pTableName, 0);
124163 goto trigger_cleanup;
124166 #ifndef SQLITE_OMIT_AUTHORIZATION
124168 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
124169 int code = SQLITE_CREATE_TRIGGER;
124170 const char *zDb = db->aDb[iTabDb].zDbSName;
124171 const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
124172 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
124173 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
124174 goto trigger_cleanup;
124176 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
124177 goto trigger_cleanup;
124180 #endif
124182 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
124183 ** cannot appear on views. So we might as well translate every
124184 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
124185 ** elsewhere.
124187 if (tr_tm == TK_INSTEAD){
124188 tr_tm = TK_BEFORE;
124191 /* Build the Trigger object */
124192 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
124193 if( pTrigger==0 ) goto trigger_cleanup;
124194 pTrigger->zName = zName;
124195 zName = 0;
124196 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
124197 pTrigger->pSchema = db->aDb[iDb].pSchema;
124198 pTrigger->pTabSchema = pTab->pSchema;
124199 pTrigger->op = (u8)op;
124200 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
124201 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
124202 pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
124203 assert( pParse->pNewTrigger==0 );
124204 pParse->pNewTrigger = pTrigger;
124206 trigger_cleanup:
124207 sqlite3DbFree(db, zName);
124208 sqlite3SrcListDelete(db, pTableName);
124209 sqlite3IdListDelete(db, pColumns);
124210 sqlite3ExprDelete(db, pWhen);
124211 if( !pParse->pNewTrigger ){
124212 sqlite3DeleteTrigger(db, pTrigger);
124213 }else{
124214 assert( pParse->pNewTrigger==pTrigger );
124219 ** This routine is called after all of the trigger actions have been parsed
124220 ** in order to complete the process of building the trigger.
124222 SQLITE_PRIVATE void sqlite3FinishTrigger(
124223 Parse *pParse, /* Parser context */
124224 TriggerStep *pStepList, /* The triggered program */
124225 Token *pAll /* Token that describes the complete CREATE TRIGGER */
124227 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
124228 char *zName; /* Name of trigger */
124229 sqlite3 *db = pParse->db; /* The database */
124230 DbFixer sFix; /* Fixer object */
124231 int iDb; /* Database containing the trigger */
124232 Token nameToken; /* Trigger name for error reporting */
124234 pParse->pNewTrigger = 0;
124235 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
124236 zName = pTrig->zName;
124237 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
124238 pTrig->step_list = pStepList;
124239 while( pStepList ){
124240 pStepList->pTrig = pTrig;
124241 pStepList = pStepList->pNext;
124243 sqlite3TokenInit(&nameToken, pTrig->zName);
124244 sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
124245 if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
124246 || sqlite3FixExpr(&sFix, pTrig->pWhen)
124248 goto triggerfinish_cleanup;
124251 /* if we are not initializing,
124252 ** build the sqlite_master entry
124254 if( !db->init.busy ){
124255 Vdbe *v;
124256 char *z;
124258 /* Make an entry in the sqlite_master table */
124259 v = sqlite3GetVdbe(pParse);
124260 if( v==0 ) goto triggerfinish_cleanup;
124261 sqlite3BeginWriteOperation(pParse, 0, iDb);
124262 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
124263 testcase( z==0 );
124264 sqlite3NestedParse(pParse,
124265 "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
124266 db->aDb[iDb].zDbSName, MASTER_NAME, zName,
124267 pTrig->table, z);
124268 sqlite3DbFree(db, z);
124269 sqlite3ChangeCookie(pParse, iDb);
124270 sqlite3VdbeAddParseSchemaOp(v, iDb,
124271 sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
124274 if( db->init.busy ){
124275 Trigger *pLink = pTrig;
124276 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
124277 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
124278 pTrig = sqlite3HashInsert(pHash, zName, pTrig);
124279 if( pTrig ){
124280 sqlite3OomFault(db);
124281 }else if( pLink->pSchema==pLink->pTabSchema ){
124282 Table *pTab;
124283 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
124284 assert( pTab!=0 );
124285 pLink->pNext = pTab->pTrigger;
124286 pTab->pTrigger = pLink;
124290 triggerfinish_cleanup:
124291 sqlite3DeleteTrigger(db, pTrig);
124292 assert( !pParse->pNewTrigger );
124293 sqlite3DeleteTriggerStep(db, pStepList);
124297 ** Turn a SELECT statement (that the pSelect parameter points to) into
124298 ** a trigger step. Return a pointer to a TriggerStep structure.
124300 ** The parser calls this routine when it finds a SELECT statement in
124301 ** body of a TRIGGER.
124303 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
124304 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
124305 if( pTriggerStep==0 ) {
124306 sqlite3SelectDelete(db, pSelect);
124307 return 0;
124309 pTriggerStep->op = TK_SELECT;
124310 pTriggerStep->pSelect = pSelect;
124311 pTriggerStep->orconf = OE_Default;
124312 return pTriggerStep;
124316 ** Allocate space to hold a new trigger step. The allocated space
124317 ** holds both the TriggerStep object and the TriggerStep.target.z string.
124319 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
124321 static TriggerStep *triggerStepAllocate(
124322 sqlite3 *db, /* Database connection */
124323 u8 op, /* Trigger opcode */
124324 Token *pName /* The target name */
124326 TriggerStep *pTriggerStep;
124328 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
124329 if( pTriggerStep ){
124330 char *z = (char*)&pTriggerStep[1];
124331 memcpy(z, pName->z, pName->n);
124332 sqlite3Dequote(z);
124333 pTriggerStep->zTarget = z;
124334 pTriggerStep->op = op;
124336 return pTriggerStep;
124340 ** Build a trigger step out of an INSERT statement. Return a pointer
124341 ** to the new trigger step.
124343 ** The parser calls this routine when it sees an INSERT inside the
124344 ** body of a trigger.
124346 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
124347 sqlite3 *db, /* The database connection */
124348 Token *pTableName, /* Name of the table into which we insert */
124349 IdList *pColumn, /* List of columns in pTableName to insert into */
124350 Select *pSelect, /* A SELECT statement that supplies values */
124351 u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
124353 TriggerStep *pTriggerStep;
124355 assert(pSelect != 0 || db->mallocFailed);
124357 pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
124358 if( pTriggerStep ){
124359 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
124360 pTriggerStep->pIdList = pColumn;
124361 pTriggerStep->orconf = orconf;
124362 }else{
124363 sqlite3IdListDelete(db, pColumn);
124365 sqlite3SelectDelete(db, pSelect);
124367 return pTriggerStep;
124371 ** Construct a trigger step that implements an UPDATE statement and return
124372 ** a pointer to that trigger step. The parser calls this routine when it
124373 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
124375 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
124376 sqlite3 *db, /* The database connection */
124377 Token *pTableName, /* Name of the table to be updated */
124378 ExprList *pEList, /* The SET clause: list of column and new values */
124379 Expr *pWhere, /* The WHERE clause */
124380 u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
124382 TriggerStep *pTriggerStep;
124384 pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
124385 if( pTriggerStep ){
124386 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
124387 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
124388 pTriggerStep->orconf = orconf;
124390 sqlite3ExprListDelete(db, pEList);
124391 sqlite3ExprDelete(db, pWhere);
124392 return pTriggerStep;
124396 ** Construct a trigger step that implements a DELETE statement and return
124397 ** a pointer to that trigger step. The parser calls this routine when it
124398 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
124400 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
124401 sqlite3 *db, /* Database connection */
124402 Token *pTableName, /* The table from which rows are deleted */
124403 Expr *pWhere /* The WHERE clause */
124405 TriggerStep *pTriggerStep;
124407 pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
124408 if( pTriggerStep ){
124409 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
124410 pTriggerStep->orconf = OE_Default;
124412 sqlite3ExprDelete(db, pWhere);
124413 return pTriggerStep;
124417 ** Recursively delete a Trigger structure
124419 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
124420 if( pTrigger==0 ) return;
124421 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
124422 sqlite3DbFree(db, pTrigger->zName);
124423 sqlite3DbFree(db, pTrigger->table);
124424 sqlite3ExprDelete(db, pTrigger->pWhen);
124425 sqlite3IdListDelete(db, pTrigger->pColumns);
124426 sqlite3DbFree(db, pTrigger);
124430 ** This function is called to drop a trigger from the database schema.
124432 ** This may be called directly from the parser and therefore identifies
124433 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
124434 ** same job as this routine except it takes a pointer to the trigger
124435 ** instead of the trigger name.
124437 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
124438 Trigger *pTrigger = 0;
124439 int i;
124440 const char *zDb;
124441 const char *zName;
124442 sqlite3 *db = pParse->db;
124444 if( db->mallocFailed ) goto drop_trigger_cleanup;
124445 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
124446 goto drop_trigger_cleanup;
124449 assert( pName->nSrc==1 );
124450 zDb = pName->a[0].zDatabase;
124451 zName = pName->a[0].zName;
124452 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
124453 for(i=OMIT_TEMPDB; i<db->nDb; i++){
124454 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
124455 if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
124456 assert( sqlite3SchemaMutexHeld(db, j, 0) );
124457 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
124458 if( pTrigger ) break;
124460 if( !pTrigger ){
124461 if( !noErr ){
124462 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
124463 }else{
124464 sqlite3CodeVerifyNamedSchema(pParse, zDb);
124466 pParse->checkSchema = 1;
124467 goto drop_trigger_cleanup;
124469 sqlite3DropTriggerPtr(pParse, pTrigger);
124471 drop_trigger_cleanup:
124472 sqlite3SrcListDelete(db, pName);
124476 ** Return a pointer to the Table structure for the table that a trigger
124477 ** is set on.
124479 static Table *tableOfTrigger(Trigger *pTrigger){
124480 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
124485 ** Drop a trigger given a pointer to that trigger.
124487 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
124488 Table *pTable;
124489 Vdbe *v;
124490 sqlite3 *db = pParse->db;
124491 int iDb;
124493 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
124494 assert( iDb>=0 && iDb<db->nDb );
124495 pTable = tableOfTrigger(pTrigger);
124496 assert( pTable );
124497 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
124498 #ifndef SQLITE_OMIT_AUTHORIZATION
124500 int code = SQLITE_DROP_TRIGGER;
124501 const char *zDb = db->aDb[iDb].zDbSName;
124502 const char *zTab = SCHEMA_TABLE(iDb);
124503 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
124504 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
124505 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
124506 return;
124509 #endif
124511 /* Generate code to destroy the database record of the trigger.
124513 assert( pTable!=0 );
124514 if( (v = sqlite3GetVdbe(pParse))!=0 ){
124515 sqlite3NestedParse(pParse,
124516 "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
124517 db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
124519 sqlite3ChangeCookie(pParse, iDb);
124520 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
124525 ** Remove a trigger from the hash tables of the sqlite* pointer.
124527 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
124528 Trigger *pTrigger;
124529 Hash *pHash;
124531 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
124532 pHash = &(db->aDb[iDb].pSchema->trigHash);
124533 pTrigger = sqlite3HashInsert(pHash, zName, 0);
124534 if( ALWAYS(pTrigger) ){
124535 if( pTrigger->pSchema==pTrigger->pTabSchema ){
124536 Table *pTab = tableOfTrigger(pTrigger);
124537 Trigger **pp;
124538 for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
124539 *pp = (*pp)->pNext;
124541 sqlite3DeleteTrigger(db, pTrigger);
124542 db->mDbFlags |= DBFLAG_SchemaChange;
124547 ** pEList is the SET clause of an UPDATE statement. Each entry
124548 ** in pEList is of the format <id>=<expr>. If any of the entries
124549 ** in pEList have an <id> which matches an identifier in pIdList,
124550 ** then return TRUE. If pIdList==NULL, then it is considered a
124551 ** wildcard that matches anything. Likewise if pEList==NULL then
124552 ** it matches anything so always return true. Return false only
124553 ** if there is no match.
124555 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
124556 int e;
124557 if( pIdList==0 || NEVER(pEList==0) ) return 1;
124558 for(e=0; e<pEList->nExpr; e++){
124559 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
124561 return 0;
124565 ** Return a list of all triggers on table pTab if there exists at least
124566 ** one trigger that must be fired when an operation of type 'op' is
124567 ** performed on the table, and, if that operation is an UPDATE, if at
124568 ** least one of the columns in pChanges is being modified.
124570 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
124571 Parse *pParse, /* Parse context */
124572 Table *pTab, /* The table the contains the triggers */
124573 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
124574 ExprList *pChanges, /* Columns that change in an UPDATE statement */
124575 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
124577 int mask = 0;
124578 Trigger *pList = 0;
124579 Trigger *p;
124581 if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
124582 pList = sqlite3TriggerList(pParse, pTab);
124584 assert( pList==0 || IsVirtual(pTab)==0 );
124585 for(p=pList; p; p=p->pNext){
124586 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
124587 mask |= p->tr_tm;
124590 if( pMask ){
124591 *pMask = mask;
124593 return (mask ? pList : 0);
124597 ** Convert the pStep->zTarget string into a SrcList and return a pointer
124598 ** to that SrcList.
124600 ** This routine adds a specific database name, if needed, to the target when
124601 ** forming the SrcList. This prevents a trigger in one database from
124602 ** referring to a target in another database. An exception is when the
124603 ** trigger is in TEMP in which case it can refer to any other database it
124604 ** wants.
124606 static SrcList *targetSrcList(
124607 Parse *pParse, /* The parsing context */
124608 TriggerStep *pStep /* The trigger containing the target token */
124610 sqlite3 *db = pParse->db;
124611 int iDb; /* Index of the database to use */
124612 SrcList *pSrc; /* SrcList to be returned */
124614 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
124615 if( pSrc ){
124616 assert( pSrc->nSrc>0 );
124617 pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
124618 iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
124619 if( iDb==0 || iDb>=2 ){
124620 const char *zDb;
124621 assert( iDb<db->nDb );
124622 zDb = db->aDb[iDb].zDbSName;
124623 pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
124626 return pSrc;
124630 ** Generate VDBE code for the statements inside the body of a single
124631 ** trigger.
124633 static int codeTriggerProgram(
124634 Parse *pParse, /* The parser context */
124635 TriggerStep *pStepList, /* List of statements inside the trigger body */
124636 int orconf /* Conflict algorithm. (OE_Abort, etc) */
124638 TriggerStep *pStep;
124639 Vdbe *v = pParse->pVdbe;
124640 sqlite3 *db = pParse->db;
124642 assert( pParse->pTriggerTab && pParse->pToplevel );
124643 assert( pStepList );
124644 assert( v!=0 );
124645 for(pStep=pStepList; pStep; pStep=pStep->pNext){
124646 /* Figure out the ON CONFLICT policy that will be used for this step
124647 ** of the trigger program. If the statement that caused this trigger
124648 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
124649 ** the ON CONFLICT policy that was specified as part of the trigger
124650 ** step statement. Example:
124652 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
124653 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
124654 ** END;
124656 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
124657 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
124659 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
124660 assert( pParse->okConstFactor==0 );
124662 switch( pStep->op ){
124663 case TK_UPDATE: {
124664 sqlite3Update(pParse,
124665 targetSrcList(pParse, pStep),
124666 sqlite3ExprListDup(db, pStep->pExprList, 0),
124667 sqlite3ExprDup(db, pStep->pWhere, 0),
124668 pParse->eOrconf
124670 break;
124672 case TK_INSERT: {
124673 sqlite3Insert(pParse,
124674 targetSrcList(pParse, pStep),
124675 sqlite3SelectDup(db, pStep->pSelect, 0),
124676 sqlite3IdListDup(db, pStep->pIdList),
124677 pParse->eOrconf
124679 break;
124681 case TK_DELETE: {
124682 sqlite3DeleteFrom(pParse,
124683 targetSrcList(pParse, pStep),
124684 sqlite3ExprDup(db, pStep->pWhere, 0)
124686 break;
124688 default: assert( pStep->op==TK_SELECT ); {
124689 SelectDest sDest;
124690 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
124691 sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
124692 sqlite3Select(pParse, pSelect, &sDest);
124693 sqlite3SelectDelete(db, pSelect);
124694 break;
124697 if( pStep->op!=TK_SELECT ){
124698 sqlite3VdbeAddOp0(v, OP_ResetCount);
124702 return 0;
124705 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
124707 ** This function is used to add VdbeComment() annotations to a VDBE
124708 ** program. It is not used in production code, only for debugging.
124710 static const char *onErrorText(int onError){
124711 switch( onError ){
124712 case OE_Abort: return "abort";
124713 case OE_Rollback: return "rollback";
124714 case OE_Fail: return "fail";
124715 case OE_Replace: return "replace";
124716 case OE_Ignore: return "ignore";
124717 case OE_Default: return "default";
124719 return "n/a";
124721 #endif
124724 ** Parse context structure pFrom has just been used to create a sub-vdbe
124725 ** (trigger program). If an error has occurred, transfer error information
124726 ** from pFrom to pTo.
124728 static void transferParseError(Parse *pTo, Parse *pFrom){
124729 assert( pFrom->zErrMsg==0 || pFrom->nErr );
124730 assert( pTo->zErrMsg==0 || pTo->nErr );
124731 if( pTo->nErr==0 ){
124732 pTo->zErrMsg = pFrom->zErrMsg;
124733 pTo->nErr = pFrom->nErr;
124734 pTo->rc = pFrom->rc;
124735 }else{
124736 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
124741 ** Create and populate a new TriggerPrg object with a sub-program
124742 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
124744 static TriggerPrg *codeRowTrigger(
124745 Parse *pParse, /* Current parse context */
124746 Trigger *pTrigger, /* Trigger to code */
124747 Table *pTab, /* The table pTrigger is attached to */
124748 int orconf /* ON CONFLICT policy to code trigger program with */
124750 Parse *pTop = sqlite3ParseToplevel(pParse);
124751 sqlite3 *db = pParse->db; /* Database handle */
124752 TriggerPrg *pPrg; /* Value to return */
124753 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
124754 Vdbe *v; /* Temporary VM */
124755 NameContext sNC; /* Name context for sub-vdbe */
124756 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
124757 Parse *pSubParse; /* Parse context for sub-vdbe */
124758 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
124760 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
124761 assert( pTop->pVdbe );
124763 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
124764 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
124765 ** list of the top-level Parse object sooner rather than later. */
124766 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
124767 if( !pPrg ) return 0;
124768 pPrg->pNext = pTop->pTriggerPrg;
124769 pTop->pTriggerPrg = pPrg;
124770 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
124771 if( !pProgram ) return 0;
124772 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
124773 pPrg->pTrigger = pTrigger;
124774 pPrg->orconf = orconf;
124775 pPrg->aColmask[0] = 0xffffffff;
124776 pPrg->aColmask[1] = 0xffffffff;
124778 /* Allocate and populate a new Parse context to use for coding the
124779 ** trigger sub-program. */
124780 pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
124781 if( !pSubParse ) return 0;
124782 memset(&sNC, 0, sizeof(sNC));
124783 sNC.pParse = pSubParse;
124784 pSubParse->db = db;
124785 pSubParse->pTriggerTab = pTab;
124786 pSubParse->pToplevel = pTop;
124787 pSubParse->zAuthContext = pTrigger->zName;
124788 pSubParse->eTriggerOp = pTrigger->op;
124789 pSubParse->nQueryLoop = pParse->nQueryLoop;
124791 v = sqlite3GetVdbe(pSubParse);
124792 if( v ){
124793 VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
124794 pTrigger->zName, onErrorText(orconf),
124795 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
124796 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
124797 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
124798 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
124799 pTab->zName
124801 #ifndef SQLITE_OMIT_TRACE
124802 sqlite3VdbeChangeP4(v, -1,
124803 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
124805 #endif
124807 /* If one was specified, code the WHEN clause. If it evaluates to false
124808 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
124809 ** OP_Halt inserted at the end of the program. */
124810 if( pTrigger->pWhen ){
124811 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
124812 if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
124813 && db->mallocFailed==0
124815 iEndTrigger = sqlite3VdbeMakeLabel(v);
124816 sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
124818 sqlite3ExprDelete(db, pWhen);
124821 /* Code the trigger program into the sub-vdbe. */
124822 codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
124824 /* Insert an OP_Halt at the end of the sub-program. */
124825 if( iEndTrigger ){
124826 sqlite3VdbeResolveLabel(v, iEndTrigger);
124828 sqlite3VdbeAddOp0(v, OP_Halt);
124829 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
124831 transferParseError(pParse, pSubParse);
124832 if( db->mallocFailed==0 ){
124833 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
124835 pProgram->nMem = pSubParse->nMem;
124836 pProgram->nCsr = pSubParse->nTab;
124837 pProgram->token = (void *)pTrigger;
124838 pPrg->aColmask[0] = pSubParse->oldmask;
124839 pPrg->aColmask[1] = pSubParse->newmask;
124840 sqlite3VdbeDelete(v);
124843 assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
124844 assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
124845 sqlite3ParserReset(pSubParse);
124846 sqlite3StackFree(db, pSubParse);
124848 return pPrg;
124852 ** Return a pointer to a TriggerPrg object containing the sub-program for
124853 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
124854 ** TriggerPrg object exists, a new object is allocated and populated before
124855 ** being returned.
124857 static TriggerPrg *getRowTrigger(
124858 Parse *pParse, /* Current parse context */
124859 Trigger *pTrigger, /* Trigger to code */
124860 Table *pTab, /* The table trigger pTrigger is attached to */
124861 int orconf /* ON CONFLICT algorithm. */
124863 Parse *pRoot = sqlite3ParseToplevel(pParse);
124864 TriggerPrg *pPrg;
124866 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
124868 /* It may be that this trigger has already been coded (or is in the
124869 ** process of being coded). If this is the case, then an entry with
124870 ** a matching TriggerPrg.pTrigger field will be present somewhere
124871 ** in the Parse.pTriggerPrg list. Search for such an entry. */
124872 for(pPrg=pRoot->pTriggerPrg;
124873 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
124874 pPrg=pPrg->pNext
124877 /* If an existing TriggerPrg could not be located, create a new one. */
124878 if( !pPrg ){
124879 pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
124882 return pPrg;
124886 ** Generate code for the trigger program associated with trigger p on
124887 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
124888 ** function are the same as those described in the header function for
124889 ** sqlite3CodeRowTrigger()
124891 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
124892 Parse *pParse, /* Parse context */
124893 Trigger *p, /* Trigger to code */
124894 Table *pTab, /* The table to code triggers from */
124895 int reg, /* Reg array containing OLD.* and NEW.* values */
124896 int orconf, /* ON CONFLICT policy */
124897 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
124899 Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
124900 TriggerPrg *pPrg;
124901 pPrg = getRowTrigger(pParse, p, pTab, orconf);
124902 assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
124904 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
124905 ** is a pointer to the sub-vdbe containing the trigger program. */
124906 if( pPrg ){
124907 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
124909 sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
124910 (const char *)pPrg->pProgram, P4_SUBPROGRAM);
124911 VdbeComment(
124912 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
124914 /* Set the P5 operand of the OP_Program instruction to non-zero if
124915 ** recursive invocation of this trigger program is disallowed. Recursive
124916 ** invocation is disallowed if (a) the sub-program is really a trigger,
124917 ** not a foreign key action, and (b) the flag to enable recursive triggers
124918 ** is clear. */
124919 sqlite3VdbeChangeP5(v, (u8)bRecursive);
124924 ** This is called to code the required FOR EACH ROW triggers for an operation
124925 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
124926 ** is given by the op parameter. The tr_tm parameter determines whether the
124927 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
124928 ** parameter pChanges is passed the list of columns being modified.
124930 ** If there are no triggers that fire at the specified time for the specified
124931 ** operation on pTab, this function is a no-op.
124933 ** The reg argument is the address of the first in an array of registers
124934 ** that contain the values substituted for the new.* and old.* references
124935 ** in the trigger program. If N is the number of columns in table pTab
124936 ** (a copy of pTab->nCol), then registers are populated as follows:
124938 ** Register Contains
124939 ** ------------------------------------------------------
124940 ** reg+0 OLD.rowid
124941 ** reg+1 OLD.* value of left-most column of pTab
124942 ** ... ...
124943 ** reg+N OLD.* value of right-most column of pTab
124944 ** reg+N+1 NEW.rowid
124945 ** reg+N+2 OLD.* value of left-most column of pTab
124946 ** ... ...
124947 ** reg+N+N+1 NEW.* value of right-most column of pTab
124949 ** For ON DELETE triggers, the registers containing the NEW.* values will
124950 ** never be accessed by the trigger program, so they are not allocated or
124951 ** populated by the caller (there is no data to populate them with anyway).
124952 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
124953 ** are never accessed, and so are not allocated by the caller. So, for an
124954 ** ON INSERT trigger, the value passed to this function as parameter reg
124955 ** is not a readable register, although registers (reg+N) through
124956 ** (reg+N+N+1) are.
124958 ** Parameter orconf is the default conflict resolution algorithm for the
124959 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
124960 ** is the instruction that control should jump to if a trigger program
124961 ** raises an IGNORE exception.
124963 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
124964 Parse *pParse, /* Parse context */
124965 Trigger *pTrigger, /* List of triggers on table pTab */
124966 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
124967 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
124968 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
124969 Table *pTab, /* The table to code triggers from */
124970 int reg, /* The first in an array of registers (see above) */
124971 int orconf, /* ON CONFLICT policy */
124972 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
124974 Trigger *p; /* Used to iterate through pTrigger list */
124976 assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
124977 assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
124978 assert( (op==TK_UPDATE)==(pChanges!=0) );
124980 for(p=pTrigger; p; p=p->pNext){
124982 /* Sanity checking: The schema for the trigger and for the table are
124983 ** always defined. The trigger must be in the same schema as the table
124984 ** or else it must be a TEMP trigger. */
124985 assert( p->pSchema!=0 );
124986 assert( p->pTabSchema!=0 );
124987 assert( p->pSchema==p->pTabSchema
124988 || p->pSchema==pParse->db->aDb[1].pSchema );
124990 /* Determine whether we should code this trigger */
124991 if( p->op==op
124992 && p->tr_tm==tr_tm
124993 && checkColumnOverlap(p->pColumns, pChanges)
124995 sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
125001 ** Triggers may access values stored in the old.* or new.* pseudo-table.
125002 ** This function returns a 32-bit bitmask indicating which columns of the
125003 ** old.* or new.* tables actually are used by triggers. This information
125004 ** may be used by the caller, for example, to avoid having to load the entire
125005 ** old.* record into memory when executing an UPDATE or DELETE command.
125007 ** Bit 0 of the returned mask is set if the left-most column of the
125008 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
125009 ** the second leftmost column value is required, and so on. If there
125010 ** are more than 32 columns in the table, and at least one of the columns
125011 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
125013 ** It is not possible to determine if the old.rowid or new.rowid column is
125014 ** accessed by triggers. The caller must always assume that it is.
125016 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
125017 ** applies to the old.* table. If 1, the new.* table.
125019 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
125020 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
125021 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
125022 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
125023 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
125025 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
125026 Parse *pParse, /* Parse context */
125027 Trigger *pTrigger, /* List of triggers on table pTab */
125028 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
125029 int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
125030 int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
125031 Table *pTab, /* The table to code triggers from */
125032 int orconf /* Default ON CONFLICT policy for trigger steps */
125034 const int op = pChanges ? TK_UPDATE : TK_DELETE;
125035 u32 mask = 0;
125036 Trigger *p;
125038 assert( isNew==1 || isNew==0 );
125039 for(p=pTrigger; p; p=p->pNext){
125040 if( p->op==op && (tr_tm&p->tr_tm)
125041 && checkColumnOverlap(p->pColumns,pChanges)
125043 TriggerPrg *pPrg;
125044 pPrg = getRowTrigger(pParse, p, pTab, orconf);
125045 if( pPrg ){
125046 mask |= pPrg->aColmask[isNew];
125051 return mask;
125054 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
125056 /************** End of trigger.c *********************************************/
125057 /************** Begin file update.c ******************************************/
125059 ** 2001 September 15
125061 ** The author disclaims copyright to this source code. In place of
125062 ** a legal notice, here is a blessing:
125064 ** May you do good and not evil.
125065 ** May you find forgiveness for yourself and forgive others.
125066 ** May you share freely, never taking more than you give.
125068 *************************************************************************
125069 ** This file contains C code routines that are called by the parser
125070 ** to handle UPDATE statements.
125072 /* #include "sqliteInt.h" */
125074 #ifndef SQLITE_OMIT_VIRTUALTABLE
125075 /* Forward declaration */
125076 static void updateVirtualTable(
125077 Parse *pParse, /* The parsing context */
125078 SrcList *pSrc, /* The virtual table to be modified */
125079 Table *pTab, /* The virtual table */
125080 ExprList *pChanges, /* The columns to change in the UPDATE statement */
125081 Expr *pRowidExpr, /* Expression used to recompute the rowid */
125082 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
125083 Expr *pWhere, /* WHERE clause of the UPDATE statement */
125084 int onError /* ON CONFLICT strategy */
125086 #endif /* SQLITE_OMIT_VIRTUALTABLE */
125089 ** The most recently coded instruction was an OP_Column to retrieve the
125090 ** i-th column of table pTab. This routine sets the P4 parameter of the
125091 ** OP_Column to the default value, if any.
125093 ** The default value of a column is specified by a DEFAULT clause in the
125094 ** column definition. This was either supplied by the user when the table
125095 ** was created, or added later to the table definition by an ALTER TABLE
125096 ** command. If the latter, then the row-records in the table btree on disk
125097 ** may not contain a value for the column and the default value, taken
125098 ** from the P4 parameter of the OP_Column instruction, is returned instead.
125099 ** If the former, then all row-records are guaranteed to include a value
125100 ** for the column and the P4 value is not required.
125102 ** Column definitions created by an ALTER TABLE command may only have
125103 ** literal default values specified: a number, null or a string. (If a more
125104 ** complicated default expression value was provided, it is evaluated
125105 ** when the ALTER TABLE is executed and one of the literal values written
125106 ** into the sqlite_master table.)
125108 ** Therefore, the P4 parameter is only required if the default value for
125109 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
125110 ** function is capable of transforming these types of expressions into
125111 ** sqlite3_value objects.
125113 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
125114 ** on register iReg. This is used when an equivalent integer value is
125115 ** stored in place of an 8-byte floating point value in order to save
125116 ** space.
125118 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
125119 assert( pTab!=0 );
125120 if( !pTab->pSelect ){
125121 sqlite3_value *pValue = 0;
125122 u8 enc = ENC(sqlite3VdbeDb(v));
125123 Column *pCol = &pTab->aCol[i];
125124 VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
125125 assert( i<pTab->nCol );
125126 sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
125127 pCol->affinity, &pValue);
125128 if( pValue ){
125129 sqlite3VdbeAppendP4(v, pValue, P4_MEM);
125132 #ifndef SQLITE_OMIT_FLOATING_POINT
125133 if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
125134 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
125136 #endif
125140 ** Process an UPDATE statement.
125142 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
125143 ** \_______/ \________/ \______/ \________________/
125144 * onError pTabList pChanges pWhere
125146 SQLITE_PRIVATE void sqlite3Update(
125147 Parse *pParse, /* The parser context */
125148 SrcList *pTabList, /* The table in which we should change things */
125149 ExprList *pChanges, /* Things to be changed */
125150 Expr *pWhere, /* The WHERE clause. May be null */
125151 int onError /* How to handle constraint errors */
125153 int i, j; /* Loop counters */
125154 Table *pTab; /* The table to be updated */
125155 int addrTop = 0; /* VDBE instruction address of the start of the loop */
125156 WhereInfo *pWInfo; /* Information about the WHERE clause */
125157 Vdbe *v; /* The virtual database engine */
125158 Index *pIdx; /* For looping over indices */
125159 Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
125160 int nIdx; /* Number of indices that need updating */
125161 int iBaseCur; /* Base cursor number */
125162 int iDataCur; /* Cursor for the canonical data btree */
125163 int iIdxCur; /* Cursor for the first index */
125164 sqlite3 *db; /* The database structure */
125165 int *aRegIdx = 0; /* First register in array assigned to each index */
125166 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
125167 ** an expression for the i-th column of the table.
125168 ** aXRef[i]==-1 if the i-th column is not changed. */
125169 u8 *aToOpen; /* 1 for tables and indices to be opened */
125170 u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
125171 u8 chngRowid; /* Rowid changed in a normal table */
125172 u8 chngKey; /* Either chngPk or chngRowid */
125173 Expr *pRowidExpr = 0; /* Expression defining the new record number */
125174 AuthContext sContext; /* The authorization context */
125175 NameContext sNC; /* The name-context to resolve expressions in */
125176 int iDb; /* Database containing the table being updated */
125177 int eOnePass; /* ONEPASS_XXX value from where.c */
125178 int hasFK; /* True if foreign key processing is required */
125179 int labelBreak; /* Jump here to break out of UPDATE loop */
125180 int labelContinue; /* Jump here to continue next step of UPDATE loop */
125181 int flags; /* Flags for sqlite3WhereBegin() */
125183 #ifndef SQLITE_OMIT_TRIGGER
125184 int isView; /* True when updating a view (INSTEAD OF trigger) */
125185 Trigger *pTrigger; /* List of triggers on pTab, if required */
125186 int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
125187 #endif
125188 int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
125189 int iEph = 0; /* Ephemeral table holding all primary key values */
125190 int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
125191 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
125192 int addrOpen = 0; /* Address of OP_OpenEphemeral */
125193 int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
125194 i16 nPk = 0; /* Number of components of the PRIMARY KEY */
125195 int bReplace = 0; /* True if REPLACE conflict resolution might happen */
125197 /* Register Allocations */
125198 int regRowCount = 0; /* A count of rows changed */
125199 int regOldRowid = 0; /* The old rowid */
125200 int regNewRowid = 0; /* The new rowid */
125201 int regNew = 0; /* Content of the NEW.* table in triggers */
125202 int regOld = 0; /* Content of OLD.* table in triggers */
125203 int regRowSet = 0; /* Rowset of rows to be updated */
125204 int regKey = 0; /* composite PRIMARY KEY value */
125206 memset(&sContext, 0, sizeof(sContext));
125207 db = pParse->db;
125208 if( pParse->nErr || db->mallocFailed ){
125209 goto update_cleanup;
125211 assert( pTabList->nSrc==1 );
125213 /* Locate the table which we want to update.
125215 pTab = sqlite3SrcListLookup(pParse, pTabList);
125216 if( pTab==0 ) goto update_cleanup;
125217 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
125219 /* Figure out if we have any triggers and if the table being
125220 ** updated is a view.
125222 #ifndef SQLITE_OMIT_TRIGGER
125223 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
125224 isView = pTab->pSelect!=0;
125225 assert( pTrigger || tmask==0 );
125226 #else
125227 # define pTrigger 0
125228 # define isView 0
125229 # define tmask 0
125230 #endif
125231 #ifdef SQLITE_OMIT_VIEW
125232 # undef isView
125233 # define isView 0
125234 #endif
125236 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
125237 goto update_cleanup;
125239 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
125240 goto update_cleanup;
125243 /* Allocate a cursors for the main database table and for all indices.
125244 ** The index cursors might not be used, but if they are used they
125245 ** need to occur right after the database cursor. So go ahead and
125246 ** allocate enough space, just in case.
125248 pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
125249 iIdxCur = iDataCur+1;
125250 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
125251 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
125252 if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
125253 iDataCur = pParse->nTab;
125254 pTabList->a[0].iCursor = iDataCur;
125256 pParse->nTab++;
125259 /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
125260 ** Initialize aXRef[] and aToOpen[] to their default values.
125262 aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
125263 if( aXRef==0 ) goto update_cleanup;
125264 aRegIdx = aXRef+pTab->nCol;
125265 aToOpen = (u8*)(aRegIdx+nIdx);
125266 memset(aToOpen, 1, nIdx+1);
125267 aToOpen[nIdx+1] = 0;
125268 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
125270 /* Initialize the name-context */
125271 memset(&sNC, 0, sizeof(sNC));
125272 sNC.pParse = pParse;
125273 sNC.pSrcList = pTabList;
125275 /* Resolve the column names in all the expressions of the
125276 ** of the UPDATE statement. Also find the column index
125277 ** for each column to be updated in the pChanges array. For each
125278 ** column to be updated, make sure we have authorization to change
125279 ** that column.
125281 chngRowid = chngPk = 0;
125282 for(i=0; i<pChanges->nExpr; i++){
125283 if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
125284 goto update_cleanup;
125286 for(j=0; j<pTab->nCol; j++){
125287 if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
125288 if( j==pTab->iPKey ){
125289 chngRowid = 1;
125290 pRowidExpr = pChanges->a[i].pExpr;
125291 }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
125292 chngPk = 1;
125294 aXRef[j] = i;
125295 break;
125298 if( j>=pTab->nCol ){
125299 if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
125300 j = -1;
125301 chngRowid = 1;
125302 pRowidExpr = pChanges->a[i].pExpr;
125303 }else{
125304 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
125305 pParse->checkSchema = 1;
125306 goto update_cleanup;
125309 #ifndef SQLITE_OMIT_AUTHORIZATION
125311 int rc;
125312 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
125313 j<0 ? "ROWID" : pTab->aCol[j].zName,
125314 db->aDb[iDb].zDbSName);
125315 if( rc==SQLITE_DENY ){
125316 goto update_cleanup;
125317 }else if( rc==SQLITE_IGNORE ){
125318 aXRef[j] = -1;
125321 #endif
125323 assert( (chngRowid & chngPk)==0 );
125324 assert( chngRowid==0 || chngRowid==1 );
125325 assert( chngPk==0 || chngPk==1 );
125326 chngKey = chngRowid + chngPk;
125328 /* The SET expressions are not actually used inside the WHERE loop.
125329 ** So reset the colUsed mask. Unless this is a virtual table. In that
125330 ** case, set all bits of the colUsed mask (to ensure that the virtual
125331 ** table implementation makes all columns available).
125333 pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
125335 hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
125337 /* There is one entry in the aRegIdx[] array for each index on the table
125338 ** being updated. Fill in aRegIdx[] with a register number that will hold
125339 ** the key for accessing each index.
125341 ** FIXME: Be smarter about omitting indexes that use expressions.
125343 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
125344 int reg;
125345 if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
125346 reg = ++pParse->nMem;
125347 pParse->nMem += pIdx->nColumn;
125348 }else{
125349 reg = 0;
125350 for(i=0; i<pIdx->nKeyCol; i++){
125351 i16 iIdxCol = pIdx->aiColumn[i];
125352 if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
125353 reg = ++pParse->nMem;
125354 pParse->nMem += pIdx->nColumn;
125355 if( (onError==OE_Replace)
125356 || (onError==OE_Default && pIdx->onError==OE_Replace)
125358 bReplace = 1;
125360 break;
125364 if( reg==0 ) aToOpen[j+1] = 0;
125365 aRegIdx[j] = reg;
125367 if( bReplace ){
125368 /* If REPLACE conflict resolution might be invoked, open cursors on all
125369 ** indexes in case they are needed to delete records. */
125370 memset(aToOpen, 1, nIdx+1);
125373 /* Begin generating code. */
125374 v = sqlite3GetVdbe(pParse);
125375 if( v==0 ) goto update_cleanup;
125376 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
125377 sqlite3BeginWriteOperation(pParse, 1, iDb);
125379 /* Allocate required registers. */
125380 if( !IsVirtual(pTab) ){
125381 regRowSet = ++pParse->nMem;
125382 regOldRowid = regNewRowid = ++pParse->nMem;
125383 if( chngPk || pTrigger || hasFK ){
125384 regOld = pParse->nMem + 1;
125385 pParse->nMem += pTab->nCol;
125387 if( chngKey || pTrigger || hasFK ){
125388 regNewRowid = ++pParse->nMem;
125390 regNew = pParse->nMem + 1;
125391 pParse->nMem += pTab->nCol;
125394 /* Start the view context. */
125395 if( isView ){
125396 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
125399 /* If we are trying to update a view, realize that view into
125400 ** an ephemeral table.
125402 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
125403 if( isView ){
125404 sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
125406 #endif
125408 /* Resolve the column names in all the expressions in the
125409 ** WHERE clause.
125411 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
125412 goto update_cleanup;
125415 #ifndef SQLITE_OMIT_VIRTUALTABLE
125416 /* Virtual tables must be handled separately */
125417 if( IsVirtual(pTab) ){
125418 updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
125419 pWhere, onError);
125420 goto update_cleanup;
125422 #endif
125424 /* Initialize the count of updated rows */
125425 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
125426 regRowCount = ++pParse->nMem;
125427 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
125430 if( HasRowid(pTab) ){
125431 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
125432 }else{
125433 assert( pPk!=0 );
125434 nPk = pPk->nKeyCol;
125435 iPk = pParse->nMem+1;
125436 pParse->nMem += nPk;
125437 regKey = ++pParse->nMem;
125438 iEph = pParse->nTab++;
125440 sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
125441 addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
125442 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
125445 /* Begin the database scan.
125447 ** Do not consider a single-pass strategy for a multi-row update if
125448 ** there are any triggers or foreign keys to process, or rows may
125449 ** be deleted as a result of REPLACE conflict handling. Any of these
125450 ** things might disturb a cursor being used to scan through the table
125451 ** or index, causing a single-pass approach to malfunction. */
125452 flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
125453 if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
125454 flags |= WHERE_ONEPASS_MULTIROW;
125456 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
125457 if( pWInfo==0 ) goto update_cleanup;
125459 /* A one-pass strategy that might update more than one row may not
125460 ** be used if any column of the index used for the scan is being
125461 ** updated. Otherwise, if there is an index on "b", statements like
125462 ** the following could create an infinite loop:
125464 ** UPDATE t1 SET b=b+1 WHERE b>?
125466 ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
125467 ** strategy that uses an index for which one or more columns are being
125468 ** updated. */
125469 eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
125470 if( eOnePass==ONEPASS_MULTI ){
125471 int iCur = aiCurOnePass[1];
125472 if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
125473 eOnePass = ONEPASS_OFF;
125475 assert( iCur!=iDataCur || !HasRowid(pTab) );
125478 if( HasRowid(pTab) ){
125479 /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
125480 ** mode, write the rowid into the FIFO. In either of the one-pass modes,
125481 ** leave it in register regOldRowid. */
125482 sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
125483 if( eOnePass==ONEPASS_OFF ){
125484 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
125486 }else{
125487 /* Read the PK of the current row into an array of registers. In
125488 ** ONEPASS_OFF mode, serialize the array into a record and store it in
125489 ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
125490 ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
125491 ** is not required) and leave the PK fields in the array of registers. */
125492 for(i=0; i<nPk; i++){
125493 assert( pPk->aiColumn[i]>=0 );
125494 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
125496 if( eOnePass ){
125497 sqlite3VdbeChangeToNoop(v, addrOpen);
125498 nKey = nPk;
125499 regKey = iPk;
125500 }else{
125501 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
125502 sqlite3IndexAffinityStr(db, pPk), nPk);
125503 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
125507 if( eOnePass!=ONEPASS_MULTI ){
125508 sqlite3WhereEnd(pWInfo);
125511 labelBreak = sqlite3VdbeMakeLabel(v);
125512 if( !isView ){
125513 int addrOnce = 0;
125515 /* Open every index that needs updating. */
125516 if( eOnePass!=ONEPASS_OFF ){
125517 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
125518 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
125521 if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
125522 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
125524 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
125525 0, 0);
125526 if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
125529 /* Top of the update loop */
125530 if( eOnePass!=ONEPASS_OFF ){
125531 if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
125532 assert( pPk );
125533 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
125534 VdbeCoverageNeverTaken(v);
125536 if( eOnePass==ONEPASS_SINGLE ){
125537 labelContinue = labelBreak;
125538 }else{
125539 labelContinue = sqlite3VdbeMakeLabel(v);
125541 sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
125542 VdbeCoverageIf(v, pPk==0);
125543 VdbeCoverageIf(v, pPk!=0);
125544 }else if( pPk ){
125545 labelContinue = sqlite3VdbeMakeLabel(v);
125546 sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
125547 addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
125548 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
125549 VdbeCoverage(v);
125550 }else{
125551 labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
125552 regOldRowid);
125553 VdbeCoverage(v);
125554 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
125555 VdbeCoverage(v);
125558 /* If the record number will change, set register regNewRowid to
125559 ** contain the new value. If the record number is not being modified,
125560 ** then regNewRowid is the same register as regOldRowid, which is
125561 ** already populated. */
125562 assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
125563 if( chngRowid ){
125564 sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
125565 sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
125568 /* Compute the old pre-UPDATE content of the row being changed, if that
125569 ** information is needed */
125570 if( chngPk || hasFK || pTrigger ){
125571 u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
125572 oldmask |= sqlite3TriggerColmask(pParse,
125573 pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
125575 for(i=0; i<pTab->nCol; i++){
125576 if( oldmask==0xffffffff
125577 || (i<32 && (oldmask & MASKBIT32(i))!=0)
125578 || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
125580 testcase( oldmask!=0xffffffff && i==31 );
125581 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
125582 }else{
125583 sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
125586 if( chngRowid==0 && pPk==0 ){
125587 sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
125591 /* Populate the array of registers beginning at regNew with the new
125592 ** row data. This array is used to check constants, create the new
125593 ** table and index records, and as the values for any new.* references
125594 ** made by triggers.
125596 ** If there are one or more BEFORE triggers, then do not populate the
125597 ** registers associated with columns that are (a) not modified by
125598 ** this UPDATE statement and (b) not accessed by new.* references. The
125599 ** values for registers not modified by the UPDATE must be reloaded from
125600 ** the database after the BEFORE triggers are fired anyway (as the trigger
125601 ** may have modified them). So not loading those that are not going to
125602 ** be used eliminates some redundant opcodes.
125604 newmask = sqlite3TriggerColmask(
125605 pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
125607 for(i=0; i<pTab->nCol; i++){
125608 if( i==pTab->iPKey ){
125609 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
125610 }else{
125611 j = aXRef[i];
125612 if( j>=0 ){
125613 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
125614 }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
125615 /* This branch loads the value of a column that will not be changed
125616 ** into a register. This is done if there are no BEFORE triggers, or
125617 ** if there are one or more BEFORE triggers that use this value via
125618 ** a new.* reference in a trigger program.
125620 testcase( i==31 );
125621 testcase( i==32 );
125622 sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
125623 }else{
125624 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
125629 /* Fire any BEFORE UPDATE triggers. This happens before constraints are
125630 ** verified. One could argue that this is wrong.
125632 if( tmask&TRIGGER_BEFORE ){
125633 sqlite3TableAffinity(v, pTab, regNew);
125634 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
125635 TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
125637 /* The row-trigger may have deleted the row being updated. In this
125638 ** case, jump to the next row. No updates or AFTER triggers are
125639 ** required. This behavior - what happens when the row being updated
125640 ** is deleted or renamed by a BEFORE trigger - is left undefined in the
125641 ** documentation.
125643 if( pPk ){
125644 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
125645 VdbeCoverage(v);
125646 }else{
125647 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
125648 VdbeCoverage(v);
125651 /* If it did not delete it, the row-trigger may still have modified
125652 ** some of the columns of the row being updated. Load the values for
125653 ** all columns not modified by the update statement into their
125654 ** registers in case this has happened.
125656 for(i=0; i<pTab->nCol; i++){
125657 if( aXRef[i]<0 && i!=pTab->iPKey ){
125658 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
125663 if( !isView ){
125664 int addr1 = 0; /* Address of jump instruction */
125666 /* Do constraint checks. */
125667 assert( regOldRowid>0 );
125668 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
125669 regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
125670 aXRef);
125672 /* Do FK constraint checks. */
125673 if( hasFK ){
125674 sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
125677 /* Delete the index entries associated with the current record. */
125678 if( bReplace || chngKey ){
125679 if( pPk ){
125680 addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
125681 }else{
125682 addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
125684 VdbeCoverageNeverTaken(v);
125686 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
125688 /* If changing the rowid value, or if there are foreign key constraints
125689 ** to process, delete the old record. Otherwise, add a noop OP_Delete
125690 ** to invoke the pre-update hook.
125692 ** That (regNew==regnewRowid+1) is true is also important for the
125693 ** pre-update hook. If the caller invokes preupdate_new(), the returned
125694 ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
125695 ** is the column index supplied by the user.
125697 assert( regNew==regNewRowid+1 );
125698 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
125699 sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
125700 OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
125701 regNewRowid
125703 if( eOnePass==ONEPASS_MULTI ){
125704 assert( hasFK==0 && chngKey==0 );
125705 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
125707 if( !pParse->nested ){
125708 sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
125710 #else
125711 if( hasFK>1 || chngKey ){
125712 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
125714 #endif
125715 if( bReplace || chngKey ){
125716 sqlite3VdbeJumpHere(v, addr1);
125719 if( hasFK ){
125720 sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
125723 /* Insert the new index entries and the new record. */
125724 sqlite3CompleteInsertion(
125725 pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
125726 OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
125730 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
125731 ** handle rows (possibly in other tables) that refer via a foreign key
125732 ** to the row just updated. */
125733 if( hasFK ){
125734 sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
125738 /* Increment the row counter
125740 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
125741 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
125744 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
125745 TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
125747 /* Repeat the above with the next record to be updated, until
125748 ** all record selected by the WHERE clause have been updated.
125750 if( eOnePass==ONEPASS_SINGLE ){
125751 /* Nothing to do at end-of-loop for a single-pass */
125752 }else if( eOnePass==ONEPASS_MULTI ){
125753 sqlite3VdbeResolveLabel(v, labelContinue);
125754 sqlite3WhereEnd(pWInfo);
125755 }else if( pPk ){
125756 sqlite3VdbeResolveLabel(v, labelContinue);
125757 sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
125758 }else{
125759 sqlite3VdbeGoto(v, labelContinue);
125761 sqlite3VdbeResolveLabel(v, labelBreak);
125763 /* Update the sqlite_sequence table by storing the content of the
125764 ** maximum rowid counter values recorded while inserting into
125765 ** autoincrement tables.
125767 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
125768 sqlite3AutoincrementEnd(pParse);
125772 ** Return the number of rows that were changed. If this routine is
125773 ** generating code because of a call to sqlite3NestedParse(), do not
125774 ** invoke the callback function.
125776 if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
125777 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
125778 sqlite3VdbeSetNumCols(v, 1);
125779 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
125782 update_cleanup:
125783 sqlite3AuthContextPop(&sContext);
125784 sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
125785 sqlite3SrcListDelete(db, pTabList);
125786 sqlite3ExprListDelete(db, pChanges);
125787 sqlite3ExprDelete(db, pWhere);
125788 return;
125790 /* Make sure "isView" and other macros defined above are undefined. Otherwise
125791 ** they may interfere with compilation of other functions in this file
125792 ** (or in another file, if this file becomes part of the amalgamation). */
125793 #ifdef isView
125794 #undef isView
125795 #endif
125796 #ifdef pTrigger
125797 #undef pTrigger
125798 #endif
125800 #ifndef SQLITE_OMIT_VIRTUALTABLE
125802 ** Generate code for an UPDATE of a virtual table.
125804 ** There are two possible strategies - the default and the special
125805 ** "onepass" strategy. Onepass is only used if the virtual table
125806 ** implementation indicates that pWhere may match at most one row.
125808 ** The default strategy is to create an ephemeral table that contains
125809 ** for each row to be changed:
125811 ** (A) The original rowid of that row.
125812 ** (B) The revised rowid for the row.
125813 ** (C) The content of every column in the row.
125815 ** Then loop through the contents of this ephemeral table executing a
125816 ** VUpdate for each row. When finished, drop the ephemeral table.
125818 ** The "onepass" strategy does not use an ephemeral table. Instead, it
125819 ** stores the same values (A, B and C above) in a register array and
125820 ** makes a single invocation of VUpdate.
125822 static void updateVirtualTable(
125823 Parse *pParse, /* The parsing context */
125824 SrcList *pSrc, /* The virtual table to be modified */
125825 Table *pTab, /* The virtual table */
125826 ExprList *pChanges, /* The columns to change in the UPDATE statement */
125827 Expr *pRowid, /* Expression used to recompute the rowid */
125828 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
125829 Expr *pWhere, /* WHERE clause of the UPDATE statement */
125830 int onError /* ON CONFLICT strategy */
125832 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
125833 int ephemTab; /* Table holding the result of the SELECT */
125834 int i; /* Loop counter */
125835 sqlite3 *db = pParse->db; /* Database connection */
125836 const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
125837 WhereInfo *pWInfo;
125838 int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
125839 int regArg; /* First register in VUpdate arg array */
125840 int regRec; /* Register in which to assemble record */
125841 int regRowid; /* Register for ephem table rowid */
125842 int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
125843 int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
125844 int bOnePass; /* True to use onepass strategy */
125845 int addr; /* Address of OP_OpenEphemeral */
125847 /* Allocate nArg registers to martial the arguments to VUpdate. Then
125848 ** create and open the ephemeral table in which the records created from
125849 ** these arguments will be temporarily stored. */
125850 assert( v );
125851 ephemTab = pParse->nTab++;
125852 addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
125853 regArg = pParse->nMem + 1;
125854 pParse->nMem += nArg;
125855 regRec = ++pParse->nMem;
125856 regRowid = ++pParse->nMem;
125858 /* Start scanning the virtual table */
125859 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
125860 if( pWInfo==0 ) return;
125862 /* Populate the argument registers. */
125863 for(i=0; i<pTab->nCol; i++){
125864 if( aXRef[i]>=0 ){
125865 sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
125866 }else{
125867 sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
125870 if( HasRowid(pTab) ){
125871 sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
125872 if( pRowid ){
125873 sqlite3ExprCode(pParse, pRowid, regArg+1);
125874 }else{
125875 sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
125877 }else{
125878 Index *pPk; /* PRIMARY KEY index */
125879 i16 iPk; /* PRIMARY KEY column */
125880 pPk = sqlite3PrimaryKeyIndex(pTab);
125881 assert( pPk!=0 );
125882 assert( pPk->nKeyCol==1 );
125883 iPk = pPk->aiColumn[0];
125884 sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
125885 sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
125888 bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
125890 if( bOnePass ){
125891 /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
125892 ** above. Also, if this is a top-level parse (not a trigger), clear the
125893 ** multi-write flag so that the VM does not open a statement journal */
125894 sqlite3VdbeChangeToNoop(v, addr);
125895 if( sqlite3IsToplevel(pParse) ){
125896 pParse->isMultiWrite = 0;
125898 }else{
125899 /* Create a record from the argument register contents and insert it into
125900 ** the ephemeral table. */
125901 sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
125902 sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
125903 sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
125907 if( bOnePass==0 ){
125908 /* End the virtual table scan */
125909 sqlite3WhereEnd(pWInfo);
125911 /* Begin scannning through the ephemeral table. */
125912 addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
125914 /* Extract arguments from the current row of the ephemeral table and
125915 ** invoke the VUpdate method. */
125916 for(i=0; i<nArg; i++){
125917 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
125920 sqlite3VtabMakeWritable(pParse, pTab);
125921 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
125922 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
125923 sqlite3MayAbort(pParse);
125925 /* End of the ephemeral table scan. Or, if using the onepass strategy,
125926 ** jump to here if the scan visited zero rows. */
125927 if( bOnePass==0 ){
125928 sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
125929 sqlite3VdbeJumpHere(v, addr);
125930 sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
125931 }else{
125932 sqlite3WhereEnd(pWInfo);
125935 #endif /* SQLITE_OMIT_VIRTUALTABLE */
125937 /************** End of update.c **********************************************/
125938 /************** Begin file vacuum.c ******************************************/
125940 ** 2003 April 6
125942 ** The author disclaims copyright to this source code. In place of
125943 ** a legal notice, here is a blessing:
125945 ** May you do good and not evil.
125946 ** May you find forgiveness for yourself and forgive others.
125947 ** May you share freely, never taking more than you give.
125949 *************************************************************************
125950 ** This file contains code used to implement the VACUUM command.
125952 ** Most of the code in this file may be omitted by defining the
125953 ** SQLITE_OMIT_VACUUM macro.
125955 /* #include "sqliteInt.h" */
125956 /* #include "vdbeInt.h" */
125958 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
125961 ** Execute zSql on database db.
125963 ** If zSql returns rows, then each row will have exactly one
125964 ** column. (This will only happen if zSql begins with "SELECT".)
125965 ** Take each row of result and call execSql() again recursively.
125967 ** The execSqlF() routine does the same thing, except it accepts
125968 ** a format string as its third argument
125970 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
125971 sqlite3_stmt *pStmt;
125972 int rc;
125974 /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
125975 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
125976 if( rc!=SQLITE_OK ) return rc;
125977 while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
125978 const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
125979 assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
125980 if( zSubSql ){
125981 assert( zSubSql[0]!='S' );
125982 rc = execSql(db, pzErrMsg, zSubSql);
125983 if( rc!=SQLITE_OK ) break;
125986 assert( rc!=SQLITE_ROW );
125987 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
125988 if( rc ){
125989 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
125991 (void)sqlite3_finalize(pStmt);
125992 return rc;
125994 static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
125995 char *z;
125996 va_list ap;
125997 int rc;
125998 va_start(ap, zSql);
125999 z = sqlite3VMPrintf(db, zSql, ap);
126000 va_end(ap);
126001 if( z==0 ) return SQLITE_NOMEM;
126002 rc = execSql(db, pzErrMsg, z);
126003 sqlite3DbFree(db, z);
126004 return rc;
126008 ** The VACUUM command is used to clean up the database,
126009 ** collapse free space, etc. It is modelled after the VACUUM command
126010 ** in PostgreSQL. The VACUUM command works as follows:
126012 ** (1) Create a new transient database file
126013 ** (2) Copy all content from the database being vacuumed into
126014 ** the new transient database file
126015 ** (3) Copy content from the transient database back into the
126016 ** original database.
126018 ** The transient database requires temporary disk space approximately
126019 ** equal to the size of the original database. The copy operation of
126020 ** step (3) requires additional temporary disk space approximately equal
126021 ** to the size of the original database for the rollback journal.
126022 ** Hence, temporary disk space that is approximately 2x the size of the
126023 ** original database is required. Every page of the database is written
126024 ** approximately 3 times: Once for step (2) and twice for step (3).
126025 ** Two writes per page are required in step (3) because the original
126026 ** database content must be written into the rollback journal prior to
126027 ** overwriting the database with the vacuumed content.
126029 ** Only 1x temporary space and only 1x writes would be required if
126030 ** the copy of step (3) were replaced by deleting the original database
126031 ** and renaming the transient database as the original. But that will
126032 ** not work if other processes are attached to the original database.
126033 ** And a power loss in between deleting the original and renaming the
126034 ** transient would cause the database file to appear to be deleted
126035 ** following reboot.
126037 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
126038 Vdbe *v = sqlite3GetVdbe(pParse);
126039 int iDb = 0;
126040 if( v==0 ) return;
126041 if( pNm ){
126042 #ifndef SQLITE_BUG_COMPATIBLE_20160819
126043 /* Default behavior: Report an error if the argument to VACUUM is
126044 ** not recognized */
126045 iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
126046 if( iDb<0 ) return;
126047 #else
126048 /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
126049 ** to VACUUM are silently ignored. This is a back-out of a bug fix that
126050 ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
126051 ** The buggy behavior is required for binary compatibility with some
126052 ** legacy applications. */
126053 iDb = sqlite3FindDb(pParse->db, pNm);
126054 if( iDb<0 ) iDb = 0;
126055 #endif
126057 if( iDb!=1 ){
126058 sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
126059 sqlite3VdbeUsesBtree(v, iDb);
126061 return;
126065 ** This routine implements the OP_Vacuum opcode of the VDBE.
126067 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
126068 int rc = SQLITE_OK; /* Return code from service routines */
126069 Btree *pMain; /* The database being vacuumed */
126070 Btree *pTemp; /* The temporary database we vacuum into */
126071 u16 saved_mDbFlags; /* Saved value of db->mDbFlags */
126072 u32 saved_flags; /* Saved value of db->flags */
126073 int saved_nChange; /* Saved value of db->nChange */
126074 int saved_nTotalChange; /* Saved value of db->nTotalChange */
126075 u8 saved_mTrace; /* Saved trace settings */
126076 Db *pDb = 0; /* Database to detach at end of vacuum */
126077 int isMemDb; /* True if vacuuming a :memory: database */
126078 int nRes; /* Bytes of reserved space at the end of each page */
126079 int nDb; /* Number of attached databases */
126080 const char *zDbMain; /* Schema name of database to vacuum */
126082 if( !db->autoCommit ){
126083 sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
126084 return SQLITE_ERROR;
126086 if( db->nVdbeActive>1 ){
126087 sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
126088 return SQLITE_ERROR;
126091 /* Save the current value of the database flags so that it can be
126092 ** restored before returning. Then set the writable-schema flag, and
126093 ** disable CHECK and foreign key constraints. */
126094 saved_flags = db->flags;
126095 saved_mDbFlags = db->mDbFlags;
126096 saved_nChange = db->nChange;
126097 saved_nTotalChange = db->nTotalChange;
126098 saved_mTrace = db->mTrace;
126099 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
126100 db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
126101 db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
126102 db->mTrace = 0;
126104 zDbMain = db->aDb[iDb].zDbSName;
126105 pMain = db->aDb[iDb].pBt;
126106 isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
126108 /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
126109 ** can be set to 'off' for this file, as it is not recovered if a crash
126110 ** occurs anyway. The integrity of the database is maintained by a
126111 ** (possibly synchronous) transaction opened on the main database before
126112 ** sqlite3BtreeCopyFile() is called.
126114 ** An optimisation would be to use a non-journaled pager.
126115 ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
126116 ** that actually made the VACUUM run slower. Very little journalling
126117 ** actually occurs when doing a vacuum since the vacuum_db is initially
126118 ** empty. Only the journal header is written. Apparently it takes more
126119 ** time to parse and run the PRAGMA to turn journalling off than it does
126120 ** to write the journal header file.
126122 nDb = db->nDb;
126123 rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
126124 if( rc!=SQLITE_OK ) goto end_of_vacuum;
126125 assert( (db->nDb-1)==nDb );
126126 pDb = &db->aDb[nDb];
126127 assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
126128 pTemp = pDb->pBt;
126130 /* The call to execSql() to attach the temp database has left the file
126131 ** locked (as there was more than one active statement when the transaction
126132 ** to read the schema was concluded. Unlock it here so that this doesn't
126133 ** cause problems for the call to BtreeSetPageSize() below. */
126134 sqlite3BtreeCommit(pTemp);
126136 nRes = sqlite3BtreeGetOptimalReserve(pMain);
126138 /* A VACUUM cannot change the pagesize of an encrypted database. */
126139 #ifdef SQLITE_HAS_CODEC
126140 if( db->nextPagesize ){
126141 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
126142 int nKey;
126143 char *zKey;
126144 sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
126145 if( nKey ) db->nextPagesize = 0;
126147 #endif
126149 sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
126150 sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
126151 sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
126153 /* Begin a transaction and take an exclusive lock on the main database
126154 ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
126155 ** to ensure that we do not try to change the page-size on a WAL database.
126157 rc = execSql(db, pzErrMsg, "BEGIN");
126158 if( rc!=SQLITE_OK ) goto end_of_vacuum;
126159 rc = sqlite3BtreeBeginTrans(pMain, 2);
126160 if( rc!=SQLITE_OK ) goto end_of_vacuum;
126162 /* Do not attempt to change the page size for a WAL database */
126163 if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
126164 ==PAGER_JOURNALMODE_WAL ){
126165 db->nextPagesize = 0;
126168 if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
126169 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
126170 || NEVER(db->mallocFailed)
126172 rc = SQLITE_NOMEM_BKPT;
126173 goto end_of_vacuum;
126176 #ifndef SQLITE_OMIT_AUTOVACUUM
126177 sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
126178 sqlite3BtreeGetAutoVacuum(pMain));
126179 #endif
126181 /* Query the schema of the main database. Create a mirror schema
126182 ** in the temporary database.
126184 db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
126185 rc = execSqlF(db, pzErrMsg,
126186 "SELECT sql FROM \"%w\".sqlite_master"
126187 " WHERE type='table'AND name<>'sqlite_sequence'"
126188 " AND coalesce(rootpage,1)>0",
126189 zDbMain
126191 if( rc!=SQLITE_OK ) goto end_of_vacuum;
126192 rc = execSqlF(db, pzErrMsg,
126193 "SELECT sql FROM \"%w\".sqlite_master"
126194 " WHERE type='index' AND length(sql)>10",
126195 zDbMain
126197 if( rc!=SQLITE_OK ) goto end_of_vacuum;
126198 db->init.iDb = 0;
126200 /* Loop through the tables in the main database. For each, do
126201 ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
126202 ** the contents to the temporary database.
126204 rc = execSqlF(db, pzErrMsg,
126205 "SELECT'INSERT INTO vacuum_db.'||quote(name)"
126206 "||' SELECT*FROM\"%w\".'||quote(name)"
126207 "FROM vacuum_db.sqlite_master "
126208 "WHERE type='table'AND coalesce(rootpage,1)>0",
126209 zDbMain
126211 assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
126212 db->mDbFlags &= ~DBFLAG_Vacuum;
126213 if( rc!=SQLITE_OK ) goto end_of_vacuum;
126215 /* Copy the triggers, views, and virtual tables from the main database
126216 ** over to the temporary database. None of these objects has any
126217 ** associated storage, so all we have to do is copy their entries
126218 ** from the SQLITE_MASTER table.
126220 rc = execSqlF(db, pzErrMsg,
126221 "INSERT INTO vacuum_db.sqlite_master"
126222 " SELECT*FROM \"%w\".sqlite_master"
126223 " WHERE type IN('view','trigger')"
126224 " OR(type='table'AND rootpage=0)",
126225 zDbMain
126227 if( rc ) goto end_of_vacuum;
126229 /* At this point, there is a write transaction open on both the
126230 ** vacuum database and the main database. Assuming no error occurs,
126231 ** both transactions are closed by this block - the main database
126232 ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
126233 ** call to sqlite3BtreeCommit().
126236 u32 meta;
126237 int i;
126239 /* This array determines which meta meta values are preserved in the
126240 ** vacuum. Even entries are the meta value number and odd entries
126241 ** are an increment to apply to the meta value after the vacuum.
126242 ** The increment is used to increase the schema cookie so that other
126243 ** connections to the same database will know to reread the schema.
126245 static const unsigned char aCopy[] = {
126246 BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
126247 BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
126248 BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
126249 BTREE_USER_VERSION, 0, /* Preserve the user version */
126250 BTREE_APPLICATION_ID, 0, /* Preserve the application id */
126253 assert( 1==sqlite3BtreeIsInTrans(pTemp) );
126254 assert( 1==sqlite3BtreeIsInTrans(pMain) );
126256 /* Copy Btree meta values */
126257 for(i=0; i<ArraySize(aCopy); i+=2){
126258 /* GetMeta() and UpdateMeta() cannot fail in this context because
126259 ** we already have page 1 loaded into cache and marked dirty. */
126260 sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
126261 rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
126262 if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
126265 rc = sqlite3BtreeCopyFile(pMain, pTemp);
126266 if( rc!=SQLITE_OK ) goto end_of_vacuum;
126267 rc = sqlite3BtreeCommit(pTemp);
126268 if( rc!=SQLITE_OK ) goto end_of_vacuum;
126269 #ifndef SQLITE_OMIT_AUTOVACUUM
126270 sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
126271 #endif
126274 assert( rc==SQLITE_OK );
126275 rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
126277 end_of_vacuum:
126278 /* Restore the original value of db->flags */
126279 db->init.iDb = 0;
126280 db->mDbFlags = saved_mDbFlags;
126281 db->flags = saved_flags;
126282 db->nChange = saved_nChange;
126283 db->nTotalChange = saved_nTotalChange;
126284 db->mTrace = saved_mTrace;
126285 sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
126287 /* Currently there is an SQL level transaction open on the vacuum
126288 ** database. No locks are held on any other files (since the main file
126289 ** was committed at the btree level). So it safe to end the transaction
126290 ** by manually setting the autoCommit flag to true and detaching the
126291 ** vacuum database. The vacuum_db journal file is deleted when the pager
126292 ** is closed by the DETACH.
126294 db->autoCommit = 1;
126296 if( pDb ){
126297 sqlite3BtreeClose(pDb->pBt);
126298 pDb->pBt = 0;
126299 pDb->pSchema = 0;
126302 /* This both clears the schemas and reduces the size of the db->aDb[]
126303 ** array. */
126304 sqlite3ResetAllSchemasOfConnection(db);
126306 return rc;
126309 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
126311 /************** End of vacuum.c **********************************************/
126312 /************** Begin file vtab.c ********************************************/
126314 ** 2006 June 10
126316 ** The author disclaims copyright to this source code. In place of
126317 ** a legal notice, here is a blessing:
126319 ** May you do good and not evil.
126320 ** May you find forgiveness for yourself and forgive others.
126321 ** May you share freely, never taking more than you give.
126323 *************************************************************************
126324 ** This file contains code used to help implement virtual tables.
126326 #ifndef SQLITE_OMIT_VIRTUALTABLE
126327 /* #include "sqliteInt.h" */
126330 ** Before a virtual table xCreate() or xConnect() method is invoked, the
126331 ** sqlite3.pVtabCtx member variable is set to point to an instance of
126332 ** this struct allocated on the stack. It is used by the implementation of
126333 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
126334 ** are invoked only from within xCreate and xConnect methods.
126336 struct VtabCtx {
126337 VTable *pVTable; /* The virtual table being constructed */
126338 Table *pTab; /* The Table object to which the virtual table belongs */
126339 VtabCtx *pPrior; /* Parent context (if any) */
126340 int bDeclared; /* True after sqlite3_declare_vtab() is called */
126344 ** Construct and install a Module object for a virtual table. When this
126345 ** routine is called, it is guaranteed that all appropriate locks are held
126346 ** and the module is not already part of the connection.
126348 SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
126349 sqlite3 *db, /* Database in which module is registered */
126350 const char *zName, /* Name assigned to this module */
126351 const sqlite3_module *pModule, /* The definition of the module */
126352 void *pAux, /* Context pointer for xCreate/xConnect */
126353 void (*xDestroy)(void *) /* Module destructor function */
126355 Module *pMod;
126356 int nName = sqlite3Strlen30(zName);
126357 pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
126358 if( pMod==0 ){
126359 sqlite3OomFault(db);
126360 }else{
126361 Module *pDel;
126362 char *zCopy = (char *)(&pMod[1]);
126363 memcpy(zCopy, zName, nName+1);
126364 pMod->zName = zCopy;
126365 pMod->pModule = pModule;
126366 pMod->pAux = pAux;
126367 pMod->xDestroy = xDestroy;
126368 pMod->pEpoTab = 0;
126369 pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
126370 assert( pDel==0 || pDel==pMod );
126371 if( pDel ){
126372 sqlite3OomFault(db);
126373 sqlite3DbFree(db, pDel);
126374 pMod = 0;
126377 return pMod;
126381 ** The actual function that does the work of creating a new module.
126382 ** This function implements the sqlite3_create_module() and
126383 ** sqlite3_create_module_v2() interfaces.
126385 static int createModule(
126386 sqlite3 *db, /* Database in which module is registered */
126387 const char *zName, /* Name assigned to this module */
126388 const sqlite3_module *pModule, /* The definition of the module */
126389 void *pAux, /* Context pointer for xCreate/xConnect */
126390 void (*xDestroy)(void *) /* Module destructor function */
126392 int rc = SQLITE_OK;
126394 sqlite3_mutex_enter(db->mutex);
126395 if( sqlite3HashFind(&db->aModule, zName) ){
126396 rc = SQLITE_MISUSE_BKPT;
126397 }else{
126398 (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
126400 rc = sqlite3ApiExit(db, rc);
126401 if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
126402 sqlite3_mutex_leave(db->mutex);
126403 return rc;
126408 ** External API function used to create a new virtual-table module.
126410 SQLITE_API int sqlite3_create_module(
126411 sqlite3 *db, /* Database in which module is registered */
126412 const char *zName, /* Name assigned to this module */
126413 const sqlite3_module *pModule, /* The definition of the module */
126414 void *pAux /* Context pointer for xCreate/xConnect */
126416 #ifdef SQLITE_ENABLE_API_ARMOR
126417 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
126418 #endif
126419 return createModule(db, zName, pModule, pAux, 0);
126423 ** External API function used to create a new virtual-table module.
126425 SQLITE_API int sqlite3_create_module_v2(
126426 sqlite3 *db, /* Database in which module is registered */
126427 const char *zName, /* Name assigned to this module */
126428 const sqlite3_module *pModule, /* The definition of the module */
126429 void *pAux, /* Context pointer for xCreate/xConnect */
126430 void (*xDestroy)(void *) /* Module destructor function */
126432 #ifdef SQLITE_ENABLE_API_ARMOR
126433 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
126434 #endif
126435 return createModule(db, zName, pModule, pAux, xDestroy);
126439 ** Lock the virtual table so that it cannot be disconnected.
126440 ** Locks nest. Every lock should have a corresponding unlock.
126441 ** If an unlock is omitted, resources leaks will occur.
126443 ** If a disconnect is attempted while a virtual table is locked,
126444 ** the disconnect is deferred until all locks have been removed.
126446 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
126447 pVTab->nRef++;
126452 ** pTab is a pointer to a Table structure representing a virtual-table.
126453 ** Return a pointer to the VTable object used by connection db to access
126454 ** this virtual-table, if one has been created, or NULL otherwise.
126456 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
126457 VTable *pVtab;
126458 assert( IsVirtual(pTab) );
126459 for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
126460 return pVtab;
126464 ** Decrement the ref-count on a virtual table object. When the ref-count
126465 ** reaches zero, call the xDisconnect() method to delete the object.
126467 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
126468 sqlite3 *db = pVTab->db;
126470 assert( db );
126471 assert( pVTab->nRef>0 );
126472 assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
126474 pVTab->nRef--;
126475 if( pVTab->nRef==0 ){
126476 sqlite3_vtab *p = pVTab->pVtab;
126477 if( p ){
126478 p->pModule->xDisconnect(p);
126480 sqlite3DbFree(db, pVTab);
126485 ** Table p is a virtual table. This function moves all elements in the
126486 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
126487 ** database connections to be disconnected at the next opportunity.
126488 ** Except, if argument db is not NULL, then the entry associated with
126489 ** connection db is left in the p->pVTable list.
126491 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
126492 VTable *pRet = 0;
126493 VTable *pVTable = p->pVTable;
126494 p->pVTable = 0;
126496 /* Assert that the mutex (if any) associated with the BtShared database
126497 ** that contains table p is held by the caller. See header comments
126498 ** above function sqlite3VtabUnlockList() for an explanation of why
126499 ** this makes it safe to access the sqlite3.pDisconnect list of any
126500 ** database connection that may have an entry in the p->pVTable list.
126502 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
126504 while( pVTable ){
126505 sqlite3 *db2 = pVTable->db;
126506 VTable *pNext = pVTable->pNext;
126507 assert( db2 );
126508 if( db2==db ){
126509 pRet = pVTable;
126510 p->pVTable = pRet;
126511 pRet->pNext = 0;
126512 }else{
126513 pVTable->pNext = db2->pDisconnect;
126514 db2->pDisconnect = pVTable;
126516 pVTable = pNext;
126519 assert( !db || pRet );
126520 return pRet;
126524 ** Table *p is a virtual table. This function removes the VTable object
126525 ** for table *p associated with database connection db from the linked
126526 ** list in p->pVTab. It also decrements the VTable ref count. This is
126527 ** used when closing database connection db to free all of its VTable
126528 ** objects without disturbing the rest of the Schema object (which may
126529 ** be being used by other shared-cache connections).
126531 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
126532 VTable **ppVTab;
126534 assert( IsVirtual(p) );
126535 assert( sqlite3BtreeHoldsAllMutexes(db) );
126536 assert( sqlite3_mutex_held(db->mutex) );
126538 for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
126539 if( (*ppVTab)->db==db ){
126540 VTable *pVTab = *ppVTab;
126541 *ppVTab = pVTab->pNext;
126542 sqlite3VtabUnlock(pVTab);
126543 break;
126550 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
126552 ** This function may only be called when the mutexes associated with all
126553 ** shared b-tree databases opened using connection db are held by the
126554 ** caller. This is done to protect the sqlite3.pDisconnect list. The
126555 ** sqlite3.pDisconnect list is accessed only as follows:
126557 ** 1) By this function. In this case, all BtShared mutexes and the mutex
126558 ** associated with the database handle itself must be held.
126560 ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
126561 ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
126562 ** associated with the database the virtual table is stored in is held
126563 ** or, if the virtual table is stored in a non-sharable database, then
126564 ** the database handle mutex is held.
126566 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
126567 ** by multiple threads. It is thread-safe.
126569 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
126570 VTable *p = db->pDisconnect;
126571 db->pDisconnect = 0;
126573 assert( sqlite3BtreeHoldsAllMutexes(db) );
126574 assert( sqlite3_mutex_held(db->mutex) );
126576 if( p ){
126577 sqlite3ExpirePreparedStatements(db);
126579 VTable *pNext = p->pNext;
126580 sqlite3VtabUnlock(p);
126581 p = pNext;
126582 }while( p );
126587 ** Clear any and all virtual-table information from the Table record.
126588 ** This routine is called, for example, just before deleting the Table
126589 ** record.
126591 ** Since it is a virtual-table, the Table structure contains a pointer
126592 ** to the head of a linked list of VTable structures. Each VTable
126593 ** structure is associated with a single sqlite3* user of the schema.
126594 ** The reference count of the VTable structure associated with database
126595 ** connection db is decremented immediately (which may lead to the
126596 ** structure being xDisconnected and free). Any other VTable structures
126597 ** in the list are moved to the sqlite3.pDisconnect list of the associated
126598 ** database connection.
126600 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
126601 if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
126602 if( p->azModuleArg ){
126603 int i;
126604 for(i=0; i<p->nModuleArg; i++){
126605 if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
126607 sqlite3DbFree(db, p->azModuleArg);
126612 ** Add a new module argument to pTable->azModuleArg[].
126613 ** The string is not copied - the pointer is stored. The
126614 ** string will be freed automatically when the table is
126615 ** deleted.
126617 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
126618 int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
126619 char **azModuleArg;
126620 azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
126621 if( azModuleArg==0 ){
126622 sqlite3DbFree(db, zArg);
126623 }else{
126624 int i = pTable->nModuleArg++;
126625 azModuleArg[i] = zArg;
126626 azModuleArg[i+1] = 0;
126627 pTable->azModuleArg = azModuleArg;
126632 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
126633 ** statement. The module name has been parsed, but the optional list
126634 ** of parameters that follow the module name are still pending.
126636 SQLITE_PRIVATE void sqlite3VtabBeginParse(
126637 Parse *pParse, /* Parsing context */
126638 Token *pName1, /* Name of new table, or database name */
126639 Token *pName2, /* Name of new table or NULL */
126640 Token *pModuleName, /* Name of the module for the virtual table */
126641 int ifNotExists /* No error if the table already exists */
126643 int iDb; /* The database the table is being created in */
126644 Table *pTable; /* The new virtual table */
126645 sqlite3 *db; /* Database connection */
126647 sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
126648 pTable = pParse->pNewTable;
126649 if( pTable==0 ) return;
126650 assert( 0==pTable->pIndex );
126652 db = pParse->db;
126653 iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
126654 assert( iDb>=0 );
126656 assert( pTable->nModuleArg==0 );
126657 addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
126658 addModuleArgument(db, pTable, 0);
126659 addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
126660 assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
126661 || (pParse->sNameToken.z==pName1->z && pName2->z==0)
126663 pParse->sNameToken.n = (int)(
126664 &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
126667 #ifndef SQLITE_OMIT_AUTHORIZATION
126668 /* Creating a virtual table invokes the authorization callback twice.
126669 ** The first invocation, to obtain permission to INSERT a row into the
126670 ** sqlite_master table, has already been made by sqlite3StartTable().
126671 ** The second call, to obtain permission to create the table, is made now.
126673 if( pTable->azModuleArg ){
126674 sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
126675 pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
126677 #endif
126681 ** This routine takes the module argument that has been accumulating
126682 ** in pParse->zArg[] and appends it to the list of arguments on the
126683 ** virtual table currently under construction in pParse->pTable.
126685 static void addArgumentToVtab(Parse *pParse){
126686 if( pParse->sArg.z && pParse->pNewTable ){
126687 const char *z = (const char*)pParse->sArg.z;
126688 int n = pParse->sArg.n;
126689 sqlite3 *db = pParse->db;
126690 addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
126695 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
126696 ** has been completely parsed.
126698 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
126699 Table *pTab = pParse->pNewTable; /* The table being constructed */
126700 sqlite3 *db = pParse->db; /* The database connection */
126702 if( pTab==0 ) return;
126703 addArgumentToVtab(pParse);
126704 pParse->sArg.z = 0;
126705 if( pTab->nModuleArg<1 ) return;
126707 /* If the CREATE VIRTUAL TABLE statement is being entered for the
126708 ** first time (in other words if the virtual table is actually being
126709 ** created now instead of just being read out of sqlite_master) then
126710 ** do additional initialization work and store the statement text
126711 ** in the sqlite_master table.
126713 if( !db->init.busy ){
126714 char *zStmt;
126715 char *zWhere;
126716 int iDb;
126717 int iReg;
126718 Vdbe *v;
126720 /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
126721 if( pEnd ){
126722 pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
126724 zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
126726 /* A slot for the record has already been allocated in the
126727 ** SQLITE_MASTER table. We just need to update that slot with all
126728 ** the information we've collected.
126730 ** The VM register number pParse->regRowid holds the rowid of an
126731 ** entry in the sqlite_master table tht was created for this vtab
126732 ** by sqlite3StartTable().
126734 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
126735 sqlite3NestedParse(pParse,
126736 "UPDATE %Q.%s "
126737 "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
126738 "WHERE rowid=#%d",
126739 db->aDb[iDb].zDbSName, MASTER_NAME,
126740 pTab->zName,
126741 pTab->zName,
126742 zStmt,
126743 pParse->regRowid
126745 sqlite3DbFree(db, zStmt);
126746 v = sqlite3GetVdbe(pParse);
126747 sqlite3ChangeCookie(pParse, iDb);
126749 sqlite3VdbeAddOp0(v, OP_Expire);
126750 zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
126751 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
126753 iReg = ++pParse->nMem;
126754 sqlite3VdbeLoadString(v, iReg, pTab->zName);
126755 sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
126758 /* If we are rereading the sqlite_master table create the in-memory
126759 ** record of the table. The xConnect() method is not called until
126760 ** the first time the virtual table is used in an SQL statement. This
126761 ** allows a schema that contains virtual tables to be loaded before
126762 ** the required virtual table implementations are registered. */
126763 else {
126764 Table *pOld;
126765 Schema *pSchema = pTab->pSchema;
126766 const char *zName = pTab->zName;
126767 assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
126768 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
126769 if( pOld ){
126770 sqlite3OomFault(db);
126771 assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
126772 return;
126774 pParse->pNewTable = 0;
126779 ** The parser calls this routine when it sees the first token
126780 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
126782 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
126783 addArgumentToVtab(pParse);
126784 pParse->sArg.z = 0;
126785 pParse->sArg.n = 0;
126789 ** The parser calls this routine for each token after the first token
126790 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
126792 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
126793 Token *pArg = &pParse->sArg;
126794 if( pArg->z==0 ){
126795 pArg->z = p->z;
126796 pArg->n = p->n;
126797 }else{
126798 assert(pArg->z <= p->z);
126799 pArg->n = (int)(&p->z[p->n] - pArg->z);
126804 ** Invoke a virtual table constructor (either xCreate or xConnect). The
126805 ** pointer to the function to invoke is passed as the fourth parameter
126806 ** to this procedure.
126808 static int vtabCallConstructor(
126809 sqlite3 *db,
126810 Table *pTab,
126811 Module *pMod,
126812 int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
126813 char **pzErr
126815 VtabCtx sCtx;
126816 VTable *pVTable;
126817 int rc;
126818 const char *const*azArg = (const char *const*)pTab->azModuleArg;
126819 int nArg = pTab->nModuleArg;
126820 char *zErr = 0;
126821 char *zModuleName;
126822 int iDb;
126823 VtabCtx *pCtx;
126825 /* Check that the virtual-table is not already being initialized */
126826 for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
126827 if( pCtx->pTab==pTab ){
126828 *pzErr = sqlite3MPrintf(db,
126829 "vtable constructor called recursively: %s", pTab->zName
126831 return SQLITE_LOCKED;
126835 zModuleName = sqlite3DbStrDup(db, pTab->zName);
126836 if( !zModuleName ){
126837 return SQLITE_NOMEM_BKPT;
126840 pVTable = sqlite3MallocZero(sizeof(VTable));
126841 if( !pVTable ){
126842 sqlite3OomFault(db);
126843 sqlite3DbFree(db, zModuleName);
126844 return SQLITE_NOMEM_BKPT;
126846 pVTable->db = db;
126847 pVTable->pMod = pMod;
126849 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
126850 pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
126852 /* Invoke the virtual table constructor */
126853 assert( &db->pVtabCtx );
126854 assert( xConstruct );
126855 sCtx.pTab = pTab;
126856 sCtx.pVTable = pVTable;
126857 sCtx.pPrior = db->pVtabCtx;
126858 sCtx.bDeclared = 0;
126859 db->pVtabCtx = &sCtx;
126860 rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
126861 db->pVtabCtx = sCtx.pPrior;
126862 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
126863 assert( sCtx.pTab==pTab );
126865 if( SQLITE_OK!=rc ){
126866 if( zErr==0 ){
126867 *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
126868 }else {
126869 *pzErr = sqlite3MPrintf(db, "%s", zErr);
126870 sqlite3_free(zErr);
126872 sqlite3DbFree(db, pVTable);
126873 }else if( ALWAYS(pVTable->pVtab) ){
126874 /* Justification of ALWAYS(): A correct vtab constructor must allocate
126875 ** the sqlite3_vtab object if successful. */
126876 memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
126877 pVTable->pVtab->pModule = pMod->pModule;
126878 pVTable->nRef = 1;
126879 if( sCtx.bDeclared==0 ){
126880 const char *zFormat = "vtable constructor did not declare schema: %s";
126881 *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
126882 sqlite3VtabUnlock(pVTable);
126883 rc = SQLITE_ERROR;
126884 }else{
126885 int iCol;
126886 u8 oooHidden = 0;
126887 /* If everything went according to plan, link the new VTable structure
126888 ** into the linked list headed by pTab->pVTable. Then loop through the
126889 ** columns of the table to see if any of them contain the token "hidden".
126890 ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
126891 ** the type string. */
126892 pVTable->pNext = pTab->pVTable;
126893 pTab->pVTable = pVTable;
126895 for(iCol=0; iCol<pTab->nCol; iCol++){
126896 char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
126897 int nType;
126898 int i = 0;
126899 nType = sqlite3Strlen30(zType);
126900 for(i=0; i<nType; i++){
126901 if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
126902 && (i==0 || zType[i-1]==' ')
126903 && (zType[i+6]=='\0' || zType[i+6]==' ')
126905 break;
126908 if( i<nType ){
126909 int j;
126910 int nDel = 6 + (zType[i+6] ? 1 : 0);
126911 for(j=i; (j+nDel)<=nType; j++){
126912 zType[j] = zType[j+nDel];
126914 if( zType[i]=='\0' && i>0 ){
126915 assert(zType[i-1]==' ');
126916 zType[i-1] = '\0';
126918 pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
126919 oooHidden = TF_OOOHidden;
126920 }else{
126921 pTab->tabFlags |= oooHidden;
126927 sqlite3DbFree(db, zModuleName);
126928 return rc;
126932 ** This function is invoked by the parser to call the xConnect() method
126933 ** of the virtual table pTab. If an error occurs, an error code is returned
126934 ** and an error left in pParse.
126936 ** This call is a no-op if table pTab is not a virtual table.
126938 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
126939 sqlite3 *db = pParse->db;
126940 const char *zMod;
126941 Module *pMod;
126942 int rc;
126944 assert( pTab );
126945 if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
126946 return SQLITE_OK;
126949 /* Locate the required virtual table module */
126950 zMod = pTab->azModuleArg[0];
126951 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
126953 if( !pMod ){
126954 const char *zModule = pTab->azModuleArg[0];
126955 sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
126956 rc = SQLITE_ERROR;
126957 }else{
126958 char *zErr = 0;
126959 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
126960 if( rc!=SQLITE_OK ){
126961 sqlite3ErrorMsg(pParse, "%s", zErr);
126962 pParse->rc = rc;
126964 sqlite3DbFree(db, zErr);
126967 return rc;
126970 ** Grow the db->aVTrans[] array so that there is room for at least one
126971 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
126973 static int growVTrans(sqlite3 *db){
126974 const int ARRAY_INCR = 5;
126976 /* Grow the sqlite3.aVTrans array if required */
126977 if( (db->nVTrans%ARRAY_INCR)==0 ){
126978 VTable **aVTrans;
126979 int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
126980 aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
126981 if( !aVTrans ){
126982 return SQLITE_NOMEM_BKPT;
126984 memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
126985 db->aVTrans = aVTrans;
126988 return SQLITE_OK;
126992 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
126993 ** have already been reserved using growVTrans().
126995 static void addToVTrans(sqlite3 *db, VTable *pVTab){
126996 /* Add pVtab to the end of sqlite3.aVTrans */
126997 db->aVTrans[db->nVTrans++] = pVTab;
126998 sqlite3VtabLock(pVTab);
127002 ** This function is invoked by the vdbe to call the xCreate method
127003 ** of the virtual table named zTab in database iDb.
127005 ** If an error occurs, *pzErr is set to point to an English language
127006 ** description of the error and an SQLITE_XXX error code is returned.
127007 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
127009 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
127010 int rc = SQLITE_OK;
127011 Table *pTab;
127012 Module *pMod;
127013 const char *zMod;
127015 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
127016 assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
127018 /* Locate the required virtual table module */
127019 zMod = pTab->azModuleArg[0];
127020 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
127022 /* If the module has been registered and includes a Create method,
127023 ** invoke it now. If the module has not been registered, return an
127024 ** error. Otherwise, do nothing.
127026 if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
127027 *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
127028 rc = SQLITE_ERROR;
127029 }else{
127030 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
127033 /* Justification of ALWAYS(): The xConstructor method is required to
127034 ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
127035 if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
127036 rc = growVTrans(db);
127037 if( rc==SQLITE_OK ){
127038 addToVTrans(db, sqlite3GetVTable(db, pTab));
127042 return rc;
127046 ** This function is used to set the schema of a virtual table. It is only
127047 ** valid to call this function from within the xCreate() or xConnect() of a
127048 ** virtual table module.
127050 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
127051 VtabCtx *pCtx;
127052 int rc = SQLITE_OK;
127053 Table *pTab;
127054 char *zErr = 0;
127055 Parse sParse;
127057 #ifdef SQLITE_ENABLE_API_ARMOR
127058 if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
127059 return SQLITE_MISUSE_BKPT;
127061 #endif
127062 sqlite3_mutex_enter(db->mutex);
127063 pCtx = db->pVtabCtx;
127064 if( !pCtx || pCtx->bDeclared ){
127065 sqlite3Error(db, SQLITE_MISUSE);
127066 sqlite3_mutex_leave(db->mutex);
127067 return SQLITE_MISUSE_BKPT;
127069 pTab = pCtx->pTab;
127070 assert( IsVirtual(pTab) );
127072 memset(&sParse, 0, sizeof(sParse));
127073 sParse.declareVtab = 1;
127074 sParse.db = db;
127075 sParse.nQueryLoop = 1;
127076 if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
127077 && sParse.pNewTable
127078 && !db->mallocFailed
127079 && !sParse.pNewTable->pSelect
127080 && !IsVirtual(sParse.pNewTable)
127082 if( !pTab->aCol ){
127083 Table *pNew = sParse.pNewTable;
127084 Index *pIdx;
127085 pTab->aCol = pNew->aCol;
127086 pTab->nCol = pNew->nCol;
127087 pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
127088 pNew->nCol = 0;
127089 pNew->aCol = 0;
127090 assert( pTab->pIndex==0 );
127091 assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
127092 if( !HasRowid(pNew)
127093 && pCtx->pVTable->pMod->pModule->xUpdate!=0
127094 && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
127096 /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
127097 ** or else must have a single-column PRIMARY KEY */
127098 rc = SQLITE_ERROR;
127100 pIdx = pNew->pIndex;
127101 if( pIdx ){
127102 assert( pIdx->pNext==0 );
127103 pTab->pIndex = pIdx;
127104 pNew->pIndex = 0;
127105 pIdx->pTable = pTab;
127108 pCtx->bDeclared = 1;
127109 }else{
127110 sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
127111 sqlite3DbFree(db, zErr);
127112 rc = SQLITE_ERROR;
127114 sParse.declareVtab = 0;
127116 if( sParse.pVdbe ){
127117 sqlite3VdbeFinalize(sParse.pVdbe);
127119 sqlite3DeleteTable(db, sParse.pNewTable);
127120 sqlite3ParserReset(&sParse);
127122 assert( (rc&0xff)==rc );
127123 rc = sqlite3ApiExit(db, rc);
127124 sqlite3_mutex_leave(db->mutex);
127125 return rc;
127129 ** This function is invoked by the vdbe to call the xDestroy method
127130 ** of the virtual table named zTab in database iDb. This occurs
127131 ** when a DROP TABLE is mentioned.
127133 ** This call is a no-op if zTab is not a virtual table.
127135 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
127136 int rc = SQLITE_OK;
127137 Table *pTab;
127139 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
127140 if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
127141 VTable *p;
127142 int (*xDestroy)(sqlite3_vtab *);
127143 for(p=pTab->pVTable; p; p=p->pNext){
127144 assert( p->pVtab );
127145 if( p->pVtab->nRef>0 ){
127146 return SQLITE_LOCKED;
127149 p = vtabDisconnectAll(db, pTab);
127150 xDestroy = p->pMod->pModule->xDestroy;
127151 assert( xDestroy!=0 ); /* Checked before the virtual table is created */
127152 rc = xDestroy(p->pVtab);
127153 /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
127154 if( rc==SQLITE_OK ){
127155 assert( pTab->pVTable==p && p->pNext==0 );
127156 p->pVtab = 0;
127157 pTab->pVTable = 0;
127158 sqlite3VtabUnlock(p);
127162 return rc;
127166 ** This function invokes either the xRollback or xCommit method
127167 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
127168 ** called is identified by the second argument, "offset", which is
127169 ** the offset of the method to call in the sqlite3_module structure.
127171 ** The array is cleared after invoking the callbacks.
127173 static void callFinaliser(sqlite3 *db, int offset){
127174 int i;
127175 if( db->aVTrans ){
127176 VTable **aVTrans = db->aVTrans;
127177 db->aVTrans = 0;
127178 for(i=0; i<db->nVTrans; i++){
127179 VTable *pVTab = aVTrans[i];
127180 sqlite3_vtab *p = pVTab->pVtab;
127181 if( p ){
127182 int (*x)(sqlite3_vtab *);
127183 x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
127184 if( x ) x(p);
127186 pVTab->iSavepoint = 0;
127187 sqlite3VtabUnlock(pVTab);
127189 sqlite3DbFree(db, aVTrans);
127190 db->nVTrans = 0;
127195 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
127196 ** array. Return the error code for the first error that occurs, or
127197 ** SQLITE_OK if all xSync operations are successful.
127199 ** If an error message is available, leave it in p->zErrMsg.
127201 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
127202 int i;
127203 int rc = SQLITE_OK;
127204 VTable **aVTrans = db->aVTrans;
127206 db->aVTrans = 0;
127207 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
127208 int (*x)(sqlite3_vtab *);
127209 sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
127210 if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
127211 rc = x(pVtab);
127212 sqlite3VtabImportErrmsg(p, pVtab);
127215 db->aVTrans = aVTrans;
127216 return rc;
127220 ** Invoke the xRollback method of all virtual tables in the
127221 ** sqlite3.aVTrans array. Then clear the array itself.
127223 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
127224 callFinaliser(db, offsetof(sqlite3_module,xRollback));
127225 return SQLITE_OK;
127229 ** Invoke the xCommit method of all virtual tables in the
127230 ** sqlite3.aVTrans array. Then clear the array itself.
127232 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
127233 callFinaliser(db, offsetof(sqlite3_module,xCommit));
127234 return SQLITE_OK;
127238 ** If the virtual table pVtab supports the transaction interface
127239 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
127240 ** not currently open, invoke the xBegin method now.
127242 ** If the xBegin call is successful, place the sqlite3_vtab pointer
127243 ** in the sqlite3.aVTrans array.
127245 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
127246 int rc = SQLITE_OK;
127247 const sqlite3_module *pModule;
127249 /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
127250 ** than zero, then this function is being called from within a
127251 ** virtual module xSync() callback. It is illegal to write to
127252 ** virtual module tables in this case, so return SQLITE_LOCKED.
127254 if( sqlite3VtabInSync(db) ){
127255 return SQLITE_LOCKED;
127257 if( !pVTab ){
127258 return SQLITE_OK;
127260 pModule = pVTab->pVtab->pModule;
127262 if( pModule->xBegin ){
127263 int i;
127265 /* If pVtab is already in the aVTrans array, return early */
127266 for(i=0; i<db->nVTrans; i++){
127267 if( db->aVTrans[i]==pVTab ){
127268 return SQLITE_OK;
127272 /* Invoke the xBegin method. If successful, add the vtab to the
127273 ** sqlite3.aVTrans[] array. */
127274 rc = growVTrans(db);
127275 if( rc==SQLITE_OK ){
127276 rc = pModule->xBegin(pVTab->pVtab);
127277 if( rc==SQLITE_OK ){
127278 int iSvpt = db->nStatement + db->nSavepoint;
127279 addToVTrans(db, pVTab);
127280 if( iSvpt && pModule->xSavepoint ){
127281 pVTab->iSavepoint = iSvpt;
127282 rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
127287 return rc;
127291 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
127292 ** virtual tables that currently have an open transaction. Pass iSavepoint
127293 ** as the second argument to the virtual table method invoked.
127295 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
127296 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
127297 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
127298 ** an open transaction is invoked.
127300 ** If any virtual table method returns an error code other than SQLITE_OK,
127301 ** processing is abandoned and the error returned to the caller of this
127302 ** function immediately. If all calls to virtual table methods are successful,
127303 ** SQLITE_OK is returned.
127305 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
127306 int rc = SQLITE_OK;
127308 assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
127309 assert( iSavepoint>=-1 );
127310 if( db->aVTrans ){
127311 int i;
127312 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
127313 VTable *pVTab = db->aVTrans[i];
127314 const sqlite3_module *pMod = pVTab->pMod->pModule;
127315 if( pVTab->pVtab && pMod->iVersion>=2 ){
127316 int (*xMethod)(sqlite3_vtab *, int);
127317 switch( op ){
127318 case SAVEPOINT_BEGIN:
127319 xMethod = pMod->xSavepoint;
127320 pVTab->iSavepoint = iSavepoint+1;
127321 break;
127322 case SAVEPOINT_ROLLBACK:
127323 xMethod = pMod->xRollbackTo;
127324 break;
127325 default:
127326 xMethod = pMod->xRelease;
127327 break;
127329 if( xMethod && pVTab->iSavepoint>iSavepoint ){
127330 rc = xMethod(pVTab->pVtab, iSavepoint);
127335 return rc;
127339 ** The first parameter (pDef) is a function implementation. The
127340 ** second parameter (pExpr) is the first argument to this function.
127341 ** If pExpr is a column in a virtual table, then let the virtual
127342 ** table implementation have an opportunity to overload the function.
127344 ** This routine is used to allow virtual table implementations to
127345 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
127347 ** Return either the pDef argument (indicating no change) or a
127348 ** new FuncDef structure that is marked as ephemeral using the
127349 ** SQLITE_FUNC_EPHEM flag.
127351 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
127352 sqlite3 *db, /* Database connection for reporting malloc problems */
127353 FuncDef *pDef, /* Function to possibly overload */
127354 int nArg, /* Number of arguments to the function */
127355 Expr *pExpr /* First argument to the function */
127357 Table *pTab;
127358 sqlite3_vtab *pVtab;
127359 sqlite3_module *pMod;
127360 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
127361 void *pArg = 0;
127362 FuncDef *pNew;
127363 int rc = 0;
127364 char *zLowerName;
127365 unsigned char *z;
127368 /* Check to see the left operand is a column in a virtual table */
127369 if( NEVER(pExpr==0) ) return pDef;
127370 if( pExpr->op!=TK_COLUMN ) return pDef;
127371 pTab = pExpr->pTab;
127372 if( pTab==0 ) return pDef;
127373 if( !IsVirtual(pTab) ) return pDef;
127374 pVtab = sqlite3GetVTable(db, pTab)->pVtab;
127375 assert( pVtab!=0 );
127376 assert( pVtab->pModule!=0 );
127377 pMod = (sqlite3_module *)pVtab->pModule;
127378 if( pMod->xFindFunction==0 ) return pDef;
127380 /* Call the xFindFunction method on the virtual table implementation
127381 ** to see if the implementation wants to overload this function
127383 zLowerName = sqlite3DbStrDup(db, pDef->zName);
127384 if( zLowerName ){
127385 for(z=(unsigned char*)zLowerName; *z; z++){
127386 *z = sqlite3UpperToLower[*z];
127388 rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
127389 sqlite3DbFree(db, zLowerName);
127391 if( rc==0 ){
127392 return pDef;
127395 /* Create a new ephemeral function definition for the overloaded
127396 ** function */
127397 pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
127398 + sqlite3Strlen30(pDef->zName) + 1);
127399 if( pNew==0 ){
127400 return pDef;
127402 *pNew = *pDef;
127403 pNew->zName = (const char*)&pNew[1];
127404 memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
127405 pNew->xSFunc = xSFunc;
127406 pNew->pUserData = pArg;
127407 pNew->funcFlags |= SQLITE_FUNC_EPHEM;
127408 return pNew;
127412 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
127413 ** array so that an OP_VBegin will get generated for it. Add pTab to the
127414 ** array if it is missing. If pTab is already in the array, this routine
127415 ** is a no-op.
127417 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
127418 Parse *pToplevel = sqlite3ParseToplevel(pParse);
127419 int i, n;
127420 Table **apVtabLock;
127422 assert( IsVirtual(pTab) );
127423 for(i=0; i<pToplevel->nVtabLock; i++){
127424 if( pTab==pToplevel->apVtabLock[i] ) return;
127426 n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
127427 apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
127428 if( apVtabLock ){
127429 pToplevel->apVtabLock = apVtabLock;
127430 pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
127431 }else{
127432 sqlite3OomFault(pToplevel->db);
127437 ** Check to see if virtual table module pMod can be have an eponymous
127438 ** virtual table instance. If it can, create one if one does not already
127439 ** exist. Return non-zero if the eponymous virtual table instance exists
127440 ** when this routine returns, and return zero if it does not exist.
127442 ** An eponymous virtual table instance is one that is named after its
127443 ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
127444 ** statement in order to come into existance. Eponymous virtual table
127445 ** instances always exist. They cannot be DROP-ed.
127447 ** Any virtual table module for which xConnect and xCreate are the same
127448 ** method can have an eponymous virtual table instance.
127450 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
127451 const sqlite3_module *pModule = pMod->pModule;
127452 Table *pTab;
127453 char *zErr = 0;
127454 int rc;
127455 sqlite3 *db = pParse->db;
127456 if( pMod->pEpoTab ) return 1;
127457 if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
127458 pTab = sqlite3DbMallocZero(db, sizeof(Table));
127459 if( pTab==0 ) return 0;
127460 pTab->zName = sqlite3DbStrDup(db, pMod->zName);
127461 if( pTab->zName==0 ){
127462 sqlite3DbFree(db, pTab);
127463 return 0;
127465 pMod->pEpoTab = pTab;
127466 pTab->nTabRef = 1;
127467 pTab->pSchema = db->aDb[0].pSchema;
127468 assert( pTab->nModuleArg==0 );
127469 pTab->iPKey = -1;
127470 addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
127471 addModuleArgument(db, pTab, 0);
127472 addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
127473 rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
127474 if( rc ){
127475 sqlite3ErrorMsg(pParse, "%s", zErr);
127476 sqlite3DbFree(db, zErr);
127477 sqlite3VtabEponymousTableClear(db, pMod);
127478 return 0;
127480 return 1;
127484 ** Erase the eponymous virtual table instance associated with
127485 ** virtual table module pMod, if it exists.
127487 SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
127488 Table *pTab = pMod->pEpoTab;
127489 if( pTab!=0 ){
127490 /* Mark the table as Ephemeral prior to deleting it, so that the
127491 ** sqlite3DeleteTable() routine will know that it is not stored in
127492 ** the schema. */
127493 pTab->tabFlags |= TF_Ephemeral;
127494 sqlite3DeleteTable(db, pTab);
127495 pMod->pEpoTab = 0;
127500 ** Return the ON CONFLICT resolution mode in effect for the virtual
127501 ** table update operation currently in progress.
127503 ** The results of this routine are undefined unless it is called from
127504 ** within an xUpdate method.
127506 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
127507 static const unsigned char aMap[] = {
127508 SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
127510 #ifdef SQLITE_ENABLE_API_ARMOR
127511 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
127512 #endif
127513 assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
127514 assert( OE_Ignore==4 && OE_Replace==5 );
127515 assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
127516 return (int)aMap[db->vtabOnConflict-1];
127520 ** Call from within the xCreate() or xConnect() methods to provide
127521 ** the SQLite core with additional information about the behavior
127522 ** of the virtual table being implemented.
127524 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
127525 va_list ap;
127526 int rc = SQLITE_OK;
127528 #ifdef SQLITE_ENABLE_API_ARMOR
127529 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
127530 #endif
127531 sqlite3_mutex_enter(db->mutex);
127532 va_start(ap, op);
127533 switch( op ){
127534 case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
127535 VtabCtx *p = db->pVtabCtx;
127536 if( !p ){
127537 rc = SQLITE_MISUSE_BKPT;
127538 }else{
127539 assert( p->pTab==0 || IsVirtual(p->pTab) );
127540 p->pVTable->bConstraint = (u8)va_arg(ap, int);
127542 break;
127544 default:
127545 rc = SQLITE_MISUSE_BKPT;
127546 break;
127548 va_end(ap);
127550 if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
127551 sqlite3_mutex_leave(db->mutex);
127552 return rc;
127555 #endif /* SQLITE_OMIT_VIRTUALTABLE */
127557 /************** End of vtab.c ************************************************/
127558 /************** Begin file wherecode.c ***************************************/
127560 ** 2015-06-06
127562 ** The author disclaims copyright to this source code. In place of
127563 ** a legal notice, here is a blessing:
127565 ** May you do good and not evil.
127566 ** May you find forgiveness for yourself and forgive others.
127567 ** May you share freely, never taking more than you give.
127569 *************************************************************************
127570 ** This module contains C code that generates VDBE code used to process
127571 ** the WHERE clause of SQL statements.
127573 ** This file was split off from where.c on 2015-06-06 in order to reduce the
127574 ** size of where.c and make it easier to edit. This file contains the routines
127575 ** that actually generate the bulk of the WHERE loop code. The original where.c
127576 ** file retains the code that does query planning and analysis.
127578 /* #include "sqliteInt.h" */
127579 /************** Include whereInt.h in the middle of wherecode.c **************/
127580 /************** Begin file whereInt.h ****************************************/
127582 ** 2013-11-12
127584 ** The author disclaims copyright to this source code. In place of
127585 ** a legal notice, here is a blessing:
127587 ** May you do good and not evil.
127588 ** May you find forgiveness for yourself and forgive others.
127589 ** May you share freely, never taking more than you give.
127591 *************************************************************************
127593 ** This file contains structure and macro definitions for the query
127594 ** planner logic in "where.c". These definitions are broken out into
127595 ** a separate source file for easier editing.
127599 ** Trace output macros
127601 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
127602 /***/ int sqlite3WhereTrace;
127603 #endif
127604 #if defined(SQLITE_DEBUG) \
127605 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
127606 # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
127607 # define WHERETRACE_ENABLED 1
127608 #else
127609 # define WHERETRACE(K,X)
127610 #endif
127612 /* Forward references
127614 typedef struct WhereClause WhereClause;
127615 typedef struct WhereMaskSet WhereMaskSet;
127616 typedef struct WhereOrInfo WhereOrInfo;
127617 typedef struct WhereAndInfo WhereAndInfo;
127618 typedef struct WhereLevel WhereLevel;
127619 typedef struct WhereLoop WhereLoop;
127620 typedef struct WherePath WherePath;
127621 typedef struct WhereTerm WhereTerm;
127622 typedef struct WhereLoopBuilder WhereLoopBuilder;
127623 typedef struct WhereScan WhereScan;
127624 typedef struct WhereOrCost WhereOrCost;
127625 typedef struct WhereOrSet WhereOrSet;
127628 ** This object contains information needed to implement a single nested
127629 ** loop in WHERE clause.
127631 ** Contrast this object with WhereLoop. This object describes the
127632 ** implementation of the loop. WhereLoop describes the algorithm.
127633 ** This object contains a pointer to the WhereLoop algorithm as one of
127634 ** its elements.
127636 ** The WhereInfo object contains a single instance of this object for
127637 ** each term in the FROM clause (which is to say, for each of the
127638 ** nested loops as implemented). The order of WhereLevel objects determines
127639 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
127640 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
127642 struct WhereLevel {
127643 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
127644 int iTabCur; /* The VDBE cursor used to access the table */
127645 int iIdxCur; /* The VDBE cursor used to access pIdx */
127646 int addrBrk; /* Jump here to break out of the loop */
127647 int addrNxt; /* Jump here to start the next IN combination */
127648 int addrSkip; /* Jump here for next iteration of skip-scan */
127649 int addrCont; /* Jump here to continue with the next loop cycle */
127650 int addrFirst; /* First instruction of interior of the loop */
127651 int addrBody; /* Beginning of the body of this loop */
127652 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
127653 u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
127654 int addrLikeRep; /* LIKE range processing address */
127655 #endif
127656 u8 iFrom; /* Which entry in the FROM clause */
127657 u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
127658 int p1, p2; /* Operands of the opcode used to ends the loop */
127659 union { /* Information that depends on pWLoop->wsFlags */
127660 struct {
127661 int nIn; /* Number of entries in aInLoop[] */
127662 struct InLoop {
127663 int iCur; /* The VDBE cursor used by this IN operator */
127664 int addrInTop; /* Top of the IN loop */
127665 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
127666 } *aInLoop; /* Information about each nested IN operator */
127667 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
127668 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
127670 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
127671 Bitmask notReady; /* FROM entries not usable at this level */
127672 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
127673 int addrVisit; /* Address at which row is visited */
127674 #endif
127678 ** Each instance of this object represents an algorithm for evaluating one
127679 ** term of a join. Every term of the FROM clause will have at least
127680 ** one corresponding WhereLoop object (unless INDEXED BY constraints
127681 ** prevent a query solution - which is an error) and many terms of the
127682 ** FROM clause will have multiple WhereLoop objects, each describing a
127683 ** potential way of implementing that FROM-clause term, together with
127684 ** dependencies and cost estimates for using the chosen algorithm.
127686 ** Query planning consists of building up a collection of these WhereLoop
127687 ** objects, then computing a particular sequence of WhereLoop objects, with
127688 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
127689 ** and that minimize the overall cost.
127691 struct WhereLoop {
127692 Bitmask prereq; /* Bitmask of other loops that must run first */
127693 Bitmask maskSelf; /* Bitmask identifying table iTab */
127694 #ifdef SQLITE_DEBUG
127695 char cId; /* Symbolic ID of this loop for debugging use */
127696 #endif
127697 u8 iTab; /* Position in FROM clause of table for this loop */
127698 u8 iSortIdx; /* Sorting index number. 0==None */
127699 LogEst rSetup; /* One-time setup cost (ex: create transient index) */
127700 LogEst rRun; /* Cost of running each loop */
127701 LogEst nOut; /* Estimated number of output rows */
127702 union {
127703 struct { /* Information for internal btree tables */
127704 u16 nEq; /* Number of equality constraints */
127705 u16 nBtm; /* Size of BTM vector */
127706 u16 nTop; /* Size of TOP vector */
127707 u16 nIdxCol; /* Index column used for ORDER BY */
127708 Index *pIndex; /* Index used, or NULL */
127709 } btree;
127710 struct { /* Information for virtual tables */
127711 int idxNum; /* Index number */
127712 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
127713 i8 isOrdered; /* True if satisfies ORDER BY */
127714 u16 omitMask; /* Terms that may be omitted */
127715 char *idxStr; /* Index identifier string */
127716 } vtab;
127718 u32 wsFlags; /* WHERE_* flags describing the plan */
127719 u16 nLTerm; /* Number of entries in aLTerm[] */
127720 u16 nSkip; /* Number of NULL aLTerm[] entries */
127721 /**** whereLoopXfer() copies fields above ***********************/
127722 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
127723 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
127724 WhereTerm **aLTerm; /* WhereTerms used */
127725 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
127726 WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
127729 /* This object holds the prerequisites and the cost of running a
127730 ** subquery on one operand of an OR operator in the WHERE clause.
127731 ** See WhereOrSet for additional information
127733 struct WhereOrCost {
127734 Bitmask prereq; /* Prerequisites */
127735 LogEst rRun; /* Cost of running this subquery */
127736 LogEst nOut; /* Number of outputs for this subquery */
127739 /* The WhereOrSet object holds a set of possible WhereOrCosts that
127740 ** correspond to the subquery(s) of OR-clause processing. Only the
127741 ** best N_OR_COST elements are retained.
127743 #define N_OR_COST 3
127744 struct WhereOrSet {
127745 u16 n; /* Number of valid a[] entries */
127746 WhereOrCost a[N_OR_COST]; /* Set of best costs */
127750 ** Each instance of this object holds a sequence of WhereLoop objects
127751 ** that implement some or all of a query plan.
127753 ** Think of each WhereLoop object as a node in a graph with arcs
127754 ** showing dependencies and costs for travelling between nodes. (That is
127755 ** not a completely accurate description because WhereLoop costs are a
127756 ** vector, not a scalar, and because dependencies are many-to-one, not
127757 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
127758 ** Then a WherePath object is a path through the graph that visits some
127759 ** or all of the WhereLoop objects once.
127761 ** The "solver" works by creating the N best WherePath objects of length
127762 ** 1. Then using those as a basis to compute the N best WherePath objects
127763 ** of length 2. And so forth until the length of WherePaths equals the
127764 ** number of nodes in the FROM clause. The best (lowest cost) WherePath
127765 ** at the end is the chosen query plan.
127767 struct WherePath {
127768 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
127769 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
127770 LogEst nRow; /* Estimated number of rows generated by this path */
127771 LogEst rCost; /* Total cost of this path */
127772 LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
127773 i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
127774 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
127778 ** The query generator uses an array of instances of this structure to
127779 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
127780 ** clause subexpression is separated from the others by AND operators,
127781 ** usually, or sometimes subexpressions separated by OR.
127783 ** All WhereTerms are collected into a single WhereClause structure.
127784 ** The following identity holds:
127786 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
127788 ** When a term is of the form:
127790 ** X <op> <expr>
127792 ** where X is a column name and <op> is one of certain operators,
127793 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
127794 ** cursor number and column number for X. WhereTerm.eOperator records
127795 ** the <op> using a bitmask encoding defined by WO_xxx below. The
127796 ** use of a bitmask encoding for the operator allows us to search
127797 ** quickly for terms that match any of several different operators.
127799 ** A WhereTerm might also be two or more subterms connected by OR:
127801 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
127803 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
127804 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
127805 ** is collected about the OR clause.
127807 ** If a term in the WHERE clause does not match either of the two previous
127808 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
127809 ** to the original subexpression content and wtFlags is set up appropriately
127810 ** but no other fields in the WhereTerm object are meaningful.
127812 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
127813 ** but they do so indirectly. A single WhereMaskSet structure translates
127814 ** cursor number into bits and the translated bit is stored in the prereq
127815 ** fields. The translation is used in order to maximize the number of
127816 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
127817 ** spread out over the non-negative integers. For example, the cursor
127818 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
127819 ** translates these sparse cursor numbers into consecutive integers
127820 ** beginning with 0 in order to make the best possible use of the available
127821 ** bits in the Bitmask. So, in the example above, the cursor numbers
127822 ** would be mapped into integers 0 through 7.
127824 ** The number of terms in a join is limited by the number of bits
127825 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
127826 ** is only able to process joins with 64 or fewer tables.
127828 struct WhereTerm {
127829 Expr *pExpr; /* Pointer to the subexpression that is this term */
127830 WhereClause *pWC; /* The clause this term is part of */
127831 LogEst truthProb; /* Probability of truth for this expression */
127832 u16 wtFlags; /* TERM_xxx bit flags. See below */
127833 u16 eOperator; /* A WO_xx value describing <op> */
127834 u8 nChild; /* Number of children that must disable us */
127835 u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
127836 int iParent; /* Disable pWC->a[iParent] when this term disabled */
127837 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
127838 int iField; /* Field in (?,?,?) IN (SELECT...) vector */
127839 union {
127840 int leftColumn; /* Column number of X in "X <op> <expr>" */
127841 WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
127842 WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
127844 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
127845 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
127849 ** Allowed values of WhereTerm.wtFlags
127851 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
127852 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
127853 #define TERM_CODED 0x04 /* This term is already coded */
127854 #define TERM_COPIED 0x08 /* Has a child */
127855 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
127856 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
127857 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
127858 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127859 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
127860 #else
127861 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
127862 #endif
127863 #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
127864 #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
127865 #define TERM_LIKE 0x400 /* The original LIKE operator */
127866 #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
127867 #define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */
127870 ** An instance of the WhereScan object is used as an iterator for locating
127871 ** terms in the WHERE clause that are useful to the query planner.
127873 struct WhereScan {
127874 WhereClause *pOrigWC; /* Original, innermost WhereClause */
127875 WhereClause *pWC; /* WhereClause currently being scanned */
127876 const char *zCollName; /* Required collating sequence, if not NULL */
127877 Expr *pIdxExpr; /* Search for this index expression */
127878 char idxaff; /* Must match this affinity, if zCollName!=NULL */
127879 unsigned char nEquiv; /* Number of entries in aEquiv[] */
127880 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
127881 u32 opMask; /* Acceptable operators */
127882 int k; /* Resume scanning at this->pWC->a[this->k] */
127883 int aiCur[11]; /* Cursors in the equivalence class */
127884 i16 aiColumn[11]; /* Corresponding column number in the eq-class */
127888 ** An instance of the following structure holds all information about a
127889 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
127891 ** Explanation of pOuter: For a WHERE clause of the form
127893 ** a AND ((b AND c) OR (d AND e)) AND f
127895 ** There are separate WhereClause objects for the whole clause and for
127896 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
127897 ** subclauses points to the WhereClause object for the whole clause.
127899 struct WhereClause {
127900 WhereInfo *pWInfo; /* WHERE clause processing context */
127901 WhereClause *pOuter; /* Outer conjunction */
127902 u8 op; /* Split operator. TK_AND or TK_OR */
127903 int nTerm; /* Number of terms */
127904 int nSlot; /* Number of entries in a[] */
127905 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
127906 #if defined(SQLITE_SMALL_STACK)
127907 WhereTerm aStatic[1]; /* Initial static space for a[] */
127908 #else
127909 WhereTerm aStatic[8]; /* Initial static space for a[] */
127910 #endif
127914 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
127915 ** a dynamically allocated instance of the following structure.
127917 struct WhereOrInfo {
127918 WhereClause wc; /* Decomposition into subterms */
127919 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
127923 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
127924 ** a dynamically allocated instance of the following structure.
127926 struct WhereAndInfo {
127927 WhereClause wc; /* The subexpression broken out */
127931 ** An instance of the following structure keeps track of a mapping
127932 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
127934 ** The VDBE cursor numbers are small integers contained in
127935 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
127936 ** clause, the cursor numbers might not begin with 0 and they might
127937 ** contain gaps in the numbering sequence. But we want to make maximum
127938 ** use of the bits in our bitmasks. This structure provides a mapping
127939 ** from the sparse cursor numbers into consecutive integers beginning
127940 ** with 0.
127942 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
127943 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
127945 ** For example, if the WHERE clause expression used these VDBE
127946 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
127947 ** would map those cursor numbers into bits 0 through 5.
127949 ** Note that the mapping is not necessarily ordered. In the example
127950 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
127951 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
127952 ** does not really matter. What is important is that sparse cursor
127953 ** numbers all get mapped into bit numbers that begin with 0 and contain
127954 ** no gaps.
127956 struct WhereMaskSet {
127957 int bVarSelect; /* Used by sqlite3WhereExprUsage() */
127958 int n; /* Number of assigned cursor values */
127959 int ix[BMS]; /* Cursor assigned to each bit */
127963 ** Initialize a WhereMaskSet object
127965 #define initMaskSet(P) (P)->n=0
127968 ** This object is a convenience wrapper holding all information needed
127969 ** to construct WhereLoop objects for a particular query.
127971 struct WhereLoopBuilder {
127972 WhereInfo *pWInfo; /* Information about this WHERE */
127973 WhereClause *pWC; /* WHERE clause terms */
127974 ExprList *pOrderBy; /* ORDER BY clause */
127975 WhereLoop *pNew; /* Template WhereLoop */
127976 WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
127977 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127978 UnpackedRecord *pRec; /* Probe for stat4 (if required) */
127979 int nRecValid; /* Number of valid fields currently in pRec */
127980 #endif
127981 unsigned int bldFlags; /* SQLITE_BLDF_* flags */
127984 /* Allowed values for WhereLoopBuider.bldFlags */
127985 #define SQLITE_BLDF_INDEXED 0x0001 /* An index is used */
127986 #define SQLITE_BLDF_UNIQUE 0x0002 /* All keys of a UNIQUE index used */
127989 ** The WHERE clause processing routine has two halves. The
127990 ** first part does the start of the WHERE loop and the second
127991 ** half does the tail of the WHERE loop. An instance of
127992 ** this structure is returned by the first half and passed
127993 ** into the second half to give some continuity.
127995 ** An instance of this object holds the complete state of the query
127996 ** planner.
127998 struct WhereInfo {
127999 Parse *pParse; /* Parsing and code generating context */
128000 SrcList *pTabList; /* List of tables in the join */
128001 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
128002 ExprList *pResultSet; /* Result set of the query */
128003 Expr *pWhere; /* The complete WHERE clause */
128004 LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
128005 int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
128006 int iContinue; /* Jump here to continue with next record */
128007 int iBreak; /* Jump here to break out of the loop */
128008 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
128009 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
128010 u8 nLevel; /* Number of nested loop */
128011 i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
128012 u8 sorted; /* True if really sorted (not just grouped) */
128013 u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
128014 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
128015 u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
128016 u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */
128017 int iTop; /* The very beginning of the WHERE loop */
128018 WhereLoop *pLoops; /* List of all WhereLoop objects */
128019 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
128020 LogEst nRowOut; /* Estimated number of output rows */
128021 WhereClause sWC; /* Decomposition of the WHERE clause */
128022 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
128023 WhereLevel a[1]; /* Information about each nest loop in WHERE */
128027 ** Private interfaces - callable only by other where.c routines.
128029 ** where.c:
128031 SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
128032 #ifdef WHERETRACE_ENABLED
128033 SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
128034 #endif
128035 SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
128036 WhereClause *pWC, /* The WHERE clause to be searched */
128037 int iCur, /* Cursor number of LHS */
128038 int iColumn, /* Column number of LHS */
128039 Bitmask notReady, /* RHS must not overlap with this mask */
128040 u32 op, /* Mask of WO_xx values describing operator */
128041 Index *pIdx /* Must be compatible with this index, if not NULL */
128044 /* wherecode.c: */
128045 #ifndef SQLITE_OMIT_EXPLAIN
128046 SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
128047 Parse *pParse, /* Parse context */
128048 SrcList *pTabList, /* Table list this loop refers to */
128049 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
128050 int iLevel, /* Value for "level" column of output */
128051 int iFrom, /* Value for "from" column of output */
128052 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
128054 #else
128055 # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
128056 #endif /* SQLITE_OMIT_EXPLAIN */
128057 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
128058 SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
128059 Vdbe *v, /* Vdbe to add scanstatus entry to */
128060 SrcList *pSrclist, /* FROM clause pLvl reads data from */
128061 WhereLevel *pLvl, /* Level to add scanstatus() entry for */
128062 int addrExplain /* Address of OP_Explain (or 0) */
128064 #else
128065 # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
128066 #endif
128067 SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
128068 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
128069 int iLevel, /* Which level of pWInfo->a[] should be coded */
128070 Bitmask notReady /* Which tables are currently available */
128073 /* whereexpr.c: */
128074 SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
128075 SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
128076 SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
128077 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
128078 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
128079 SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
128080 SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
128087 ** Bitmasks for the operators on WhereTerm objects. These are all
128088 ** operators that are of interest to the query planner. An
128089 ** OR-ed combination of these values can be used when searching for
128090 ** particular WhereTerms within a WhereClause.
128092 ** Value constraints:
128093 ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
128094 ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
128095 ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
128096 ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
128097 ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
128099 #define WO_IN 0x0001
128100 #define WO_EQ 0x0002
128101 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
128102 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
128103 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
128104 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
128105 #define WO_AUX 0x0040 /* Op useful to virtual tables only */
128106 #define WO_IS 0x0080
128107 #define WO_ISNULL 0x0100
128108 #define WO_OR 0x0200 /* Two or more OR-connected terms */
128109 #define WO_AND 0x0400 /* Two or more AND-connected terms */
128110 #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
128111 #define WO_NOOP 0x1000 /* This term does not restrict search space */
128113 #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
128114 #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
128117 ** These are definitions of bits in the WhereLoop.wsFlags field.
128118 ** The particular combination of bits in each WhereLoop help to
128119 ** determine the algorithm that WhereLoop represents.
128121 #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
128122 #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
128123 #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
128124 #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
128125 #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
128126 #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
128127 #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
128128 #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
128129 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
128130 #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
128131 #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
128132 #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
128133 #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
128134 #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
128135 #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
128136 #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
128137 #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
128138 #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
128139 #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
128141 /************** End of whereInt.h ********************************************/
128142 /************** Continuing where we left off in wherecode.c ******************/
128144 #ifndef SQLITE_OMIT_EXPLAIN
128147 ** Return the name of the i-th column of the pIdx index.
128149 static const char *explainIndexColumnName(Index *pIdx, int i){
128150 i = pIdx->aiColumn[i];
128151 if( i==XN_EXPR ) return "<expr>";
128152 if( i==XN_ROWID ) return "rowid";
128153 return pIdx->pTable->aCol[i].zName;
128157 ** This routine is a helper for explainIndexRange() below
128159 ** pStr holds the text of an expression that we are building up one term
128160 ** at a time. This routine adds a new term to the end of the expression.
128161 ** Terms are separated by AND so add the "AND" text for second and subsequent
128162 ** terms only.
128164 static void explainAppendTerm(
128165 StrAccum *pStr, /* The text expression being built */
128166 Index *pIdx, /* Index to read column names from */
128167 int nTerm, /* Number of terms */
128168 int iTerm, /* Zero-based index of first term. */
128169 int bAnd, /* Non-zero to append " AND " */
128170 const char *zOp /* Name of the operator */
128172 int i;
128174 assert( nTerm>=1 );
128175 if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
128177 if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
128178 for(i=0; i<nTerm; i++){
128179 if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
128180 sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
128182 if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
128184 sqlite3StrAccumAppend(pStr, zOp, 1);
128186 if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
128187 for(i=0; i<nTerm; i++){
128188 if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
128189 sqlite3StrAccumAppend(pStr, "?", 1);
128191 if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
128195 ** Argument pLevel describes a strategy for scanning table pTab. This
128196 ** function appends text to pStr that describes the subset of table
128197 ** rows scanned by the strategy in the form of an SQL expression.
128199 ** For example, if the query:
128201 ** SELECT * FROM t1 WHERE a=1 AND b>2;
128203 ** is run and there is an index on (a, b), then this function returns a
128204 ** string similar to:
128206 ** "a=? AND b>?"
128208 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
128209 Index *pIndex = pLoop->u.btree.pIndex;
128210 u16 nEq = pLoop->u.btree.nEq;
128211 u16 nSkip = pLoop->nSkip;
128212 int i, j;
128214 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
128215 sqlite3StrAccumAppend(pStr, " (", 2);
128216 for(i=0; i<nEq; i++){
128217 const char *z = explainIndexColumnName(pIndex, i);
128218 if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
128219 sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
128222 j = i;
128223 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
128224 explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
128225 i = 1;
128227 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
128228 explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
128230 sqlite3StrAccumAppend(pStr, ")", 1);
128234 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
128235 ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
128236 ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
128237 ** is added to the output to describe the table scan strategy in pLevel.
128239 ** If an OP_Explain opcode is added to the VM, its address is returned.
128240 ** Otherwise, if no OP_Explain is coded, zero is returned.
128242 SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
128243 Parse *pParse, /* Parse context */
128244 SrcList *pTabList, /* Table list this loop refers to */
128245 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
128246 int iLevel, /* Value for "level" column of output */
128247 int iFrom, /* Value for "from" column of output */
128248 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
128250 int ret = 0;
128251 #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
128252 if( pParse->explain==2 )
128253 #endif
128255 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
128256 Vdbe *v = pParse->pVdbe; /* VM being constructed */
128257 sqlite3 *db = pParse->db; /* Database handle */
128258 int iId = pParse->iSelectId; /* Select id (left-most output column) */
128259 int isSearch; /* True for a SEARCH. False for SCAN. */
128260 WhereLoop *pLoop; /* The controlling WhereLoop object */
128261 u32 flags; /* Flags that describe this loop */
128262 char *zMsg; /* Text to add to EQP output */
128263 StrAccum str; /* EQP output string */
128264 char zBuf[100]; /* Initial space for EQP output string */
128266 pLoop = pLevel->pWLoop;
128267 flags = pLoop->wsFlags;
128268 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
128270 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
128271 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
128272 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
128274 sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
128275 sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
128276 if( pItem->pSelect ){
128277 sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
128278 }else{
128279 sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
128282 if( pItem->zAlias ){
128283 sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
128285 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
128286 const char *zFmt = 0;
128287 Index *pIdx;
128289 assert( pLoop->u.btree.pIndex!=0 );
128290 pIdx = pLoop->u.btree.pIndex;
128291 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
128292 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
128293 if( isSearch ){
128294 zFmt = "PRIMARY KEY";
128296 }else if( flags & WHERE_PARTIALIDX ){
128297 zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
128298 }else if( flags & WHERE_AUTO_INDEX ){
128299 zFmt = "AUTOMATIC COVERING INDEX";
128300 }else if( flags & WHERE_IDX_ONLY ){
128301 zFmt = "COVERING INDEX %s";
128302 }else{
128303 zFmt = "INDEX %s";
128305 if( zFmt ){
128306 sqlite3StrAccumAppend(&str, " USING ", 7);
128307 sqlite3XPrintf(&str, zFmt, pIdx->zName);
128308 explainIndexRange(&str, pLoop);
128310 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
128311 const char *zRangeOp;
128312 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
128313 zRangeOp = "=";
128314 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
128315 zRangeOp = ">? AND rowid<";
128316 }else if( flags&WHERE_BTM_LIMIT ){
128317 zRangeOp = ">";
128318 }else{
128319 assert( flags&WHERE_TOP_LIMIT);
128320 zRangeOp = "<";
128322 sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
128324 #ifndef SQLITE_OMIT_VIRTUALTABLE
128325 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
128326 sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
128327 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
128329 #endif
128330 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
128331 if( pLoop->nOut>=10 ){
128332 sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
128333 }else{
128334 sqlite3StrAccumAppend(&str, " (~1 row)", 9);
128336 #endif
128337 zMsg = sqlite3StrAccumFinish(&str);
128338 ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
128340 return ret;
128342 #endif /* SQLITE_OMIT_EXPLAIN */
128344 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
128346 ** Configure the VM passed as the first argument with an
128347 ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
128348 ** implement level pLvl. Argument pSrclist is a pointer to the FROM
128349 ** clause that the scan reads data from.
128351 ** If argument addrExplain is not 0, it must be the address of an
128352 ** OP_Explain instruction that describes the same loop.
128354 SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
128355 Vdbe *v, /* Vdbe to add scanstatus entry to */
128356 SrcList *pSrclist, /* FROM clause pLvl reads data from */
128357 WhereLevel *pLvl, /* Level to add scanstatus() entry for */
128358 int addrExplain /* Address of OP_Explain (or 0) */
128360 const char *zObj = 0;
128361 WhereLoop *pLoop = pLvl->pWLoop;
128362 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
128363 zObj = pLoop->u.btree.pIndex->zName;
128364 }else{
128365 zObj = pSrclist->a[pLvl->iFrom].zName;
128367 sqlite3VdbeScanStatus(
128368 v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
128371 #endif
128375 ** Disable a term in the WHERE clause. Except, do not disable the term
128376 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
128377 ** or USING clause of that join.
128379 ** Consider the term t2.z='ok' in the following queries:
128381 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
128382 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
128383 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
128385 ** The t2.z='ok' is disabled in the in (2) because it originates
128386 ** in the ON clause. The term is disabled in (3) because it is not part
128387 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
128389 ** Disabling a term causes that term to not be tested in the inner loop
128390 ** of the join. Disabling is an optimization. When terms are satisfied
128391 ** by indices, we disable them to prevent redundant tests in the inner
128392 ** loop. We would get the correct results if nothing were ever disabled,
128393 ** but joins might run a little slower. The trick is to disable as much
128394 ** as we can without disabling too much. If we disabled in (1), we'd get
128395 ** the wrong answer. See ticket #813.
128397 ** If all the children of a term are disabled, then that term is also
128398 ** automatically disabled. In this way, terms get disabled if derived
128399 ** virtual terms are tested first. For example:
128401 ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
128402 ** \___________/ \______/ \_____/
128403 ** parent child1 child2
128405 ** Only the parent term was in the original WHERE clause. The child1
128406 ** and child2 terms were added by the LIKE optimization. If both of
128407 ** the virtual child terms are valid, then testing of the parent can be
128408 ** skipped.
128410 ** Usually the parent term is marked as TERM_CODED. But if the parent
128411 ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
128412 ** The TERM_LIKECOND marking indicates that the term should be coded inside
128413 ** a conditional such that is only evaluated on the second pass of a
128414 ** LIKE-optimization loop, when scanning BLOBs instead of strings.
128416 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
128417 int nLoop = 0;
128418 while( ALWAYS(pTerm!=0)
128419 && (pTerm->wtFlags & TERM_CODED)==0
128420 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
128421 && (pLevel->notReady & pTerm->prereqAll)==0
128423 if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
128424 pTerm->wtFlags |= TERM_LIKECOND;
128425 }else{
128426 pTerm->wtFlags |= TERM_CODED;
128428 if( pTerm->iParent<0 ) break;
128429 pTerm = &pTerm->pWC->a[pTerm->iParent];
128430 pTerm->nChild--;
128431 if( pTerm->nChild!=0 ) break;
128432 nLoop++;
128437 ** Code an OP_Affinity opcode to apply the column affinity string zAff
128438 ** to the n registers starting at base.
128440 ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
128441 ** beginning and end of zAff are ignored. If all entries in zAff are
128442 ** SQLITE_AFF_BLOB, then no code gets generated.
128444 ** This routine makes its own copy of zAff so that the caller is free
128445 ** to modify zAff after this routine returns.
128447 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
128448 Vdbe *v = pParse->pVdbe;
128449 if( zAff==0 ){
128450 assert( pParse->db->mallocFailed );
128451 return;
128453 assert( v!=0 );
128455 /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
128456 ** and end of the affinity string.
128458 while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
128460 base++;
128461 zAff++;
128463 while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
128467 /* Code the OP_Affinity opcode if there is anything left to do. */
128468 if( n>0 ){
128469 sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
128470 sqlite3ExprCacheAffinityChange(pParse, base, n);
128475 ** Expression pRight, which is the RHS of a comparison operation, is
128476 ** either a vector of n elements or, if n==1, a scalar expression.
128477 ** Before the comparison operation, affinity zAff is to be applied
128478 ** to the pRight values. This function modifies characters within the
128479 ** affinity string to SQLITE_AFF_BLOB if either:
128481 ** * the comparison will be performed with no affinity, or
128482 ** * the affinity change in zAff is guaranteed not to change the value.
128484 static void updateRangeAffinityStr(
128485 Expr *pRight, /* RHS of comparison */
128486 int n, /* Number of vector elements in comparison */
128487 char *zAff /* Affinity string to modify */
128489 int i;
128490 for(i=0; i<n; i++){
128491 Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
128492 if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
128493 || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
128495 zAff[i] = SQLITE_AFF_BLOB;
128501 ** Generate code for a single equality term of the WHERE clause. An equality
128502 ** term can be either X=expr or X IN (...). pTerm is the term to be
128503 ** coded.
128505 ** The current value for the constraint is left in a register, the index
128506 ** of which is returned. An attempt is made store the result in iTarget but
128507 ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
128508 ** constraint is a TK_EQ or TK_IS, then the current value might be left in
128509 ** some other register and it is the caller's responsibility to compensate.
128511 ** For a constraint of the form X=expr, the expression is evaluated in
128512 ** straight-line code. For constraints of the form X IN (...)
128513 ** this routine sets up a loop that will iterate over all values of X.
128515 static int codeEqualityTerm(
128516 Parse *pParse, /* The parsing context */
128517 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
128518 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
128519 int iEq, /* Index of the equality term within this level */
128520 int bRev, /* True for reverse-order IN operations */
128521 int iTarget /* Attempt to leave results in this register */
128523 Expr *pX = pTerm->pExpr;
128524 Vdbe *v = pParse->pVdbe;
128525 int iReg; /* Register holding results */
128527 assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
128528 assert( iTarget>0 );
128529 if( pX->op==TK_EQ || pX->op==TK_IS ){
128530 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
128531 }else if( pX->op==TK_ISNULL ){
128532 iReg = iTarget;
128533 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
128534 #ifndef SQLITE_OMIT_SUBQUERY
128535 }else{
128536 int eType = IN_INDEX_NOOP;
128537 int iTab;
128538 struct InLoop *pIn;
128539 WhereLoop *pLoop = pLevel->pWLoop;
128540 int i;
128541 int nEq = 0;
128542 int *aiMap = 0;
128544 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
128545 && pLoop->u.btree.pIndex!=0
128546 && pLoop->u.btree.pIndex->aSortOrder[iEq]
128548 testcase( iEq==0 );
128549 testcase( bRev );
128550 bRev = !bRev;
128552 assert( pX->op==TK_IN );
128553 iReg = iTarget;
128555 for(i=0; i<iEq; i++){
128556 if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
128557 disableTerm(pLevel, pTerm);
128558 return iTarget;
128561 for(i=iEq;i<pLoop->nLTerm; i++){
128562 if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++;
128565 if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
128566 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
128567 }else{
128568 Select *pSelect = pX->x.pSelect;
128569 sqlite3 *db = pParse->db;
128570 u16 savedDbOptFlags = db->dbOptFlags;
128571 ExprList *pOrigRhs = pSelect->pEList;
128572 ExprList *pOrigLhs = pX->pLeft->x.pList;
128573 ExprList *pRhs = 0; /* New Select.pEList for RHS */
128574 ExprList *pLhs = 0; /* New pX->pLeft vector */
128576 for(i=iEq;i<pLoop->nLTerm; i++){
128577 if( pLoop->aLTerm[i]->pExpr==pX ){
128578 int iField = pLoop->aLTerm[i]->iField - 1;
128579 Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0);
128580 Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0);
128582 pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs);
128583 pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs);
128586 if( !db->mallocFailed ){
128587 Expr *pLeft = pX->pLeft;
128589 if( pSelect->pOrderBy ){
128590 /* If the SELECT statement has an ORDER BY clause, zero the
128591 ** iOrderByCol variables. These are set to non-zero when an
128592 ** ORDER BY term exactly matches one of the terms of the
128593 ** result-set. Since the result-set of the SELECT statement may
128594 ** have been modified or reordered, these variables are no longer
128595 ** set correctly. Since setting them is just an optimization,
128596 ** it's easiest just to zero them here. */
128597 ExprList *pOrderBy = pSelect->pOrderBy;
128598 for(i=0; i<pOrderBy->nExpr; i++){
128599 pOrderBy->a[i].u.x.iOrderByCol = 0;
128603 /* Take care here not to generate a TK_VECTOR containing only a
128604 ** single value. Since the parser never creates such a vector, some
128605 ** of the subroutines do not handle this case. */
128606 if( pLhs->nExpr==1 ){
128607 pX->pLeft = pLhs->a[0].pExpr;
128608 }else{
128609 pLeft->x.pList = pLhs;
128610 aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq);
128611 testcase( aiMap==0 );
128613 pSelect->pEList = pRhs;
128614 db->dbOptFlags |= SQLITE_QueryFlattener;
128615 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
128616 db->dbOptFlags = savedDbOptFlags;
128617 testcase( aiMap!=0 && aiMap[0]!=0 );
128618 pSelect->pEList = pOrigRhs;
128619 pLeft->x.pList = pOrigLhs;
128620 pX->pLeft = pLeft;
128622 sqlite3ExprListDelete(pParse->db, pLhs);
128623 sqlite3ExprListDelete(pParse->db, pRhs);
128626 if( eType==IN_INDEX_INDEX_DESC ){
128627 testcase( bRev );
128628 bRev = !bRev;
128630 iTab = pX->iTable;
128631 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
128632 VdbeCoverageIf(v, bRev);
128633 VdbeCoverageIf(v, !bRev);
128634 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
128636 pLoop->wsFlags |= WHERE_IN_ABLE;
128637 if( pLevel->u.in.nIn==0 ){
128638 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
128641 i = pLevel->u.in.nIn;
128642 pLevel->u.in.nIn += nEq;
128643 pLevel->u.in.aInLoop =
128644 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
128645 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
128646 pIn = pLevel->u.in.aInLoop;
128647 if( pIn ){
128648 int iMap = 0; /* Index in aiMap[] */
128649 pIn += i;
128650 for(i=iEq;i<pLoop->nLTerm; i++){
128651 if( pLoop->aLTerm[i]->pExpr==pX ){
128652 int iOut = iReg + i - iEq;
128653 if( eType==IN_INDEX_ROWID ){
128654 testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */
128655 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
128656 }else{
128657 int iCol = aiMap ? aiMap[iMap++] : 0;
128658 pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
128660 sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
128661 if( i==iEq ){
128662 pIn->iCur = iTab;
128663 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
128664 }else{
128665 pIn->eEndLoopOp = OP_Noop;
128667 pIn++;
128670 }else{
128671 pLevel->u.in.nIn = 0;
128673 sqlite3DbFree(pParse->db, aiMap);
128674 #endif
128676 disableTerm(pLevel, pTerm);
128677 return iReg;
128681 ** Generate code that will evaluate all == and IN constraints for an
128682 ** index scan.
128684 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
128685 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
128686 ** The index has as many as three equality constraints, but in this
128687 ** example, the third "c" value is an inequality. So only two
128688 ** constraints are coded. This routine will generate code to evaluate
128689 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
128690 ** in consecutive registers and the index of the first register is returned.
128692 ** In the example above nEq==2. But this subroutine works for any value
128693 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
128694 ** The only thing it does is allocate the pLevel->iMem memory cell and
128695 ** compute the affinity string.
128697 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
128698 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
128699 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
128700 ** occurs after the nEq quality constraints.
128702 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
128703 ** the index of the first memory cell in that range. The code that
128704 ** calls this routine will use that memory range to store keys for
128705 ** start and termination conditions of the loop.
128706 ** key value of the loop. If one or more IN operators appear, then
128707 ** this routine allocates an additional nEq memory cells for internal
128708 ** use.
128710 ** Before returning, *pzAff is set to point to a buffer containing a
128711 ** copy of the column affinity string of the index allocated using
128712 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
128713 ** with equality constraints that use BLOB or NONE affinity are set to
128714 ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
128716 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
128717 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
128719 ** In the example above, the index on t1(a) has TEXT affinity. But since
128720 ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
128721 ** no conversion should be attempted before using a t2.b value as part of
128722 ** a key to search the index. Hence the first byte in the returned affinity
128723 ** string in this example would be set to SQLITE_AFF_BLOB.
128725 static int codeAllEqualityTerms(
128726 Parse *pParse, /* Parsing context */
128727 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
128728 int bRev, /* Reverse the order of IN operators */
128729 int nExtraReg, /* Number of extra registers to allocate */
128730 char **pzAff /* OUT: Set to point to affinity string */
128732 u16 nEq; /* The number of == or IN constraints to code */
128733 u16 nSkip; /* Number of left-most columns to skip */
128734 Vdbe *v = pParse->pVdbe; /* The vm under construction */
128735 Index *pIdx; /* The index being used for this loop */
128736 WhereTerm *pTerm; /* A single constraint term */
128737 WhereLoop *pLoop; /* The WhereLoop object */
128738 int j; /* Loop counter */
128739 int regBase; /* Base register */
128740 int nReg; /* Number of registers to allocate */
128741 char *zAff; /* Affinity string to return */
128743 /* This module is only called on query plans that use an index. */
128744 pLoop = pLevel->pWLoop;
128745 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
128746 nEq = pLoop->u.btree.nEq;
128747 nSkip = pLoop->nSkip;
128748 pIdx = pLoop->u.btree.pIndex;
128749 assert( pIdx!=0 );
128751 /* Figure out how many memory cells we will need then allocate them.
128753 regBase = pParse->nMem + 1;
128754 nReg = pLoop->u.btree.nEq + nExtraReg;
128755 pParse->nMem += nReg;
128757 zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
128758 assert( zAff!=0 || pParse->db->mallocFailed );
128760 if( nSkip ){
128761 int iIdxCur = pLevel->iIdxCur;
128762 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
128763 VdbeCoverageIf(v, bRev==0);
128764 VdbeCoverageIf(v, bRev!=0);
128765 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
128766 j = sqlite3VdbeAddOp0(v, OP_Goto);
128767 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
128768 iIdxCur, 0, regBase, nSkip);
128769 VdbeCoverageIf(v, bRev==0);
128770 VdbeCoverageIf(v, bRev!=0);
128771 sqlite3VdbeJumpHere(v, j);
128772 for(j=0; j<nSkip; j++){
128773 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
128774 testcase( pIdx->aiColumn[j]==XN_EXPR );
128775 VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
128779 /* Evaluate the equality constraints
128781 assert( zAff==0 || (int)strlen(zAff)>=nEq );
128782 for(j=nSkip; j<nEq; j++){
128783 int r1;
128784 pTerm = pLoop->aLTerm[j];
128785 assert( pTerm!=0 );
128786 /* The following testcase is true for indices with redundant columns.
128787 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
128788 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
128789 testcase( pTerm->wtFlags & TERM_VIRTUAL );
128790 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
128791 if( r1!=regBase+j ){
128792 if( nReg==1 ){
128793 sqlite3ReleaseTempReg(pParse, regBase);
128794 regBase = r1;
128795 }else{
128796 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
128799 if( pTerm->eOperator & WO_IN ){
128800 if( pTerm->pExpr->flags & EP_xIsSelect ){
128801 /* No affinity ever needs to be (or should be) applied to a value
128802 ** from the RHS of an "? IN (SELECT ...)" expression. The
128803 ** sqlite3FindInIndex() routine has already ensured that the
128804 ** affinity of the comparison has been applied to the value. */
128805 if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
128807 }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
128808 Expr *pRight = pTerm->pExpr->pRight;
128809 if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
128810 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
128811 VdbeCoverage(v);
128813 if( zAff ){
128814 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
128815 zAff[j] = SQLITE_AFF_BLOB;
128817 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
128818 zAff[j] = SQLITE_AFF_BLOB;
128823 *pzAff = zAff;
128824 return regBase;
128827 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
128829 ** If the most recently coded instruction is a constant range constraint
128830 ** (a string literal) that originated from the LIKE optimization, then
128831 ** set P3 and P5 on the OP_String opcode so that the string will be cast
128832 ** to a BLOB at appropriate times.
128834 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
128835 ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
128836 ** scan loop run twice, once for strings and a second time for BLOBs.
128837 ** The OP_String opcodes on the second pass convert the upper and lower
128838 ** bound string constants to blobs. This routine makes the necessary changes
128839 ** to the OP_String opcodes for that to happen.
128841 ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
128842 ** only the one pass through the string space is required, so this routine
128843 ** becomes a no-op.
128845 static void whereLikeOptimizationStringFixup(
128846 Vdbe *v, /* prepared statement under construction */
128847 WhereLevel *pLevel, /* The loop that contains the LIKE operator */
128848 WhereTerm *pTerm /* The upper or lower bound just coded */
128850 if( pTerm->wtFlags & TERM_LIKEOPT ){
128851 VdbeOp *pOp;
128852 assert( pLevel->iLikeRepCntr>0 );
128853 pOp = sqlite3VdbeGetOp(v, -1);
128854 assert( pOp!=0 );
128855 assert( pOp->opcode==OP_String8
128856 || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
128857 pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
128858 pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
128861 #else
128862 # define whereLikeOptimizationStringFixup(A,B,C)
128863 #endif
128865 #ifdef SQLITE_ENABLE_CURSOR_HINTS
128867 ** Information is passed from codeCursorHint() down to individual nodes of
128868 ** the expression tree (by sqlite3WalkExpr()) using an instance of this
128869 ** structure.
128871 struct CCurHint {
128872 int iTabCur; /* Cursor for the main table */
128873 int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
128874 Index *pIdx; /* The index used to access the table */
128878 ** This function is called for every node of an expression that is a candidate
128879 ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
128880 ** the table CCurHint.iTabCur, verify that the same column can be
128881 ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
128883 static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
128884 struct CCurHint *pHint = pWalker->u.pCCurHint;
128885 assert( pHint->pIdx!=0 );
128886 if( pExpr->op==TK_COLUMN
128887 && pExpr->iTable==pHint->iTabCur
128888 && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
128890 pWalker->eCode = 1;
128892 return WRC_Continue;
128896 ** Test whether or not expression pExpr, which was part of a WHERE clause,
128897 ** should be included in the cursor-hint for a table that is on the rhs
128898 ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
128899 ** expression is not suitable.
128901 ** An expression is unsuitable if it might evaluate to non NULL even if
128902 ** a TK_COLUMN node that does affect the value of the expression is set
128903 ** to NULL. For example:
128905 ** col IS NULL
128906 ** col IS NOT NULL
128907 ** coalesce(col, 1)
128908 ** CASE WHEN col THEN 0 ELSE 1 END
128910 static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
128911 if( pExpr->op==TK_IS
128912 || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
128913 || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
128915 pWalker->eCode = 1;
128916 }else if( pExpr->op==TK_FUNCTION ){
128917 int d1;
128918 char d2[4];
128919 if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
128920 pWalker->eCode = 1;
128924 return WRC_Continue;
128929 ** This function is called on every node of an expression tree used as an
128930 ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
128931 ** that accesses any table other than the one identified by
128932 ** CCurHint.iTabCur, then do the following:
128934 ** 1) allocate a register and code an OP_Column instruction to read
128935 ** the specified column into the new register, and
128937 ** 2) transform the expression node to a TK_REGISTER node that reads
128938 ** from the newly populated register.
128940 ** Also, if the node is a TK_COLUMN that does access the table idenified
128941 ** by pCCurHint.iTabCur, and an index is being used (which we will
128942 ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
128943 ** an access of the index rather than the original table.
128945 static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
128946 int rc = WRC_Continue;
128947 struct CCurHint *pHint = pWalker->u.pCCurHint;
128948 if( pExpr->op==TK_COLUMN ){
128949 if( pExpr->iTable!=pHint->iTabCur ){
128950 Vdbe *v = pWalker->pParse->pVdbe;
128951 int reg = ++pWalker->pParse->nMem; /* Register for column value */
128952 sqlite3ExprCodeGetColumnOfTable(
128953 v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
128955 pExpr->op = TK_REGISTER;
128956 pExpr->iTable = reg;
128957 }else if( pHint->pIdx!=0 ){
128958 pExpr->iTable = pHint->iIdxCur;
128959 pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
128960 assert( pExpr->iColumn>=0 );
128962 }else if( pExpr->op==TK_AGG_FUNCTION ){
128963 /* An aggregate function in the WHERE clause of a query means this must
128964 ** be a correlated sub-query, and expression pExpr is an aggregate from
128965 ** the parent context. Do not walk the function arguments in this case.
128967 ** todo: It should be possible to replace this node with a TK_REGISTER
128968 ** expression, as the result of the expression must be stored in a
128969 ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
128970 rc = WRC_Prune;
128972 return rc;
128976 ** Insert an OP_CursorHint instruction if it is appropriate to do so.
128978 static void codeCursorHint(
128979 struct SrcList_item *pTabItem, /* FROM clause item */
128980 WhereInfo *pWInfo, /* The where clause */
128981 WhereLevel *pLevel, /* Which loop to provide hints for */
128982 WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
128984 Parse *pParse = pWInfo->pParse;
128985 sqlite3 *db = pParse->db;
128986 Vdbe *v = pParse->pVdbe;
128987 Expr *pExpr = 0;
128988 WhereLoop *pLoop = pLevel->pWLoop;
128989 int iCur;
128990 WhereClause *pWC;
128991 WhereTerm *pTerm;
128992 int i, j;
128993 struct CCurHint sHint;
128994 Walker sWalker;
128996 if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
128997 iCur = pLevel->iTabCur;
128998 assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
128999 sHint.iTabCur = iCur;
129000 sHint.iIdxCur = pLevel->iIdxCur;
129001 sHint.pIdx = pLoop->u.btree.pIndex;
129002 memset(&sWalker, 0, sizeof(sWalker));
129003 sWalker.pParse = pParse;
129004 sWalker.u.pCCurHint = &sHint;
129005 pWC = &pWInfo->sWC;
129006 for(i=0; i<pWC->nTerm; i++){
129007 pTerm = &pWC->a[i];
129008 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
129009 if( pTerm->prereqAll & pLevel->notReady ) continue;
129011 /* Any terms specified as part of the ON(...) clause for any LEFT
129012 ** JOIN for which the current table is not the rhs are omitted
129013 ** from the cursor-hint.
129015 ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
129016 ** that were specified as part of the WHERE clause must be excluded.
129017 ** This is to address the following:
129019 ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
129021 ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
129022 ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
129023 ** pushed down to the cursor, this row is filtered out, causing
129024 ** SQLite to synthesize a row of NULL values. Which does match the
129025 ** WHERE clause, and so the query returns a row. Which is incorrect.
129027 ** For the same reason, WHERE terms such as:
129029 ** WHERE 1 = (t2.c IS NULL)
129031 ** are also excluded. See codeCursorHintIsOrFunction() for details.
129033 if( pTabItem->fg.jointype & JT_LEFT ){
129034 Expr *pExpr = pTerm->pExpr;
129035 if( !ExprHasProperty(pExpr, EP_FromJoin)
129036 || pExpr->iRightJoinTable!=pTabItem->iCursor
129038 sWalker.eCode = 0;
129039 sWalker.xExprCallback = codeCursorHintIsOrFunction;
129040 sqlite3WalkExpr(&sWalker, pTerm->pExpr);
129041 if( sWalker.eCode ) continue;
129043 }else{
129044 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
129047 /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
129048 ** the cursor. These terms are not needed as hints for a pure range
129049 ** scan (that has no == terms) so omit them. */
129050 if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
129051 for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
129052 if( j<pLoop->nLTerm ) continue;
129055 /* No subqueries or non-deterministic functions allowed */
129056 if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
129058 /* For an index scan, make sure referenced columns are actually in
129059 ** the index. */
129060 if( sHint.pIdx!=0 ){
129061 sWalker.eCode = 0;
129062 sWalker.xExprCallback = codeCursorHintCheckExpr;
129063 sqlite3WalkExpr(&sWalker, pTerm->pExpr);
129064 if( sWalker.eCode ) continue;
129067 /* If we survive all prior tests, that means this term is worth hinting */
129068 pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
129070 if( pExpr!=0 ){
129071 sWalker.xExprCallback = codeCursorHintFixExpr;
129072 sqlite3WalkExpr(&sWalker, pExpr);
129073 sqlite3VdbeAddOp4(v, OP_CursorHint,
129074 (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
129075 (const char*)pExpr, P4_EXPR);
129078 #else
129079 # define codeCursorHint(A,B,C,D) /* No-op */
129080 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
129083 ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
129084 ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
129085 ** function generates code to do a deferred seek of cursor iCur to the
129086 ** rowid stored in register iRowid.
129088 ** Normally, this is just:
129090 ** OP_DeferredSeek $iCur $iRowid
129092 ** However, if the scan currently being coded is a branch of an OR-loop and
129093 ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
129094 ** is set to iIdxCur and P4 is set to point to an array of integers
129095 ** containing one entry for each column of the table cursor iCur is open
129096 ** on. For each table column, if the column is the i'th column of the
129097 ** index, then the corresponding array entry is set to (i+1). If the column
129098 ** does not appear in the index at all, the array entry is set to 0.
129100 static void codeDeferredSeek(
129101 WhereInfo *pWInfo, /* Where clause context */
129102 Index *pIdx, /* Index scan is using */
129103 int iCur, /* Cursor for IPK b-tree */
129104 int iIdxCur /* Index cursor */
129106 Parse *pParse = pWInfo->pParse; /* Parse context */
129107 Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
129109 assert( iIdxCur>0 );
129110 assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
129112 sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
129113 if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
129114 && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
129116 int i;
129117 Table *pTab = pIdx->pTable;
129118 int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
129119 if( ai ){
129120 ai[0] = pTab->nCol;
129121 for(i=0; i<pIdx->nColumn-1; i++){
129122 assert( pIdx->aiColumn[i]<pTab->nCol );
129123 if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
129125 sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
129131 ** If the expression passed as the second argument is a vector, generate
129132 ** code to write the first nReg elements of the vector into an array
129133 ** of registers starting with iReg.
129135 ** If the expression is not a vector, then nReg must be passed 1. In
129136 ** this case, generate code to evaluate the expression and leave the
129137 ** result in register iReg.
129139 static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
129140 assert( nReg>0 );
129141 if( p && sqlite3ExprIsVector(p) ){
129142 #ifndef SQLITE_OMIT_SUBQUERY
129143 if( (p->flags & EP_xIsSelect) ){
129144 Vdbe *v = pParse->pVdbe;
129145 int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
129146 sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
129147 }else
129148 #endif
129150 int i;
129151 ExprList *pList = p->x.pList;
129152 assert( nReg<=pList->nExpr );
129153 for(i=0; i<nReg; i++){
129154 sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
129157 }else{
129158 assert( nReg==1 );
129159 sqlite3ExprCode(pParse, p, iReg);
129163 /* An instance of the IdxExprTrans object carries information about a
129164 ** mapping from an expression on table columns into a column in an index
129165 ** down through the Walker.
129167 typedef struct IdxExprTrans {
129168 Expr *pIdxExpr; /* The index expression */
129169 int iTabCur; /* The cursor of the corresponding table */
129170 int iIdxCur; /* The cursor for the index */
129171 int iIdxCol; /* The column for the index */
129172 } IdxExprTrans;
129174 /* The walker node callback used to transform matching expressions into
129175 ** a reference to an index column for an index on an expression.
129177 ** If pExpr matches, then transform it into a reference to the index column
129178 ** that contains the value of pExpr.
129180 static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
129181 IdxExprTrans *pX = p->u.pIdxTrans;
129182 if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
129183 pExpr->op = TK_COLUMN;
129184 pExpr->iTable = pX->iIdxCur;
129185 pExpr->iColumn = pX->iIdxCol;
129186 pExpr->pTab = 0;
129187 return WRC_Prune;
129188 }else{
129189 return WRC_Continue;
129194 ** For an indexes on expression X, locate every instance of expression X
129195 ** in pExpr and change that subexpression into a reference to the appropriate
129196 ** column of the index.
129198 static void whereIndexExprTrans(
129199 Index *pIdx, /* The Index */
129200 int iTabCur, /* Cursor of the table that is being indexed */
129201 int iIdxCur, /* Cursor of the index itself */
129202 WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
129204 int iIdxCol; /* Column number of the index */
129205 ExprList *aColExpr; /* Expressions that are indexed */
129206 Walker w;
129207 IdxExprTrans x;
129208 aColExpr = pIdx->aColExpr;
129209 if( aColExpr==0 ) return; /* Not an index on expressions */
129210 memset(&w, 0, sizeof(w));
129211 w.xExprCallback = whereIndexExprTransNode;
129212 w.u.pIdxTrans = &x;
129213 x.iTabCur = iTabCur;
129214 x.iIdxCur = iIdxCur;
129215 for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
129216 if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
129217 assert( aColExpr->a[iIdxCol].pExpr!=0 );
129218 x.iIdxCol = iIdxCol;
129219 x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
129220 sqlite3WalkExpr(&w, pWInfo->pWhere);
129221 sqlite3WalkExprList(&w, pWInfo->pOrderBy);
129222 sqlite3WalkExprList(&w, pWInfo->pResultSet);
129227 ** Generate code for the start of the iLevel-th loop in the WHERE clause
129228 ** implementation described by pWInfo.
129230 SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
129231 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
129232 int iLevel, /* Which level of pWInfo->a[] should be coded */
129233 Bitmask notReady /* Which tables are currently available */
129235 int j, k; /* Loop counters */
129236 int iCur; /* The VDBE cursor for the table */
129237 int addrNxt; /* Where to jump to continue with the next IN case */
129238 int omitTable; /* True if we use the index only */
129239 int bRev; /* True if we need to scan in reverse order */
129240 WhereLevel *pLevel; /* The where level to be coded */
129241 WhereLoop *pLoop; /* The WhereLoop object being coded */
129242 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
129243 WhereTerm *pTerm; /* A WHERE clause term */
129244 Parse *pParse; /* Parsing context */
129245 sqlite3 *db; /* Database connection */
129246 Vdbe *v; /* The prepared stmt under constructions */
129247 struct SrcList_item *pTabItem; /* FROM clause term being coded */
129248 int addrBrk; /* Jump here to break out of the loop */
129249 int addrHalt; /* addrBrk for the outermost loop */
129250 int addrCont; /* Jump here to continue with next cycle */
129251 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
129252 int iReleaseReg = 0; /* Temp register to free before returning */
129253 Index *pIdx = 0; /* Index used by loop (if any) */
129254 int iLoop; /* Iteration of constraint generator loop */
129256 pParse = pWInfo->pParse;
129257 v = pParse->pVdbe;
129258 pWC = &pWInfo->sWC;
129259 db = pParse->db;
129260 pLevel = &pWInfo->a[iLevel];
129261 pLoop = pLevel->pWLoop;
129262 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
129263 iCur = pTabItem->iCursor;
129264 pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
129265 bRev = (pWInfo->revMask>>iLevel)&1;
129266 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
129267 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
129268 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
129270 /* Create labels for the "break" and "continue" instructions
129271 ** for the current loop. Jump to addrBrk to break out of a loop.
129272 ** Jump to cont to go immediately to the next iteration of the
129273 ** loop.
129275 ** When there is an IN operator, we also have a "addrNxt" label that
129276 ** means to continue with the next IN value combination. When
129277 ** there are no IN operators in the constraints, the "addrNxt" label
129278 ** is the same as "addrBrk".
129280 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
129281 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
129283 /* If this is the right table of a LEFT OUTER JOIN, allocate and
129284 ** initialize a memory cell that records if this table matches any
129285 ** row of the left table of the join.
129287 if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
129288 pLevel->iLeftJoin = ++pParse->nMem;
129289 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
129290 VdbeComment((v, "init LEFT JOIN no-match flag"));
129293 /* Compute a safe address to jump to if we discover that the table for
129294 ** this loop is empty and can never contribute content. */
129295 for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
129296 addrHalt = pWInfo->a[j].addrBrk;
129298 /* Special case of a FROM clause subquery implemented as a co-routine */
129299 if( pTabItem->fg.viaCoroutine ){
129300 int regYield = pTabItem->regReturn;
129301 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
129302 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
129303 VdbeCoverage(v);
129304 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
129305 pLevel->op = OP_Goto;
129306 }else
129308 #ifndef SQLITE_OMIT_VIRTUALTABLE
129309 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
129310 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
129311 ** to access the data.
129313 int iReg; /* P3 Value for OP_VFilter */
129314 int addrNotFound;
129315 int nConstraint = pLoop->nLTerm;
129316 int iIn; /* Counter for IN constraints */
129318 sqlite3ExprCachePush(pParse);
129319 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
129320 addrNotFound = pLevel->addrBrk;
129321 for(j=0; j<nConstraint; j++){
129322 int iTarget = iReg+j+2;
129323 pTerm = pLoop->aLTerm[j];
129324 if( NEVER(pTerm==0) ) continue;
129325 if( pTerm->eOperator & WO_IN ){
129326 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
129327 addrNotFound = pLevel->addrNxt;
129328 }else{
129329 Expr *pRight = pTerm->pExpr->pRight;
129330 codeExprOrVector(pParse, pRight, iTarget, 1);
129333 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
129334 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
129335 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
129336 pLoop->u.vtab.idxStr,
129337 pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
129338 VdbeCoverage(v);
129339 pLoop->u.vtab.needFree = 0;
129340 pLevel->p1 = iCur;
129341 pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
129342 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
129343 iIn = pLevel->u.in.nIn;
129344 for(j=nConstraint-1; j>=0; j--){
129345 pTerm = pLoop->aLTerm[j];
129346 if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
129347 disableTerm(pLevel, pTerm);
129348 }else if( (pTerm->eOperator & WO_IN)!=0 ){
129349 Expr *pCompare; /* The comparison operator */
129350 Expr *pRight; /* RHS of the comparison */
129351 VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
129353 /* Reload the constraint value into reg[iReg+j+2]. The same value
129354 ** was loaded into the same register prior to the OP_VFilter, but
129355 ** the xFilter implementation might have changed the datatype or
129356 ** encoding of the value in the register, so it *must* be reloaded. */
129357 assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
129358 if( !db->mallocFailed ){
129359 assert( iIn>0 );
129360 pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
129361 assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
129362 assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
129363 assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
129364 testcase( pOp->opcode==OP_Rowid );
129365 sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
129368 /* Generate code that will continue to the next row if
129369 ** the IN constraint is not satisfied */
129370 pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
129371 assert( pCompare!=0 || db->mallocFailed );
129372 if( pCompare ){
129373 pCompare->pLeft = pTerm->pExpr->pLeft;
129374 pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
129375 if( pRight ){
129376 pRight->iTable = iReg+j+2;
129377 sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
129379 pCompare->pLeft = 0;
129380 sqlite3ExprDelete(db, pCompare);
129384 /* These registers need to be preserved in case there is an IN operator
129385 ** loop. So we could deallocate the registers here (and potentially
129386 ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
129387 ** simpler and safer to simply not reuse the registers.
129389 ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
129391 sqlite3ExprCachePop(pParse);
129392 }else
129393 #endif /* SQLITE_OMIT_VIRTUALTABLE */
129395 if( (pLoop->wsFlags & WHERE_IPK)!=0
129396 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
129398 /* Case 2: We can directly reference a single row using an
129399 ** equality comparison against the ROWID field. Or
129400 ** we reference multiple rows using a "rowid IN (...)"
129401 ** construct.
129403 assert( pLoop->u.btree.nEq==1 );
129404 pTerm = pLoop->aLTerm[0];
129405 assert( pTerm!=0 );
129406 assert( pTerm->pExpr!=0 );
129407 assert( omitTable==0 );
129408 testcase( pTerm->wtFlags & TERM_VIRTUAL );
129409 iReleaseReg = ++pParse->nMem;
129410 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
129411 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
129412 addrNxt = pLevel->addrNxt;
129413 sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
129414 VdbeCoverage(v);
129415 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
129416 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
129417 VdbeComment((v, "pk"));
129418 pLevel->op = OP_Noop;
129419 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
129420 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
129422 /* Case 3: We have an inequality comparison against the ROWID field.
129424 int testOp = OP_Noop;
129425 int start;
129426 int memEndValue = 0;
129427 WhereTerm *pStart, *pEnd;
129429 assert( omitTable==0 );
129430 j = 0;
129431 pStart = pEnd = 0;
129432 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
129433 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
129434 assert( pStart!=0 || pEnd!=0 );
129435 if( bRev ){
129436 pTerm = pStart;
129437 pStart = pEnd;
129438 pEnd = pTerm;
129440 codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
129441 if( pStart ){
129442 Expr *pX; /* The expression that defines the start bound */
129443 int r1, rTemp; /* Registers for holding the start boundary */
129444 int op; /* Cursor seek operation */
129446 /* The following constant maps TK_xx codes into corresponding
129447 ** seek opcodes. It depends on a particular ordering of TK_xx
129449 const u8 aMoveOp[] = {
129450 /* TK_GT */ OP_SeekGT,
129451 /* TK_LE */ OP_SeekLE,
129452 /* TK_LT */ OP_SeekLT,
129453 /* TK_GE */ OP_SeekGE
129455 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
129456 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
129457 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
129459 assert( (pStart->wtFlags & TERM_VNULL)==0 );
129460 testcase( pStart->wtFlags & TERM_VIRTUAL );
129461 pX = pStart->pExpr;
129462 assert( pX!=0 );
129463 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
129464 if( sqlite3ExprIsVector(pX->pRight) ){
129465 r1 = rTemp = sqlite3GetTempReg(pParse);
129466 codeExprOrVector(pParse, pX->pRight, r1, 1);
129467 op = aMoveOp[(pX->op - TK_GT) | 0x0001];
129468 }else{
129469 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
129470 disableTerm(pLevel, pStart);
129471 op = aMoveOp[(pX->op - TK_GT)];
129473 sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
129474 VdbeComment((v, "pk"));
129475 VdbeCoverageIf(v, pX->op==TK_GT);
129476 VdbeCoverageIf(v, pX->op==TK_LE);
129477 VdbeCoverageIf(v, pX->op==TK_LT);
129478 VdbeCoverageIf(v, pX->op==TK_GE);
129479 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
129480 sqlite3ReleaseTempReg(pParse, rTemp);
129481 }else{
129482 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
129483 VdbeCoverageIf(v, bRev==0);
129484 VdbeCoverageIf(v, bRev!=0);
129486 if( pEnd ){
129487 Expr *pX;
129488 pX = pEnd->pExpr;
129489 assert( pX!=0 );
129490 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
129491 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
129492 testcase( pEnd->wtFlags & TERM_VIRTUAL );
129493 memEndValue = ++pParse->nMem;
129494 codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
129495 if( 0==sqlite3ExprIsVector(pX->pRight)
129496 && (pX->op==TK_LT || pX->op==TK_GT)
129498 testOp = bRev ? OP_Le : OP_Ge;
129499 }else{
129500 testOp = bRev ? OP_Lt : OP_Gt;
129502 if( 0==sqlite3ExprIsVector(pX->pRight) ){
129503 disableTerm(pLevel, pEnd);
129506 start = sqlite3VdbeCurrentAddr(v);
129507 pLevel->op = bRev ? OP_Prev : OP_Next;
129508 pLevel->p1 = iCur;
129509 pLevel->p2 = start;
129510 assert( pLevel->p5==0 );
129511 if( testOp!=OP_Noop ){
129512 iRowidReg = ++pParse->nMem;
129513 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
129514 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
129515 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
129516 VdbeCoverageIf(v, testOp==OP_Le);
129517 VdbeCoverageIf(v, testOp==OP_Lt);
129518 VdbeCoverageIf(v, testOp==OP_Ge);
129519 VdbeCoverageIf(v, testOp==OP_Gt);
129520 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
129522 }else if( pLoop->wsFlags & WHERE_INDEXED ){
129523 /* Case 4: A scan using an index.
129525 ** The WHERE clause may contain zero or more equality
129526 ** terms ("==" or "IN" operators) that refer to the N
129527 ** left-most columns of the index. It may also contain
129528 ** inequality constraints (>, <, >= or <=) on the indexed
129529 ** column that immediately follows the N equalities. Only
129530 ** the right-most column can be an inequality - the rest must
129531 ** use the "==" and "IN" operators. For example, if the
129532 ** index is on (x,y,z), then the following clauses are all
129533 ** optimized:
129535 ** x=5
129536 ** x=5 AND y=10
129537 ** x=5 AND y<10
129538 ** x=5 AND y>5 AND y<10
129539 ** x=5 AND y=5 AND z<=10
129541 ** The z<10 term of the following cannot be used, only
129542 ** the x=5 term:
129544 ** x=5 AND z<10
129546 ** N may be zero if there are inequality constraints.
129547 ** If there are no inequality constraints, then N is at
129548 ** least one.
129550 ** This case is also used when there are no WHERE clause
129551 ** constraints but an index is selected anyway, in order
129552 ** to force the output order to conform to an ORDER BY.
129554 static const u8 aStartOp[] = {
129557 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
129558 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
129559 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
129560 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
129561 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
129562 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
129564 static const u8 aEndOp[] = {
129565 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
129566 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
129567 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
129568 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
129570 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
129571 u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
129572 u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
129573 int regBase; /* Base register holding constraint values */
129574 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
129575 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
129576 int startEq; /* True if range start uses ==, >= or <= */
129577 int endEq; /* True if range end uses ==, >= or <= */
129578 int start_constraints; /* Start of range is constrained */
129579 int nConstraint; /* Number of constraint terms */
129580 int iIdxCur; /* The VDBE cursor for the index */
129581 int nExtraReg = 0; /* Number of extra registers needed */
129582 int op; /* Instruction opcode */
129583 char *zStartAff; /* Affinity for start of range constraint */
129584 char *zEndAff = 0; /* Affinity for end of range constraint */
129585 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
129586 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
129588 pIdx = pLoop->u.btree.pIndex;
129589 iIdxCur = pLevel->iIdxCur;
129590 assert( nEq>=pLoop->nSkip );
129592 /* If this loop satisfies a sort order (pOrderBy) request that
129593 ** was passed to this function to implement a "SELECT min(x) ..."
129594 ** query, then the caller will only allow the loop to run for
129595 ** a single iteration. This means that the first row returned
129596 ** should not have a NULL value stored in 'x'. If column 'x' is
129597 ** the first one after the nEq equality constraints in the index,
129598 ** this requires some special handling.
129600 assert( pWInfo->pOrderBy==0
129601 || pWInfo->pOrderBy->nExpr==1
129602 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
129603 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
129604 && pWInfo->nOBSat>0
129605 && (pIdx->nKeyCol>nEq)
129607 assert( pLoop->nSkip==0 );
129608 bSeekPastNull = 1;
129609 nExtraReg = 1;
129612 /* Find any inequality constraint terms for the start and end
129613 ** of the range.
129615 j = nEq;
129616 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
129617 pRangeStart = pLoop->aLTerm[j++];
129618 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
129619 /* Like optimization range constraints always occur in pairs */
129620 assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
129621 (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
129623 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
129624 pRangeEnd = pLoop->aLTerm[j++];
129625 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
129626 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
129627 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
129628 assert( pRangeStart!=0 ); /* LIKE opt constraints */
129629 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
129630 pLevel->iLikeRepCntr = (u32)++pParse->nMem;
129631 sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
129632 VdbeComment((v, "LIKE loop counter"));
129633 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
129634 /* iLikeRepCntr actually stores 2x the counter register number. The
129635 ** bottom bit indicates whether the search order is ASC or DESC. */
129636 testcase( bRev );
129637 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
129638 assert( (bRev & ~1)==0 );
129639 pLevel->iLikeRepCntr <<=1;
129640 pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
129642 #endif
129643 if( pRangeStart==0 ){
129644 j = pIdx->aiColumn[nEq];
129645 if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
129646 bSeekPastNull = 1;
129650 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
129652 /* If we are doing a reverse order scan on an ascending index, or
129653 ** a forward order scan on a descending index, interchange the
129654 ** start and end terms (pRangeStart and pRangeEnd).
129656 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
129657 || (bRev && pIdx->nKeyCol==nEq)
129659 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
129660 SWAP(u8, bSeekPastNull, bStopAtNull);
129661 SWAP(u8, nBtm, nTop);
129664 /* Generate code to evaluate all constraint terms using == or IN
129665 ** and store the values of those terms in an array of registers
129666 ** starting at regBase.
129668 codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
129669 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
129670 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
129671 if( zStartAff && nTop ){
129672 zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
129674 addrNxt = pLevel->addrNxt;
129676 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
129677 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
129678 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
129679 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
129680 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
129681 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
129682 start_constraints = pRangeStart || nEq>0;
129684 /* Seek the index cursor to the start of the range. */
129685 nConstraint = nEq;
129686 if( pRangeStart ){
129687 Expr *pRight = pRangeStart->pExpr->pRight;
129688 codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
129689 whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
129690 if( (pRangeStart->wtFlags & TERM_VNULL)==0
129691 && sqlite3ExprCanBeNull(pRight)
129693 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
129694 VdbeCoverage(v);
129696 if( zStartAff ){
129697 updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
129699 nConstraint += nBtm;
129700 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
129701 if( sqlite3ExprIsVector(pRight)==0 ){
129702 disableTerm(pLevel, pRangeStart);
129703 }else{
129704 startEq = 1;
129706 bSeekPastNull = 0;
129707 }else if( bSeekPastNull ){
129708 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
129709 nConstraint++;
129710 startEq = 0;
129711 start_constraints = 1;
129713 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
129714 if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
129715 /* The skip-scan logic inside the call to codeAllEqualityConstraints()
129716 ** above has already left the cursor sitting on the correct row,
129717 ** so no further seeking is needed */
129718 }else{
129719 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
129720 assert( op!=0 );
129721 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
129722 VdbeCoverage(v);
129723 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
129724 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
129725 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
129726 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
129727 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
129728 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
129731 /* Load the value for the inequality constraint at the end of the
129732 ** range (if any).
129734 nConstraint = nEq;
129735 if( pRangeEnd ){
129736 Expr *pRight = pRangeEnd->pExpr->pRight;
129737 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
129738 codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
129739 whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
129740 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
129741 && sqlite3ExprCanBeNull(pRight)
129743 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
129744 VdbeCoverage(v);
129746 if( zEndAff ){
129747 updateRangeAffinityStr(pRight, nTop, zEndAff);
129748 codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
129749 }else{
129750 assert( pParse->db->mallocFailed );
129752 nConstraint += nTop;
129753 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
129755 if( sqlite3ExprIsVector(pRight)==0 ){
129756 disableTerm(pLevel, pRangeEnd);
129757 }else{
129758 endEq = 1;
129760 }else if( bStopAtNull ){
129761 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
129762 endEq = 0;
129763 nConstraint++;
129765 sqlite3DbFree(db, zStartAff);
129766 sqlite3DbFree(db, zEndAff);
129768 /* Top of the loop body */
129769 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
129771 /* Check if the index cursor is past the end of the range. */
129772 if( nConstraint ){
129773 op = aEndOp[bRev*2 + endEq];
129774 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
129775 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
129776 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
129777 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
129778 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
129781 /* Seek the table cursor, if required */
129782 if( omitTable ){
129783 /* pIdx is a covering index. No need to access the main table. */
129784 }else if( HasRowid(pIdx->pTable) ){
129785 if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
129786 (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
129787 && (pWInfo->eOnePass==ONEPASS_SINGLE)
129789 iRowidReg = ++pParse->nMem;
129790 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
129791 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
129792 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
129793 VdbeCoverage(v);
129794 }else{
129795 codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
129797 }else if( iCur!=iIdxCur ){
129798 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
129799 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
129800 for(j=0; j<pPk->nKeyCol; j++){
129801 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
129802 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
129804 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
129805 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
129808 /* If pIdx is an index on one or more expressions, then look through
129809 ** all the expressions in pWInfo and try to transform matching expressions
129810 ** into reference to index columns.
129812 whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
129815 /* Record the instruction used to terminate the loop. */
129816 if( pLoop->wsFlags & WHERE_ONEROW ){
129817 pLevel->op = OP_Noop;
129818 }else if( bRev ){
129819 pLevel->op = OP_Prev;
129820 }else{
129821 pLevel->op = OP_Next;
129823 pLevel->p1 = iIdxCur;
129824 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
129825 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
129826 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
129827 }else{
129828 assert( pLevel->p5==0 );
129830 if( omitTable ) pIdx = 0;
129831 }else
129833 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
129834 if( pLoop->wsFlags & WHERE_MULTI_OR ){
129835 /* Case 5: Two or more separately indexed terms connected by OR
129837 ** Example:
129839 ** CREATE TABLE t1(a,b,c,d);
129840 ** CREATE INDEX i1 ON t1(a);
129841 ** CREATE INDEX i2 ON t1(b);
129842 ** CREATE INDEX i3 ON t1(c);
129844 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
129846 ** In the example, there are three indexed terms connected by OR.
129847 ** The top of the loop looks like this:
129849 ** Null 1 # Zero the rowset in reg 1
129851 ** Then, for each indexed term, the following. The arguments to
129852 ** RowSetTest are such that the rowid of the current row is inserted
129853 ** into the RowSet. If it is already present, control skips the
129854 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
129856 ** sqlite3WhereBegin(<term>)
129857 ** RowSetTest # Insert rowid into rowset
129858 ** Gosub 2 A
129859 ** sqlite3WhereEnd()
129861 ** Following the above, code to terminate the loop. Label A, the target
129862 ** of the Gosub above, jumps to the instruction right after the Goto.
129864 ** Null 1 # Zero the rowset in reg 1
129865 ** Goto B # The loop is finished.
129867 ** A: <loop body> # Return data, whatever.
129869 ** Return 2 # Jump back to the Gosub
129871 ** B: <after the loop>
129873 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
129874 ** use an ephemeral index instead of a RowSet to record the primary
129875 ** keys of the rows we have already seen.
129878 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
129879 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
129880 Index *pCov = 0; /* Potential covering index (or NULL) */
129881 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
129883 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
129884 int regRowset = 0; /* Register for RowSet object */
129885 int regRowid = 0; /* Register holding rowid */
129886 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
129887 int iRetInit; /* Address of regReturn init */
129888 int untestedTerms = 0; /* Some terms not completely tested */
129889 int ii; /* Loop counter */
129890 u16 wctrlFlags; /* Flags for sub-WHERE clause */
129891 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
129892 Table *pTab = pTabItem->pTab;
129894 pTerm = pLoop->aLTerm[0];
129895 assert( pTerm!=0 );
129896 assert( pTerm->eOperator & WO_OR );
129897 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
129898 pOrWc = &pTerm->u.pOrInfo->wc;
129899 pLevel->op = OP_Return;
129900 pLevel->p1 = regReturn;
129902 /* Set up a new SrcList in pOrTab containing the table being scanned
129903 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
129904 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
129906 if( pWInfo->nLevel>1 ){
129907 int nNotReady; /* The number of notReady tables */
129908 struct SrcList_item *origSrc; /* Original list of tables */
129909 nNotReady = pWInfo->nLevel - iLevel - 1;
129910 pOrTab = sqlite3StackAllocRaw(db,
129911 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
129912 if( pOrTab==0 ) return notReady;
129913 pOrTab->nAlloc = (u8)(nNotReady + 1);
129914 pOrTab->nSrc = pOrTab->nAlloc;
129915 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
129916 origSrc = pWInfo->pTabList->a;
129917 for(k=1; k<=nNotReady; k++){
129918 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
129920 }else{
129921 pOrTab = pWInfo->pTabList;
129924 /* Initialize the rowset register to contain NULL. An SQL NULL is
129925 ** equivalent to an empty rowset. Or, create an ephemeral index
129926 ** capable of holding primary keys in the case of a WITHOUT ROWID.
129928 ** Also initialize regReturn to contain the address of the instruction
129929 ** immediately following the OP_Return at the bottom of the loop. This
129930 ** is required in a few obscure LEFT JOIN cases where control jumps
129931 ** over the top of the loop into the body of it. In this case the
129932 ** correct response for the end-of-loop code (the OP_Return) is to
129933 ** fall through to the next instruction, just as an OP_Next does if
129934 ** called on an uninitialized cursor.
129936 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
129937 if( HasRowid(pTab) ){
129938 regRowset = ++pParse->nMem;
129939 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
129940 }else{
129941 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
129942 regRowset = pParse->nTab++;
129943 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
129944 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
129946 regRowid = ++pParse->nMem;
129948 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
129950 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
129951 ** Then for every term xN, evaluate as the subexpression: xN AND z
129952 ** That way, terms in y that are factored into the disjunction will
129953 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
129955 ** Actually, each subexpression is converted to "xN AND w" where w is
129956 ** the "interesting" terms of z - terms that did not originate in the
129957 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
129958 ** indices.
129960 ** This optimization also only applies if the (x1 OR x2 OR ...) term
129961 ** is not contained in the ON clause of a LEFT JOIN.
129962 ** See ticket http://www.sqlite.org/src/info/f2369304e4
129964 if( pWC->nTerm>1 ){
129965 int iTerm;
129966 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
129967 Expr *pExpr = pWC->a[iTerm].pExpr;
129968 if( &pWC->a[iTerm] == pTerm ) continue;
129969 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
129970 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
129971 testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
129972 if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
129973 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
129974 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
129975 pExpr = sqlite3ExprDup(db, pExpr, 0);
129976 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
129978 if( pAndExpr ){
129979 pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
129983 /* Run a separate WHERE clause for each term of the OR clause. After
129984 ** eliminating duplicates from other WHERE clauses, the action for each
129985 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
129987 wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
129988 for(ii=0; ii<pOrWc->nTerm; ii++){
129989 WhereTerm *pOrTerm = &pOrWc->a[ii];
129990 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
129991 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
129992 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
129993 int jmp1 = 0; /* Address of jump operation */
129994 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
129995 pAndExpr->pLeft = pOrExpr;
129996 pOrExpr = pAndExpr;
129998 /* Loop through table entries that match term pOrTerm. */
129999 WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
130000 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
130001 wctrlFlags, iCovCur);
130002 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
130003 if( pSubWInfo ){
130004 WhereLoop *pSubLoop;
130005 int addrExplain = sqlite3WhereExplainOneScan(
130006 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
130008 sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
130010 /* This is the sub-WHERE clause body. First skip over
130011 ** duplicate rows from prior sub-WHERE clauses, and record the
130012 ** rowid (or PRIMARY KEY) for the current row so that the same
130013 ** row will be skipped in subsequent sub-WHERE clauses.
130015 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
130016 int r;
130017 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
130018 if( HasRowid(pTab) ){
130019 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
130020 jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
130021 r,iSet);
130022 VdbeCoverage(v);
130023 }else{
130024 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
130025 int nPk = pPk->nKeyCol;
130026 int iPk;
130028 /* Read the PK into an array of temp registers. */
130029 r = sqlite3GetTempRange(pParse, nPk);
130030 for(iPk=0; iPk<nPk; iPk++){
130031 int iCol = pPk->aiColumn[iPk];
130032 sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
130035 /* Check if the temp table already contains this key. If so,
130036 ** the row has already been included in the result set and
130037 ** can be ignored (by jumping past the Gosub below). Otherwise,
130038 ** insert the key into the temp table and proceed with processing
130039 ** the row.
130041 ** Use some of the same optimizations as OP_RowSetTest: If iSet
130042 ** is zero, assume that the key cannot already be present in
130043 ** the temp table. And if iSet is -1, assume that there is no
130044 ** need to insert the key into the temp table, as it will never
130045 ** be tested for. */
130046 if( iSet ){
130047 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
130048 VdbeCoverage(v);
130050 if( iSet>=0 ){
130051 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
130052 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
130053 r, nPk);
130054 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
130057 /* Release the array of temp registers */
130058 sqlite3ReleaseTempRange(pParse, r, nPk);
130062 /* Invoke the main loop body as a subroutine */
130063 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
130065 /* Jump here (skipping the main loop body subroutine) if the
130066 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
130067 if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
130069 /* The pSubWInfo->untestedTerms flag means that this OR term
130070 ** contained one or more AND term from a notReady table. The
130071 ** terms from the notReady table could not be tested and will
130072 ** need to be tested later.
130074 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
130076 /* If all of the OR-connected terms are optimized using the same
130077 ** index, and the index is opened using the same cursor number
130078 ** by each call to sqlite3WhereBegin() made by this loop, it may
130079 ** be possible to use that index as a covering index.
130081 ** If the call to sqlite3WhereBegin() above resulted in a scan that
130082 ** uses an index, and this is either the first OR-connected term
130083 ** processed or the index is the same as that used by all previous
130084 ** terms, set pCov to the candidate covering index. Otherwise, set
130085 ** pCov to NULL to indicate that no candidate covering index will
130086 ** be available.
130088 pSubLoop = pSubWInfo->a[0].pWLoop;
130089 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
130090 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
130091 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
130092 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
130094 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
130095 pCov = pSubLoop->u.btree.pIndex;
130096 }else{
130097 pCov = 0;
130100 /* Finish the loop through table entries that match term pOrTerm. */
130101 sqlite3WhereEnd(pSubWInfo);
130105 pLevel->u.pCovidx = pCov;
130106 if( pCov ) pLevel->iIdxCur = iCovCur;
130107 if( pAndExpr ){
130108 pAndExpr->pLeft = 0;
130109 sqlite3ExprDelete(db, pAndExpr);
130111 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
130112 sqlite3VdbeGoto(v, pLevel->addrBrk);
130113 sqlite3VdbeResolveLabel(v, iLoopBody);
130115 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
130116 if( !untestedTerms ) disableTerm(pLevel, pTerm);
130117 }else
130118 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
130121 /* Case 6: There is no usable index. We must do a complete
130122 ** scan of the entire table.
130124 static const u8 aStep[] = { OP_Next, OP_Prev };
130125 static const u8 aStart[] = { OP_Rewind, OP_Last };
130126 assert( bRev==0 || bRev==1 );
130127 if( pTabItem->fg.isRecursive ){
130128 /* Tables marked isRecursive have only a single row that is stored in
130129 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
130130 pLevel->op = OP_Noop;
130131 }else{
130132 codeCursorHint(pTabItem, pWInfo, pLevel, 0);
130133 pLevel->op = aStep[bRev];
130134 pLevel->p1 = iCur;
130135 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
130136 VdbeCoverageIf(v, bRev==0);
130137 VdbeCoverageIf(v, bRev!=0);
130138 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
130142 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
130143 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
130144 #endif
130146 /* Insert code to test every subexpression that can be completely
130147 ** computed using the current set of tables.
130149 ** This loop may run between one and three times, depending on the
130150 ** constraints to be generated. The value of stack variable iLoop
130151 ** determines the constraints coded by each iteration, as follows:
130153 ** iLoop==1: Code only expressions that are entirely covered by pIdx.
130154 ** iLoop==2: Code remaining expressions that do not contain correlated
130155 ** sub-queries.
130156 ** iLoop==3: Code all remaining expressions.
130158 ** An effort is made to skip unnecessary iterations of the loop.
130160 iLoop = (pIdx ? 1 : 2);
130162 int iNext = 0; /* Next value for iLoop */
130163 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
130164 Expr *pE;
130165 int skipLikeAddr = 0;
130166 testcase( pTerm->wtFlags & TERM_VIRTUAL );
130167 testcase( pTerm->wtFlags & TERM_CODED );
130168 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
130169 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
130170 testcase( pWInfo->untestedTerms==0
130171 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
130172 pWInfo->untestedTerms = 1;
130173 continue;
130175 pE = pTerm->pExpr;
130176 assert( pE!=0 );
130177 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
130178 continue;
130181 if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
130182 iNext = 2;
130183 continue;
130185 if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
130186 if( iNext==0 ) iNext = 3;
130187 continue;
130190 if( pTerm->wtFlags & TERM_LIKECOND ){
130191 /* If the TERM_LIKECOND flag is set, that means that the range search
130192 ** is sufficient to guarantee that the LIKE operator is true, so we
130193 ** can skip the call to the like(A,B) function. But this only works
130194 ** for strings. So do not skip the call to the function on the pass
130195 ** that compares BLOBs. */
130196 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
130197 continue;
130198 #else
130199 u32 x = pLevel->iLikeRepCntr;
130200 assert( x>0 );
130201 skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If, (int)(x>>1));
130202 VdbeCoverage(v);
130203 #endif
130205 #ifdef WHERETRACE_ENABLED /* 0xffff */
130206 if( sqlite3WhereTrace ){
130207 VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
130208 pWC->nTerm-j, pTerm, iLoop));
130210 #endif
130211 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
130212 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
130213 pTerm->wtFlags |= TERM_CODED;
130215 iLoop = iNext;
130216 }while( iLoop>0 );
130218 /* Insert code to test for implied constraints based on transitivity
130219 ** of the "==" operator.
130221 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
130222 ** and we are coding the t1 loop and the t2 loop has not yet coded,
130223 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
130224 ** the implied "t1.a=123" constraint.
130226 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
130227 Expr *pE, sEAlt;
130228 WhereTerm *pAlt;
130229 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
130230 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
130231 if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
130232 if( pTerm->leftCursor!=iCur ) continue;
130233 if( pLevel->iLeftJoin ) continue;
130234 pE = pTerm->pExpr;
130235 assert( !ExprHasProperty(pE, EP_FromJoin) );
130236 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
130237 pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
130238 WO_EQ|WO_IN|WO_IS, 0);
130239 if( pAlt==0 ) continue;
130240 if( pAlt->wtFlags & (TERM_CODED) ) continue;
130241 testcase( pAlt->eOperator & WO_EQ );
130242 testcase( pAlt->eOperator & WO_IS );
130243 testcase( pAlt->eOperator & WO_IN );
130244 VdbeModuleComment((v, "begin transitive constraint"));
130245 sEAlt = *pAlt->pExpr;
130246 sEAlt.pLeft = pE->pLeft;
130247 sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
130250 /* For a LEFT OUTER JOIN, generate code that will record the fact that
130251 ** at least one row of the right table has matched the left table.
130253 if( pLevel->iLeftJoin ){
130254 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
130255 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
130256 VdbeComment((v, "record LEFT JOIN hit"));
130257 sqlite3ExprCacheClear(pParse);
130258 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
130259 testcase( pTerm->wtFlags & TERM_VIRTUAL );
130260 testcase( pTerm->wtFlags & TERM_CODED );
130261 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
130262 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
130263 assert( pWInfo->untestedTerms );
130264 continue;
130266 assert( pTerm->pExpr );
130267 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
130268 pTerm->wtFlags |= TERM_CODED;
130272 return pLevel->notReady;
130275 /************** End of wherecode.c *******************************************/
130276 /************** Begin file whereexpr.c ***************************************/
130278 ** 2015-06-08
130280 ** The author disclaims copyright to this source code. In place of
130281 ** a legal notice, here is a blessing:
130283 ** May you do good and not evil.
130284 ** May you find forgiveness for yourself and forgive others.
130285 ** May you share freely, never taking more than you give.
130287 *************************************************************************
130288 ** This module contains C code that generates VDBE code used to process
130289 ** the WHERE clause of SQL statements.
130291 ** This file was originally part of where.c but was split out to improve
130292 ** readability and editabiliity. This file contains utility routines for
130293 ** analyzing Expr objects in the WHERE clause.
130295 /* #include "sqliteInt.h" */
130296 /* #include "whereInt.h" */
130298 /* Forward declarations */
130299 static void exprAnalyze(SrcList*, WhereClause*, int);
130302 ** Deallocate all memory associated with a WhereOrInfo object.
130304 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
130305 sqlite3WhereClauseClear(&p->wc);
130306 sqlite3DbFree(db, p);
130310 ** Deallocate all memory associated with a WhereAndInfo object.
130312 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
130313 sqlite3WhereClauseClear(&p->wc);
130314 sqlite3DbFree(db, p);
130318 ** Add a single new WhereTerm entry to the WhereClause object pWC.
130319 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
130320 ** The index in pWC->a[] of the new WhereTerm is returned on success.
130321 ** 0 is returned if the new WhereTerm could not be added due to a memory
130322 ** allocation error. The memory allocation failure will be recorded in
130323 ** the db->mallocFailed flag so that higher-level functions can detect it.
130325 ** This routine will increase the size of the pWC->a[] array as necessary.
130327 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
130328 ** for freeing the expression p is assumed by the WhereClause object pWC.
130329 ** This is true even if this routine fails to allocate a new WhereTerm.
130331 ** WARNING: This routine might reallocate the space used to store
130332 ** WhereTerms. All pointers to WhereTerms should be invalidated after
130333 ** calling this routine. Such pointers may be reinitialized by referencing
130334 ** the pWC->a[] array.
130336 static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
130337 WhereTerm *pTerm;
130338 int idx;
130339 testcase( wtFlags & TERM_VIRTUAL );
130340 if( pWC->nTerm>=pWC->nSlot ){
130341 WhereTerm *pOld = pWC->a;
130342 sqlite3 *db = pWC->pWInfo->pParse->db;
130343 pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
130344 if( pWC->a==0 ){
130345 if( wtFlags & TERM_DYNAMIC ){
130346 sqlite3ExprDelete(db, p);
130348 pWC->a = pOld;
130349 return 0;
130351 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
130352 if( pOld!=pWC->aStatic ){
130353 sqlite3DbFree(db, pOld);
130355 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
130357 pTerm = &pWC->a[idx = pWC->nTerm++];
130358 if( p && ExprHasProperty(p, EP_Unlikely) ){
130359 pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
130360 }else{
130361 pTerm->truthProb = 1;
130363 pTerm->pExpr = sqlite3ExprSkipCollate(p);
130364 pTerm->wtFlags = wtFlags;
130365 pTerm->pWC = pWC;
130366 pTerm->iParent = -1;
130367 memset(&pTerm->eOperator, 0,
130368 sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
130369 return idx;
130373 ** Return TRUE if the given operator is one of the operators that is
130374 ** allowed for an indexable WHERE clause term. The allowed operators are
130375 ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
130377 static int allowedOp(int op){
130378 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
130379 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
130380 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
130381 assert( TK_GE==TK_EQ+4 );
130382 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
130386 ** Commute a comparison operator. Expressions of the form "X op Y"
130387 ** are converted into "Y op X".
130389 ** If left/right precedence rules come into play when determining the
130390 ** collating sequence, then COLLATE operators are adjusted to ensure
130391 ** that the collating sequence does not change. For example:
130392 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
130393 ** the left hand side of a comparison overrides any collation sequence
130394 ** attached to the right. For the same reason the EP_Collate flag
130395 ** is not commuted.
130397 static void exprCommute(Parse *pParse, Expr *pExpr){
130398 u16 expRight = (pExpr->pRight->flags & EP_Collate);
130399 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
130400 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
130401 if( expRight==expLeft ){
130402 /* Either X and Y both have COLLATE operator or neither do */
130403 if( expRight ){
130404 /* Both X and Y have COLLATE operators. Make sure X is always
130405 ** used by clearing the EP_Collate flag from Y. */
130406 pExpr->pRight->flags &= ~EP_Collate;
130407 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
130408 /* Neither X nor Y have COLLATE operators, but X has a non-default
130409 ** collating sequence. So add the EP_Collate marker on X to cause
130410 ** it to be searched first. */
130411 pExpr->pLeft->flags |= EP_Collate;
130414 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
130415 if( pExpr->op>=TK_GT ){
130416 assert( TK_LT==TK_GT+2 );
130417 assert( TK_GE==TK_LE+2 );
130418 assert( TK_GT>TK_EQ );
130419 assert( TK_GT<TK_LE );
130420 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
130421 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
130426 ** Translate from TK_xx operator to WO_xx bitmask.
130428 static u16 operatorMask(int op){
130429 u16 c;
130430 assert( allowedOp(op) );
130431 if( op==TK_IN ){
130432 c = WO_IN;
130433 }else if( op==TK_ISNULL ){
130434 c = WO_ISNULL;
130435 }else if( op==TK_IS ){
130436 c = WO_IS;
130437 }else{
130438 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
130439 c = (u16)(WO_EQ<<(op-TK_EQ));
130441 assert( op!=TK_ISNULL || c==WO_ISNULL );
130442 assert( op!=TK_IN || c==WO_IN );
130443 assert( op!=TK_EQ || c==WO_EQ );
130444 assert( op!=TK_LT || c==WO_LT );
130445 assert( op!=TK_LE || c==WO_LE );
130446 assert( op!=TK_GT || c==WO_GT );
130447 assert( op!=TK_GE || c==WO_GE );
130448 assert( op!=TK_IS || c==WO_IS );
130449 return c;
130453 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
130455 ** Check to see if the given expression is a LIKE or GLOB operator that
130456 ** can be optimized using inequality constraints. Return TRUE if it is
130457 ** so and false if not.
130459 ** In order for the operator to be optimizible, the RHS must be a string
130460 ** literal that does not begin with a wildcard. The LHS must be a column
130461 ** that may only be NULL, a string, or a BLOB, never a number. (This means
130462 ** that virtual tables cannot participate in the LIKE optimization.) The
130463 ** collating sequence for the column on the LHS must be appropriate for
130464 ** the operator.
130466 static int isLikeOrGlob(
130467 Parse *pParse, /* Parsing and code generating context */
130468 Expr *pExpr, /* Test this expression */
130469 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
130470 int *pisComplete, /* True if the only wildcard is % in the last character */
130471 int *pnoCase /* True if uppercase is equivalent to lowercase */
130473 const u8 *z = 0; /* String on RHS of LIKE operator */
130474 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
130475 ExprList *pList; /* List of operands to the LIKE operator */
130476 int c; /* One character in z[] */
130477 int cnt; /* Number of non-wildcard prefix characters */
130478 char wc[4]; /* Wildcard characters */
130479 sqlite3 *db = pParse->db; /* Database connection */
130480 sqlite3_value *pVal = 0;
130481 int op; /* Opcode of pRight */
130482 int rc; /* Result code to return */
130484 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
130485 return 0;
130487 #ifdef SQLITE_EBCDIC
130488 if( *pnoCase ) return 0;
130489 #endif
130490 pList = pExpr->x.pList;
130491 pLeft = pList->a[1].pExpr;
130493 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
130494 op = pRight->op;
130495 if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
130496 Vdbe *pReprepare = pParse->pReprepare;
130497 int iCol = pRight->iColumn;
130498 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
130499 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
130500 z = sqlite3_value_text(pVal);
130502 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
130503 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
130504 }else if( op==TK_STRING ){
130505 z = (u8*)pRight->u.zToken;
130507 if( z ){
130509 /* If the RHS begins with a digit or a minus sign, then the LHS must
130510 ** be an ordinary column (not a virtual table column) with TEXT affinity.
130511 ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
130512 ** even though "lhs LIKE rhs" is true. But if the RHS does not start
130513 ** with a digit or '-', then "lhs LIKE rhs" will always be false if
130514 ** the LHS is numeric and so the optimization still works.
130516 if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
130517 if( pLeft->op!=TK_COLUMN
130518 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
130519 || IsVirtual(pLeft->pTab) /* Value might be numeric */
130521 sqlite3ValueFree(pVal);
130522 return 0;
130526 /* Count the number of prefix characters prior to the first wildcard */
130527 cnt = 0;
130528 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
130529 cnt++;
130530 if( c==wc[3] && z[cnt]!=0 ) cnt++;
130533 /* The optimization is possible only if (1) the pattern does not begin
130534 ** with a wildcard and if (2) the non-wildcard prefix does not end with
130535 ** an (illegal 0xff) character. The second condition is necessary so
130536 ** that we can increment the prefix key to find an upper bound for the
130537 ** range search.
130539 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
130540 Expr *pPrefix;
130542 /* A "complete" match if the pattern ends with "*" or "%" */
130543 *pisComplete = c==wc[0] && z[cnt+1]==0;
130545 /* Get the pattern prefix. Remove all escapes from the prefix. */
130546 pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
130547 if( pPrefix ){
130548 int iFrom, iTo;
130549 char *zNew = pPrefix->u.zToken;
130550 zNew[cnt] = 0;
130551 for(iFrom=iTo=0; iFrom<cnt; iFrom++){
130552 if( zNew[iFrom]==wc[3] ) iFrom++;
130553 zNew[iTo++] = zNew[iFrom];
130555 zNew[iTo] = 0;
130557 *ppPrefix = pPrefix;
130559 /* If the RHS pattern is a bound parameter, make arrangements to
130560 ** reprepare the statement when that parameter is rebound */
130561 if( op==TK_VARIABLE ){
130562 Vdbe *v = pParse->pVdbe;
130563 sqlite3VdbeSetVarmask(v, pRight->iColumn);
130564 if( *pisComplete && pRight->u.zToken[1] ){
130565 /* If the rhs of the LIKE expression is a variable, and the current
130566 ** value of the variable means there is no need to invoke the LIKE
130567 ** function, then no OP_Variable will be added to the program.
130568 ** This causes problems for the sqlite3_bind_parameter_name()
130569 ** API. To work around them, add a dummy OP_Variable here.
130571 int r1 = sqlite3GetTempReg(pParse);
130572 sqlite3ExprCodeTarget(pParse, pRight, r1);
130573 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
130574 sqlite3ReleaseTempReg(pParse, r1);
130577 }else{
130578 z = 0;
130582 rc = (z!=0);
130583 sqlite3ValueFree(pVal);
130584 return rc;
130586 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
130589 #ifndef SQLITE_OMIT_VIRTUALTABLE
130591 ** Check to see if the pExpr expression is a form that needs to be passed
130592 ** to the xBestIndex method of virtual tables. Forms of interest include:
130594 ** Expression Virtual Table Operator
130595 ** ----------------------- ---------------------------------
130596 ** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
130597 ** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
130598 ** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
130599 ** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
130600 ** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
130601 ** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
130602 ** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
130603 ** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
130604 ** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
130606 ** In every case, "column" must be a column of a virtual table. If there
130607 ** is a match, set *ppLeft to the "column" expression, set *ppRight to the
130608 ** "expr" expression (even though in forms (6) and (8) the column is on the
130609 ** right and the expression is on the left). Also set *peOp2 to the
130610 ** appropriate virtual table operator. The return value is 1 or 2 if there
130611 ** is a match. The usual return is 1, but if the RHS is also a column
130612 ** of virtual table in forms (5) or (7) then return 2.
130614 ** If the expression matches none of the patterns above, return 0.
130616 static int isAuxiliaryVtabOperator(
130617 Expr *pExpr, /* Test this expression */
130618 unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
130619 Expr **ppLeft, /* Column expression to left of MATCH/op2 */
130620 Expr **ppRight /* Expression to left of MATCH/op2 */
130622 if( pExpr->op==TK_FUNCTION ){
130623 static const struct Op2 {
130624 const char *zOp;
130625 unsigned char eOp2;
130626 } aOp[] = {
130627 { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
130628 { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
130629 { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
130630 { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
130632 ExprList *pList;
130633 Expr *pCol; /* Column reference */
130634 int i;
130636 pList = pExpr->x.pList;
130637 if( pList==0 || pList->nExpr!=2 ){
130638 return 0;
130640 pCol = pList->a[1].pExpr;
130641 if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
130642 return 0;
130644 for(i=0; i<ArraySize(aOp); i++){
130645 if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
130646 *peOp2 = aOp[i].eOp2;
130647 *ppRight = pList->a[0].pExpr;
130648 *ppLeft = pCol;
130649 return 1;
130652 }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
130653 int res = 0;
130654 Expr *pLeft = pExpr->pLeft;
130655 Expr *pRight = pExpr->pRight;
130656 if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->pTab) ){
130657 res++;
130659 if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->pTab) ){
130660 res++;
130661 SWAP(Expr*, pLeft, pRight);
130663 *ppLeft = pLeft;
130664 *ppRight = pRight;
130665 if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
130666 if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
130667 if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
130668 return res;
130670 return 0;
130672 #endif /* SQLITE_OMIT_VIRTUALTABLE */
130675 ** If the pBase expression originated in the ON or USING clause of
130676 ** a join, then transfer the appropriate markings over to derived.
130678 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
130679 if( pDerived ){
130680 pDerived->flags |= pBase->flags & EP_FromJoin;
130681 pDerived->iRightJoinTable = pBase->iRightJoinTable;
130686 ** Mark term iChild as being a child of term iParent
130688 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
130689 pWC->a[iChild].iParent = iParent;
130690 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
130691 pWC->a[iParent].nChild++;
130695 ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
130696 ** a conjunction, then return just pTerm when N==0. If N is exceeds
130697 ** the number of available subterms, return NULL.
130699 static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
130700 if( pTerm->eOperator!=WO_AND ){
130701 return N==0 ? pTerm : 0;
130703 if( N<pTerm->u.pAndInfo->wc.nTerm ){
130704 return &pTerm->u.pAndInfo->wc.a[N];
130706 return 0;
130710 ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
130711 ** two subterms are in disjunction - they are OR-ed together.
130713 ** If these two terms are both of the form: "A op B" with the same
130714 ** A and B values but different operators and if the operators are
130715 ** compatible (if one is = and the other is <, for example) then
130716 ** add a new virtual AND term to pWC that is the combination of the
130717 ** two.
130719 ** Some examples:
130721 ** x<y OR x=y --> x<=y
130722 ** x=y OR x=y --> x=y
130723 ** x<=y OR x<y --> x<=y
130725 ** The following is NOT generated:
130727 ** x<y OR x>y --> x!=y
130729 static void whereCombineDisjuncts(
130730 SrcList *pSrc, /* the FROM clause */
130731 WhereClause *pWC, /* The complete WHERE clause */
130732 WhereTerm *pOne, /* First disjunct */
130733 WhereTerm *pTwo /* Second disjunct */
130735 u16 eOp = pOne->eOperator | pTwo->eOperator;
130736 sqlite3 *db; /* Database connection (for malloc) */
130737 Expr *pNew; /* New virtual expression */
130738 int op; /* Operator for the combined expression */
130739 int idxNew; /* Index in pWC of the next virtual term */
130741 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
130742 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
130743 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
130744 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
130745 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
130746 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
130747 if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
130748 if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
130749 /* If we reach this point, it means the two subterms can be combined */
130750 if( (eOp & (eOp-1))!=0 ){
130751 if( eOp & (WO_LT|WO_LE) ){
130752 eOp = WO_LE;
130753 }else{
130754 assert( eOp & (WO_GT|WO_GE) );
130755 eOp = WO_GE;
130758 db = pWC->pWInfo->pParse->db;
130759 pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
130760 if( pNew==0 ) return;
130761 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
130762 pNew->op = op;
130763 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
130764 exprAnalyze(pSrc, pWC, idxNew);
130767 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
130769 ** Analyze a term that consists of two or more OR-connected
130770 ** subterms. So in:
130772 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
130773 ** ^^^^^^^^^^^^^^^^^^^^
130775 ** This routine analyzes terms such as the middle term in the above example.
130776 ** A WhereOrTerm object is computed and attached to the term under
130777 ** analysis, regardless of the outcome of the analysis. Hence:
130779 ** WhereTerm.wtFlags |= TERM_ORINFO
130780 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
130782 ** The term being analyzed must have two or more of OR-connected subterms.
130783 ** A single subterm might be a set of AND-connected sub-subterms.
130784 ** Examples of terms under analysis:
130786 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
130787 ** (B) x=expr1 OR expr2=x OR x=expr3
130788 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
130789 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
130790 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
130791 ** (F) x>A OR (x=A AND y>=B)
130793 ** CASE 1:
130795 ** If all subterms are of the form T.C=expr for some single column of C and
130796 ** a single table T (as shown in example B above) then create a new virtual
130797 ** term that is an equivalent IN expression. In other words, if the term
130798 ** being analyzed is:
130800 ** x = expr1 OR expr2 = x OR x = expr3
130802 ** then create a new virtual term like this:
130804 ** x IN (expr1,expr2,expr3)
130806 ** CASE 2:
130808 ** If there are exactly two disjuncts and one side has x>A and the other side
130809 ** has x=A (for the same x and A) then add a new virtual conjunct term to the
130810 ** WHERE clause of the form "x>=A". Example:
130812 ** x>A OR (x=A AND y>B) adds: x>=A
130814 ** The added conjunct can sometimes be helpful in query planning.
130816 ** CASE 3:
130818 ** If all subterms are indexable by a single table T, then set
130820 ** WhereTerm.eOperator = WO_OR
130821 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
130823 ** A subterm is "indexable" if it is of the form
130824 ** "T.C <op> <expr>" where C is any column of table T and
130825 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
130826 ** A subterm is also indexable if it is an AND of two or more
130827 ** subsubterms at least one of which is indexable. Indexable AND
130828 ** subterms have their eOperator set to WO_AND and they have
130829 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
130831 ** From another point of view, "indexable" means that the subterm could
130832 ** potentially be used with an index if an appropriate index exists.
130833 ** This analysis does not consider whether or not the index exists; that
130834 ** is decided elsewhere. This analysis only looks at whether subterms
130835 ** appropriate for indexing exist.
130837 ** All examples A through E above satisfy case 3. But if a term
130838 ** also satisfies case 1 (such as B) we know that the optimizer will
130839 ** always prefer case 1, so in that case we pretend that case 3 is not
130840 ** satisfied.
130842 ** It might be the case that multiple tables are indexable. For example,
130843 ** (E) above is indexable on tables P, Q, and R.
130845 ** Terms that satisfy case 3 are candidates for lookup by using
130846 ** separate indices to find rowids for each subterm and composing
130847 ** the union of all rowids using a RowSet object. This is similar
130848 ** to "bitmap indices" in other database engines.
130850 ** OTHERWISE:
130852 ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
130853 ** zero. This term is not useful for search.
130855 static void exprAnalyzeOrTerm(
130856 SrcList *pSrc, /* the FROM clause */
130857 WhereClause *pWC, /* the complete WHERE clause */
130858 int idxTerm /* Index of the OR-term to be analyzed */
130860 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
130861 Parse *pParse = pWInfo->pParse; /* Parser context */
130862 sqlite3 *db = pParse->db; /* Database connection */
130863 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
130864 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
130865 int i; /* Loop counters */
130866 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
130867 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
130868 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
130869 Bitmask chngToIN; /* Tables that might satisfy case 1 */
130870 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
130873 ** Break the OR clause into its separate subterms. The subterms are
130874 ** stored in a WhereClause structure containing within the WhereOrInfo
130875 ** object that is attached to the original OR clause term.
130877 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
130878 assert( pExpr->op==TK_OR );
130879 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
130880 if( pOrInfo==0 ) return;
130881 pTerm->wtFlags |= TERM_ORINFO;
130882 pOrWc = &pOrInfo->wc;
130883 memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
130884 sqlite3WhereClauseInit(pOrWc, pWInfo);
130885 sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
130886 sqlite3WhereExprAnalyze(pSrc, pOrWc);
130887 if( db->mallocFailed ) return;
130888 assert( pOrWc->nTerm>=2 );
130891 ** Compute the set of tables that might satisfy cases 1 or 3.
130893 indexable = ~(Bitmask)0;
130894 chngToIN = ~(Bitmask)0;
130895 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
130896 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
130897 WhereAndInfo *pAndInfo;
130898 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
130899 chngToIN = 0;
130900 pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
130901 if( pAndInfo ){
130902 WhereClause *pAndWC;
130903 WhereTerm *pAndTerm;
130904 int j;
130905 Bitmask b = 0;
130906 pOrTerm->u.pAndInfo = pAndInfo;
130907 pOrTerm->wtFlags |= TERM_ANDINFO;
130908 pOrTerm->eOperator = WO_AND;
130909 pAndWC = &pAndInfo->wc;
130910 memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
130911 sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
130912 sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
130913 sqlite3WhereExprAnalyze(pSrc, pAndWC);
130914 pAndWC->pOuter = pWC;
130915 if( !db->mallocFailed ){
130916 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
130917 assert( pAndTerm->pExpr );
130918 if( allowedOp(pAndTerm->pExpr->op)
130919 || pAndTerm->eOperator==WO_AUX
130921 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
130925 indexable &= b;
130927 }else if( pOrTerm->wtFlags & TERM_COPIED ){
130928 /* Skip this term for now. We revisit it when we process the
130929 ** corresponding TERM_VIRTUAL term */
130930 }else{
130931 Bitmask b;
130932 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
130933 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
130934 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
130935 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
130937 indexable &= b;
130938 if( (pOrTerm->eOperator & WO_EQ)==0 ){
130939 chngToIN = 0;
130940 }else{
130941 chngToIN &= b;
130947 ** Record the set of tables that satisfy case 3. The set might be
130948 ** empty.
130950 pOrInfo->indexable = indexable;
130951 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
130953 /* For a two-way OR, attempt to implementation case 2.
130955 if( indexable && pOrWc->nTerm==2 ){
130956 int iOne = 0;
130957 WhereTerm *pOne;
130958 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
130959 int iTwo = 0;
130960 WhereTerm *pTwo;
130961 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
130962 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
130968 ** chngToIN holds a set of tables that *might* satisfy case 1. But
130969 ** we have to do some additional checking to see if case 1 really
130970 ** is satisfied.
130972 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
130973 ** that there is no possibility of transforming the OR clause into an
130974 ** IN operator because one or more terms in the OR clause contain
130975 ** something other than == on a column in the single table. The 1-bit
130976 ** case means that every term of the OR clause is of the form
130977 ** "table.column=expr" for some single table. The one bit that is set
130978 ** will correspond to the common table. We still need to check to make
130979 ** sure the same column is used on all terms. The 2-bit case is when
130980 ** the all terms are of the form "table1.column=table2.column". It
130981 ** might be possible to form an IN operator with either table1.column
130982 ** or table2.column as the LHS if either is common to every term of
130983 ** the OR clause.
130985 ** Note that terms of the form "table.column1=table.column2" (the
130986 ** same table on both sizes of the ==) cannot be optimized.
130988 if( chngToIN ){
130989 int okToChngToIN = 0; /* True if the conversion to IN is valid */
130990 int iColumn = -1; /* Column index on lhs of IN operator */
130991 int iCursor = -1; /* Table cursor common to all terms */
130992 int j = 0; /* Loop counter */
130994 /* Search for a table and column that appears on one side or the
130995 ** other of the == operator in every subterm. That table and column
130996 ** will be recorded in iCursor and iColumn. There might not be any
130997 ** such table and column. Set okToChngToIN if an appropriate table
130998 ** and column is found but leave okToChngToIN false if not found.
131000 for(j=0; j<2 && !okToChngToIN; j++){
131001 pOrTerm = pOrWc->a;
131002 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
131003 assert( pOrTerm->eOperator & WO_EQ );
131004 pOrTerm->wtFlags &= ~TERM_OR_OK;
131005 if( pOrTerm->leftCursor==iCursor ){
131006 /* This is the 2-bit case and we are on the second iteration and
131007 ** current term is from the first iteration. So skip this term. */
131008 assert( j==1 );
131009 continue;
131011 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
131012 pOrTerm->leftCursor))==0 ){
131013 /* This term must be of the form t1.a==t2.b where t2 is in the
131014 ** chngToIN set but t1 is not. This term will be either preceded
131015 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
131016 ** and use its inversion. */
131017 testcase( pOrTerm->wtFlags & TERM_COPIED );
131018 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
131019 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
131020 continue;
131022 iColumn = pOrTerm->u.leftColumn;
131023 iCursor = pOrTerm->leftCursor;
131024 break;
131026 if( i<0 ){
131027 /* No candidate table+column was found. This can only occur
131028 ** on the second iteration */
131029 assert( j==1 );
131030 assert( IsPowerOfTwo(chngToIN) );
131031 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
131032 break;
131034 testcase( j==1 );
131036 /* We have found a candidate table and column. Check to see if that
131037 ** table and column is common to every term in the OR clause */
131038 okToChngToIN = 1;
131039 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
131040 assert( pOrTerm->eOperator & WO_EQ );
131041 if( pOrTerm->leftCursor!=iCursor ){
131042 pOrTerm->wtFlags &= ~TERM_OR_OK;
131043 }else if( pOrTerm->u.leftColumn!=iColumn ){
131044 okToChngToIN = 0;
131045 }else{
131046 int affLeft, affRight;
131047 /* If the right-hand side is also a column, then the affinities
131048 ** of both right and left sides must be such that no type
131049 ** conversions are required on the right. (Ticket #2249)
131051 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
131052 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
131053 if( affRight!=0 && affRight!=affLeft ){
131054 okToChngToIN = 0;
131055 }else{
131056 pOrTerm->wtFlags |= TERM_OR_OK;
131062 /* At this point, okToChngToIN is true if original pTerm satisfies
131063 ** case 1. In that case, construct a new virtual term that is
131064 ** pTerm converted into an IN operator.
131066 if( okToChngToIN ){
131067 Expr *pDup; /* A transient duplicate expression */
131068 ExprList *pList = 0; /* The RHS of the IN operator */
131069 Expr *pLeft = 0; /* The LHS of the IN operator */
131070 Expr *pNew; /* The complete IN operator */
131072 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
131073 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
131074 assert( pOrTerm->eOperator & WO_EQ );
131075 assert( pOrTerm->leftCursor==iCursor );
131076 assert( pOrTerm->u.leftColumn==iColumn );
131077 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
131078 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
131079 pLeft = pOrTerm->pExpr->pLeft;
131081 assert( pLeft!=0 );
131082 pDup = sqlite3ExprDup(db, pLeft, 0);
131083 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
131084 if( pNew ){
131085 int idxNew;
131086 transferJoinMarkings(pNew, pExpr);
131087 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
131088 pNew->x.pList = pList;
131089 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
131090 testcase( idxNew==0 );
131091 exprAnalyze(pSrc, pWC, idxNew);
131092 pTerm = &pWC->a[idxTerm];
131093 markTermAsChild(pWC, idxNew, idxTerm);
131094 }else{
131095 sqlite3ExprListDelete(db, pList);
131097 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
131101 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
131104 ** We already know that pExpr is a binary operator where both operands are
131105 ** column references. This routine checks to see if pExpr is an equivalence
131106 ** relation:
131107 ** 1. The SQLITE_Transitive optimization must be enabled
131108 ** 2. Must be either an == or an IS operator
131109 ** 3. Not originating in the ON clause of an OUTER JOIN
131110 ** 4. The affinities of A and B must be compatible
131111 ** 5a. Both operands use the same collating sequence OR
131112 ** 5b. The overall collating sequence is BINARY
131113 ** If this routine returns TRUE, that means that the RHS can be substituted
131114 ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
131115 ** This is an optimization. No harm comes from returning 0. But if 1 is
131116 ** returned when it should not be, then incorrect answers might result.
131118 static int termIsEquivalence(Parse *pParse, Expr *pExpr){
131119 char aff1, aff2;
131120 CollSeq *pColl;
131121 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
131122 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
131123 if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
131124 aff1 = sqlite3ExprAffinity(pExpr->pLeft);
131125 aff2 = sqlite3ExprAffinity(pExpr->pRight);
131126 if( aff1!=aff2
131127 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
131129 return 0;
131131 pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
131132 if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
131133 return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
131137 ** Recursively walk the expressions of a SELECT statement and generate
131138 ** a bitmask indicating which tables are used in that expression
131139 ** tree.
131141 static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
131142 Bitmask mask = 0;
131143 while( pS ){
131144 SrcList *pSrc = pS->pSrc;
131145 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
131146 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
131147 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
131148 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
131149 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
131150 if( ALWAYS(pSrc!=0) ){
131151 int i;
131152 for(i=0; i<pSrc->nSrc; i++){
131153 mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
131154 mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
131157 pS = pS->pPrior;
131159 return mask;
131163 ** Expression pExpr is one operand of a comparison operator that might
131164 ** be useful for indexing. This routine checks to see if pExpr appears
131165 ** in any index. Return TRUE (1) if pExpr is an indexed term and return
131166 ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
131167 ** number of the table that is indexed and aiCurCol[1] to the column number
131168 ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
131169 ** indexed.
131171 ** If pExpr is a TK_COLUMN column reference, then this routine always returns
131172 ** true even if that particular column is not indexed, because the column
131173 ** might be added to an automatic index later.
131175 static SQLITE_NOINLINE int exprMightBeIndexed2(
131176 SrcList *pFrom, /* The FROM clause */
131177 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
131178 int *aiCurCol, /* Write the referenced table cursor and column here */
131179 Expr *pExpr /* An operand of a comparison operator */
131181 Index *pIdx;
131182 int i;
131183 int iCur;
131184 for(i=0; mPrereq>1; i++, mPrereq>>=1){}
131185 iCur = pFrom->a[i].iCursor;
131186 for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
131187 if( pIdx->aColExpr==0 ) continue;
131188 for(i=0; i<pIdx->nKeyCol; i++){
131189 if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
131190 if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
131191 aiCurCol[0] = iCur;
131192 aiCurCol[1] = XN_EXPR;
131193 return 1;
131197 return 0;
131199 static int exprMightBeIndexed(
131200 SrcList *pFrom, /* The FROM clause */
131201 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
131202 int *aiCurCol, /* Write the referenced table cursor & column here */
131203 Expr *pExpr, /* An operand of a comparison operator */
131204 int op /* The specific comparison operator */
131206 /* If this expression is a vector to the left or right of a
131207 ** inequality constraint (>, <, >= or <=), perform the processing
131208 ** on the first element of the vector. */
131209 assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
131210 assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
131211 assert( op<=TK_GE );
131212 if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
131213 pExpr = pExpr->x.pList->a[0].pExpr;
131216 if( pExpr->op==TK_COLUMN ){
131217 aiCurCol[0] = pExpr->iTable;
131218 aiCurCol[1] = pExpr->iColumn;
131219 return 1;
131221 if( mPrereq==0 ) return 0; /* No table references */
131222 if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
131223 return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
131227 ** The input to this routine is an WhereTerm structure with only the
131228 ** "pExpr" field filled in. The job of this routine is to analyze the
131229 ** subexpression and populate all the other fields of the WhereTerm
131230 ** structure.
131232 ** If the expression is of the form "<expr> <op> X" it gets commuted
131233 ** to the standard form of "X <op> <expr>".
131235 ** If the expression is of the form "X <op> Y" where both X and Y are
131236 ** columns, then the original expression is unchanged and a new virtual
131237 ** term of the form "Y <op> X" is added to the WHERE clause and
131238 ** analyzed separately. The original term is marked with TERM_COPIED
131239 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
131240 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
131241 ** is a commuted copy of a prior term.) The original term has nChild=1
131242 ** and the copy has idxParent set to the index of the original term.
131244 static void exprAnalyze(
131245 SrcList *pSrc, /* the FROM clause */
131246 WhereClause *pWC, /* the WHERE clause */
131247 int idxTerm /* Index of the term to be analyzed */
131249 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
131250 WhereTerm *pTerm; /* The term to be analyzed */
131251 WhereMaskSet *pMaskSet; /* Set of table index masks */
131252 Expr *pExpr; /* The expression to be analyzed */
131253 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
131254 Bitmask prereqAll; /* Prerequesites of pExpr */
131255 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
131256 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
131257 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
131258 int noCase = 0; /* uppercase equivalent to lowercase */
131259 int op; /* Top-level operator. pExpr->op */
131260 Parse *pParse = pWInfo->pParse; /* Parsing context */
131261 sqlite3 *db = pParse->db; /* Database connection */
131262 unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
131263 int nLeft; /* Number of elements on left side vector */
131265 if( db->mallocFailed ){
131266 return;
131268 pTerm = &pWC->a[idxTerm];
131269 pMaskSet = &pWInfo->sMaskSet;
131270 pExpr = pTerm->pExpr;
131271 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
131272 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
131273 op = pExpr->op;
131274 if( op==TK_IN ){
131275 assert( pExpr->pRight==0 );
131276 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
131277 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
131278 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
131279 }else{
131280 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
131282 }else if( op==TK_ISNULL ){
131283 pTerm->prereqRight = 0;
131284 }else{
131285 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
131287 pMaskSet->bVarSelect = 0;
131288 prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
131289 if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
131290 if( ExprHasProperty(pExpr, EP_FromJoin) ){
131291 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
131292 prereqAll |= x;
131293 extraRight = x-1; /* ON clause terms may not be used with an index
131294 ** on left table of a LEFT JOIN. Ticket #3015 */
131295 if( (prereqAll>>1)>=x ){
131296 sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
131297 return;
131300 pTerm->prereqAll = prereqAll;
131301 pTerm->leftCursor = -1;
131302 pTerm->iParent = -1;
131303 pTerm->eOperator = 0;
131304 if( allowedOp(op) ){
131305 int aiCurCol[2];
131306 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
131307 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
131308 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
131310 if( pTerm->iField>0 ){
131311 assert( op==TK_IN );
131312 assert( pLeft->op==TK_VECTOR );
131313 pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
131316 if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
131317 pTerm->leftCursor = aiCurCol[0];
131318 pTerm->u.leftColumn = aiCurCol[1];
131319 pTerm->eOperator = operatorMask(op) & opMask;
131321 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
131322 if( pRight
131323 && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
131325 WhereTerm *pNew;
131326 Expr *pDup;
131327 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
131328 assert( pTerm->iField==0 );
131329 if( pTerm->leftCursor>=0 ){
131330 int idxNew;
131331 pDup = sqlite3ExprDup(db, pExpr, 0);
131332 if( db->mallocFailed ){
131333 sqlite3ExprDelete(db, pDup);
131334 return;
131336 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
131337 if( idxNew==0 ) return;
131338 pNew = &pWC->a[idxNew];
131339 markTermAsChild(pWC, idxNew, idxTerm);
131340 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
131341 pTerm = &pWC->a[idxTerm];
131342 pTerm->wtFlags |= TERM_COPIED;
131344 if( termIsEquivalence(pParse, pDup) ){
131345 pTerm->eOperator |= WO_EQUIV;
131346 eExtraOp = WO_EQUIV;
131348 }else{
131349 pDup = pExpr;
131350 pNew = pTerm;
131352 exprCommute(pParse, pDup);
131353 pNew->leftCursor = aiCurCol[0];
131354 pNew->u.leftColumn = aiCurCol[1];
131355 testcase( (prereqLeft | extraRight) != prereqLeft );
131356 pNew->prereqRight = prereqLeft | extraRight;
131357 pNew->prereqAll = prereqAll;
131358 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
131362 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
131363 /* If a term is the BETWEEN operator, create two new virtual terms
131364 ** that define the range that the BETWEEN implements. For example:
131366 ** a BETWEEN b AND c
131368 ** is converted into:
131370 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
131372 ** The two new terms are added onto the end of the WhereClause object.
131373 ** The new terms are "dynamic" and are children of the original BETWEEN
131374 ** term. That means that if the BETWEEN term is coded, the children are
131375 ** skipped. Or, if the children are satisfied by an index, the original
131376 ** BETWEEN term is skipped.
131378 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
131379 ExprList *pList = pExpr->x.pList;
131380 int i;
131381 static const u8 ops[] = {TK_GE, TK_LE};
131382 assert( pList!=0 );
131383 assert( pList->nExpr==2 );
131384 for(i=0; i<2; i++){
131385 Expr *pNewExpr;
131386 int idxNew;
131387 pNewExpr = sqlite3PExpr(pParse, ops[i],
131388 sqlite3ExprDup(db, pExpr->pLeft, 0),
131389 sqlite3ExprDup(db, pList->a[i].pExpr, 0));
131390 transferJoinMarkings(pNewExpr, pExpr);
131391 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
131392 testcase( idxNew==0 );
131393 exprAnalyze(pSrc, pWC, idxNew);
131394 pTerm = &pWC->a[idxTerm];
131395 markTermAsChild(pWC, idxNew, idxTerm);
131398 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
131400 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
131401 /* Analyze a term that is composed of two or more subterms connected by
131402 ** an OR operator.
131404 else if( pExpr->op==TK_OR ){
131405 assert( pWC->op==TK_AND );
131406 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
131407 pTerm = &pWC->a[idxTerm];
131409 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
131411 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
131412 /* Add constraints to reduce the search space on a LIKE or GLOB
131413 ** operator.
131415 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
131417 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
131419 ** The last character of the prefix "abc" is incremented to form the
131420 ** termination condition "abd". If case is not significant (the default
131421 ** for LIKE) then the lower-bound is made all uppercase and the upper-
131422 ** bound is made all lowercase so that the bounds also work when comparing
131423 ** BLOBs.
131425 if( pWC->op==TK_AND
131426 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
131428 Expr *pLeft; /* LHS of LIKE/GLOB operator */
131429 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
131430 Expr *pNewExpr1;
131431 Expr *pNewExpr2;
131432 int idxNew1;
131433 int idxNew2;
131434 const char *zCollSeqName; /* Name of collating sequence */
131435 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
131437 pLeft = pExpr->x.pList->a[1].pExpr;
131438 pStr2 = sqlite3ExprDup(db, pStr1, 0);
131440 /* Convert the lower bound to upper-case and the upper bound to
131441 ** lower-case (upper-case is less than lower-case in ASCII) so that
131442 ** the range constraints also work for BLOBs
131444 if( noCase && !pParse->db->mallocFailed ){
131445 int i;
131446 char c;
131447 pTerm->wtFlags |= TERM_LIKE;
131448 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
131449 pStr1->u.zToken[i] = sqlite3Toupper(c);
131450 pStr2->u.zToken[i] = sqlite3Tolower(c);
131454 if( !db->mallocFailed ){
131455 u8 c, *pC; /* Last character before the first wildcard */
131456 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
131457 c = *pC;
131458 if( noCase ){
131459 /* The point is to increment the last character before the first
131460 ** wildcard. But if we increment '@', that will push it into the
131461 ** alphabetic range where case conversions will mess up the
131462 ** inequality. To avoid this, make sure to also run the full
131463 ** LIKE on all candidate expressions by clearing the isComplete flag
131465 if( c=='A'-1 ) isComplete = 0;
131466 c = sqlite3UpperToLower[c];
131468 *pC = c + 1;
131470 zCollSeqName = noCase ? "NOCASE" : "BINARY";
131471 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
131472 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
131473 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
131474 pStr1);
131475 transferJoinMarkings(pNewExpr1, pExpr);
131476 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
131477 testcase( idxNew1==0 );
131478 exprAnalyze(pSrc, pWC, idxNew1);
131479 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
131480 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
131481 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
131482 pStr2);
131483 transferJoinMarkings(pNewExpr2, pExpr);
131484 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
131485 testcase( idxNew2==0 );
131486 exprAnalyze(pSrc, pWC, idxNew2);
131487 pTerm = &pWC->a[idxTerm];
131488 if( isComplete ){
131489 markTermAsChild(pWC, idxNew1, idxTerm);
131490 markTermAsChild(pWC, idxNew2, idxTerm);
131493 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
131495 #ifndef SQLITE_OMIT_VIRTUALTABLE
131496 /* Add a WO_AUX auxiliary term to the constraint set if the
131497 ** current expression is of the form "column OP expr" where OP
131498 ** is an operator that gets passed into virtual tables but which is
131499 ** not normally optimized for ordinary tables. In other words, OP
131500 ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
131501 ** This information is used by the xBestIndex methods of
131502 ** virtual tables. The native query optimizer does not attempt
131503 ** to do anything with MATCH functions.
131505 if( pWC->op==TK_AND ){
131506 Expr *pRight, *pLeft;
131507 int res = isAuxiliaryVtabOperator(pExpr, &eOp2, &pLeft, &pRight);
131508 while( res-- > 0 ){
131509 int idxNew;
131510 WhereTerm *pNewTerm;
131511 Bitmask prereqColumn, prereqExpr;
131513 prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
131514 prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
131515 if( (prereqExpr & prereqColumn)==0 ){
131516 Expr *pNewExpr;
131517 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
131518 0, sqlite3ExprDup(db, pRight, 0));
131519 if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
131520 ExprSetProperty(pNewExpr, EP_FromJoin);
131522 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
131523 testcase( idxNew==0 );
131524 pNewTerm = &pWC->a[idxNew];
131525 pNewTerm->prereqRight = prereqExpr;
131526 pNewTerm->leftCursor = pLeft->iTable;
131527 pNewTerm->u.leftColumn = pLeft->iColumn;
131528 pNewTerm->eOperator = WO_AUX;
131529 pNewTerm->eMatchOp = eOp2;
131530 markTermAsChild(pWC, idxNew, idxTerm);
131531 pTerm = &pWC->a[idxTerm];
131532 pTerm->wtFlags |= TERM_COPIED;
131533 pNewTerm->prereqAll = pTerm->prereqAll;
131535 SWAP(Expr*, pLeft, pRight);
131538 #endif /* SQLITE_OMIT_VIRTUALTABLE */
131540 /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
131541 ** new terms for each component comparison - "a = ?" and "b = ?". The
131542 ** new terms completely replace the original vector comparison, which is
131543 ** no longer used.
131545 ** This is only required if at least one side of the comparison operation
131546 ** is not a sub-select. */
131547 if( pWC->op==TK_AND
131548 && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
131549 && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
131550 && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
131551 && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
131552 || (pExpr->pRight->flags & EP_xIsSelect)==0)
131554 int i;
131555 for(i=0; i<nLeft; i++){
131556 int idxNew;
131557 Expr *pNew;
131558 Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
131559 Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
131561 pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
131562 transferJoinMarkings(pNew, pExpr);
131563 idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
131564 exprAnalyze(pSrc, pWC, idxNew);
131566 pTerm = &pWC->a[idxTerm];
131567 pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */
131568 pTerm->eOperator = 0;
131571 /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
131572 ** a virtual term for each vector component. The expression object
131573 ** used by each such virtual term is pExpr (the full vector IN(...)
131574 ** expression). The WhereTerm.iField variable identifies the index within
131575 ** the vector on the LHS that the virtual term represents.
131577 ** This only works if the RHS is a simple SELECT, not a compound
131579 if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
131580 && pExpr->pLeft->op==TK_VECTOR
131581 && pExpr->x.pSelect->pPrior==0
131583 int i;
131584 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
131585 int idxNew;
131586 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
131587 pWC->a[idxNew].iField = i+1;
131588 exprAnalyze(pSrc, pWC, idxNew);
131589 markTermAsChild(pWC, idxNew, idxTerm);
131593 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
131594 /* When sqlite_stat3 histogram data is available an operator of the
131595 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
131596 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
131597 ** virtual term of that form.
131599 ** Note that the virtual term must be tagged with TERM_VNULL.
131601 if( pExpr->op==TK_NOTNULL
131602 && pExpr->pLeft->op==TK_COLUMN
131603 && pExpr->pLeft->iColumn>=0
131604 && OptimizationEnabled(db, SQLITE_Stat34)
131606 Expr *pNewExpr;
131607 Expr *pLeft = pExpr->pLeft;
131608 int idxNew;
131609 WhereTerm *pNewTerm;
131611 pNewExpr = sqlite3PExpr(pParse, TK_GT,
131612 sqlite3ExprDup(db, pLeft, 0),
131613 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
131615 idxNew = whereClauseInsert(pWC, pNewExpr,
131616 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
131617 if( idxNew ){
131618 pNewTerm = &pWC->a[idxNew];
131619 pNewTerm->prereqRight = 0;
131620 pNewTerm->leftCursor = pLeft->iTable;
131621 pNewTerm->u.leftColumn = pLeft->iColumn;
131622 pNewTerm->eOperator = WO_GT;
131623 markTermAsChild(pWC, idxNew, idxTerm);
131624 pTerm = &pWC->a[idxTerm];
131625 pTerm->wtFlags |= TERM_COPIED;
131626 pNewTerm->prereqAll = pTerm->prereqAll;
131629 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
131631 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
131632 ** an index for tables to the left of the join.
131634 testcase( pTerm!=&pWC->a[idxTerm] );
131635 pTerm = &pWC->a[idxTerm];
131636 pTerm->prereqRight |= extraRight;
131639 /***************************************************************************
131640 ** Routines with file scope above. Interface to the rest of the where.c
131641 ** subsystem follows.
131642 ***************************************************************************/
131645 ** This routine identifies subexpressions in the WHERE clause where
131646 ** each subexpression is separated by the AND operator or some other
131647 ** operator specified in the op parameter. The WhereClause structure
131648 ** is filled with pointers to subexpressions. For example:
131650 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
131651 ** \________/ \_______________/ \________________/
131652 ** slot[0] slot[1] slot[2]
131654 ** The original WHERE clause in pExpr is unaltered. All this routine
131655 ** does is make slot[] entries point to substructure within pExpr.
131657 ** In the previous sentence and in the diagram, "slot[]" refers to
131658 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
131659 ** all terms of the WHERE clause.
131661 SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
131662 Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
131663 pWC->op = op;
131664 if( pE2==0 ) return;
131665 if( pE2->op!=op ){
131666 whereClauseInsert(pWC, pExpr, 0);
131667 }else{
131668 sqlite3WhereSplit(pWC, pE2->pLeft, op);
131669 sqlite3WhereSplit(pWC, pE2->pRight, op);
131674 ** Initialize a preallocated WhereClause structure.
131676 SQLITE_PRIVATE void sqlite3WhereClauseInit(
131677 WhereClause *pWC, /* The WhereClause to be initialized */
131678 WhereInfo *pWInfo /* The WHERE processing context */
131680 pWC->pWInfo = pWInfo;
131681 pWC->pOuter = 0;
131682 pWC->nTerm = 0;
131683 pWC->nSlot = ArraySize(pWC->aStatic);
131684 pWC->a = pWC->aStatic;
131688 ** Deallocate a WhereClause structure. The WhereClause structure
131689 ** itself is not freed. This routine is the inverse of
131690 ** sqlite3WhereClauseInit().
131692 SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
131693 int i;
131694 WhereTerm *a;
131695 sqlite3 *db = pWC->pWInfo->pParse->db;
131696 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
131697 if( a->wtFlags & TERM_DYNAMIC ){
131698 sqlite3ExprDelete(db, a->pExpr);
131700 if( a->wtFlags & TERM_ORINFO ){
131701 whereOrInfoDelete(db, a->u.pOrInfo);
131702 }else if( a->wtFlags & TERM_ANDINFO ){
131703 whereAndInfoDelete(db, a->u.pAndInfo);
131706 if( pWC->a!=pWC->aStatic ){
131707 sqlite3DbFree(db, pWC->a);
131713 ** These routines walk (recursively) an expression tree and generate
131714 ** a bitmask indicating which tables are used in that expression
131715 ** tree.
131717 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
131718 Bitmask mask;
131719 if( p==0 ) return 0;
131720 if( p->op==TK_COLUMN ){
131721 return sqlite3WhereGetMask(pMaskSet, p->iTable);
131723 mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
131724 assert( !ExprHasProperty(p, EP_TokenOnly) );
131725 if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
131726 if( p->pRight ){
131727 mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
131728 assert( p->x.pList==0 );
131729 }else if( ExprHasProperty(p, EP_xIsSelect) ){
131730 if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
131731 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
131732 }else if( p->x.pList ){
131733 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
131735 return mask;
131737 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
131738 int i;
131739 Bitmask mask = 0;
131740 if( pList ){
131741 for(i=0; i<pList->nExpr; i++){
131742 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
131745 return mask;
131750 ** Call exprAnalyze on all terms in a WHERE clause.
131752 ** Note that exprAnalyze() might add new virtual terms onto the
131753 ** end of the WHERE clause. We do not want to analyze these new
131754 ** virtual terms, so start analyzing at the end and work forward
131755 ** so that the added virtual terms are never processed.
131757 SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
131758 SrcList *pTabList, /* the FROM clause */
131759 WhereClause *pWC /* the WHERE clause to be analyzed */
131761 int i;
131762 for(i=pWC->nTerm-1; i>=0; i--){
131763 exprAnalyze(pTabList, pWC, i);
131768 ** For table-valued-functions, transform the function arguments into
131769 ** new WHERE clause terms.
131771 ** Each function argument translates into an equality constraint against
131772 ** a HIDDEN column in the table.
131774 SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
131775 Parse *pParse, /* Parsing context */
131776 struct SrcList_item *pItem, /* The FROM clause term to process */
131777 WhereClause *pWC /* Xfer function arguments to here */
131779 Table *pTab;
131780 int j, k;
131781 ExprList *pArgs;
131782 Expr *pColRef;
131783 Expr *pTerm;
131784 if( pItem->fg.isTabFunc==0 ) return;
131785 pTab = pItem->pTab;
131786 assert( pTab!=0 );
131787 pArgs = pItem->u1.pFuncArg;
131788 if( pArgs==0 ) return;
131789 for(j=k=0; j<pArgs->nExpr; j++){
131790 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
131791 if( k>=pTab->nCol ){
131792 sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
131793 pTab->zName, j);
131794 return;
131796 pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
131797 if( pColRef==0 ) return;
131798 pColRef->iTable = pItem->iCursor;
131799 pColRef->iColumn = k++;
131800 pColRef->pTab = pTab;
131801 pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
131802 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
131803 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
131807 /************** End of whereexpr.c *******************************************/
131808 /************** Begin file where.c *******************************************/
131810 ** 2001 September 15
131812 ** The author disclaims copyright to this source code. In place of
131813 ** a legal notice, here is a blessing:
131815 ** May you do good and not evil.
131816 ** May you find forgiveness for yourself and forgive others.
131817 ** May you share freely, never taking more than you give.
131819 *************************************************************************
131820 ** This module contains C code that generates VDBE code used to process
131821 ** the WHERE clause of SQL statements. This module is responsible for
131822 ** generating the code that loops through a table looking for applicable
131823 ** rows. Indices are selected and used to speed the search when doing
131824 ** so is applicable. Because this module is responsible for selecting
131825 ** indices, you might also think of this module as the "query optimizer".
131827 /* #include "sqliteInt.h" */
131828 /* #include "whereInt.h" */
131830 /* Forward declaration of methods */
131831 static int whereLoopResize(sqlite3*, WhereLoop*, int);
131833 /* Test variable that can be set to enable WHERE tracing */
131834 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
131835 /***/ int sqlite3WhereTrace = 0;
131836 #endif
131840 ** Return the estimated number of output rows from a WHERE clause
131842 SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
131843 return pWInfo->nRowOut;
131847 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
131848 ** WHERE clause returns outputs for DISTINCT processing.
131850 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
131851 return pWInfo->eDistinct;
131855 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
131856 ** Return FALSE if the output needs to be sorted.
131858 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
131859 return pWInfo->nOBSat;
131863 ** Return TRUE if the innermost loop of the WHERE clause implementation
131864 ** returns rows in ORDER BY order for complete run of the inner loop.
131866 ** Across multiple iterations of outer loops, the output rows need not be
131867 ** sorted. As long as rows are sorted for just the innermost loop, this
131868 ** routine can return TRUE.
131870 SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
131871 return pWInfo->bOrderedInnerLoop;
131875 ** Return the VDBE address or label to jump to in order to continue
131876 ** immediately with the next row of a WHERE clause.
131878 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
131879 assert( pWInfo->iContinue!=0 );
131880 return pWInfo->iContinue;
131884 ** Return the VDBE address or label to jump to in order to break
131885 ** out of a WHERE loop.
131887 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
131888 return pWInfo->iBreak;
131892 ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
131893 ** operate directly on the rowis returned by a WHERE clause. Return
131894 ** ONEPASS_SINGLE (1) if the statement can operation directly because only
131895 ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
131896 ** optimization can be used on multiple
131898 ** If the ONEPASS optimization is used (if this routine returns true)
131899 ** then also write the indices of open cursors used by ONEPASS
131900 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
131901 ** table and iaCur[1] gets the cursor used by an auxiliary index.
131902 ** Either value may be -1, indicating that cursor is not used.
131903 ** Any cursors returned will have been opened for writing.
131905 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
131906 ** unable to use the ONEPASS optimization.
131908 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
131909 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
131910 #ifdef WHERETRACE_ENABLED
131911 if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
131912 sqlite3DebugPrintf("%s cursors: %d %d\n",
131913 pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
131914 aiCur[0], aiCur[1]);
131916 #endif
131917 return pWInfo->eOnePass;
131921 ** Move the content of pSrc into pDest
131923 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
131924 pDest->n = pSrc->n;
131925 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
131929 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
131931 ** The new entry might overwrite an existing entry, or it might be
131932 ** appended, or it might be discarded. Do whatever is the right thing
131933 ** so that pSet keeps the N_OR_COST best entries seen so far.
131935 static int whereOrInsert(
131936 WhereOrSet *pSet, /* The WhereOrSet to be updated */
131937 Bitmask prereq, /* Prerequisites of the new entry */
131938 LogEst rRun, /* Run-cost of the new entry */
131939 LogEst nOut /* Number of outputs for the new entry */
131941 u16 i;
131942 WhereOrCost *p;
131943 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
131944 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
131945 goto whereOrInsert_done;
131947 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
131948 return 0;
131951 if( pSet->n<N_OR_COST ){
131952 p = &pSet->a[pSet->n++];
131953 p->nOut = nOut;
131954 }else{
131955 p = pSet->a;
131956 for(i=1; i<pSet->n; i++){
131957 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
131959 if( p->rRun<=rRun ) return 0;
131961 whereOrInsert_done:
131962 p->prereq = prereq;
131963 p->rRun = rRun;
131964 if( p->nOut>nOut ) p->nOut = nOut;
131965 return 1;
131969 ** Return the bitmask for the given cursor number. Return 0 if
131970 ** iCursor is not in the set.
131972 SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
131973 int i;
131974 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
131975 for(i=0; i<pMaskSet->n; i++){
131976 if( pMaskSet->ix[i]==iCursor ){
131977 return MASKBIT(i);
131980 return 0;
131984 ** Create a new mask for cursor iCursor.
131986 ** There is one cursor per table in the FROM clause. The number of
131987 ** tables in the FROM clause is limited by a test early in the
131988 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
131989 ** array will never overflow.
131991 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
131992 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
131993 pMaskSet->ix[pMaskSet->n++] = iCursor;
131997 ** Advance to the next WhereTerm that matches according to the criteria
131998 ** established when the pScan object was initialized by whereScanInit().
131999 ** Return NULL if there are no more matching WhereTerms.
132001 static WhereTerm *whereScanNext(WhereScan *pScan){
132002 int iCur; /* The cursor on the LHS of the term */
132003 i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
132004 Expr *pX; /* An expression being tested */
132005 WhereClause *pWC; /* Shorthand for pScan->pWC */
132006 WhereTerm *pTerm; /* The term being tested */
132007 int k = pScan->k; /* Where to start scanning */
132009 assert( pScan->iEquiv<=pScan->nEquiv );
132010 pWC = pScan->pWC;
132011 while(1){
132012 iColumn = pScan->aiColumn[pScan->iEquiv-1];
132013 iCur = pScan->aiCur[pScan->iEquiv-1];
132014 assert( pWC!=0 );
132016 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
132017 if( pTerm->leftCursor==iCur
132018 && pTerm->u.leftColumn==iColumn
132019 && (iColumn!=XN_EXPR
132020 || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
132021 pScan->pIdxExpr,iCur)==0)
132022 && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
132024 if( (pTerm->eOperator & WO_EQUIV)!=0
132025 && pScan->nEquiv<ArraySize(pScan->aiCur)
132026 && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
132028 int j;
132029 for(j=0; j<pScan->nEquiv; j++){
132030 if( pScan->aiCur[j]==pX->iTable
132031 && pScan->aiColumn[j]==pX->iColumn ){
132032 break;
132035 if( j==pScan->nEquiv ){
132036 pScan->aiCur[j] = pX->iTable;
132037 pScan->aiColumn[j] = pX->iColumn;
132038 pScan->nEquiv++;
132041 if( (pTerm->eOperator & pScan->opMask)!=0 ){
132042 /* Verify the affinity and collating sequence match */
132043 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
132044 CollSeq *pColl;
132045 Parse *pParse = pWC->pWInfo->pParse;
132046 pX = pTerm->pExpr;
132047 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
132048 continue;
132050 assert(pX->pLeft);
132051 pColl = sqlite3BinaryCompareCollSeq(pParse,
132052 pX->pLeft, pX->pRight);
132053 if( pColl==0 ) pColl = pParse->db->pDfltColl;
132054 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
132055 continue;
132058 if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
132059 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
132060 && pX->iTable==pScan->aiCur[0]
132061 && pX->iColumn==pScan->aiColumn[0]
132063 testcase( pTerm->eOperator & WO_IS );
132064 continue;
132066 pScan->pWC = pWC;
132067 pScan->k = k+1;
132068 return pTerm;
132072 pWC = pWC->pOuter;
132073 k = 0;
132074 }while( pWC!=0 );
132075 if( pScan->iEquiv>=pScan->nEquiv ) break;
132076 pWC = pScan->pOrigWC;
132077 k = 0;
132078 pScan->iEquiv++;
132080 return 0;
132084 ** Initialize a WHERE clause scanner object. Return a pointer to the
132085 ** first match. Return NULL if there are no matches.
132087 ** The scanner will be searching the WHERE clause pWC. It will look
132088 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
132089 ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
132090 ** must be one of the indexes of table iCur.
132092 ** The <op> must be one of the operators described by opMask.
132094 ** If the search is for X and the WHERE clause contains terms of the
132095 ** form X=Y then this routine might also return terms of the form
132096 ** "Y <op> <expr>". The number of levels of transitivity is limited,
132097 ** but is enough to handle most commonly occurring SQL statements.
132099 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
132100 ** index pIdx.
132102 static WhereTerm *whereScanInit(
132103 WhereScan *pScan, /* The WhereScan object being initialized */
132104 WhereClause *pWC, /* The WHERE clause to be scanned */
132105 int iCur, /* Cursor to scan for */
132106 int iColumn, /* Column to scan for */
132107 u32 opMask, /* Operator(s) to scan for */
132108 Index *pIdx /* Must be compatible with this index */
132110 pScan->pOrigWC = pWC;
132111 pScan->pWC = pWC;
132112 pScan->pIdxExpr = 0;
132113 pScan->idxaff = 0;
132114 pScan->zCollName = 0;
132115 if( pIdx ){
132116 int j = iColumn;
132117 iColumn = pIdx->aiColumn[j];
132118 if( iColumn==XN_EXPR ){
132119 pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
132120 pScan->zCollName = pIdx->azColl[j];
132121 }else if( iColumn==pIdx->pTable->iPKey ){
132122 iColumn = XN_ROWID;
132123 }else if( iColumn>=0 ){
132124 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
132125 pScan->zCollName = pIdx->azColl[j];
132127 }else if( iColumn==XN_EXPR ){
132128 return 0;
132130 pScan->opMask = opMask;
132131 pScan->k = 0;
132132 pScan->aiCur[0] = iCur;
132133 pScan->aiColumn[0] = iColumn;
132134 pScan->nEquiv = 1;
132135 pScan->iEquiv = 1;
132136 return whereScanNext(pScan);
132140 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
132141 ** where X is a reference to the iColumn of table iCur or of index pIdx
132142 ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
132143 ** the op parameter. Return a pointer to the term. Return 0 if not found.
132145 ** If pIdx!=0 then it must be one of the indexes of table iCur.
132146 ** Search for terms matching the iColumn-th column of pIdx
132147 ** rather than the iColumn-th column of table iCur.
132149 ** The term returned might by Y=<expr> if there is another constraint in
132150 ** the WHERE clause that specifies that X=Y. Any such constraints will be
132151 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
132152 ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
132153 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
132154 ** other equivalent values. Hence a search for X will return <expr> if X=A1
132155 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
132157 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
132158 ** then try for the one with no dependencies on <expr> - in other words where
132159 ** <expr> is a constant expression of some kind. Only return entries of
132160 ** the form "X <op> Y" where Y is a column in another table if no terms of
132161 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
132162 ** exist, try to return a term that does not use WO_EQUIV.
132164 SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
132165 WhereClause *pWC, /* The WHERE clause to be searched */
132166 int iCur, /* Cursor number of LHS */
132167 int iColumn, /* Column number of LHS */
132168 Bitmask notReady, /* RHS must not overlap with this mask */
132169 u32 op, /* Mask of WO_xx values describing operator */
132170 Index *pIdx /* Must be compatible with this index, if not NULL */
132172 WhereTerm *pResult = 0;
132173 WhereTerm *p;
132174 WhereScan scan;
132176 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
132177 op &= WO_EQ|WO_IS;
132178 while( p ){
132179 if( (p->prereqRight & notReady)==0 ){
132180 if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
132181 testcase( p->eOperator & WO_IS );
132182 return p;
132184 if( pResult==0 ) pResult = p;
132186 p = whereScanNext(&scan);
132188 return pResult;
132192 ** This function searches pList for an entry that matches the iCol-th column
132193 ** of index pIdx.
132195 ** If such an expression is found, its index in pList->a[] is returned. If
132196 ** no expression is found, -1 is returned.
132198 static int findIndexCol(
132199 Parse *pParse, /* Parse context */
132200 ExprList *pList, /* Expression list to search */
132201 int iBase, /* Cursor for table associated with pIdx */
132202 Index *pIdx, /* Index to match column of */
132203 int iCol /* Column of index to match */
132205 int i;
132206 const char *zColl = pIdx->azColl[iCol];
132208 for(i=0; i<pList->nExpr; i++){
132209 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
132210 if( p->op==TK_COLUMN
132211 && p->iColumn==pIdx->aiColumn[iCol]
132212 && p->iTable==iBase
132214 CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
132215 if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
132216 return i;
132221 return -1;
132225 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
132227 static int indexColumnNotNull(Index *pIdx, int iCol){
132228 int j;
132229 assert( pIdx!=0 );
132230 assert( iCol>=0 && iCol<pIdx->nColumn );
132231 j = pIdx->aiColumn[iCol];
132232 if( j>=0 ){
132233 return pIdx->pTable->aCol[j].notNull;
132234 }else if( j==(-1) ){
132235 return 1;
132236 }else{
132237 assert( j==(-2) );
132238 return 0; /* Assume an indexed expression can always yield a NULL */
132244 ** Return true if the DISTINCT expression-list passed as the third argument
132245 ** is redundant.
132247 ** A DISTINCT list is redundant if any subset of the columns in the
132248 ** DISTINCT list are collectively unique and individually non-null.
132250 static int isDistinctRedundant(
132251 Parse *pParse, /* Parsing context */
132252 SrcList *pTabList, /* The FROM clause */
132253 WhereClause *pWC, /* The WHERE clause */
132254 ExprList *pDistinct /* The result set that needs to be DISTINCT */
132256 Table *pTab;
132257 Index *pIdx;
132258 int i;
132259 int iBase;
132261 /* If there is more than one table or sub-select in the FROM clause of
132262 ** this query, then it will not be possible to show that the DISTINCT
132263 ** clause is redundant. */
132264 if( pTabList->nSrc!=1 ) return 0;
132265 iBase = pTabList->a[0].iCursor;
132266 pTab = pTabList->a[0].pTab;
132268 /* If any of the expressions is an IPK column on table iBase, then return
132269 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
132270 ** current SELECT is a correlated sub-query.
132272 for(i=0; i<pDistinct->nExpr; i++){
132273 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
132274 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
132277 /* Loop through all indices on the table, checking each to see if it makes
132278 ** the DISTINCT qualifier redundant. It does so if:
132280 ** 1. The index is itself UNIQUE, and
132282 ** 2. All of the columns in the index are either part of the pDistinct
132283 ** list, or else the WHERE clause contains a term of the form "col=X",
132284 ** where X is a constant value. The collation sequences of the
132285 ** comparison and select-list expressions must match those of the index.
132287 ** 3. All of those index columns for which the WHERE clause does not
132288 ** contain a "col=X" term are subject to a NOT NULL constraint.
132290 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
132291 if( !IsUniqueIndex(pIdx) ) continue;
132292 for(i=0; i<pIdx->nKeyCol; i++){
132293 if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
132294 if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
132295 if( indexColumnNotNull(pIdx, i)==0 ) break;
132298 if( i==pIdx->nKeyCol ){
132299 /* This index implies that the DISTINCT qualifier is redundant. */
132300 return 1;
132304 return 0;
132309 ** Estimate the logarithm of the input value to base 2.
132311 static LogEst estLog(LogEst N){
132312 return N<=10 ? 0 : sqlite3LogEst(N) - 33;
132316 ** Convert OP_Column opcodes to OP_Copy in previously generated code.
132318 ** This routine runs over generated VDBE code and translates OP_Column
132319 ** opcodes into OP_Copy when the table is being accessed via co-routine
132320 ** instead of via table lookup.
132322 ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
132323 ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
132324 ** then each OP_Rowid is transformed into an instruction to increment the
132325 ** value stored in its output register.
132327 static void translateColumnToCopy(
132328 Parse *pParse, /* Parsing context */
132329 int iStart, /* Translate from this opcode to the end */
132330 int iTabCur, /* OP_Column/OP_Rowid references to this table */
132331 int iRegister, /* The first column is in this register */
132332 int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
132334 Vdbe *v = pParse->pVdbe;
132335 VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
132336 int iEnd = sqlite3VdbeCurrentAddr(v);
132337 if( pParse->db->mallocFailed ) return;
132338 for(; iStart<iEnd; iStart++, pOp++){
132339 if( pOp->p1!=iTabCur ) continue;
132340 if( pOp->opcode==OP_Column ){
132341 pOp->opcode = OP_Copy;
132342 pOp->p1 = pOp->p2 + iRegister;
132343 pOp->p2 = pOp->p3;
132344 pOp->p3 = 0;
132345 }else if( pOp->opcode==OP_Rowid ){
132346 if( bIncrRowid ){
132347 /* Increment the value stored in the P2 operand of the OP_Rowid. */
132348 pOp->opcode = OP_AddImm;
132349 pOp->p1 = pOp->p2;
132350 pOp->p2 = 1;
132351 }else{
132352 pOp->opcode = OP_Null;
132353 pOp->p1 = 0;
132354 pOp->p3 = 0;
132361 ** Two routines for printing the content of an sqlite3_index_info
132362 ** structure. Used for testing and debugging only. If neither
132363 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
132364 ** are no-ops.
132366 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
132367 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
132368 int i;
132369 if( !sqlite3WhereTrace ) return;
132370 for(i=0; i<p->nConstraint; i++){
132371 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
132373 p->aConstraint[i].iColumn,
132374 p->aConstraint[i].iTermOffset,
132375 p->aConstraint[i].op,
132376 p->aConstraint[i].usable);
132378 for(i=0; i<p->nOrderBy; i++){
132379 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
132381 p->aOrderBy[i].iColumn,
132382 p->aOrderBy[i].desc);
132385 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
132386 int i;
132387 if( !sqlite3WhereTrace ) return;
132388 for(i=0; i<p->nConstraint; i++){
132389 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
132391 p->aConstraintUsage[i].argvIndex,
132392 p->aConstraintUsage[i].omit);
132394 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
132395 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
132396 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
132397 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
132398 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
132400 #else
132401 #define TRACE_IDX_INPUTS(A)
132402 #define TRACE_IDX_OUTPUTS(A)
132403 #endif
132405 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
132407 ** Return TRUE if the WHERE clause term pTerm is of a form where it
132408 ** could be used with an index to access pSrc, assuming an appropriate
132409 ** index existed.
132411 static int termCanDriveIndex(
132412 WhereTerm *pTerm, /* WHERE clause term to check */
132413 struct SrcList_item *pSrc, /* Table we are trying to access */
132414 Bitmask notReady /* Tables in outer loops of the join */
132416 char aff;
132417 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
132418 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
132419 if( (pSrc->fg.jointype & JT_LEFT)
132420 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
132421 && (pTerm->eOperator & WO_IS)
132423 /* Cannot use an IS term from the WHERE clause as an index driver for
132424 ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
132425 ** the ON clause. */
132426 return 0;
132428 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
132429 if( pTerm->u.leftColumn<0 ) return 0;
132430 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
132431 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
132432 testcase( pTerm->pExpr->op==TK_IS );
132433 return 1;
132435 #endif
132438 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
132440 ** Generate code to construct the Index object for an automatic index
132441 ** and to set up the WhereLevel object pLevel so that the code generator
132442 ** makes use of the automatic index.
132444 static void constructAutomaticIndex(
132445 Parse *pParse, /* The parsing context */
132446 WhereClause *pWC, /* The WHERE clause */
132447 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
132448 Bitmask notReady, /* Mask of cursors that are not available */
132449 WhereLevel *pLevel /* Write new index here */
132451 int nKeyCol; /* Number of columns in the constructed index */
132452 WhereTerm *pTerm; /* A single term of the WHERE clause */
132453 WhereTerm *pWCEnd; /* End of pWC->a[] */
132454 Index *pIdx; /* Object describing the transient index */
132455 Vdbe *v; /* Prepared statement under construction */
132456 int addrInit; /* Address of the initialization bypass jump */
132457 Table *pTable; /* The table being indexed */
132458 int addrTop; /* Top of the index fill loop */
132459 int regRecord; /* Register holding an index record */
132460 int n; /* Column counter */
132461 int i; /* Loop counter */
132462 int mxBitCol; /* Maximum column in pSrc->colUsed */
132463 CollSeq *pColl; /* Collating sequence to on a column */
132464 WhereLoop *pLoop; /* The Loop object */
132465 char *zNotUsed; /* Extra space on the end of pIdx */
132466 Bitmask idxCols; /* Bitmap of columns used for indexing */
132467 Bitmask extraCols; /* Bitmap of additional columns */
132468 u8 sentWarning = 0; /* True if a warnning has been issued */
132469 Expr *pPartial = 0; /* Partial Index Expression */
132470 int iContinue = 0; /* Jump here to skip excluded rows */
132471 struct SrcList_item *pTabItem; /* FROM clause term being indexed */
132472 int addrCounter = 0; /* Address where integer counter is initialized */
132473 int regBase; /* Array of registers where record is assembled */
132475 /* Generate code to skip over the creation and initialization of the
132476 ** transient index on 2nd and subsequent iterations of the loop. */
132477 v = pParse->pVdbe;
132478 assert( v!=0 );
132479 addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
132481 /* Count the number of columns that will be added to the index
132482 ** and used to match WHERE clause constraints */
132483 nKeyCol = 0;
132484 pTable = pSrc->pTab;
132485 pWCEnd = &pWC->a[pWC->nTerm];
132486 pLoop = pLevel->pWLoop;
132487 idxCols = 0;
132488 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
132489 Expr *pExpr = pTerm->pExpr;
132490 assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
132491 || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
132492 || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
132493 if( pLoop->prereq==0
132494 && (pTerm->wtFlags & TERM_VIRTUAL)==0
132495 && !ExprHasProperty(pExpr, EP_FromJoin)
132496 && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
132497 pPartial = sqlite3ExprAnd(pParse->db, pPartial,
132498 sqlite3ExprDup(pParse->db, pExpr, 0));
132500 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
132501 int iCol = pTerm->u.leftColumn;
132502 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
132503 testcase( iCol==BMS );
132504 testcase( iCol==BMS-1 );
132505 if( !sentWarning ){
132506 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
132507 "automatic index on %s(%s)", pTable->zName,
132508 pTable->aCol[iCol].zName);
132509 sentWarning = 1;
132511 if( (idxCols & cMask)==0 ){
132512 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
132513 goto end_auto_index_create;
132515 pLoop->aLTerm[nKeyCol++] = pTerm;
132516 idxCols |= cMask;
132520 assert( nKeyCol>0 );
132521 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
132522 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
132523 | WHERE_AUTO_INDEX;
132525 /* Count the number of additional columns needed to create a
132526 ** covering index. A "covering index" is an index that contains all
132527 ** columns that are needed by the query. With a covering index, the
132528 ** original table never needs to be accessed. Automatic indices must
132529 ** be a covering index because the index will not be updated if the
132530 ** original table changes and the index and table cannot both be used
132531 ** if they go out of sync.
132533 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
132534 mxBitCol = MIN(BMS-1,pTable->nCol);
132535 testcase( pTable->nCol==BMS-1 );
132536 testcase( pTable->nCol==BMS-2 );
132537 for(i=0; i<mxBitCol; i++){
132538 if( extraCols & MASKBIT(i) ) nKeyCol++;
132540 if( pSrc->colUsed & MASKBIT(BMS-1) ){
132541 nKeyCol += pTable->nCol - BMS + 1;
132544 /* Construct the Index object to describe this index */
132545 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
132546 if( pIdx==0 ) goto end_auto_index_create;
132547 pLoop->u.btree.pIndex = pIdx;
132548 pIdx->zName = "auto-index";
132549 pIdx->pTable = pTable;
132550 n = 0;
132551 idxCols = 0;
132552 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
132553 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
132554 int iCol = pTerm->u.leftColumn;
132555 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
132556 testcase( iCol==BMS-1 );
132557 testcase( iCol==BMS );
132558 if( (idxCols & cMask)==0 ){
132559 Expr *pX = pTerm->pExpr;
132560 idxCols |= cMask;
132561 pIdx->aiColumn[n] = pTerm->u.leftColumn;
132562 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
132563 pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
132568 assert( (u32)n==pLoop->u.btree.nEq );
132570 /* Add additional columns needed to make the automatic index into
132571 ** a covering index */
132572 for(i=0; i<mxBitCol; i++){
132573 if( extraCols & MASKBIT(i) ){
132574 pIdx->aiColumn[n] = i;
132575 pIdx->azColl[n] = sqlite3StrBINARY;
132579 if( pSrc->colUsed & MASKBIT(BMS-1) ){
132580 for(i=BMS-1; i<pTable->nCol; i++){
132581 pIdx->aiColumn[n] = i;
132582 pIdx->azColl[n] = sqlite3StrBINARY;
132586 assert( n==nKeyCol );
132587 pIdx->aiColumn[n] = XN_ROWID;
132588 pIdx->azColl[n] = sqlite3StrBINARY;
132590 /* Create the automatic index */
132591 assert( pLevel->iIdxCur>=0 );
132592 pLevel->iIdxCur = pParse->nTab++;
132593 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
132594 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
132595 VdbeComment((v, "for %s", pTable->zName));
132597 /* Fill the automatic index with content */
132598 sqlite3ExprCachePush(pParse);
132599 pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
132600 if( pTabItem->fg.viaCoroutine ){
132601 int regYield = pTabItem->regReturn;
132602 addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
132603 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
132604 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
132605 VdbeCoverage(v);
132606 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
132607 }else{
132608 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
132610 if( pPartial ){
132611 iContinue = sqlite3VdbeMakeLabel(v);
132612 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
132613 pLoop->wsFlags |= WHERE_PARTIALIDX;
132615 regRecord = sqlite3GetTempReg(pParse);
132616 regBase = sqlite3GenerateIndexKey(
132617 pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
132619 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
132620 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
132621 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
132622 if( pTabItem->fg.viaCoroutine ){
132623 sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
132624 testcase( pParse->db->mallocFailed );
132625 translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
132626 pTabItem->regResult, 1);
132627 sqlite3VdbeGoto(v, addrTop);
132628 pTabItem->fg.viaCoroutine = 0;
132629 }else{
132630 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
132632 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
132633 sqlite3VdbeJumpHere(v, addrTop);
132634 sqlite3ReleaseTempReg(pParse, regRecord);
132635 sqlite3ExprCachePop(pParse);
132637 /* Jump here when skipping the initialization */
132638 sqlite3VdbeJumpHere(v, addrInit);
132640 end_auto_index_create:
132641 sqlite3ExprDelete(pParse->db, pPartial);
132643 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
132645 #ifndef SQLITE_OMIT_VIRTUALTABLE
132647 ** Allocate and populate an sqlite3_index_info structure. It is the
132648 ** responsibility of the caller to eventually release the structure
132649 ** by passing the pointer returned by this function to sqlite3_free().
132651 static sqlite3_index_info *allocateIndexInfo(
132652 Parse *pParse,
132653 WhereClause *pWC,
132654 Bitmask mUnusable, /* Ignore terms with these prereqs */
132655 struct SrcList_item *pSrc,
132656 ExprList *pOrderBy,
132657 u16 *pmNoOmit /* Mask of terms not to omit */
132659 int i, j;
132660 int nTerm;
132661 struct sqlite3_index_constraint *pIdxCons;
132662 struct sqlite3_index_orderby *pIdxOrderBy;
132663 struct sqlite3_index_constraint_usage *pUsage;
132664 WhereTerm *pTerm;
132665 int nOrderBy;
132666 sqlite3_index_info *pIdxInfo;
132667 u16 mNoOmit = 0;
132669 /* Count the number of possible WHERE clause constraints referring
132670 ** to this virtual table */
132671 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
132672 if( pTerm->leftCursor != pSrc->iCursor ) continue;
132673 if( pTerm->prereqRight & mUnusable ) continue;
132674 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
132675 testcase( pTerm->eOperator & WO_IN );
132676 testcase( pTerm->eOperator & WO_ISNULL );
132677 testcase( pTerm->eOperator & WO_IS );
132678 testcase( pTerm->eOperator & WO_ALL );
132679 if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
132680 if( pTerm->wtFlags & TERM_VNULL ) continue;
132681 assert( pTerm->u.leftColumn>=(-1) );
132682 nTerm++;
132685 /* If the ORDER BY clause contains only columns in the current
132686 ** virtual table then allocate space for the aOrderBy part of
132687 ** the sqlite3_index_info structure.
132689 nOrderBy = 0;
132690 if( pOrderBy ){
132691 int n = pOrderBy->nExpr;
132692 for(i=0; i<n; i++){
132693 Expr *pExpr = pOrderBy->a[i].pExpr;
132694 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
132696 if( i==n){
132697 nOrderBy = n;
132701 /* Allocate the sqlite3_index_info structure
132703 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
132704 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
132705 + sizeof(*pIdxOrderBy)*nOrderBy );
132706 if( pIdxInfo==0 ){
132707 sqlite3ErrorMsg(pParse, "out of memory");
132708 return 0;
132711 /* Initialize the structure. The sqlite3_index_info structure contains
132712 ** many fields that are declared "const" to prevent xBestIndex from
132713 ** changing them. We have to do some funky casting in order to
132714 ** initialize those fields.
132716 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
132717 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
132718 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
132719 *(int*)&pIdxInfo->nConstraint = nTerm;
132720 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
132721 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
132722 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
132723 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
132724 pUsage;
132726 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
132727 u16 op;
132728 if( pTerm->leftCursor != pSrc->iCursor ) continue;
132729 if( pTerm->prereqRight & mUnusable ) continue;
132730 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
132731 testcase( pTerm->eOperator & WO_IN );
132732 testcase( pTerm->eOperator & WO_IS );
132733 testcase( pTerm->eOperator & WO_ISNULL );
132734 testcase( pTerm->eOperator & WO_ALL );
132735 if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
132736 if( pTerm->wtFlags & TERM_VNULL ) continue;
132737 assert( pTerm->u.leftColumn>=(-1) );
132738 pIdxCons[j].iColumn = pTerm->u.leftColumn;
132739 pIdxCons[j].iTermOffset = i;
132740 op = pTerm->eOperator & WO_ALL;
132741 if( op==WO_IN ) op = WO_EQ;
132742 if( op==WO_AUX ){
132743 pIdxCons[j].op = pTerm->eMatchOp;
132744 }else if( op & (WO_ISNULL|WO_IS) ){
132745 if( op==WO_ISNULL ){
132746 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
132747 }else{
132748 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
132750 }else{
132751 pIdxCons[j].op = (u8)op;
132752 /* The direct assignment in the previous line is possible only because
132753 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
132754 ** following asserts verify this fact. */
132755 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
132756 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
132757 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
132758 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
132759 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
132760 assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
132762 if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
132763 && sqlite3ExprIsVector(pTerm->pExpr->pRight)
132765 if( i<16 ) mNoOmit |= (1 << i);
132766 if( op==WO_LT ) pIdxCons[j].op = WO_LE;
132767 if( op==WO_GT ) pIdxCons[j].op = WO_GE;
132773 for(i=0; i<nOrderBy; i++){
132774 Expr *pExpr = pOrderBy->a[i].pExpr;
132775 pIdxOrderBy[i].iColumn = pExpr->iColumn;
132776 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
132779 *pmNoOmit = mNoOmit;
132780 return pIdxInfo;
132784 ** The table object reference passed as the second argument to this function
132785 ** must represent a virtual table. This function invokes the xBestIndex()
132786 ** method of the virtual table with the sqlite3_index_info object that
132787 ** comes in as the 3rd argument to this function.
132789 ** If an error occurs, pParse is populated with an error message and a
132790 ** non-zero value is returned. Otherwise, 0 is returned and the output
132791 ** part of the sqlite3_index_info structure is left populated.
132793 ** Whether or not an error is returned, it is the responsibility of the
132794 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
132795 ** that this is required.
132797 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
132798 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
132799 int rc;
132801 TRACE_IDX_INPUTS(p);
132802 rc = pVtab->pModule->xBestIndex(pVtab, p);
132803 TRACE_IDX_OUTPUTS(p);
132805 if( rc!=SQLITE_OK ){
132806 if( rc==SQLITE_NOMEM ){
132807 sqlite3OomFault(pParse->db);
132808 }else if( !pVtab->zErrMsg ){
132809 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
132810 }else{
132811 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
132814 sqlite3_free(pVtab->zErrMsg);
132815 pVtab->zErrMsg = 0;
132817 #if 0
132818 /* This error is now caught by the caller.
132819 ** Search for "xBestIndex malfunction" below */
132820 for(i=0; i<p->nConstraint; i++){
132821 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
132822 sqlite3ErrorMsg(pParse,
132823 "table %s: xBestIndex returned an invalid plan", pTab->zName);
132826 #endif
132828 return pParse->nErr;
132830 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
132832 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
132834 ** Estimate the location of a particular key among all keys in an
132835 ** index. Store the results in aStat as follows:
132837 ** aStat[0] Est. number of rows less than pRec
132838 ** aStat[1] Est. number of rows equal to pRec
132840 ** Return the index of the sample that is the smallest sample that
132841 ** is greater than or equal to pRec. Note that this index is not an index
132842 ** into the aSample[] array - it is an index into a virtual set of samples
132843 ** based on the contents of aSample[] and the number of fields in record
132844 ** pRec.
132846 static int whereKeyStats(
132847 Parse *pParse, /* Database connection */
132848 Index *pIdx, /* Index to consider domain of */
132849 UnpackedRecord *pRec, /* Vector of values to consider */
132850 int roundUp, /* Round up if true. Round down if false */
132851 tRowcnt *aStat /* OUT: stats written here */
132853 IndexSample *aSample = pIdx->aSample;
132854 int iCol; /* Index of required stats in anEq[] etc. */
132855 int i; /* Index of first sample >= pRec */
132856 int iSample; /* Smallest sample larger than or equal to pRec */
132857 int iMin = 0; /* Smallest sample not yet tested */
132858 int iTest; /* Next sample to test */
132859 int res; /* Result of comparison operation */
132860 int nField; /* Number of fields in pRec */
132861 tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
132863 #ifndef SQLITE_DEBUG
132864 UNUSED_PARAMETER( pParse );
132865 #endif
132866 assert( pRec!=0 );
132867 assert( pIdx->nSample>0 );
132868 assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
132870 /* Do a binary search to find the first sample greater than or equal
132871 ** to pRec. If pRec contains a single field, the set of samples to search
132872 ** is simply the aSample[] array. If the samples in aSample[] contain more
132873 ** than one fields, all fields following the first are ignored.
132875 ** If pRec contains N fields, where N is more than one, then as well as the
132876 ** samples in aSample[] (truncated to N fields), the search also has to
132877 ** consider prefixes of those samples. For example, if the set of samples
132878 ** in aSample is:
132880 ** aSample[0] = (a, 5)
132881 ** aSample[1] = (a, 10)
132882 ** aSample[2] = (b, 5)
132883 ** aSample[3] = (c, 100)
132884 ** aSample[4] = (c, 105)
132886 ** Then the search space should ideally be the samples above and the
132887 ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
132888 ** the code actually searches this set:
132890 ** 0: (a)
132891 ** 1: (a, 5)
132892 ** 2: (a, 10)
132893 ** 3: (a, 10)
132894 ** 4: (b)
132895 ** 5: (b, 5)
132896 ** 6: (c)
132897 ** 7: (c, 100)
132898 ** 8: (c, 105)
132899 ** 9: (c, 105)
132901 ** For each sample in the aSample[] array, N samples are present in the
132902 ** effective sample array. In the above, samples 0 and 1 are based on
132903 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
132905 ** Often, sample i of each block of N effective samples has (i+1) fields.
132906 ** Except, each sample may be extended to ensure that it is greater than or
132907 ** equal to the previous sample in the array. For example, in the above,
132908 ** sample 2 is the first sample of a block of N samples, so at first it
132909 ** appears that it should be 1 field in size. However, that would make it
132910 ** smaller than sample 1, so the binary search would not work. As a result,
132911 ** it is extended to two fields. The duplicates that this creates do not
132912 ** cause any problems.
132914 nField = pRec->nField;
132915 iCol = 0;
132916 iSample = pIdx->nSample * nField;
132918 int iSamp; /* Index in aSample[] of test sample */
132919 int n; /* Number of fields in test sample */
132921 iTest = (iMin+iSample)/2;
132922 iSamp = iTest / nField;
132923 if( iSamp>0 ){
132924 /* The proposed effective sample is a prefix of sample aSample[iSamp].
132925 ** Specifically, the shortest prefix of at least (1 + iTest%nField)
132926 ** fields that is greater than the previous effective sample. */
132927 for(n=(iTest % nField) + 1; n<nField; n++){
132928 if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
132930 }else{
132931 n = iTest + 1;
132934 pRec->nField = n;
132935 res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
132936 if( res<0 ){
132937 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
132938 iMin = iTest+1;
132939 }else if( res==0 && n<nField ){
132940 iLower = aSample[iSamp].anLt[n-1];
132941 iMin = iTest+1;
132942 res = -1;
132943 }else{
132944 iSample = iTest;
132945 iCol = n-1;
132947 }while( res && iMin<iSample );
132948 i = iSample / nField;
132950 #ifdef SQLITE_DEBUG
132951 /* The following assert statements check that the binary search code
132952 ** above found the right answer. This block serves no purpose other
132953 ** than to invoke the asserts. */
132954 if( pParse->db->mallocFailed==0 ){
132955 if( res==0 ){
132956 /* If (res==0) is true, then pRec must be equal to sample i. */
132957 assert( i<pIdx->nSample );
132958 assert( iCol==nField-1 );
132959 pRec->nField = nField;
132960 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
132961 || pParse->db->mallocFailed
132963 }else{
132964 /* Unless i==pIdx->nSample, indicating that pRec is larger than
132965 ** all samples in the aSample[] array, pRec must be smaller than the
132966 ** (iCol+1) field prefix of sample i. */
132967 assert( i<=pIdx->nSample && i>=0 );
132968 pRec->nField = iCol+1;
132969 assert( i==pIdx->nSample
132970 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
132971 || pParse->db->mallocFailed );
132973 /* if i==0 and iCol==0, then record pRec is smaller than all samples
132974 ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
132975 ** be greater than or equal to the (iCol) field prefix of sample i.
132976 ** If (i>0), then pRec must also be greater than sample (i-1). */
132977 if( iCol>0 ){
132978 pRec->nField = iCol;
132979 assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
132980 || pParse->db->mallocFailed );
132982 if( i>0 ){
132983 pRec->nField = nField;
132984 assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
132985 || pParse->db->mallocFailed );
132989 #endif /* ifdef SQLITE_DEBUG */
132991 if( res==0 ){
132992 /* Record pRec is equal to sample i */
132993 assert( iCol==nField-1 );
132994 aStat[0] = aSample[i].anLt[iCol];
132995 aStat[1] = aSample[i].anEq[iCol];
132996 }else{
132997 /* At this point, the (iCol+1) field prefix of aSample[i] is the first
132998 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
132999 ** is larger than all samples in the array. */
133000 tRowcnt iUpper, iGap;
133001 if( i>=pIdx->nSample ){
133002 iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
133003 }else{
133004 iUpper = aSample[i].anLt[iCol];
133007 if( iLower>=iUpper ){
133008 iGap = 0;
133009 }else{
133010 iGap = iUpper - iLower;
133012 if( roundUp ){
133013 iGap = (iGap*2)/3;
133014 }else{
133015 iGap = iGap/3;
133017 aStat[0] = iLower + iGap;
133018 aStat[1] = pIdx->aAvgEq[nField-1];
133021 /* Restore the pRec->nField value before returning. */
133022 pRec->nField = nField;
133023 return i;
133025 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
133028 ** If it is not NULL, pTerm is a term that provides an upper or lower
133029 ** bound on a range scan. Without considering pTerm, it is estimated
133030 ** that the scan will visit nNew rows. This function returns the number
133031 ** estimated to be visited after taking pTerm into account.
133033 ** If the user explicitly specified a likelihood() value for this term,
133034 ** then the return value is the likelihood multiplied by the number of
133035 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
133036 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
133038 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
133039 LogEst nRet = nNew;
133040 if( pTerm ){
133041 if( pTerm->truthProb<=0 ){
133042 nRet += pTerm->truthProb;
133043 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
133044 nRet -= 20; assert( 20==sqlite3LogEst(4) );
133047 return nRet;
133051 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133053 ** Return the affinity for a single column of an index.
133055 SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
133056 assert( iCol>=0 && iCol<pIdx->nColumn );
133057 if( !pIdx->zColAff ){
133058 if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
133060 return pIdx->zColAff[iCol];
133062 #endif
133065 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133067 ** This function is called to estimate the number of rows visited by a
133068 ** range-scan on a skip-scan index. For example:
133070 ** CREATE INDEX i1 ON t1(a, b, c);
133071 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
133073 ** Value pLoop->nOut is currently set to the estimated number of rows
133074 ** visited for scanning (a=? AND b=?). This function reduces that estimate
133075 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
133076 ** on the stat4 data for the index. this scan will be peformed multiple
133077 ** times (once for each (a,b) combination that matches a=?) is dealt with
133078 ** by the caller.
133080 ** It does this by scanning through all stat4 samples, comparing values
133081 ** extracted from pLower and pUpper with the corresponding column in each
133082 ** sample. If L and U are the number of samples found to be less than or
133083 ** equal to the values extracted from pLower and pUpper respectively, and
133084 ** N is the total number of samples, the pLoop->nOut value is adjusted
133085 ** as follows:
133087 ** nOut = nOut * ( min(U - L, 1) / N )
133089 ** If pLower is NULL, or a value cannot be extracted from the term, L is
133090 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
133091 ** U is set to N.
133093 ** Normally, this function sets *pbDone to 1 before returning. However,
133094 ** if no value can be extracted from either pLower or pUpper (and so the
133095 ** estimate of the number of rows delivered remains unchanged), *pbDone
133096 ** is left as is.
133098 ** If an error occurs, an SQLite error code is returned. Otherwise,
133099 ** SQLITE_OK.
133101 static int whereRangeSkipScanEst(
133102 Parse *pParse, /* Parsing & code generating context */
133103 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
133104 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
133105 WhereLoop *pLoop, /* Update the .nOut value of this loop */
133106 int *pbDone /* Set to true if at least one expr. value extracted */
133108 Index *p = pLoop->u.btree.pIndex;
133109 int nEq = pLoop->u.btree.nEq;
133110 sqlite3 *db = pParse->db;
133111 int nLower = -1;
133112 int nUpper = p->nSample+1;
133113 int rc = SQLITE_OK;
133114 u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
133115 CollSeq *pColl;
133117 sqlite3_value *p1 = 0; /* Value extracted from pLower */
133118 sqlite3_value *p2 = 0; /* Value extracted from pUpper */
133119 sqlite3_value *pVal = 0; /* Value extracted from record */
133121 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
133122 if( pLower ){
133123 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
133124 nLower = 0;
133126 if( pUpper && rc==SQLITE_OK ){
133127 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
133128 nUpper = p2 ? 0 : p->nSample;
133131 if( p1 || p2 ){
133132 int i;
133133 int nDiff;
133134 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
133135 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
133136 if( rc==SQLITE_OK && p1 ){
133137 int res = sqlite3MemCompare(p1, pVal, pColl);
133138 if( res>=0 ) nLower++;
133140 if( rc==SQLITE_OK && p2 ){
133141 int res = sqlite3MemCompare(p2, pVal, pColl);
133142 if( res>=0 ) nUpper++;
133145 nDiff = (nUpper - nLower);
133146 if( nDiff<=0 ) nDiff = 1;
133148 /* If there is both an upper and lower bound specified, and the
133149 ** comparisons indicate that they are close together, use the fallback
133150 ** method (assume that the scan visits 1/64 of the rows) for estimating
133151 ** the number of rows visited. Otherwise, estimate the number of rows
133152 ** using the method described in the header comment for this function. */
133153 if( nDiff!=1 || pUpper==0 || pLower==0 ){
133154 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
133155 pLoop->nOut -= nAdjust;
133156 *pbDone = 1;
133157 WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
133158 nLower, nUpper, nAdjust*-1, pLoop->nOut));
133161 }else{
133162 assert( *pbDone==0 );
133165 sqlite3ValueFree(p1);
133166 sqlite3ValueFree(p2);
133167 sqlite3ValueFree(pVal);
133169 return rc;
133171 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
133174 ** This function is used to estimate the number of rows that will be visited
133175 ** by scanning an index for a range of values. The range may have an upper
133176 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
133177 ** and lower bounds are represented by pLower and pUpper respectively. For
133178 ** example, assuming that index p is on t1(a):
133180 ** ... FROM t1 WHERE a > ? AND a < ? ...
133181 ** |_____| |_____|
133182 ** | |
133183 ** pLower pUpper
133185 ** If either of the upper or lower bound is not present, then NULL is passed in
133186 ** place of the corresponding WhereTerm.
133188 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
133189 ** column subject to the range constraint. Or, equivalently, the number of
133190 ** equality constraints optimized by the proposed index scan. For example,
133191 ** assuming index p is on t1(a, b), and the SQL query is:
133193 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
133195 ** then nEq is set to 1 (as the range restricted column, b, is the second
133196 ** left-most column of the index). Or, if the query is:
133198 ** ... FROM t1 WHERE a > ? AND a < ? ...
133200 ** then nEq is set to 0.
133202 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
133203 ** number of rows that the index scan is expected to visit without
133204 ** considering the range constraints. If nEq is 0, then *pnOut is the number of
133205 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
133206 ** to account for the range constraints pLower and pUpper.
133208 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
133209 ** used, a single range inequality reduces the search space by a factor of 4.
133210 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
133211 ** rows visited by a factor of 64.
133213 static int whereRangeScanEst(
133214 Parse *pParse, /* Parsing & code generating context */
133215 WhereLoopBuilder *pBuilder,
133216 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
133217 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
133218 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
133220 int rc = SQLITE_OK;
133221 int nOut = pLoop->nOut;
133222 LogEst nNew;
133224 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133225 Index *p = pLoop->u.btree.pIndex;
133226 int nEq = pLoop->u.btree.nEq;
133228 if( p->nSample>0 && nEq<p->nSampleCol ){
133229 if( nEq==pBuilder->nRecValid ){
133230 UnpackedRecord *pRec = pBuilder->pRec;
133231 tRowcnt a[2];
133232 int nBtm = pLoop->u.btree.nBtm;
133233 int nTop = pLoop->u.btree.nTop;
133235 /* Variable iLower will be set to the estimate of the number of rows in
133236 ** the index that are less than the lower bound of the range query. The
133237 ** lower bound being the concatenation of $P and $L, where $P is the
133238 ** key-prefix formed by the nEq values matched against the nEq left-most
133239 ** columns of the index, and $L is the value in pLower.
133241 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
133242 ** is not a simple variable or literal value), the lower bound of the
133243 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
133244 ** if $L is available, whereKeyStats() is called for both ($P) and
133245 ** ($P:$L) and the larger of the two returned values is used.
133247 ** Similarly, iUpper is to be set to the estimate of the number of rows
133248 ** less than the upper bound of the range query. Where the upper bound
133249 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
133250 ** of iUpper are requested of whereKeyStats() and the smaller used.
133252 ** The number of rows between the two bounds is then just iUpper-iLower.
133254 tRowcnt iLower; /* Rows less than the lower bound */
133255 tRowcnt iUpper; /* Rows less than the upper bound */
133256 int iLwrIdx = -2; /* aSample[] for the lower bound */
133257 int iUprIdx = -1; /* aSample[] for the upper bound */
133259 if( pRec ){
133260 testcase( pRec->nField!=pBuilder->nRecValid );
133261 pRec->nField = pBuilder->nRecValid;
133263 /* Determine iLower and iUpper using ($P) only. */
133264 if( nEq==0 ){
133265 iLower = 0;
133266 iUpper = p->nRowEst0;
133267 }else{
133268 /* Note: this call could be optimized away - since the same values must
133269 ** have been requested when testing key $P in whereEqualScanEst(). */
133270 whereKeyStats(pParse, p, pRec, 0, a);
133271 iLower = a[0];
133272 iUpper = a[0] + a[1];
133275 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
133276 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
133277 assert( p->aSortOrder!=0 );
133278 if( p->aSortOrder[nEq] ){
133279 /* The roles of pLower and pUpper are swapped for a DESC index */
133280 SWAP(WhereTerm*, pLower, pUpper);
133281 SWAP(int, nBtm, nTop);
133284 /* If possible, improve on the iLower estimate using ($P:$L). */
133285 if( pLower ){
133286 int n; /* Values extracted from pExpr */
133287 Expr *pExpr = pLower->pExpr->pRight;
133288 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
133289 if( rc==SQLITE_OK && n ){
133290 tRowcnt iNew;
133291 u16 mask = WO_GT|WO_LE;
133292 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
133293 iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
133294 iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
133295 if( iNew>iLower ) iLower = iNew;
133296 nOut--;
133297 pLower = 0;
133301 /* If possible, improve on the iUpper estimate using ($P:$U). */
133302 if( pUpper ){
133303 int n; /* Values extracted from pExpr */
133304 Expr *pExpr = pUpper->pExpr->pRight;
133305 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
133306 if( rc==SQLITE_OK && n ){
133307 tRowcnt iNew;
133308 u16 mask = WO_GT|WO_LE;
133309 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
133310 iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
133311 iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
133312 if( iNew<iUpper ) iUpper = iNew;
133313 nOut--;
133314 pUpper = 0;
133318 pBuilder->pRec = pRec;
133319 if( rc==SQLITE_OK ){
133320 if( iUpper>iLower ){
133321 nNew = sqlite3LogEst(iUpper - iLower);
133322 /* TUNING: If both iUpper and iLower are derived from the same
133323 ** sample, then assume they are 4x more selective. This brings
133324 ** the estimated selectivity more in line with what it would be
133325 ** if estimated without the use of STAT3/4 tables. */
133326 if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
133327 }else{
133328 nNew = 10; assert( 10==sqlite3LogEst(2) );
133330 if( nNew<nOut ){
133331 nOut = nNew;
133333 WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
133334 (u32)iLower, (u32)iUpper, nOut));
133336 }else{
133337 int bDone = 0;
133338 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
133339 if( bDone ) return rc;
133342 #else
133343 UNUSED_PARAMETER(pParse);
133344 UNUSED_PARAMETER(pBuilder);
133345 assert( pLower || pUpper );
133346 #endif
133347 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
133348 nNew = whereRangeAdjust(pLower, nOut);
133349 nNew = whereRangeAdjust(pUpper, nNew);
133351 /* TUNING: If there is both an upper and lower limit and neither limit
133352 ** has an application-defined likelihood(), assume the range is
133353 ** reduced by an additional 75%. This means that, by default, an open-ended
133354 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
133355 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
133356 ** match 1/64 of the index. */
133357 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
133358 nNew -= 20;
133361 nOut -= (pLower!=0) + (pUpper!=0);
133362 if( nNew<10 ) nNew = 10;
133363 if( nNew<nOut ) nOut = nNew;
133364 #if defined(WHERETRACE_ENABLED)
133365 if( pLoop->nOut>nOut ){
133366 WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
133367 pLoop->nOut, nOut));
133369 #endif
133370 pLoop->nOut = (LogEst)nOut;
133371 return rc;
133374 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133376 ** Estimate the number of rows that will be returned based on
133377 ** an equality constraint x=VALUE and where that VALUE occurs in
133378 ** the histogram data. This only works when x is the left-most
133379 ** column of an index and sqlite_stat3 histogram data is available
133380 ** for that index. When pExpr==NULL that means the constraint is
133381 ** "x IS NULL" instead of "x=VALUE".
133383 ** Write the estimated row count into *pnRow and return SQLITE_OK.
133384 ** If unable to make an estimate, leave *pnRow unchanged and return
133385 ** non-zero.
133387 ** This routine can fail if it is unable to load a collating sequence
133388 ** required for string comparison, or if unable to allocate memory
133389 ** for a UTF conversion required for comparison. The error is stored
133390 ** in the pParse structure.
133392 static int whereEqualScanEst(
133393 Parse *pParse, /* Parsing & code generating context */
133394 WhereLoopBuilder *pBuilder,
133395 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
133396 tRowcnt *pnRow /* Write the revised row estimate here */
133398 Index *p = pBuilder->pNew->u.btree.pIndex;
133399 int nEq = pBuilder->pNew->u.btree.nEq;
133400 UnpackedRecord *pRec = pBuilder->pRec;
133401 int rc; /* Subfunction return code */
133402 tRowcnt a[2]; /* Statistics */
133403 int bOk;
133405 assert( nEq>=1 );
133406 assert( nEq<=p->nColumn );
133407 assert( p->aSample!=0 );
133408 assert( p->nSample>0 );
133409 assert( pBuilder->nRecValid<nEq );
133411 /* If values are not available for all fields of the index to the left
133412 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
133413 if( pBuilder->nRecValid<(nEq-1) ){
133414 return SQLITE_NOTFOUND;
133417 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
133418 ** below would return the same value. */
133419 if( nEq>=p->nColumn ){
133420 *pnRow = 1;
133421 return SQLITE_OK;
133424 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
133425 pBuilder->pRec = pRec;
133426 if( rc!=SQLITE_OK ) return rc;
133427 if( bOk==0 ) return SQLITE_NOTFOUND;
133428 pBuilder->nRecValid = nEq;
133430 whereKeyStats(pParse, p, pRec, 0, a);
133431 WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
133432 p->zName, nEq-1, (int)a[1]));
133433 *pnRow = a[1];
133435 return rc;
133437 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
133439 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133441 ** Estimate the number of rows that will be returned based on
133442 ** an IN constraint where the right-hand side of the IN operator
133443 ** is a list of values. Example:
133445 ** WHERE x IN (1,2,3,4)
133447 ** Write the estimated row count into *pnRow and return SQLITE_OK.
133448 ** If unable to make an estimate, leave *pnRow unchanged and return
133449 ** non-zero.
133451 ** This routine can fail if it is unable to load a collating sequence
133452 ** required for string comparison, or if unable to allocate memory
133453 ** for a UTF conversion required for comparison. The error is stored
133454 ** in the pParse structure.
133456 static int whereInScanEst(
133457 Parse *pParse, /* Parsing & code generating context */
133458 WhereLoopBuilder *pBuilder,
133459 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
133460 tRowcnt *pnRow /* Write the revised row estimate here */
133462 Index *p = pBuilder->pNew->u.btree.pIndex;
133463 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
133464 int nRecValid = pBuilder->nRecValid;
133465 int rc = SQLITE_OK; /* Subfunction return code */
133466 tRowcnt nEst; /* Number of rows for a single term */
133467 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
133468 int i; /* Loop counter */
133470 assert( p->aSample!=0 );
133471 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
133472 nEst = nRow0;
133473 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
133474 nRowEst += nEst;
133475 pBuilder->nRecValid = nRecValid;
133478 if( rc==SQLITE_OK ){
133479 if( nRowEst > nRow0 ) nRowEst = nRow0;
133480 *pnRow = nRowEst;
133481 WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
133483 assert( pBuilder->nRecValid==nRecValid );
133484 return rc;
133486 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
133489 #ifdef WHERETRACE_ENABLED
133491 ** Print the content of a WhereTerm object
133493 static void whereTermPrint(WhereTerm *pTerm, int iTerm){
133494 if( pTerm==0 ){
133495 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
133496 }else{
133497 char zType[4];
133498 char zLeft[50];
133499 memcpy(zType, "...", 4);
133500 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
133501 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
133502 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
133503 if( pTerm->eOperator & WO_SINGLE ){
133504 sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
133505 pTerm->leftCursor, pTerm->u.leftColumn);
133506 }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
133507 sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
133508 pTerm->u.pOrInfo->indexable);
133509 }else{
133510 sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
133512 sqlite3DebugPrintf(
133513 "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
133514 iTerm, pTerm, zType, zLeft, pTerm->truthProb,
133515 pTerm->eOperator, pTerm->wtFlags);
133516 if( pTerm->iField ){
133517 sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
133518 }else{
133519 sqlite3DebugPrintf("\n");
133521 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
133524 #endif
133526 #ifdef WHERETRACE_ENABLED
133528 ** Show the complete content of a WhereClause
133530 SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
133531 int i;
133532 for(i=0; i<pWC->nTerm; i++){
133533 whereTermPrint(&pWC->a[i], i);
133536 #endif
133538 #ifdef WHERETRACE_ENABLED
133540 ** Print a WhereLoop object for debugging purposes
133542 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
133543 WhereInfo *pWInfo = pWC->pWInfo;
133544 int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
133545 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
133546 Table *pTab = pItem->pTab;
133547 Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
133548 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
133549 p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
133550 sqlite3DebugPrintf(" %12s",
133551 pItem->zAlias ? pItem->zAlias : pTab->zName);
133552 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
133553 const char *zName;
133554 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
133555 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
133556 int i = sqlite3Strlen30(zName) - 1;
133557 while( zName[i]!='_' ) i--;
133558 zName += i;
133560 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
133561 }else{
133562 sqlite3DebugPrintf("%20s","");
133564 }else{
133565 char *z;
133566 if( p->u.vtab.idxStr ){
133567 z = sqlite3_mprintf("(%d,\"%s\",%x)",
133568 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
133569 }else{
133570 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
133572 sqlite3DebugPrintf(" %-19s", z);
133573 sqlite3_free(z);
133575 if( p->wsFlags & WHERE_SKIPSCAN ){
133576 sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
133577 }else{
133578 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
133580 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
133581 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
133582 int i;
133583 for(i=0; i<p->nLTerm; i++){
133584 whereTermPrint(p->aLTerm[i], i);
133588 #endif
133591 ** Convert bulk memory into a valid WhereLoop that can be passed
133592 ** to whereLoopClear harmlessly.
133594 static void whereLoopInit(WhereLoop *p){
133595 p->aLTerm = p->aLTermSpace;
133596 p->nLTerm = 0;
133597 p->nLSlot = ArraySize(p->aLTermSpace);
133598 p->wsFlags = 0;
133602 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
133604 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
133605 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
133606 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
133607 sqlite3_free(p->u.vtab.idxStr);
133608 p->u.vtab.needFree = 0;
133609 p->u.vtab.idxStr = 0;
133610 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
133611 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
133612 sqlite3DbFreeNN(db, p->u.btree.pIndex);
133613 p->u.btree.pIndex = 0;
133619 ** Deallocate internal memory used by a WhereLoop object
133621 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
133622 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
133623 whereLoopClearUnion(db, p);
133624 whereLoopInit(p);
133628 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
133630 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
133631 WhereTerm **paNew;
133632 if( p->nLSlot>=n ) return SQLITE_OK;
133633 n = (n+7)&~7;
133634 paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
133635 if( paNew==0 ) return SQLITE_NOMEM_BKPT;
133636 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
133637 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
133638 p->aLTerm = paNew;
133639 p->nLSlot = n;
133640 return SQLITE_OK;
133644 ** Transfer content from the second pLoop into the first.
133646 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
133647 whereLoopClearUnion(db, pTo);
133648 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
133649 memset(&pTo->u, 0, sizeof(pTo->u));
133650 return SQLITE_NOMEM_BKPT;
133652 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
133653 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
133654 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
133655 pFrom->u.vtab.needFree = 0;
133656 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
133657 pFrom->u.btree.pIndex = 0;
133659 return SQLITE_OK;
133663 ** Delete a WhereLoop object
133665 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
133666 whereLoopClear(db, p);
133667 sqlite3DbFreeNN(db, p);
133671 ** Free a WhereInfo structure
133673 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
133674 if( ALWAYS(pWInfo) ){
133675 int i;
133676 for(i=0; i<pWInfo->nLevel; i++){
133677 WhereLevel *pLevel = &pWInfo->a[i];
133678 if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
133679 sqlite3DbFree(db, pLevel->u.in.aInLoop);
133682 sqlite3WhereClauseClear(&pWInfo->sWC);
133683 while( pWInfo->pLoops ){
133684 WhereLoop *p = pWInfo->pLoops;
133685 pWInfo->pLoops = p->pNextLoop;
133686 whereLoopDelete(db, p);
133688 sqlite3DbFreeNN(db, pWInfo);
133693 ** Return TRUE if all of the following are true:
133695 ** (1) X has the same or lower cost that Y
133696 ** (2) X uses fewer WHERE clause terms than Y
133697 ** (3) Every WHERE clause term used by X is also used by Y
133698 ** (4) X skips at least as many columns as Y
133699 ** (5) If X is a covering index, than Y is too
133701 ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
133702 ** If X is a proper subset of Y then Y is a better choice and ought
133703 ** to have a lower cost. This routine returns TRUE when that cost
133704 ** relationship is inverted and needs to be adjusted. Constraint (4)
133705 ** was added because if X uses skip-scan less than Y it still might
133706 ** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
133707 ** was added because a covering index probably deserves to have a lower cost
133708 ** than a non-covering index even if it is a proper subset.
133710 static int whereLoopCheaperProperSubset(
133711 const WhereLoop *pX, /* First WhereLoop to compare */
133712 const WhereLoop *pY /* Compare against this WhereLoop */
133714 int i, j;
133715 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
133716 return 0; /* X is not a subset of Y */
133718 if( pY->nSkip > pX->nSkip ) return 0;
133719 if( pX->rRun >= pY->rRun ){
133720 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
133721 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
133723 for(i=pX->nLTerm-1; i>=0; i--){
133724 if( pX->aLTerm[i]==0 ) continue;
133725 for(j=pY->nLTerm-1; j>=0; j--){
133726 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
133728 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
133730 if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
133731 && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
133732 return 0; /* Constraint (5) */
133734 return 1; /* All conditions meet */
133738 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
133739 ** that:
133741 ** (1) pTemplate costs less than any other WhereLoops that are a proper
133742 ** subset of pTemplate
133744 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
133745 ** is a proper subset.
133747 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
133748 ** WHERE clause terms than Y and that every WHERE clause term used by X is
133749 ** also used by Y.
133751 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
133752 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
133753 for(; p; p=p->pNextLoop){
133754 if( p->iTab!=pTemplate->iTab ) continue;
133755 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
133756 if( whereLoopCheaperProperSubset(p, pTemplate) ){
133757 /* Adjust pTemplate cost downward so that it is cheaper than its
133758 ** subset p. */
133759 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
133760 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
133761 pTemplate->rRun = p->rRun;
133762 pTemplate->nOut = p->nOut - 1;
133763 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
133764 /* Adjust pTemplate cost upward so that it is costlier than p since
133765 ** pTemplate is a proper subset of p */
133766 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
133767 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
133768 pTemplate->rRun = p->rRun;
133769 pTemplate->nOut = p->nOut + 1;
133775 ** Search the list of WhereLoops in *ppPrev looking for one that can be
133776 ** replaced by pTemplate.
133778 ** Return NULL if pTemplate does not belong on the WhereLoop list.
133779 ** In other words if pTemplate ought to be dropped from further consideration.
133781 ** If pX is a WhereLoop that pTemplate can replace, then return the
133782 ** link that points to pX.
133784 ** If pTemplate cannot replace any existing element of the list but needs
133785 ** to be added to the list as a new entry, then return a pointer to the
133786 ** tail of the list.
133788 static WhereLoop **whereLoopFindLesser(
133789 WhereLoop **ppPrev,
133790 const WhereLoop *pTemplate
133792 WhereLoop *p;
133793 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
133794 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
133795 /* If either the iTab or iSortIdx values for two WhereLoop are different
133796 ** then those WhereLoops need to be considered separately. Neither is
133797 ** a candidate to replace the other. */
133798 continue;
133800 /* In the current implementation, the rSetup value is either zero
133801 ** or the cost of building an automatic index (NlogN) and the NlogN
133802 ** is the same for compatible WhereLoops. */
133803 assert( p->rSetup==0 || pTemplate->rSetup==0
133804 || p->rSetup==pTemplate->rSetup );
133806 /* whereLoopAddBtree() always generates and inserts the automatic index
133807 ** case first. Hence compatible candidate WhereLoops never have a larger
133808 ** rSetup. Call this SETUP-INVARIANT */
133809 assert( p->rSetup>=pTemplate->rSetup );
133811 /* Any loop using an appliation-defined index (or PRIMARY KEY or
133812 ** UNIQUE constraint) with one or more == constraints is better
133813 ** than an automatic index. Unless it is a skip-scan. */
133814 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
133815 && (pTemplate->nSkip)==0
133816 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
133817 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
133818 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
133820 break;
133823 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
133824 ** discarded. WhereLoop p is better if:
133825 ** (1) p has no more dependencies than pTemplate, and
133826 ** (2) p has an equal or lower cost than pTemplate
133828 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
133829 && p->rSetup<=pTemplate->rSetup /* (2a) */
133830 && p->rRun<=pTemplate->rRun /* (2b) */
133831 && p->nOut<=pTemplate->nOut /* (2c) */
133833 return 0; /* Discard pTemplate */
133836 /* If pTemplate is always better than p, then cause p to be overwritten
133837 ** with pTemplate. pTemplate is better than p if:
133838 ** (1) pTemplate has no more dependences than p, and
133839 ** (2) pTemplate has an equal or lower cost than p.
133841 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
133842 && p->rRun>=pTemplate->rRun /* (2a) */
133843 && p->nOut>=pTemplate->nOut /* (2b) */
133845 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
133846 break; /* Cause p to be overwritten by pTemplate */
133849 return ppPrev;
133853 ** Insert or replace a WhereLoop entry using the template supplied.
133855 ** An existing WhereLoop entry might be overwritten if the new template
133856 ** is better and has fewer dependencies. Or the template will be ignored
133857 ** and no insert will occur if an existing WhereLoop is faster and has
133858 ** fewer dependencies than the template. Otherwise a new WhereLoop is
133859 ** added based on the template.
133861 ** If pBuilder->pOrSet is not NULL then we care about only the
133862 ** prerequisites and rRun and nOut costs of the N best loops. That
133863 ** information is gathered in the pBuilder->pOrSet object. This special
133864 ** processing mode is used only for OR clause processing.
133866 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
133867 ** still might overwrite similar loops with the new template if the
133868 ** new template is better. Loops may be overwritten if the following
133869 ** conditions are met:
133871 ** (1) They have the same iTab.
133872 ** (2) They have the same iSortIdx.
133873 ** (3) The template has same or fewer dependencies than the current loop
133874 ** (4) The template has the same or lower cost than the current loop
133876 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
133877 WhereLoop **ppPrev, *p;
133878 WhereInfo *pWInfo = pBuilder->pWInfo;
133879 sqlite3 *db = pWInfo->pParse->db;
133880 int rc;
133882 /* If pBuilder->pOrSet is defined, then only keep track of the costs
133883 ** and prereqs.
133885 if( pBuilder->pOrSet!=0 ){
133886 if( pTemplate->nLTerm ){
133887 #if WHERETRACE_ENABLED
133888 u16 n = pBuilder->pOrSet->n;
133889 int x =
133890 #endif
133891 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
133892 pTemplate->nOut);
133893 #if WHERETRACE_ENABLED /* 0x8 */
133894 if( sqlite3WhereTrace & 0x8 ){
133895 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
133896 whereLoopPrint(pTemplate, pBuilder->pWC);
133898 #endif
133900 return SQLITE_OK;
133903 /* Look for an existing WhereLoop to replace with pTemplate
133905 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
133906 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
133908 if( ppPrev==0 ){
133909 /* There already exists a WhereLoop on the list that is better
133910 ** than pTemplate, so just ignore pTemplate */
133911 #if WHERETRACE_ENABLED /* 0x8 */
133912 if( sqlite3WhereTrace & 0x8 ){
133913 sqlite3DebugPrintf(" skip: ");
133914 whereLoopPrint(pTemplate, pBuilder->pWC);
133916 #endif
133917 return SQLITE_OK;
133918 }else{
133919 p = *ppPrev;
133922 /* If we reach this point it means that either p[] should be overwritten
133923 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
133924 ** WhereLoop and insert it.
133926 #if WHERETRACE_ENABLED /* 0x8 */
133927 if( sqlite3WhereTrace & 0x8 ){
133928 if( p!=0 ){
133929 sqlite3DebugPrintf("replace: ");
133930 whereLoopPrint(p, pBuilder->pWC);
133931 sqlite3DebugPrintf(" with: ");
133932 }else{
133933 sqlite3DebugPrintf(" add: ");
133935 whereLoopPrint(pTemplate, pBuilder->pWC);
133937 #endif
133938 if( p==0 ){
133939 /* Allocate a new WhereLoop to add to the end of the list */
133940 *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
133941 if( p==0 ) return SQLITE_NOMEM_BKPT;
133942 whereLoopInit(p);
133943 p->pNextLoop = 0;
133944 }else{
133945 /* We will be overwriting WhereLoop p[]. But before we do, first
133946 ** go through the rest of the list and delete any other entries besides
133947 ** p[] that are also supplated by pTemplate */
133948 WhereLoop **ppTail = &p->pNextLoop;
133949 WhereLoop *pToDel;
133950 while( *ppTail ){
133951 ppTail = whereLoopFindLesser(ppTail, pTemplate);
133952 if( ppTail==0 ) break;
133953 pToDel = *ppTail;
133954 if( pToDel==0 ) break;
133955 *ppTail = pToDel->pNextLoop;
133956 #if WHERETRACE_ENABLED /* 0x8 */
133957 if( sqlite3WhereTrace & 0x8 ){
133958 sqlite3DebugPrintf(" delete: ");
133959 whereLoopPrint(pToDel, pBuilder->pWC);
133961 #endif
133962 whereLoopDelete(db, pToDel);
133965 rc = whereLoopXfer(db, p, pTemplate);
133966 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
133967 Index *pIndex = p->u.btree.pIndex;
133968 if( pIndex && pIndex->tnum==0 ){
133969 p->u.btree.pIndex = 0;
133972 return rc;
133976 ** Adjust the WhereLoop.nOut value downward to account for terms of the
133977 ** WHERE clause that reference the loop but which are not used by an
133978 ** index.
133980 ** For every WHERE clause term that is not used by the index
133981 ** and which has a truth probability assigned by one of the likelihood(),
133982 ** likely(), or unlikely() SQL functions, reduce the estimated number
133983 ** of output rows by the probability specified.
133985 ** TUNING: For every WHERE clause term that is not used by the index
133986 ** and which does not have an assigned truth probability, heuristics
133987 ** described below are used to try to estimate the truth probability.
133988 ** TODO --> Perhaps this is something that could be improved by better
133989 ** table statistics.
133991 ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
133992 ** value corresponds to -1 in LogEst notation, so this means decrement
133993 ** the WhereLoop.nOut field for every such WHERE clause term.
133995 ** Heuristic 2: If there exists one or more WHERE clause terms of the
133996 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
133997 ** final output row estimate is no greater than 1/4 of the total number
133998 ** of rows in the table. In other words, assume that x==EXPR will filter
133999 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
134000 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
134001 ** on the "x" column and so in that case only cap the output row estimate
134002 ** at 1/2 instead of 1/4.
134004 static void whereLoopOutputAdjust(
134005 WhereClause *pWC, /* The WHERE clause */
134006 WhereLoop *pLoop, /* The loop to adjust downward */
134007 LogEst nRow /* Number of rows in the entire table */
134009 WhereTerm *pTerm, *pX;
134010 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
134011 int i, j, k;
134012 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
134014 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
134015 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
134016 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
134017 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
134018 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
134019 for(j=pLoop->nLTerm-1; j>=0; j--){
134020 pX = pLoop->aLTerm[j];
134021 if( pX==0 ) continue;
134022 if( pX==pTerm ) break;
134023 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
134025 if( j<0 ){
134026 if( pTerm->truthProb<=0 ){
134027 /* If a truth probability is specified using the likelihood() hints,
134028 ** then use the probability provided by the application. */
134029 pLoop->nOut += pTerm->truthProb;
134030 }else{
134031 /* In the absence of explicit truth probabilities, use heuristics to
134032 ** guess a reasonable truth probability. */
134033 pLoop->nOut--;
134034 if( pTerm->eOperator&(WO_EQ|WO_IS) ){
134035 Expr *pRight = pTerm->pExpr->pRight;
134036 testcase( pTerm->pExpr->op==TK_IS );
134037 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
134038 k = 10;
134039 }else{
134040 k = 20;
134042 if( iReduce<k ) iReduce = k;
134047 if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
134051 ** Term pTerm is a vector range comparison operation. The first comparison
134052 ** in the vector can be optimized using column nEq of the index. This
134053 ** function returns the total number of vector elements that can be used
134054 ** as part of the range comparison.
134056 ** For example, if the query is:
134058 ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
134060 ** and the index:
134062 ** CREATE INDEX ... ON (a, b, c, d, e)
134064 ** then this function would be invoked with nEq=1. The value returned in
134065 ** this case is 3.
134067 static int whereRangeVectorLen(
134068 Parse *pParse, /* Parsing context */
134069 int iCur, /* Cursor open on pIdx */
134070 Index *pIdx, /* The index to be used for a inequality constraint */
134071 int nEq, /* Number of prior equality constraints on same index */
134072 WhereTerm *pTerm /* The vector inequality constraint */
134074 int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
134075 int i;
134077 nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
134078 for(i=1; i<nCmp; i++){
134079 /* Test if comparison i of pTerm is compatible with column (i+nEq)
134080 ** of the index. If not, exit the loop. */
134081 char aff; /* Comparison affinity */
134082 char idxaff = 0; /* Indexed columns affinity */
134083 CollSeq *pColl; /* Comparison collation sequence */
134084 Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
134085 Expr *pRhs = pTerm->pExpr->pRight;
134086 if( pRhs->flags & EP_xIsSelect ){
134087 pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
134088 }else{
134089 pRhs = pRhs->x.pList->a[i].pExpr;
134092 /* Check that the LHS of the comparison is a column reference to
134093 ** the right column of the right source table. And that the sort
134094 ** order of the index column is the same as the sort order of the
134095 ** leftmost index column. */
134096 if( pLhs->op!=TK_COLUMN
134097 || pLhs->iTable!=iCur
134098 || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
134099 || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
134101 break;
134104 testcase( pLhs->iColumn==XN_ROWID );
134105 aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
134106 idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
134107 if( aff!=idxaff ) break;
134109 pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
134110 if( pColl==0 ) break;
134111 if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
134113 return i;
134117 ** Adjust the cost C by the costMult facter T. This only occurs if
134118 ** compiled with -DSQLITE_ENABLE_COSTMULT
134120 #ifdef SQLITE_ENABLE_COSTMULT
134121 # define ApplyCostMultiplier(C,T) C += T
134122 #else
134123 # define ApplyCostMultiplier(C,T)
134124 #endif
134127 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
134128 ** index pIndex. Try to match one more.
134130 ** When this function is called, pBuilder->pNew->nOut contains the
134131 ** number of rows expected to be visited by filtering using the nEq
134132 ** terms only. If it is modified, this value is restored before this
134133 ** function returns.
134135 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
134136 ** INTEGER PRIMARY KEY.
134138 static int whereLoopAddBtreeIndex(
134139 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
134140 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
134141 Index *pProbe, /* An index on pSrc */
134142 LogEst nInMul /* log(Number of iterations due to IN) */
134144 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
134145 Parse *pParse = pWInfo->pParse; /* Parsing context */
134146 sqlite3 *db = pParse->db; /* Database connection malloc context */
134147 WhereLoop *pNew; /* Template WhereLoop under construction */
134148 WhereTerm *pTerm; /* A WhereTerm under consideration */
134149 int opMask; /* Valid operators for constraints */
134150 WhereScan scan; /* Iterator for WHERE terms */
134151 Bitmask saved_prereq; /* Original value of pNew->prereq */
134152 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
134153 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
134154 u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
134155 u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
134156 u16 saved_nSkip; /* Original value of pNew->nSkip */
134157 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
134158 LogEst saved_nOut; /* Original value of pNew->nOut */
134159 int rc = SQLITE_OK; /* Return code */
134160 LogEst rSize; /* Number of rows in the table */
134161 LogEst rLogSize; /* Logarithm of table size */
134162 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
134164 pNew = pBuilder->pNew;
134165 if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
134166 WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n",
134167 pProbe->zName, pNew->u.btree.nEq));
134169 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
134170 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
134171 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
134172 opMask = WO_LT|WO_LE;
134173 }else{
134174 assert( pNew->u.btree.nBtm==0 );
134175 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
134177 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
134179 assert( pNew->u.btree.nEq<pProbe->nColumn );
134181 saved_nEq = pNew->u.btree.nEq;
134182 saved_nBtm = pNew->u.btree.nBtm;
134183 saved_nTop = pNew->u.btree.nTop;
134184 saved_nSkip = pNew->nSkip;
134185 saved_nLTerm = pNew->nLTerm;
134186 saved_wsFlags = pNew->wsFlags;
134187 saved_prereq = pNew->prereq;
134188 saved_nOut = pNew->nOut;
134189 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
134190 opMask, pProbe);
134191 pNew->rSetup = 0;
134192 rSize = pProbe->aiRowLogEst[0];
134193 rLogSize = estLog(rSize);
134194 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
134195 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
134196 LogEst rCostIdx;
134197 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
134198 int nIn = 0;
134199 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
134200 int nRecValid = pBuilder->nRecValid;
134201 #endif
134202 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
134203 && indexColumnNotNull(pProbe, saved_nEq)
134205 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
134207 if( pTerm->prereqRight & pNew->maskSelf ) continue;
134209 /* Do not allow the upper bound of a LIKE optimization range constraint
134210 ** to mix with a lower range bound from some other source */
134211 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
134213 /* Do not allow IS constraints from the WHERE clause to be used by the
134214 ** right table of a LEFT JOIN. Only constraints in the ON clause are
134215 ** allowed */
134216 if( (pSrc->fg.jointype & JT_LEFT)!=0
134217 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
134218 && (eOp & (WO_IS|WO_ISNULL))!=0
134220 testcase( eOp & WO_IS );
134221 testcase( eOp & WO_ISNULL );
134222 continue;
134225 if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
134226 pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
134227 }else{
134228 pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
134230 pNew->wsFlags = saved_wsFlags;
134231 pNew->u.btree.nEq = saved_nEq;
134232 pNew->u.btree.nBtm = saved_nBtm;
134233 pNew->u.btree.nTop = saved_nTop;
134234 pNew->nLTerm = saved_nLTerm;
134235 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
134236 pNew->aLTerm[pNew->nLTerm++] = pTerm;
134237 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
134239 assert( nInMul==0
134240 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
134241 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
134242 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
134245 if( eOp & WO_IN ){
134246 Expr *pExpr = pTerm->pExpr;
134247 pNew->wsFlags |= WHERE_COLUMN_IN;
134248 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
134249 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
134250 int i;
134251 nIn = 46; assert( 46==sqlite3LogEst(25) );
134253 /* The expression may actually be of the form (x, y) IN (SELECT...).
134254 ** In this case there is a separate term for each of (x) and (y).
134255 ** However, the nIn multiplier should only be applied once, not once
134256 ** for each such term. The following loop checks that pTerm is the
134257 ** first such term in use, and sets nIn back to 0 if it is not. */
134258 for(i=0; i<pNew->nLTerm-1; i++){
134259 if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
134261 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
134262 /* "x IN (value, value, ...)" */
134263 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
134264 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
134265 ** changes "x IN (?)" into "x=?". */
134267 }else if( eOp & (WO_EQ|WO_IS) ){
134268 int iCol = pProbe->aiColumn[saved_nEq];
134269 pNew->wsFlags |= WHERE_COLUMN_EQ;
134270 assert( saved_nEq==pNew->u.btree.nEq );
134271 if( iCol==XN_ROWID
134272 || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
134274 if( iCol>=0 && pProbe->uniqNotNull==0 ){
134275 pNew->wsFlags |= WHERE_UNQ_WANTED;
134276 }else{
134277 pNew->wsFlags |= WHERE_ONEROW;
134280 }else if( eOp & WO_ISNULL ){
134281 pNew->wsFlags |= WHERE_COLUMN_NULL;
134282 }else if( eOp & (WO_GT|WO_GE) ){
134283 testcase( eOp & WO_GT );
134284 testcase( eOp & WO_GE );
134285 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
134286 pNew->u.btree.nBtm = whereRangeVectorLen(
134287 pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
134289 pBtm = pTerm;
134290 pTop = 0;
134291 if( pTerm->wtFlags & TERM_LIKEOPT ){
134292 /* Range contraints that come from the LIKE optimization are
134293 ** always used in pairs. */
134294 pTop = &pTerm[1];
134295 assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
134296 assert( pTop->wtFlags & TERM_LIKEOPT );
134297 assert( pTop->eOperator==WO_LT );
134298 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
134299 pNew->aLTerm[pNew->nLTerm++] = pTop;
134300 pNew->wsFlags |= WHERE_TOP_LIMIT;
134301 pNew->u.btree.nTop = 1;
134303 }else{
134304 assert( eOp & (WO_LT|WO_LE) );
134305 testcase( eOp & WO_LT );
134306 testcase( eOp & WO_LE );
134307 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
134308 pNew->u.btree.nTop = whereRangeVectorLen(
134309 pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
134311 pTop = pTerm;
134312 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
134313 pNew->aLTerm[pNew->nLTerm-2] : 0;
134316 /* At this point pNew->nOut is set to the number of rows expected to
134317 ** be visited by the index scan before considering term pTerm, or the
134318 ** values of nIn and nInMul. In other words, assuming that all
134319 ** "x IN(...)" terms are replaced with "x = ?". This block updates
134320 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
134321 assert( pNew->nOut==saved_nOut );
134322 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
134323 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
134324 ** data, using some other estimate. */
134325 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
134326 }else{
134327 int nEq = ++pNew->u.btree.nEq;
134328 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
134330 assert( pNew->nOut==saved_nOut );
134331 if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
134332 assert( (eOp & WO_IN) || nIn==0 );
134333 testcase( eOp & WO_IN );
134334 pNew->nOut += pTerm->truthProb;
134335 pNew->nOut -= nIn;
134336 }else{
134337 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
134338 tRowcnt nOut = 0;
134339 if( nInMul==0
134340 && pProbe->nSample
134341 && pNew->u.btree.nEq<=pProbe->nSampleCol
134342 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
134344 Expr *pExpr = pTerm->pExpr;
134345 if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
134346 testcase( eOp & WO_EQ );
134347 testcase( eOp & WO_IS );
134348 testcase( eOp & WO_ISNULL );
134349 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
134350 }else{
134351 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
134353 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
134354 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
134355 if( nOut ){
134356 pNew->nOut = sqlite3LogEst(nOut);
134357 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
134358 pNew->nOut -= nIn;
134361 if( nOut==0 )
134362 #endif
134364 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
134365 if( eOp & WO_ISNULL ){
134366 /* TUNING: If there is no likelihood() value, assume that a
134367 ** "col IS NULL" expression matches twice as many rows
134368 ** as (col=?). */
134369 pNew->nOut += 10;
134375 /* Set rCostIdx to the cost of visiting selected rows in index. Add
134376 ** it to pNew->rRun, which is currently set to the cost of the index
134377 ** seek only. Then, if this is a non-covering index, add the cost of
134378 ** visiting the rows in the main table. */
134379 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
134380 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
134381 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
134382 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
134384 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
134386 nOutUnadjusted = pNew->nOut;
134387 pNew->rRun += nInMul + nIn;
134388 pNew->nOut += nInMul + nIn;
134389 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
134390 rc = whereLoopInsert(pBuilder, pNew);
134392 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
134393 pNew->nOut = saved_nOut;
134394 }else{
134395 pNew->nOut = nOutUnadjusted;
134398 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
134399 && pNew->u.btree.nEq<pProbe->nColumn
134401 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
134403 pNew->nOut = saved_nOut;
134404 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
134405 pBuilder->nRecValid = nRecValid;
134406 #endif
134408 pNew->prereq = saved_prereq;
134409 pNew->u.btree.nEq = saved_nEq;
134410 pNew->u.btree.nBtm = saved_nBtm;
134411 pNew->u.btree.nTop = saved_nTop;
134412 pNew->nSkip = saved_nSkip;
134413 pNew->wsFlags = saved_wsFlags;
134414 pNew->nOut = saved_nOut;
134415 pNew->nLTerm = saved_nLTerm;
134417 /* Consider using a skip-scan if there are no WHERE clause constraints
134418 ** available for the left-most terms of the index, and if the average
134419 ** number of repeats in the left-most terms is at least 18.
134421 ** The magic number 18 is selected on the basis that scanning 17 rows
134422 ** is almost always quicker than an index seek (even though if the index
134423 ** contains fewer than 2^17 rows we assume otherwise in other parts of
134424 ** the code). And, even if it is not, it should not be too much slower.
134425 ** On the other hand, the extra seeks could end up being significantly
134426 ** more expensive. */
134427 assert( 42==sqlite3LogEst(18) );
134428 if( saved_nEq==saved_nSkip
134429 && saved_nEq+1<pProbe->nKeyCol
134430 && pProbe->noSkipScan==0
134431 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
134432 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
134434 LogEst nIter;
134435 pNew->u.btree.nEq++;
134436 pNew->nSkip++;
134437 pNew->aLTerm[pNew->nLTerm++] = 0;
134438 pNew->wsFlags |= WHERE_SKIPSCAN;
134439 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
134440 pNew->nOut -= nIter;
134441 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
134442 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
134443 nIter += 5;
134444 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
134445 pNew->nOut = saved_nOut;
134446 pNew->u.btree.nEq = saved_nEq;
134447 pNew->nSkip = saved_nSkip;
134448 pNew->wsFlags = saved_wsFlags;
134451 WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n",
134452 pProbe->zName, saved_nEq, rc));
134453 return rc;
134457 ** Return True if it is possible that pIndex might be useful in
134458 ** implementing the ORDER BY clause in pBuilder.
134460 ** Return False if pBuilder does not contain an ORDER BY clause or
134461 ** if there is no way for pIndex to be useful in implementing that
134462 ** ORDER BY clause.
134464 static int indexMightHelpWithOrderBy(
134465 WhereLoopBuilder *pBuilder,
134466 Index *pIndex,
134467 int iCursor
134469 ExprList *pOB;
134470 ExprList *aColExpr;
134471 int ii, jj;
134473 if( pIndex->bUnordered ) return 0;
134474 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
134475 for(ii=0; ii<pOB->nExpr; ii++){
134476 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
134477 if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
134478 if( pExpr->iColumn<0 ) return 1;
134479 for(jj=0; jj<pIndex->nKeyCol; jj++){
134480 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
134482 }else if( (aColExpr = pIndex->aColExpr)!=0 ){
134483 for(jj=0; jj<pIndex->nKeyCol; jj++){
134484 if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
134485 if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
134486 return 1;
134491 return 0;
134495 ** Return a bitmask where 1s indicate that the corresponding column of
134496 ** the table is used by an index. Only the first 63 columns are considered.
134498 static Bitmask columnsInIndex(Index *pIdx){
134499 Bitmask m = 0;
134500 int j;
134501 for(j=pIdx->nColumn-1; j>=0; j--){
134502 int x = pIdx->aiColumn[j];
134503 if( x>=0 ){
134504 testcase( x==BMS-1 );
134505 testcase( x==BMS-2 );
134506 if( x<BMS-1 ) m |= MASKBIT(x);
134509 return m;
134512 /* Check to see if a partial index with pPartIndexWhere can be used
134513 ** in the current query. Return true if it can be and false if not.
134515 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
134516 int i;
134517 WhereTerm *pTerm;
134518 Parse *pParse = pWC->pWInfo->pParse;
134519 while( pWhere->op==TK_AND ){
134520 if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
134521 pWhere = pWhere->pRight;
134523 if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
134524 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
134525 Expr *pExpr = pTerm->pExpr;
134526 if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
134527 && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
134529 return 1;
134532 return 0;
134536 ** Add all WhereLoop objects for a single table of the join where the table
134537 ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
134538 ** a b-tree table, not a virtual table.
134540 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
134541 ** are calculated as follows:
134543 ** For a full scan, assuming the table (or index) contains nRow rows:
134545 ** cost = nRow * 3.0 // full-table scan
134546 ** cost = nRow * K // scan of covering index
134547 ** cost = nRow * (K+3.0) // scan of non-covering index
134549 ** where K is a value between 1.1 and 3.0 set based on the relative
134550 ** estimated average size of the index and table records.
134552 ** For an index scan, where nVisit is the number of index rows visited
134553 ** by the scan, and nSeek is the number of seek operations required on
134554 ** the index b-tree:
134556 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
134557 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
134559 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
134560 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
134561 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
134563 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
134564 ** of uncertainty. For this reason, scoring is designed to pick plans that
134565 ** "do the least harm" if the estimates are inaccurate. For example, a
134566 ** log(nRow) factor is omitted from a non-covering index scan in order to
134567 ** bias the scoring in favor of using an index, since the worst-case
134568 ** performance of using an index is far better than the worst-case performance
134569 ** of a full table scan.
134571 static int whereLoopAddBtree(
134572 WhereLoopBuilder *pBuilder, /* WHERE clause information */
134573 Bitmask mPrereq /* Extra prerequesites for using this table */
134575 WhereInfo *pWInfo; /* WHERE analysis context */
134576 Index *pProbe; /* An index we are evaluating */
134577 Index sPk; /* A fake index object for the primary key */
134578 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
134579 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
134580 SrcList *pTabList; /* The FROM clause */
134581 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
134582 WhereLoop *pNew; /* Template WhereLoop object */
134583 int rc = SQLITE_OK; /* Return code */
134584 int iSortIdx = 1; /* Index number */
134585 int b; /* A boolean value */
134586 LogEst rSize; /* number of rows in the table */
134587 LogEst rLogSize; /* Logarithm of the number of rows in the table */
134588 WhereClause *pWC; /* The parsed WHERE clause */
134589 Table *pTab; /* Table being queried */
134591 pNew = pBuilder->pNew;
134592 pWInfo = pBuilder->pWInfo;
134593 pTabList = pWInfo->pTabList;
134594 pSrc = pTabList->a + pNew->iTab;
134595 pTab = pSrc->pTab;
134596 pWC = pBuilder->pWC;
134597 assert( !IsVirtual(pSrc->pTab) );
134599 if( pSrc->pIBIndex ){
134600 /* An INDEXED BY clause specifies a particular index to use */
134601 pProbe = pSrc->pIBIndex;
134602 }else if( !HasRowid(pTab) ){
134603 pProbe = pTab->pIndex;
134604 }else{
134605 /* There is no INDEXED BY clause. Create a fake Index object in local
134606 ** variable sPk to represent the rowid primary key index. Make this
134607 ** fake index the first in a chain of Index objects with all of the real
134608 ** indices to follow */
134609 Index *pFirst; /* First of real indices on the table */
134610 memset(&sPk, 0, sizeof(Index));
134611 sPk.nKeyCol = 1;
134612 sPk.nColumn = 1;
134613 sPk.aiColumn = &aiColumnPk;
134614 sPk.aiRowLogEst = aiRowEstPk;
134615 sPk.onError = OE_Replace;
134616 sPk.pTable = pTab;
134617 sPk.szIdxRow = pTab->szTabRow;
134618 aiRowEstPk[0] = pTab->nRowLogEst;
134619 aiRowEstPk[1] = 0;
134620 pFirst = pSrc->pTab->pIndex;
134621 if( pSrc->fg.notIndexed==0 ){
134622 /* The real indices of the table are only considered if the
134623 ** NOT INDEXED qualifier is omitted from the FROM clause */
134624 sPk.pNext = pFirst;
134626 pProbe = &sPk;
134628 rSize = pTab->nRowLogEst;
134629 rLogSize = estLog(rSize);
134631 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
134632 /* Automatic indexes */
134633 if( !pBuilder->pOrSet /* Not part of an OR optimization */
134634 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
134635 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
134636 && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
134637 && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
134638 && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
134639 && !pSrc->fg.isCorrelated /* Not a correlated subquery */
134640 && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
134642 /* Generate auto-index WhereLoops */
134643 WhereTerm *pTerm;
134644 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
134645 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
134646 if( pTerm->prereqRight & pNew->maskSelf ) continue;
134647 if( termCanDriveIndex(pTerm, pSrc, 0) ){
134648 pNew->u.btree.nEq = 1;
134649 pNew->nSkip = 0;
134650 pNew->u.btree.pIndex = 0;
134651 pNew->nLTerm = 1;
134652 pNew->aLTerm[0] = pTerm;
134653 /* TUNING: One-time cost for computing the automatic index is
134654 ** estimated to be X*N*log2(N) where N is the number of rows in
134655 ** the table being indexed and where X is 7 (LogEst=28) for normal
134656 ** tables or 1.375 (LogEst=4) for views and subqueries. The value
134657 ** of X is smaller for views and subqueries so that the query planner
134658 ** will be more aggressive about generating automatic indexes for
134659 ** those objects, since there is no opportunity to add schema
134660 ** indexes on subqueries and views. */
134661 pNew->rSetup = rLogSize + rSize + 4;
134662 if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
134663 pNew->rSetup += 24;
134665 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
134666 if( pNew->rSetup<0 ) pNew->rSetup = 0;
134667 /* TUNING: Each index lookup yields 20 rows in the table. This
134668 ** is more than the usual guess of 10 rows, since we have no way
134669 ** of knowing how selective the index will ultimately be. It would
134670 ** not be unreasonable to make this value much larger. */
134671 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
134672 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
134673 pNew->wsFlags = WHERE_AUTO_INDEX;
134674 pNew->prereq = mPrereq | pTerm->prereqRight;
134675 rc = whereLoopInsert(pBuilder, pNew);
134679 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
134681 /* Loop over all indices
134683 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
134684 if( pProbe->pPartIdxWhere!=0
134685 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
134686 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
134687 continue; /* Partial index inappropriate for this query */
134689 rSize = pProbe->aiRowLogEst[0];
134690 pNew->u.btree.nEq = 0;
134691 pNew->u.btree.nBtm = 0;
134692 pNew->u.btree.nTop = 0;
134693 pNew->nSkip = 0;
134694 pNew->nLTerm = 0;
134695 pNew->iSortIdx = 0;
134696 pNew->rSetup = 0;
134697 pNew->prereq = mPrereq;
134698 pNew->nOut = rSize;
134699 pNew->u.btree.pIndex = pProbe;
134700 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
134701 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
134702 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
134703 if( pProbe->tnum<=0 ){
134704 /* Integer primary key index */
134705 pNew->wsFlags = WHERE_IPK;
134707 /* Full table scan */
134708 pNew->iSortIdx = b ? iSortIdx : 0;
134709 /* TUNING: Cost of full table scan is (N*3.0). */
134710 pNew->rRun = rSize + 16;
134711 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
134712 whereLoopOutputAdjust(pWC, pNew, rSize);
134713 rc = whereLoopInsert(pBuilder, pNew);
134714 pNew->nOut = rSize;
134715 if( rc ) break;
134716 }else{
134717 Bitmask m;
134718 if( pProbe->isCovering ){
134719 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
134720 m = 0;
134721 }else{
134722 m = pSrc->colUsed & ~columnsInIndex(pProbe);
134723 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
134726 /* Full scan via index */
134727 if( b
134728 || !HasRowid(pTab)
134729 || pProbe->pPartIdxWhere!=0
134730 || ( m==0
134731 && pProbe->bUnordered==0
134732 && (pProbe->szIdxRow<pTab->szTabRow)
134733 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
134734 && sqlite3GlobalConfig.bUseCis
134735 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
134738 pNew->iSortIdx = b ? iSortIdx : 0;
134740 /* The cost of visiting the index rows is N*K, where K is
134741 ** between 1.1 and 3.0, depending on the relative sizes of the
134742 ** index and table rows. */
134743 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
134744 if( m!=0 ){
134745 /* If this is a non-covering index scan, add in the cost of
134746 ** doing table lookups. The cost will be 3x the number of
134747 ** lookups. Take into account WHERE clause terms that can be
134748 ** satisfied using just the index, and that do not require a
134749 ** table lookup. */
134750 LogEst nLookup = rSize + 16; /* Base cost: N*3 */
134751 int ii;
134752 int iCur = pSrc->iCursor;
134753 WhereClause *pWC2 = &pWInfo->sWC;
134754 for(ii=0; ii<pWC2->nTerm; ii++){
134755 WhereTerm *pTerm = &pWC2->a[ii];
134756 if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
134757 break;
134759 /* pTerm can be evaluated using just the index. So reduce
134760 ** the expected number of table lookups accordingly */
134761 if( pTerm->truthProb<=0 ){
134762 nLookup += pTerm->truthProb;
134763 }else{
134764 nLookup--;
134765 if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
134769 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
134771 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
134772 whereLoopOutputAdjust(pWC, pNew, rSize);
134773 rc = whereLoopInsert(pBuilder, pNew);
134774 pNew->nOut = rSize;
134775 if( rc ) break;
134779 pBuilder->bldFlags = 0;
134780 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
134781 if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
134782 /* If a non-unique index is used, or if a prefix of the key for
134783 ** unique index is used (making the index functionally non-unique)
134784 ** then the sqlite_stat1 data becomes important for scoring the
134785 ** plan */
134786 pTab->tabFlags |= TF_StatsUsed;
134788 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
134789 sqlite3Stat4ProbeFree(pBuilder->pRec);
134790 pBuilder->nRecValid = 0;
134791 pBuilder->pRec = 0;
134792 #endif
134794 /* If there was an INDEXED BY clause, then only that one index is
134795 ** considered. */
134796 if( pSrc->pIBIndex ) break;
134798 return rc;
134801 #ifndef SQLITE_OMIT_VIRTUALTABLE
134804 ** Argument pIdxInfo is already populated with all constraints that may
134805 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
134806 ** function marks a subset of those constraints usable, invokes the
134807 ** xBestIndex method and adds the returned plan to pBuilder.
134809 ** A constraint is marked usable if:
134811 ** * Argument mUsable indicates that its prerequisites are available, and
134813 ** * It is not one of the operators specified in the mExclude mask passed
134814 ** as the fourth argument (which in practice is either WO_IN or 0).
134816 ** Argument mPrereq is a mask of tables that must be scanned before the
134817 ** virtual table in question. These are added to the plans prerequisites
134818 ** before it is added to pBuilder.
134820 ** Output parameter *pbIn is set to true if the plan added to pBuilder
134821 ** uses one or more WO_IN terms, or false otherwise.
134823 static int whereLoopAddVirtualOne(
134824 WhereLoopBuilder *pBuilder,
134825 Bitmask mPrereq, /* Mask of tables that must be used. */
134826 Bitmask mUsable, /* Mask of usable tables */
134827 u16 mExclude, /* Exclude terms using these operators */
134828 sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
134829 u16 mNoOmit, /* Do not omit these constraints */
134830 int *pbIn /* OUT: True if plan uses an IN(...) op */
134832 WhereClause *pWC = pBuilder->pWC;
134833 struct sqlite3_index_constraint *pIdxCons;
134834 struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
134835 int i;
134836 int mxTerm;
134837 int rc = SQLITE_OK;
134838 WhereLoop *pNew = pBuilder->pNew;
134839 Parse *pParse = pBuilder->pWInfo->pParse;
134840 struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
134841 int nConstraint = pIdxInfo->nConstraint;
134843 assert( (mUsable & mPrereq)==mPrereq );
134844 *pbIn = 0;
134845 pNew->prereq = mPrereq;
134847 /* Set the usable flag on the subset of constraints identified by
134848 ** arguments mUsable and mExclude. */
134849 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
134850 for(i=0; i<nConstraint; i++, pIdxCons++){
134851 WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
134852 pIdxCons->usable = 0;
134853 if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
134854 && (pTerm->eOperator & mExclude)==0
134856 pIdxCons->usable = 1;
134860 /* Initialize the output fields of the sqlite3_index_info structure */
134861 memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
134862 assert( pIdxInfo->needToFreeIdxStr==0 );
134863 pIdxInfo->idxStr = 0;
134864 pIdxInfo->idxNum = 0;
134865 pIdxInfo->orderByConsumed = 0;
134866 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
134867 pIdxInfo->estimatedRows = 25;
134868 pIdxInfo->idxFlags = 0;
134869 pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
134871 /* Invoke the virtual table xBestIndex() method */
134872 rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
134873 if( rc ) return rc;
134875 mxTerm = -1;
134876 assert( pNew->nLSlot>=nConstraint );
134877 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
134878 pNew->u.vtab.omitMask = 0;
134879 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
134880 for(i=0; i<nConstraint; i++, pIdxCons++){
134881 int iTerm;
134882 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
134883 WhereTerm *pTerm;
134884 int j = pIdxCons->iTermOffset;
134885 if( iTerm>=nConstraint
134886 || j<0
134887 || j>=pWC->nTerm
134888 || pNew->aLTerm[iTerm]!=0
134889 || pIdxCons->usable==0
134891 rc = SQLITE_ERROR;
134892 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
134893 return rc;
134895 testcase( iTerm==nConstraint-1 );
134896 testcase( j==0 );
134897 testcase( j==pWC->nTerm-1 );
134898 pTerm = &pWC->a[j];
134899 pNew->prereq |= pTerm->prereqRight;
134900 assert( iTerm<pNew->nLSlot );
134901 pNew->aLTerm[iTerm] = pTerm;
134902 if( iTerm>mxTerm ) mxTerm = iTerm;
134903 testcase( iTerm==15 );
134904 testcase( iTerm==16 );
134905 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
134906 if( (pTerm->eOperator & WO_IN)!=0 ){
134907 /* A virtual table that is constrained by an IN clause may not
134908 ** consume the ORDER BY clause because (1) the order of IN terms
134909 ** is not necessarily related to the order of output terms and
134910 ** (2) Multiple outputs from a single IN value will not merge
134911 ** together. */
134912 pIdxInfo->orderByConsumed = 0;
134913 pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
134914 *pbIn = 1; assert( (mExclude & WO_IN)==0 );
134918 pNew->u.vtab.omitMask &= ~mNoOmit;
134920 pNew->nLTerm = mxTerm+1;
134921 assert( pNew->nLTerm<=pNew->nLSlot );
134922 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
134923 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
134924 pIdxInfo->needToFreeIdxStr = 0;
134925 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
134926 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
134927 pIdxInfo->nOrderBy : 0);
134928 pNew->rSetup = 0;
134929 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
134930 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
134932 /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
134933 ** that the scan will visit at most one row. Clear it otherwise. */
134934 if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
134935 pNew->wsFlags |= WHERE_ONEROW;
134936 }else{
134937 pNew->wsFlags &= ~WHERE_ONEROW;
134939 rc = whereLoopInsert(pBuilder, pNew);
134940 if( pNew->u.vtab.needFree ){
134941 sqlite3_free(pNew->u.vtab.idxStr);
134942 pNew->u.vtab.needFree = 0;
134944 WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
134945 *pbIn, (sqlite3_uint64)mPrereq,
134946 (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
134948 return rc;
134953 ** Add all WhereLoop objects for a table of the join identified by
134954 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
134956 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
134957 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
134958 ** entries that occur before the virtual table in the FROM clause and are
134959 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
134960 ** mUnusable mask contains all FROM clause entries that occur after the
134961 ** virtual table and are separated from it by at least one LEFT or
134962 ** CROSS JOIN.
134964 ** For example, if the query were:
134966 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
134968 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
134970 ** All the tables in mPrereq must be scanned before the current virtual
134971 ** table. So any terms for which all prerequisites are satisfied by
134972 ** mPrereq may be specified as "usable" in all calls to xBestIndex.
134973 ** Conversely, all tables in mUnusable must be scanned after the current
134974 ** virtual table, so any terms for which the prerequisites overlap with
134975 ** mUnusable should always be configured as "not-usable" for xBestIndex.
134977 static int whereLoopAddVirtual(
134978 WhereLoopBuilder *pBuilder, /* WHERE clause information */
134979 Bitmask mPrereq, /* Tables that must be scanned before this one */
134980 Bitmask mUnusable /* Tables that must be scanned after this one */
134982 int rc = SQLITE_OK; /* Return code */
134983 WhereInfo *pWInfo; /* WHERE analysis context */
134984 Parse *pParse; /* The parsing context */
134985 WhereClause *pWC; /* The WHERE clause */
134986 struct SrcList_item *pSrc; /* The FROM clause term to search */
134987 sqlite3_index_info *p; /* Object to pass to xBestIndex() */
134988 int nConstraint; /* Number of constraints in p */
134989 int bIn; /* True if plan uses IN(...) operator */
134990 WhereLoop *pNew;
134991 Bitmask mBest; /* Tables used by best possible plan */
134992 u16 mNoOmit;
134994 assert( (mPrereq & mUnusable)==0 );
134995 pWInfo = pBuilder->pWInfo;
134996 pParse = pWInfo->pParse;
134997 pWC = pBuilder->pWC;
134998 pNew = pBuilder->pNew;
134999 pSrc = &pWInfo->pTabList->a[pNew->iTab];
135000 assert( IsVirtual(pSrc->pTab) );
135001 p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
135002 &mNoOmit);
135003 if( p==0 ) return SQLITE_NOMEM_BKPT;
135004 pNew->rSetup = 0;
135005 pNew->wsFlags = WHERE_VIRTUALTABLE;
135006 pNew->nLTerm = 0;
135007 pNew->u.vtab.needFree = 0;
135008 nConstraint = p->nConstraint;
135009 if( whereLoopResize(pParse->db, pNew, nConstraint) ){
135010 sqlite3DbFree(pParse->db, p);
135011 return SQLITE_NOMEM_BKPT;
135014 /* First call xBestIndex() with all constraints usable. */
135015 WHERETRACE(0x40, (" VirtualOne: all usable\n"));
135016 rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
135018 /* If the call to xBestIndex() with all terms enabled produced a plan
135019 ** that does not require any source tables (IOW: a plan with mBest==0),
135020 ** then there is no point in making any further calls to xBestIndex()
135021 ** since they will all return the same result (if the xBestIndex()
135022 ** implementation is sane). */
135023 if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
135024 int seenZero = 0; /* True if a plan with no prereqs seen */
135025 int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
135026 Bitmask mPrev = 0;
135027 Bitmask mBestNoIn = 0;
135029 /* If the plan produced by the earlier call uses an IN(...) term, call
135030 ** xBestIndex again, this time with IN(...) terms disabled. */
135031 if( bIn ){
135032 WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
135033 rc = whereLoopAddVirtualOne(
135034 pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
135035 assert( bIn==0 );
135036 mBestNoIn = pNew->prereq & ~mPrereq;
135037 if( mBestNoIn==0 ){
135038 seenZero = 1;
135039 seenZeroNoIN = 1;
135043 /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
135044 ** in the set of terms that apply to the current virtual table. */
135045 while( rc==SQLITE_OK ){
135046 int i;
135047 Bitmask mNext = ALLBITS;
135048 assert( mNext>0 );
135049 for(i=0; i<nConstraint; i++){
135050 Bitmask mThis = (
135051 pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
135053 if( mThis>mPrev && mThis<mNext ) mNext = mThis;
135055 mPrev = mNext;
135056 if( mNext==ALLBITS ) break;
135057 if( mNext==mBest || mNext==mBestNoIn ) continue;
135058 WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
135059 (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
135060 rc = whereLoopAddVirtualOne(
135061 pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
135062 if( pNew->prereq==mPrereq ){
135063 seenZero = 1;
135064 if( bIn==0 ) seenZeroNoIN = 1;
135068 /* If the calls to xBestIndex() in the above loop did not find a plan
135069 ** that requires no source tables at all (i.e. one guaranteed to be
135070 ** usable), make a call here with all source tables disabled */
135071 if( rc==SQLITE_OK && seenZero==0 ){
135072 WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
135073 rc = whereLoopAddVirtualOne(
135074 pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
135075 if( bIn==0 ) seenZeroNoIN = 1;
135078 /* If the calls to xBestIndex() have so far failed to find a plan
135079 ** that requires no source tables at all and does not use an IN(...)
135080 ** operator, make a final call to obtain one here. */
135081 if( rc==SQLITE_OK && seenZeroNoIN==0 ){
135082 WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
135083 rc = whereLoopAddVirtualOne(
135084 pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
135088 if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
135089 sqlite3DbFreeNN(pParse->db, p);
135090 return rc;
135092 #endif /* SQLITE_OMIT_VIRTUALTABLE */
135095 ** Add WhereLoop entries to handle OR terms. This works for either
135096 ** btrees or virtual tables.
135098 static int whereLoopAddOr(
135099 WhereLoopBuilder *pBuilder,
135100 Bitmask mPrereq,
135101 Bitmask mUnusable
135103 WhereInfo *pWInfo = pBuilder->pWInfo;
135104 WhereClause *pWC;
135105 WhereLoop *pNew;
135106 WhereTerm *pTerm, *pWCEnd;
135107 int rc = SQLITE_OK;
135108 int iCur;
135109 WhereClause tempWC;
135110 WhereLoopBuilder sSubBuild;
135111 WhereOrSet sSum, sCur;
135112 struct SrcList_item *pItem;
135114 pWC = pBuilder->pWC;
135115 pWCEnd = pWC->a + pWC->nTerm;
135116 pNew = pBuilder->pNew;
135117 memset(&sSum, 0, sizeof(sSum));
135118 pItem = pWInfo->pTabList->a + pNew->iTab;
135119 iCur = pItem->iCursor;
135121 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
135122 if( (pTerm->eOperator & WO_OR)!=0
135123 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
135125 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
135126 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
135127 WhereTerm *pOrTerm;
135128 int once = 1;
135129 int i, j;
135131 sSubBuild = *pBuilder;
135132 sSubBuild.pOrderBy = 0;
135133 sSubBuild.pOrSet = &sCur;
135135 WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
135136 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
135137 if( (pOrTerm->eOperator & WO_AND)!=0 ){
135138 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
135139 }else if( pOrTerm->leftCursor==iCur ){
135140 tempWC.pWInfo = pWC->pWInfo;
135141 tempWC.pOuter = pWC;
135142 tempWC.op = TK_AND;
135143 tempWC.nTerm = 1;
135144 tempWC.a = pOrTerm;
135145 sSubBuild.pWC = &tempWC;
135146 }else{
135147 continue;
135149 sCur.n = 0;
135150 #ifdef WHERETRACE_ENABLED
135151 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
135152 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
135153 if( sqlite3WhereTrace & 0x400 ){
135154 sqlite3WhereClausePrint(sSubBuild.pWC);
135156 #endif
135157 #ifndef SQLITE_OMIT_VIRTUALTABLE
135158 if( IsVirtual(pItem->pTab) ){
135159 rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
135160 }else
135161 #endif
135163 rc = whereLoopAddBtree(&sSubBuild, mPrereq);
135165 if( rc==SQLITE_OK ){
135166 rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
135168 assert( rc==SQLITE_OK || sCur.n==0 );
135169 if( sCur.n==0 ){
135170 sSum.n = 0;
135171 break;
135172 }else if( once ){
135173 whereOrMove(&sSum, &sCur);
135174 once = 0;
135175 }else{
135176 WhereOrSet sPrev;
135177 whereOrMove(&sPrev, &sSum);
135178 sSum.n = 0;
135179 for(i=0; i<sPrev.n; i++){
135180 for(j=0; j<sCur.n; j++){
135181 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
135182 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
135183 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
135188 pNew->nLTerm = 1;
135189 pNew->aLTerm[0] = pTerm;
135190 pNew->wsFlags = WHERE_MULTI_OR;
135191 pNew->rSetup = 0;
135192 pNew->iSortIdx = 0;
135193 memset(&pNew->u, 0, sizeof(pNew->u));
135194 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
135195 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
135196 ** of all sub-scans required by the OR-scan. However, due to rounding
135197 ** errors, it may be that the cost of the OR-scan is equal to its
135198 ** most expensive sub-scan. Add the smallest possible penalty
135199 ** (equivalent to multiplying the cost by 1.07) to ensure that
135200 ** this does not happen. Otherwise, for WHERE clauses such as the
135201 ** following where there is an index on "y":
135203 ** WHERE likelihood(x=?, 0.99) OR y=?
135205 ** the planner may elect to "OR" together a full-table scan and an
135206 ** index lookup. And other similarly odd results. */
135207 pNew->rRun = sSum.a[i].rRun + 1;
135208 pNew->nOut = sSum.a[i].nOut;
135209 pNew->prereq = sSum.a[i].prereq;
135210 rc = whereLoopInsert(pBuilder, pNew);
135212 WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
135215 return rc;
135219 ** Add all WhereLoop objects for all tables
135221 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
135222 WhereInfo *pWInfo = pBuilder->pWInfo;
135223 Bitmask mPrereq = 0;
135224 Bitmask mPrior = 0;
135225 int iTab;
135226 SrcList *pTabList = pWInfo->pTabList;
135227 struct SrcList_item *pItem;
135228 struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
135229 sqlite3 *db = pWInfo->pParse->db;
135230 int rc = SQLITE_OK;
135231 WhereLoop *pNew;
135232 u8 priorJointype = 0;
135234 /* Loop over the tables in the join, from left to right */
135235 pNew = pBuilder->pNew;
135236 whereLoopInit(pNew);
135237 for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
135238 Bitmask mUnusable = 0;
135239 pNew->iTab = iTab;
135240 pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
135241 if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
135242 /* This condition is true when pItem is the FROM clause term on the
135243 ** right-hand-side of a LEFT or CROSS JOIN. */
135244 mPrereq = mPrior;
135246 priorJointype = pItem->fg.jointype;
135247 #ifndef SQLITE_OMIT_VIRTUALTABLE
135248 if( IsVirtual(pItem->pTab) ){
135249 struct SrcList_item *p;
135250 for(p=&pItem[1]; p<pEnd; p++){
135251 if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
135252 mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
135255 rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
135256 }else
135257 #endif /* SQLITE_OMIT_VIRTUALTABLE */
135259 rc = whereLoopAddBtree(pBuilder, mPrereq);
135261 if( rc==SQLITE_OK ){
135262 rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
135264 mPrior |= pNew->maskSelf;
135265 if( rc || db->mallocFailed ) break;
135268 whereLoopClear(db, pNew);
135269 return rc;
135273 ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
135274 ** parameters) to see if it outputs rows in the requested ORDER BY
135275 ** (or GROUP BY) without requiring a separate sort operation. Return N:
135277 ** N>0: N terms of the ORDER BY clause are satisfied
135278 ** N==0: No terms of the ORDER BY clause are satisfied
135279 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
135281 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
135282 ** strict. With GROUP BY and DISTINCT the only requirement is that
135283 ** equivalent rows appear immediately adjacent to one another. GROUP BY
135284 ** and DISTINCT do not require rows to appear in any particular order as long
135285 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
135286 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
135287 ** pOrderBy terms must be matched in strict left-to-right order.
135289 static i8 wherePathSatisfiesOrderBy(
135290 WhereInfo *pWInfo, /* The WHERE clause */
135291 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
135292 WherePath *pPath, /* The WherePath to check */
135293 u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
135294 u16 nLoop, /* Number of entries in pPath->aLoop[] */
135295 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
135296 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
135298 u8 revSet; /* True if rev is known */
135299 u8 rev; /* Composite sort order */
135300 u8 revIdx; /* Index sort order */
135301 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
135302 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
135303 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
135304 u16 eqOpMask; /* Allowed equality operators */
135305 u16 nKeyCol; /* Number of key columns in pIndex */
135306 u16 nColumn; /* Total number of ordered columns in the index */
135307 u16 nOrderBy; /* Number terms in the ORDER BY clause */
135308 int iLoop; /* Index of WhereLoop in pPath being processed */
135309 int i, j; /* Loop counters */
135310 int iCur; /* Cursor number for current WhereLoop */
135311 int iColumn; /* A column number within table iCur */
135312 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
135313 WhereTerm *pTerm; /* A single term of the WHERE clause */
135314 Expr *pOBExpr; /* An expression from the ORDER BY clause */
135315 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
135316 Index *pIndex; /* The index associated with pLoop */
135317 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
135318 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
135319 Bitmask obDone; /* Mask of all ORDER BY terms */
135320 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
135321 Bitmask ready; /* Mask of inner loops */
135324 ** We say the WhereLoop is "one-row" if it generates no more than one
135325 ** row of output. A WhereLoop is one-row if all of the following are true:
135326 ** (a) All index columns match with WHERE_COLUMN_EQ.
135327 ** (b) The index is unique
135328 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
135329 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
135331 ** We say the WhereLoop is "order-distinct" if the set of columns from
135332 ** that WhereLoop that are in the ORDER BY clause are different for every
135333 ** row of the WhereLoop. Every one-row WhereLoop is automatically
135334 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
135335 ** is not order-distinct. To be order-distinct is not quite the same as being
135336 ** UNIQUE since a UNIQUE column or index can have multiple rows that
135337 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
135338 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
135340 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
135341 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
135342 ** automatically order-distinct.
135345 assert( pOrderBy!=0 );
135346 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
135348 nOrderBy = pOrderBy->nExpr;
135349 testcase( nOrderBy==BMS-1 );
135350 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
135351 isOrderDistinct = 1;
135352 obDone = MASKBIT(nOrderBy)-1;
135353 orderDistinctMask = 0;
135354 ready = 0;
135355 eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
135356 if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
135357 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
135358 if( iLoop>0 ) ready |= pLoop->maskSelf;
135359 if( iLoop<nLoop ){
135360 pLoop = pPath->aLoop[iLoop];
135361 if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
135362 }else{
135363 pLoop = pLast;
135365 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
135366 if( pLoop->u.vtab.isOrdered ) obSat = obDone;
135367 break;
135368 }else{
135369 pLoop->u.btree.nIdxCol = 0;
135371 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
135373 /* Mark off any ORDER BY term X that is a column in the table of
135374 ** the current loop for which there is term in the WHERE
135375 ** clause of the form X IS NULL or X=? that reference only outer
135376 ** loops.
135378 for(i=0; i<nOrderBy; i++){
135379 if( MASKBIT(i) & obSat ) continue;
135380 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
135381 if( pOBExpr->op!=TK_COLUMN ) continue;
135382 if( pOBExpr->iTable!=iCur ) continue;
135383 pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
135384 ~ready, eqOpMask, 0);
135385 if( pTerm==0 ) continue;
135386 if( pTerm->eOperator==WO_IN ){
135387 /* IN terms are only valid for sorting in the ORDER BY LIMIT
135388 ** optimization, and then only if they are actually used
135389 ** by the query plan */
135390 assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
135391 for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
135392 if( j>=pLoop->nLTerm ) continue;
135394 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
135395 if( sqlite3ExprCollSeqMatch(pWInfo->pParse,
135396 pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){
135397 continue;
135399 testcase( pTerm->pExpr->op==TK_IS );
135401 obSat |= MASKBIT(i);
135404 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
135405 if( pLoop->wsFlags & WHERE_IPK ){
135406 pIndex = 0;
135407 nKeyCol = 0;
135408 nColumn = 1;
135409 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
135410 return 0;
135411 }else{
135412 nKeyCol = pIndex->nKeyCol;
135413 nColumn = pIndex->nColumn;
135414 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
135415 assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
135416 || !HasRowid(pIndex->pTable));
135417 isOrderDistinct = IsUniqueIndex(pIndex);
135420 /* Loop through all columns of the index and deal with the ones
135421 ** that are not constrained by == or IN.
135423 rev = revSet = 0;
135424 distinctColumns = 0;
135425 for(j=0; j<nColumn; j++){
135426 u8 bOnce = 1; /* True to run the ORDER BY search loop */
135428 assert( j>=pLoop->u.btree.nEq
135429 || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
135431 if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
135432 u16 eOp = pLoop->aLTerm[j]->eOperator;
135434 /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
135435 ** doing WHERE_ORDERBY_LIMIT processing).
135437 ** If the current term is a column of an ((?,?) IN (SELECT...))
135438 ** expression for which the SELECT returns more than one column,
135439 ** check that it is the only column used by this loop. Otherwise,
135440 ** if it is one of two or more, none of the columns can be
135441 ** considered to match an ORDER BY term. */
135442 if( (eOp & eqOpMask)!=0 ){
135443 if( eOp & WO_ISNULL ){
135444 testcase( isOrderDistinct );
135445 isOrderDistinct = 0;
135447 continue;
135448 }else if( ALWAYS(eOp & WO_IN) ){
135449 /* ALWAYS() justification: eOp is an equality operator due to the
135450 ** j<pLoop->u.btree.nEq constraint above. Any equality other
135451 ** than WO_IN is captured by the previous "if". So this one
135452 ** always has to be WO_IN. */
135453 Expr *pX = pLoop->aLTerm[j]->pExpr;
135454 for(i=j+1; i<pLoop->u.btree.nEq; i++){
135455 if( pLoop->aLTerm[i]->pExpr==pX ){
135456 assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
135457 bOnce = 0;
135458 break;
135464 /* Get the column number in the table (iColumn) and sort order
135465 ** (revIdx) for the j-th column of the index.
135467 if( pIndex ){
135468 iColumn = pIndex->aiColumn[j];
135469 revIdx = pIndex->aSortOrder[j];
135470 if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
135471 }else{
135472 iColumn = XN_ROWID;
135473 revIdx = 0;
135476 /* An unconstrained column that might be NULL means that this
135477 ** WhereLoop is not well-ordered
135479 if( isOrderDistinct
135480 && iColumn>=0
135481 && j>=pLoop->u.btree.nEq
135482 && pIndex->pTable->aCol[iColumn].notNull==0
135484 isOrderDistinct = 0;
135487 /* Find the ORDER BY term that corresponds to the j-th column
135488 ** of the index and mark that ORDER BY term off
135490 isMatch = 0;
135491 for(i=0; bOnce && i<nOrderBy; i++){
135492 if( MASKBIT(i) & obSat ) continue;
135493 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
135494 testcase( wctrlFlags & WHERE_GROUPBY );
135495 testcase( wctrlFlags & WHERE_DISTINCTBY );
135496 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
135497 if( iColumn>=XN_ROWID ){
135498 if( pOBExpr->op!=TK_COLUMN ) continue;
135499 if( pOBExpr->iTable!=iCur ) continue;
135500 if( pOBExpr->iColumn!=iColumn ) continue;
135501 }else{
135502 Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
135503 if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
135504 continue;
135507 if( iColumn!=XN_ROWID ){
135508 pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
135509 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
135511 pLoop->u.btree.nIdxCol = j+1;
135512 isMatch = 1;
135513 break;
135515 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
135516 /* Make sure the sort order is compatible in an ORDER BY clause.
135517 ** Sort order is irrelevant for a GROUP BY clause. */
135518 if( revSet ){
135519 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
135520 }else{
135521 rev = revIdx ^ pOrderBy->a[i].sortOrder;
135522 if( rev ) *pRevMask |= MASKBIT(iLoop);
135523 revSet = 1;
135526 if( isMatch ){
135527 if( iColumn==XN_ROWID ){
135528 testcase( distinctColumns==0 );
135529 distinctColumns = 1;
135531 obSat |= MASKBIT(i);
135532 }else{
135533 /* No match found */
135534 if( j==0 || j<nKeyCol ){
135535 testcase( isOrderDistinct!=0 );
135536 isOrderDistinct = 0;
135538 break;
135540 } /* end Loop over all index columns */
135541 if( distinctColumns ){
135542 testcase( isOrderDistinct==0 );
135543 isOrderDistinct = 1;
135545 } /* end-if not one-row */
135547 /* Mark off any other ORDER BY terms that reference pLoop */
135548 if( isOrderDistinct ){
135549 orderDistinctMask |= pLoop->maskSelf;
135550 for(i=0; i<nOrderBy; i++){
135551 Expr *p;
135552 Bitmask mTerm;
135553 if( MASKBIT(i) & obSat ) continue;
135554 p = pOrderBy->a[i].pExpr;
135555 mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
135556 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
135557 if( (mTerm&~orderDistinctMask)==0 ){
135558 obSat |= MASKBIT(i);
135562 } /* End the loop over all WhereLoops from outer-most down to inner-most */
135563 if( obSat==obDone ) return (i8)nOrderBy;
135564 if( !isOrderDistinct ){
135565 for(i=nOrderBy-1; i>0; i--){
135566 Bitmask m = MASKBIT(i) - 1;
135567 if( (obSat&m)==m ) return i;
135569 return 0;
135571 return -1;
135576 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
135577 ** the planner assumes that the specified pOrderBy list is actually a GROUP
135578 ** BY clause - and so any order that groups rows as required satisfies the
135579 ** request.
135581 ** Normally, in this case it is not possible for the caller to determine
135582 ** whether or not the rows are really being delivered in sorted order, or
135583 ** just in some other order that provides the required grouping. However,
135584 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
135585 ** this function may be called on the returned WhereInfo object. It returns
135586 ** true if the rows really will be sorted in the specified order, or false
135587 ** otherwise.
135589 ** For example, assuming:
135591 ** CREATE INDEX i1 ON t1(x, Y);
135593 ** then
135595 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
135596 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
135598 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
135599 assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
135600 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
135601 return pWInfo->sorted;
135604 #ifdef WHERETRACE_ENABLED
135605 /* For debugging use only: */
135606 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
135607 static char zName[65];
135608 int i;
135609 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
135610 if( pLast ) zName[i++] = pLast->cId;
135611 zName[i] = 0;
135612 return zName;
135614 #endif
135617 ** Return the cost of sorting nRow rows, assuming that the keys have
135618 ** nOrderby columns and that the first nSorted columns are already in
135619 ** order.
135621 static LogEst whereSortingCost(
135622 WhereInfo *pWInfo,
135623 LogEst nRow,
135624 int nOrderBy,
135625 int nSorted
135627 /* TUNING: Estimated cost of a full external sort, where N is
135628 ** the number of rows to sort is:
135630 ** cost = (3.0 * N * log(N)).
135632 ** Or, if the order-by clause has X terms but only the last Y
135633 ** terms are out of order, then block-sorting will reduce the
135634 ** sorting cost to:
135636 ** cost = (3.0 * N * log(N)) * (Y/X)
135638 ** The (Y/X) term is implemented using stack variable rScale
135639 ** below. */
135640 LogEst rScale, rSortCost;
135641 assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
135642 rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
135643 rSortCost = nRow + rScale + 16;
135645 /* Multiple by log(M) where M is the number of output rows.
135646 ** Use the LIMIT for M if it is smaller */
135647 if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
135648 nRow = pWInfo->iLimit;
135650 rSortCost += estLog(nRow);
135651 return rSortCost;
135655 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
135656 ** attempts to find the lowest cost path that visits each WhereLoop
135657 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
135659 ** Assume that the total number of output rows that will need to be sorted
135660 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
135661 ** costs if nRowEst==0.
135663 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
135664 ** error occurs.
135666 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
135667 int mxChoice; /* Maximum number of simultaneous paths tracked */
135668 int nLoop; /* Number of terms in the join */
135669 Parse *pParse; /* Parsing context */
135670 sqlite3 *db; /* The database connection */
135671 int iLoop; /* Loop counter over the terms of the join */
135672 int ii, jj; /* Loop counters */
135673 int mxI = 0; /* Index of next entry to replace */
135674 int nOrderBy; /* Number of ORDER BY clause terms */
135675 LogEst mxCost = 0; /* Maximum cost of a set of paths */
135676 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
135677 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
135678 WherePath *aFrom; /* All nFrom paths at the previous level */
135679 WherePath *aTo; /* The nTo best paths at the current level */
135680 WherePath *pFrom; /* An element of aFrom[] that we are working on */
135681 WherePath *pTo; /* An element of aTo[] that we are working on */
135682 WhereLoop *pWLoop; /* One of the WhereLoop objects */
135683 WhereLoop **pX; /* Used to divy up the pSpace memory */
135684 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
135685 char *pSpace; /* Temporary memory used by this routine */
135686 int nSpace; /* Bytes of space allocated at pSpace */
135688 pParse = pWInfo->pParse;
135689 db = pParse->db;
135690 nLoop = pWInfo->nLevel;
135691 /* TUNING: For simple queries, only the best path is tracked.
135692 ** For 2-way joins, the 5 best paths are followed.
135693 ** For joins of 3 or more tables, track the 10 best paths */
135694 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
135695 assert( nLoop<=pWInfo->pTabList->nSrc );
135696 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
135698 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
135699 ** case the purpose of this call is to estimate the number of rows returned
135700 ** by the overall query. Once this estimate has been obtained, the caller
135701 ** will invoke this function a second time, passing the estimate as the
135702 ** nRowEst parameter. */
135703 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
135704 nOrderBy = 0;
135705 }else{
135706 nOrderBy = pWInfo->pOrderBy->nExpr;
135709 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
135710 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
135711 nSpace += sizeof(LogEst) * nOrderBy;
135712 pSpace = sqlite3DbMallocRawNN(db, nSpace);
135713 if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
135714 aTo = (WherePath*)pSpace;
135715 aFrom = aTo+mxChoice;
135716 memset(aFrom, 0, sizeof(aFrom[0]));
135717 pX = (WhereLoop**)(aFrom+mxChoice);
135718 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
135719 pFrom->aLoop = pX;
135721 if( nOrderBy ){
135722 /* If there is an ORDER BY clause and it is not being ignored, set up
135723 ** space for the aSortCost[] array. Each element of the aSortCost array
135724 ** is either zero - meaning it has not yet been initialized - or the
135725 ** cost of sorting nRowEst rows of data where the first X terms of
135726 ** the ORDER BY clause are already in order, where X is the array
135727 ** index. */
135728 aSortCost = (LogEst*)pX;
135729 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
135731 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
135732 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
135734 /* Seed the search with a single WherePath containing zero WhereLoops.
135736 ** TUNING: Do not let the number of iterations go above 28. If the cost
135737 ** of computing an automatic index is not paid back within the first 28
135738 ** rows, then do not use the automatic index. */
135739 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
135740 nFrom = 1;
135741 assert( aFrom[0].isOrdered==0 );
135742 if( nOrderBy ){
135743 /* If nLoop is zero, then there are no FROM terms in the query. Since
135744 ** in this case the query may return a maximum of one row, the results
135745 ** are already in the requested order. Set isOrdered to nOrderBy to
135746 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
135747 ** -1, indicating that the result set may or may not be ordered,
135748 ** depending on the loops added to the current plan. */
135749 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
135752 /* Compute successively longer WherePaths using the previous generation
135753 ** of WherePaths as the basis for the next. Keep track of the mxChoice
135754 ** best paths at each generation */
135755 for(iLoop=0; iLoop<nLoop; iLoop++){
135756 nTo = 0;
135757 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
135758 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
135759 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
135760 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
135761 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
135762 i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
135763 Bitmask maskNew; /* Mask of src visited by (..) */
135764 Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
135766 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
135767 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
135768 if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
135769 /* Do not use an automatic index if the this loop is expected
135770 ** to run less than 2 times. */
135771 assert( 10==sqlite3LogEst(2) );
135772 continue;
135774 /* At this point, pWLoop is a candidate to be the next loop.
135775 ** Compute its cost */
135776 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
135777 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
135778 nOut = pFrom->nRow + pWLoop->nOut;
135779 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
135780 if( isOrdered<0 ){
135781 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
135782 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
135783 iLoop, pWLoop, &revMask);
135784 }else{
135785 revMask = pFrom->revLoop;
135787 if( isOrdered>=0 && isOrdered<nOrderBy ){
135788 if( aSortCost[isOrdered]==0 ){
135789 aSortCost[isOrdered] = whereSortingCost(
135790 pWInfo, nRowEst, nOrderBy, isOrdered
135793 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
135795 WHERETRACE(0x002,
135796 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
135797 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
135798 rUnsorted, rCost));
135799 }else{
135800 rCost = rUnsorted;
135801 rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
135804 /* Check to see if pWLoop should be added to the set of
135805 ** mxChoice best-so-far paths.
135807 ** First look for an existing path among best-so-far paths
135808 ** that covers the same set of loops and has the same isOrdered
135809 ** setting as the current path candidate.
135811 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
135812 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
135813 ** of legal values for isOrdered, -1..64.
135815 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
135816 if( pTo->maskLoop==maskNew
135817 && ((pTo->isOrdered^isOrdered)&0x80)==0
135819 testcase( jj==nTo-1 );
135820 break;
135823 if( jj>=nTo ){
135824 /* None of the existing best-so-far paths match the candidate. */
135825 if( nTo>=mxChoice
135826 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
135828 /* The current candidate is no better than any of the mxChoice
135829 ** paths currently in the best-so-far buffer. So discard
135830 ** this candidate as not viable. */
135831 #ifdef WHERETRACE_ENABLED /* 0x4 */
135832 if( sqlite3WhereTrace&0x4 ){
135833 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
135834 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135835 isOrdered>=0 ? isOrdered+'0' : '?');
135837 #endif
135838 continue;
135840 /* If we reach this points it means that the new candidate path
135841 ** needs to be added to the set of best-so-far paths. */
135842 if( nTo<mxChoice ){
135843 /* Increase the size of the aTo set by one */
135844 jj = nTo++;
135845 }else{
135846 /* New path replaces the prior worst to keep count below mxChoice */
135847 jj = mxI;
135849 pTo = &aTo[jj];
135850 #ifdef WHERETRACE_ENABLED /* 0x4 */
135851 if( sqlite3WhereTrace&0x4 ){
135852 sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
135853 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135854 isOrdered>=0 ? isOrdered+'0' : '?');
135856 #endif
135857 }else{
135858 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
135859 ** same set of loops and has the same isOrdered setting as the
135860 ** candidate path. Check to see if the candidate should replace
135861 ** pTo or if the candidate should be skipped.
135863 ** The conditional is an expanded vector comparison equivalent to:
135864 ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
135866 if( pTo->rCost<rCost
135867 || (pTo->rCost==rCost
135868 && (pTo->nRow<nOut
135869 || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
135873 #ifdef WHERETRACE_ENABLED /* 0x4 */
135874 if( sqlite3WhereTrace&0x4 ){
135875 sqlite3DebugPrintf(
135876 "Skip %s cost=%-3d,%3d,%3d order=%c",
135877 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135878 isOrdered>=0 ? isOrdered+'0' : '?');
135879 sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
135880 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
135881 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
135883 #endif
135884 /* Discard the candidate path from further consideration */
135885 testcase( pTo->rCost==rCost );
135886 continue;
135888 testcase( pTo->rCost==rCost+1 );
135889 /* Control reaches here if the candidate path is better than the
135890 ** pTo path. Replace pTo with the candidate. */
135891 #ifdef WHERETRACE_ENABLED /* 0x4 */
135892 if( sqlite3WhereTrace&0x4 ){
135893 sqlite3DebugPrintf(
135894 "Update %s cost=%-3d,%3d,%3d order=%c",
135895 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135896 isOrdered>=0 ? isOrdered+'0' : '?');
135897 sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
135898 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
135899 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
135901 #endif
135903 /* pWLoop is a winner. Add it to the set of best so far */
135904 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
135905 pTo->revLoop = revMask;
135906 pTo->nRow = nOut;
135907 pTo->rCost = rCost;
135908 pTo->rUnsorted = rUnsorted;
135909 pTo->isOrdered = isOrdered;
135910 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
135911 pTo->aLoop[iLoop] = pWLoop;
135912 if( nTo>=mxChoice ){
135913 mxI = 0;
135914 mxCost = aTo[0].rCost;
135915 mxUnsorted = aTo[0].nRow;
135916 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
135917 if( pTo->rCost>mxCost
135918 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
135920 mxCost = pTo->rCost;
135921 mxUnsorted = pTo->rUnsorted;
135922 mxI = jj;
135929 #ifdef WHERETRACE_ENABLED /* >=2 */
135930 if( sqlite3WhereTrace & 0x02 ){
135931 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
135932 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
135933 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
135934 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
135935 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
135936 if( pTo->isOrdered>0 ){
135937 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
135938 }else{
135939 sqlite3DebugPrintf("\n");
135943 #endif
135945 /* Swap the roles of aFrom and aTo for the next generation */
135946 pFrom = aTo;
135947 aTo = aFrom;
135948 aFrom = pFrom;
135949 nFrom = nTo;
135952 if( nFrom==0 ){
135953 sqlite3ErrorMsg(pParse, "no query solution");
135954 sqlite3DbFreeNN(db, pSpace);
135955 return SQLITE_ERROR;
135958 /* Find the lowest cost path. pFrom will be left pointing to that path */
135959 pFrom = aFrom;
135960 for(ii=1; ii<nFrom; ii++){
135961 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
135963 assert( pWInfo->nLevel==nLoop );
135964 /* Load the lowest cost path into pWInfo */
135965 for(iLoop=0; iLoop<nLoop; iLoop++){
135966 WhereLevel *pLevel = pWInfo->a + iLoop;
135967 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
135968 pLevel->iFrom = pWLoop->iTab;
135969 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
135971 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
135972 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
135973 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
135974 && nRowEst
135976 Bitmask notUsed;
135977 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
135978 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
135979 if( rc==pWInfo->pResultSet->nExpr ){
135980 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
135983 if( pWInfo->pOrderBy ){
135984 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
135985 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
135986 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
135988 }else{
135989 pWInfo->nOBSat = pFrom->isOrdered;
135990 pWInfo->revMask = pFrom->revLoop;
135991 if( pWInfo->nOBSat<=0 ){
135992 pWInfo->nOBSat = 0;
135993 if( nLoop>0 ){
135994 u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
135995 if( (wsFlags & WHERE_ONEROW)==0
135996 && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
135998 Bitmask m = 0;
135999 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
136000 WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
136001 testcase( wsFlags & WHERE_IPK );
136002 testcase( wsFlags & WHERE_COLUMN_IN );
136003 if( rc==pWInfo->pOrderBy->nExpr ){
136004 pWInfo->bOrderedInnerLoop = 1;
136005 pWInfo->revMask = m;
136011 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
136012 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
136014 Bitmask revMask = 0;
136015 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
136016 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
136018 assert( pWInfo->sorted==0 );
136019 if( nOrder==pWInfo->pOrderBy->nExpr ){
136020 pWInfo->sorted = 1;
136021 pWInfo->revMask = revMask;
136027 pWInfo->nRowOut = pFrom->nRow;
136029 /* Free temporary memory and return success */
136030 sqlite3DbFreeNN(db, pSpace);
136031 return SQLITE_OK;
136035 ** Most queries use only a single table (they are not joins) and have
136036 ** simple == constraints against indexed fields. This routine attempts
136037 ** to plan those simple cases using much less ceremony than the
136038 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
136039 ** times for the common case.
136041 ** Return non-zero on success, if this query can be handled by this
136042 ** no-frills query planner. Return zero if this query needs the
136043 ** general-purpose query planner.
136045 static int whereShortCut(WhereLoopBuilder *pBuilder){
136046 WhereInfo *pWInfo;
136047 struct SrcList_item *pItem;
136048 WhereClause *pWC;
136049 WhereTerm *pTerm;
136050 WhereLoop *pLoop;
136051 int iCur;
136052 int j;
136053 Table *pTab;
136054 Index *pIdx;
136056 pWInfo = pBuilder->pWInfo;
136057 if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
136058 assert( pWInfo->pTabList->nSrc>=1 );
136059 pItem = pWInfo->pTabList->a;
136060 pTab = pItem->pTab;
136061 if( IsVirtual(pTab) ) return 0;
136062 if( pItem->fg.isIndexedBy ) return 0;
136063 iCur = pItem->iCursor;
136064 pWC = &pWInfo->sWC;
136065 pLoop = pBuilder->pNew;
136066 pLoop->wsFlags = 0;
136067 pLoop->nSkip = 0;
136068 pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
136069 if( pTerm ){
136070 testcase( pTerm->eOperator & WO_IS );
136071 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
136072 pLoop->aLTerm[0] = pTerm;
136073 pLoop->nLTerm = 1;
136074 pLoop->u.btree.nEq = 1;
136075 /* TUNING: Cost of a rowid lookup is 10 */
136076 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
136077 }else{
136078 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
136079 int opMask;
136080 assert( pLoop->aLTermSpace==pLoop->aLTerm );
136081 if( !IsUniqueIndex(pIdx)
136082 || pIdx->pPartIdxWhere!=0
136083 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
136084 ) continue;
136085 opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
136086 for(j=0; j<pIdx->nKeyCol; j++){
136087 pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
136088 if( pTerm==0 ) break;
136089 testcase( pTerm->eOperator & WO_IS );
136090 pLoop->aLTerm[j] = pTerm;
136092 if( j!=pIdx->nKeyCol ) continue;
136093 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
136094 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
136095 pLoop->wsFlags |= WHERE_IDX_ONLY;
136097 pLoop->nLTerm = j;
136098 pLoop->u.btree.nEq = j;
136099 pLoop->u.btree.pIndex = pIdx;
136100 /* TUNING: Cost of a unique index lookup is 15 */
136101 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
136102 break;
136105 if( pLoop->wsFlags ){
136106 pLoop->nOut = (LogEst)1;
136107 pWInfo->a[0].pWLoop = pLoop;
136108 assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
136109 pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
136110 pWInfo->a[0].iTabCur = iCur;
136111 pWInfo->nRowOut = 1;
136112 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
136113 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
136114 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
136116 #ifdef SQLITE_DEBUG
136117 pLoop->cId = '0';
136118 #endif
136119 return 1;
136121 return 0;
136125 ** Helper function for exprIsDeterministic().
136127 static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
136128 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
136129 pWalker->eCode = 0;
136130 return WRC_Abort;
136132 return WRC_Continue;
136136 ** Return true if the expression contains no non-deterministic SQL
136137 ** functions. Do not consider non-deterministic SQL functions that are
136138 ** part of sub-select statements.
136140 static int exprIsDeterministic(Expr *p){
136141 Walker w;
136142 memset(&w, 0, sizeof(w));
136143 w.eCode = 1;
136144 w.xExprCallback = exprNodeIsDeterministic;
136145 w.xSelectCallback = sqlite3SelectWalkFail;
136146 sqlite3WalkExpr(&w, p);
136147 return w.eCode;
136151 ** Generate the beginning of the loop used for WHERE clause processing.
136152 ** The return value is a pointer to an opaque structure that contains
136153 ** information needed to terminate the loop. Later, the calling routine
136154 ** should invoke sqlite3WhereEnd() with the return value of this function
136155 ** in order to complete the WHERE clause processing.
136157 ** If an error occurs, this routine returns NULL.
136159 ** The basic idea is to do a nested loop, one loop for each table in
136160 ** the FROM clause of a select. (INSERT and UPDATE statements are the
136161 ** same as a SELECT with only a single table in the FROM clause.) For
136162 ** example, if the SQL is this:
136164 ** SELECT * FROM t1, t2, t3 WHERE ...;
136166 ** Then the code generated is conceptually like the following:
136168 ** foreach row1 in t1 do \ Code generated
136169 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
136170 ** foreach row3 in t3 do /
136171 ** ...
136172 ** end \ Code generated
136173 ** end |-- by sqlite3WhereEnd()
136174 ** end /
136176 ** Note that the loops might not be nested in the order in which they
136177 ** appear in the FROM clause if a different order is better able to make
136178 ** use of indices. Note also that when the IN operator appears in
136179 ** the WHERE clause, it might result in additional nested loops for
136180 ** scanning through all values on the right-hand side of the IN.
136182 ** There are Btree cursors associated with each table. t1 uses cursor
136183 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
136184 ** And so forth. This routine generates code to open those VDBE cursors
136185 ** and sqlite3WhereEnd() generates the code to close them.
136187 ** The code that sqlite3WhereBegin() generates leaves the cursors named
136188 ** in pTabList pointing at their appropriate entries. The [...] code
136189 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
136190 ** data from the various tables of the loop.
136192 ** If the WHERE clause is empty, the foreach loops must each scan their
136193 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
136194 ** the tables have indices and there are terms in the WHERE clause that
136195 ** refer to those indices, a complete table scan can be avoided and the
136196 ** code will run much faster. Most of the work of this routine is checking
136197 ** to see if there are indices that can be used to speed up the loop.
136199 ** Terms of the WHERE clause are also used to limit which rows actually
136200 ** make it to the "..." in the middle of the loop. After each "foreach",
136201 ** terms of the WHERE clause that use only terms in that loop and outer
136202 ** loops are evaluated and if false a jump is made around all subsequent
136203 ** inner loops (or around the "..." if the test occurs within the inner-
136204 ** most loop)
136206 ** OUTER JOINS
136208 ** An outer join of tables t1 and t2 is conceptally coded as follows:
136210 ** foreach row1 in t1 do
136211 ** flag = 0
136212 ** foreach row2 in t2 do
136213 ** start:
136214 ** ...
136215 ** flag = 1
136216 ** end
136217 ** if flag==0 then
136218 ** move the row2 cursor to a null row
136219 ** goto start
136220 ** fi
136221 ** end
136223 ** ORDER BY CLAUSE PROCESSING
136225 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
136226 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
136227 ** if there is one. If there is no ORDER BY clause or if this routine
136228 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
136230 ** The iIdxCur parameter is the cursor number of an index. If
136231 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
136232 ** to use for OR clause processing. The WHERE clause should use this
136233 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
136234 ** the first cursor in an array of cursors for all indices. iIdxCur should
136235 ** be used to compute the appropriate cursor depending on which index is
136236 ** used.
136238 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
136239 Parse *pParse, /* The parser context */
136240 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
136241 Expr *pWhere, /* The WHERE clause */
136242 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
136243 ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
136244 u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
136245 int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
136246 ** If WHERE_USE_LIMIT, then the limit amount */
136248 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
136249 int nTabList; /* Number of elements in pTabList */
136250 WhereInfo *pWInfo; /* Will become the return value of this function */
136251 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
136252 Bitmask notReady; /* Cursors that are not yet positioned */
136253 WhereLoopBuilder sWLB; /* The WhereLoop builder */
136254 WhereMaskSet *pMaskSet; /* The expression mask set */
136255 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
136256 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
136257 int ii; /* Loop counter */
136258 sqlite3 *db; /* Database connection */
136259 int rc; /* Return code */
136260 u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
136262 assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
136263 (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
136264 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
136267 /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
136268 assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
136269 || (wctrlFlags & WHERE_USE_LIMIT)==0 );
136271 /* Variable initialization */
136272 db = pParse->db;
136273 memset(&sWLB, 0, sizeof(sWLB));
136275 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
136276 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
136277 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
136278 sWLB.pOrderBy = pOrderBy;
136280 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
136281 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
136282 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
136283 wctrlFlags &= ~WHERE_WANT_DISTINCT;
136286 /* The number of tables in the FROM clause is limited by the number of
136287 ** bits in a Bitmask
136289 testcase( pTabList->nSrc==BMS );
136290 if( pTabList->nSrc>BMS ){
136291 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
136292 return 0;
136295 /* This function normally generates a nested loop for all tables in
136296 ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
136297 ** only generate code for the first table in pTabList and assume that
136298 ** any cursors associated with subsequent tables are uninitialized.
136300 nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
136302 /* Allocate and initialize the WhereInfo structure that will become the
136303 ** return value. A single allocation is used to store the WhereInfo
136304 ** struct, the contents of WhereInfo.a[], the WhereClause structure
136305 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
136306 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
136307 ** some architectures. Hence the ROUND8() below.
136309 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
136310 pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
136311 if( db->mallocFailed ){
136312 sqlite3DbFree(db, pWInfo);
136313 pWInfo = 0;
136314 goto whereBeginError;
136316 pWInfo->pParse = pParse;
136317 pWInfo->pTabList = pTabList;
136318 pWInfo->pOrderBy = pOrderBy;
136319 pWInfo->pWhere = pWhere;
136320 pWInfo->pResultSet = pResultSet;
136321 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
136322 pWInfo->nLevel = nTabList;
136323 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
136324 pWInfo->wctrlFlags = wctrlFlags;
136325 pWInfo->iLimit = iAuxArg;
136326 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
136327 memset(&pWInfo->nOBSat, 0,
136328 offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
136329 memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
136330 assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
136331 pMaskSet = &pWInfo->sMaskSet;
136332 sWLB.pWInfo = pWInfo;
136333 sWLB.pWC = &pWInfo->sWC;
136334 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
136335 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
136336 whereLoopInit(sWLB.pNew);
136337 #ifdef SQLITE_DEBUG
136338 sWLB.pNew->cId = '*';
136339 #endif
136341 /* Split the WHERE clause into separate subexpressions where each
136342 ** subexpression is separated by an AND operator.
136344 initMaskSet(pMaskSet);
136345 sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
136346 sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
136348 /* Special case: No FROM clause
136350 if( nTabList==0 ){
136351 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
136352 if( wctrlFlags & WHERE_WANT_DISTINCT ){
136353 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
136355 }else{
136356 /* Assign a bit from the bitmask to every term in the FROM clause.
136358 ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
136360 ** The rule of the previous sentence ensures thta if X is the bitmask for
136361 ** a table T, then X-1 is the bitmask for all other tables to the left of T.
136362 ** Knowing the bitmask for all tables to the left of a left join is
136363 ** important. Ticket #3015.
136365 ** Note that bitmasks are created for all pTabList->nSrc tables in
136366 ** pTabList, not just the first nTabList tables. nTabList is normally
136367 ** equal to pTabList->nSrc but might be shortened to 1 if the
136368 ** WHERE_OR_SUBCLAUSE flag is set.
136370 ii = 0;
136372 createMask(pMaskSet, pTabList->a[ii].iCursor);
136373 sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
136374 }while( (++ii)<pTabList->nSrc );
136375 #ifdef SQLITE_DEBUG
136377 Bitmask mx = 0;
136378 for(ii=0; ii<pTabList->nSrc; ii++){
136379 Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
136380 assert( m>=mx );
136381 mx = m;
136384 #endif
136387 /* Analyze all of the subexpressions. */
136388 sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
136389 if( db->mallocFailed ) goto whereBeginError;
136391 /* Special case: WHERE terms that do not refer to any tables in the join
136392 ** (constant expressions). Evaluate each such term, and jump over all the
136393 ** generated code if the result is not true.
136395 ** Do not do this if the expression contains non-deterministic functions
136396 ** that are not within a sub-select. This is not strictly required, but
136397 ** preserves SQLite's legacy behaviour in the following two cases:
136399 ** FROM ... WHERE random()>0; -- eval random() once per row
136400 ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall
136402 for(ii=0; ii<sWLB.pWC->nTerm; ii++){
136403 WhereTerm *pT = &sWLB.pWC->a[ii];
136404 if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
136405 sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
136406 pT->wtFlags |= TERM_CODED;
136410 if( wctrlFlags & WHERE_WANT_DISTINCT ){
136411 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
136412 /* The DISTINCT marking is pointless. Ignore it. */
136413 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
136414 }else if( pOrderBy==0 ){
136415 /* Try to ORDER BY the result set to make distinct processing easier */
136416 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
136417 pWInfo->pOrderBy = pResultSet;
136421 /* Construct the WhereLoop objects */
136422 #if defined(WHERETRACE_ENABLED)
136423 if( sqlite3WhereTrace & 0xffff ){
136424 sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
136425 if( wctrlFlags & WHERE_USE_LIMIT ){
136426 sqlite3DebugPrintf(", limit: %d", iAuxArg);
136428 sqlite3DebugPrintf(")\n");
136430 if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
136431 sqlite3WhereClausePrint(sWLB.pWC);
136433 #endif
136435 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
136436 rc = whereLoopAddAll(&sWLB);
136437 if( rc ) goto whereBeginError;
136439 #ifdef WHERETRACE_ENABLED
136440 if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
136441 WhereLoop *p;
136442 int i;
136443 static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
136444 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
136445 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
136446 p->cId = zLabel[i%(sizeof(zLabel)-1)];
136447 whereLoopPrint(p, sWLB.pWC);
136450 #endif
136452 wherePathSolver(pWInfo, 0);
136453 if( db->mallocFailed ) goto whereBeginError;
136454 if( pWInfo->pOrderBy ){
136455 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
136456 if( db->mallocFailed ) goto whereBeginError;
136459 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
136460 pWInfo->revMask = ALLBITS;
136462 if( pParse->nErr || NEVER(db->mallocFailed) ){
136463 goto whereBeginError;
136465 #ifdef WHERETRACE_ENABLED
136466 if( sqlite3WhereTrace ){
136467 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
136468 if( pWInfo->nOBSat>0 ){
136469 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
136471 switch( pWInfo->eDistinct ){
136472 case WHERE_DISTINCT_UNIQUE: {
136473 sqlite3DebugPrintf(" DISTINCT=unique");
136474 break;
136476 case WHERE_DISTINCT_ORDERED: {
136477 sqlite3DebugPrintf(" DISTINCT=ordered");
136478 break;
136480 case WHERE_DISTINCT_UNORDERED: {
136481 sqlite3DebugPrintf(" DISTINCT=unordered");
136482 break;
136485 sqlite3DebugPrintf("\n");
136486 for(ii=0; ii<pWInfo->nLevel; ii++){
136487 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
136490 #endif
136491 /* Attempt to omit tables from the join that do not effect the result */
136492 if( pWInfo->nLevel>=2
136493 && pResultSet!=0
136494 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
136496 Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
136497 if( sWLB.pOrderBy ){
136498 tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
136500 while( pWInfo->nLevel>=2 ){
136501 WhereTerm *pTerm, *pEnd;
136502 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
136503 if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
136504 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
136505 && (pLoop->wsFlags & WHERE_ONEROW)==0
136507 break;
136509 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
136510 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
136511 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
136512 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
136513 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
136515 break;
136518 if( pTerm<pEnd ) break;
136519 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
136520 pWInfo->nLevel--;
136521 nTabList--;
136524 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
136525 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
136527 /* If the caller is an UPDATE or DELETE statement that is requesting
136528 ** to use a one-pass algorithm, determine if this is appropriate.
136530 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
136531 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
136532 int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
136533 int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
136534 if( bOnerow
136535 || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
136536 && 0==(wsFlags & WHERE_VIRTUALTABLE))
136538 pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
136539 if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
136540 if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
136541 bFordelete = OPFLAG_FORDELETE;
136543 pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
136548 /* Open all tables in the pTabList and any indices selected for
136549 ** searching those tables.
136551 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
136552 Table *pTab; /* Table to open */
136553 int iDb; /* Index of database containing table/index */
136554 struct SrcList_item *pTabItem;
136556 pTabItem = &pTabList->a[pLevel->iFrom];
136557 pTab = pTabItem->pTab;
136558 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
136559 pLoop = pLevel->pWLoop;
136560 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
136561 /* Do nothing */
136562 }else
136563 #ifndef SQLITE_OMIT_VIRTUALTABLE
136564 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
136565 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
136566 int iCur = pTabItem->iCursor;
136567 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
136568 }else if( IsVirtual(pTab) ){
136569 /* noop */
136570 }else
136571 #endif
136572 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
136573 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
136574 int op = OP_OpenRead;
136575 if( pWInfo->eOnePass!=ONEPASS_OFF ){
136576 op = OP_OpenWrite;
136577 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
136579 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
136580 assert( pTabItem->iCursor==pLevel->iTabCur );
136581 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
136582 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
136583 if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
136584 Bitmask b = pTabItem->colUsed;
136585 int n = 0;
136586 for(; b; b=b>>1, n++){}
136587 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
136588 assert( n<=pTab->nCol );
136590 #ifdef SQLITE_ENABLE_CURSOR_HINTS
136591 if( pLoop->u.btree.pIndex!=0 ){
136592 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
136593 }else
136594 #endif
136596 sqlite3VdbeChangeP5(v, bFordelete);
136598 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
136599 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
136600 (const u8*)&pTabItem->colUsed, P4_INT64);
136601 #endif
136602 }else{
136603 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
136605 if( pLoop->wsFlags & WHERE_INDEXED ){
136606 Index *pIx = pLoop->u.btree.pIndex;
136607 int iIndexCur;
136608 int op = OP_OpenRead;
136609 /* iAuxArg is always set to a positive value if ONEPASS is possible */
136610 assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
136611 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
136612 && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
136614 /* This is one term of an OR-optimization using the PRIMARY KEY of a
136615 ** WITHOUT ROWID table. No need for a separate index */
136616 iIndexCur = pLevel->iTabCur;
136617 op = 0;
136618 }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
136619 Index *pJ = pTabItem->pTab->pIndex;
136620 iIndexCur = iAuxArg;
136621 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
136622 while( ALWAYS(pJ) && pJ!=pIx ){
136623 iIndexCur++;
136624 pJ = pJ->pNext;
136626 op = OP_OpenWrite;
136627 pWInfo->aiCurOnePass[1] = iIndexCur;
136628 }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
136629 iIndexCur = iAuxArg;
136630 op = OP_ReopenIdx;
136631 }else{
136632 iIndexCur = pParse->nTab++;
136634 pLevel->iIdxCur = iIndexCur;
136635 assert( pIx->pSchema==pTab->pSchema );
136636 assert( iIndexCur>=0 );
136637 if( op ){
136638 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
136639 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
136640 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
136641 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
136642 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
136643 && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
136645 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
136647 VdbeComment((v, "%s", pIx->zName));
136648 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
136650 u64 colUsed = 0;
136651 int ii, jj;
136652 for(ii=0; ii<pIx->nColumn; ii++){
136653 jj = pIx->aiColumn[ii];
136654 if( jj<0 ) continue;
136655 if( jj>63 ) jj = 63;
136656 if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
136657 colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
136659 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
136660 (u8*)&colUsed, P4_INT64);
136662 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
136665 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
136667 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
136668 if( db->mallocFailed ) goto whereBeginError;
136670 /* Generate the code to do the search. Each iteration of the for
136671 ** loop below generates code for a single nested loop of the VM
136672 ** program.
136674 notReady = ~(Bitmask)0;
136675 for(ii=0; ii<nTabList; ii++){
136676 int addrExplain;
136677 int wsFlags;
136678 pLevel = &pWInfo->a[ii];
136679 wsFlags = pLevel->pWLoop->wsFlags;
136680 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
136681 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
136682 constructAutomaticIndex(pParse, &pWInfo->sWC,
136683 &pTabList->a[pLevel->iFrom], notReady, pLevel);
136684 if( db->mallocFailed ) goto whereBeginError;
136686 #endif
136687 addrExplain = sqlite3WhereExplainOneScan(
136688 pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
136690 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
136691 notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
136692 pWInfo->iContinue = pLevel->addrCont;
136693 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
136694 sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
136698 /* Done. */
136699 VdbeModuleComment((v, "Begin WHERE-core"));
136700 return pWInfo;
136702 /* Jump here if malloc fails */
136703 whereBeginError:
136704 if( pWInfo ){
136705 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
136706 whereInfoFree(db, pWInfo);
136708 return 0;
136712 ** Generate the end of the WHERE loop. See comments on
136713 ** sqlite3WhereBegin() for additional information.
136715 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
136716 Parse *pParse = pWInfo->pParse;
136717 Vdbe *v = pParse->pVdbe;
136718 int i;
136719 WhereLevel *pLevel;
136720 WhereLoop *pLoop;
136721 SrcList *pTabList = pWInfo->pTabList;
136722 sqlite3 *db = pParse->db;
136724 /* Generate loop termination code.
136726 VdbeModuleComment((v, "End WHERE-core"));
136727 sqlite3ExprCacheClear(pParse);
136728 for(i=pWInfo->nLevel-1; i>=0; i--){
136729 int addr;
136730 pLevel = &pWInfo->a[i];
136731 pLoop = pLevel->pWLoop;
136732 if( pLevel->op!=OP_Noop ){
136733 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
136734 int addrSeek = 0;
136735 Index *pIdx;
136736 int n;
136737 if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
136738 && (pLoop->wsFlags & WHERE_INDEXED)!=0
136739 && (pIdx = pLoop->u.btree.pIndex)->hasStat1
136740 && (n = pLoop->u.btree.nIdxCol)>0
136741 && pIdx->aiRowLogEst[n]>=36
136743 int r1 = pParse->nMem+1;
136744 int j, op;
136745 for(j=0; j<n; j++){
136746 sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
136748 pParse->nMem += n+1;
136749 op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
136750 addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
136751 VdbeCoverageIf(v, op==OP_SeekLT);
136752 VdbeCoverageIf(v, op==OP_SeekGT);
136753 sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
136755 #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
136756 /* The common case: Advance to the next row */
136757 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
136758 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
136759 sqlite3VdbeChangeP5(v, pLevel->p5);
136760 VdbeCoverage(v);
136761 VdbeCoverageIf(v, pLevel->op==OP_Next);
136762 VdbeCoverageIf(v, pLevel->op==OP_Prev);
136763 VdbeCoverageIf(v, pLevel->op==OP_VNext);
136764 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
136765 if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
136766 #endif
136767 }else{
136768 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
136770 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
136771 struct InLoop *pIn;
136772 int j;
136773 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
136774 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
136775 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
136776 if( pIn->eEndLoopOp!=OP_Noop ){
136777 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
136778 VdbeCoverage(v);
136779 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
136780 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
136782 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
136785 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
136786 if( pLevel->addrSkip ){
136787 sqlite3VdbeGoto(v, pLevel->addrSkip);
136788 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
136789 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
136790 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
136792 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
136793 if( pLevel->addrLikeRep ){
136794 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
136795 pLevel->addrLikeRep);
136796 VdbeCoverage(v);
136798 #endif
136799 if( pLevel->iLeftJoin ){
136800 int ws = pLoop->wsFlags;
136801 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
136802 assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
136803 if( (ws & WHERE_IDX_ONLY)==0 ){
136804 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
136806 if( (ws & WHERE_INDEXED)
136807 || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
136809 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
136811 if( pLevel->op==OP_Return ){
136812 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
136813 }else{
136814 sqlite3VdbeGoto(v, pLevel->addrFirst);
136816 sqlite3VdbeJumpHere(v, addr);
136818 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
136819 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
136822 /* The "break" point is here, just past the end of the outer loop.
136823 ** Set it.
136825 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
136827 assert( pWInfo->nLevel<=pTabList->nSrc );
136828 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
136829 int k, last;
136830 VdbeOp *pOp;
136831 Index *pIdx = 0;
136832 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
136833 Table *pTab = pTabItem->pTab;
136834 assert( pTab!=0 );
136835 pLoop = pLevel->pWLoop;
136837 /* For a co-routine, change all OP_Column references to the table of
136838 ** the co-routine into OP_Copy of result contained in a register.
136839 ** OP_Rowid becomes OP_Null.
136841 if( pTabItem->fg.viaCoroutine ){
136842 testcase( pParse->db->mallocFailed );
136843 translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
136844 pTabItem->regResult, 0);
136845 continue;
136848 /* If this scan uses an index, make VDBE code substitutions to read data
136849 ** from the index instead of from the table where possible. In some cases
136850 ** this optimization prevents the table from ever being read, which can
136851 ** yield a significant performance boost.
136853 ** Calls to the code generator in between sqlite3WhereBegin and
136854 ** sqlite3WhereEnd will have created code that references the table
136855 ** directly. This loop scans all that code looking for opcodes
136856 ** that reference the table and converts them into opcodes that
136857 ** reference the index.
136859 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
136860 pIdx = pLoop->u.btree.pIndex;
136861 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
136862 pIdx = pLevel->u.pCovidx;
136864 if( pIdx
136865 && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
136866 && !db->mallocFailed
136868 last = sqlite3VdbeCurrentAddr(v);
136869 k = pLevel->addrBody;
136870 pOp = sqlite3VdbeGetOp(v, k);
136871 for(; k<last; k++, pOp++){
136872 if( pOp->p1!=pLevel->iTabCur ) continue;
136873 if( pOp->opcode==OP_Column ){
136874 int x = pOp->p2;
136875 assert( pIdx->pTable==pTab );
136876 if( !HasRowid(pTab) ){
136877 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
136878 x = pPk->aiColumn[x];
136879 assert( x>=0 );
136881 x = sqlite3ColumnOfIndex(pIdx, x);
136882 if( x>=0 ){
136883 pOp->p2 = x;
136884 pOp->p1 = pLevel->iIdxCur;
136886 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
136887 || pWInfo->eOnePass );
136888 }else if( pOp->opcode==OP_Rowid ){
136889 pOp->p1 = pLevel->iIdxCur;
136890 pOp->opcode = OP_IdxRowid;
136891 }else if( pOp->opcode==OP_IfNullRow ){
136892 pOp->p1 = pLevel->iIdxCur;
136898 /* Final cleanup
136900 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
136901 whereInfoFree(db, pWInfo);
136902 return;
136905 /************** End of where.c ***********************************************/
136906 /************** Begin file parse.c *******************************************/
136908 ** 2000-05-29
136910 ** The author disclaims copyright to this source code. In place of
136911 ** a legal notice, here is a blessing:
136913 ** May you do good and not evil.
136914 ** May you find forgiveness for yourself and forgive others.
136915 ** May you share freely, never taking more than you give.
136917 *************************************************************************
136918 ** Driver template for the LEMON parser generator.
136920 ** The "lemon" program processes an LALR(1) input grammar file, then uses
136921 ** this template to construct a parser. The "lemon" program inserts text
136922 ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
136923 ** interstitial "-" characters) contained in this template is changed into
136924 ** the value of the %name directive from the grammar. Otherwise, the content
136925 ** of this template is copied straight through into the generate parser
136926 ** source file.
136928 ** The following is the concatenation of all %include directives from the
136929 ** input grammar file:
136931 /* #include <stdio.h> */
136932 /************ Begin %include sections from the grammar ************************/
136934 /* #include "sqliteInt.h" */
136937 ** Disable all error recovery processing in the parser push-down
136938 ** automaton.
136940 #define YYNOERRORRECOVERY 1
136943 ** Make yytestcase() the same as testcase()
136945 #define yytestcase(X) testcase(X)
136948 ** Indicate that sqlite3ParserFree() will never be called with a null
136949 ** pointer.
136951 #define YYPARSEFREENEVERNULL 1
136954 ** In the amalgamation, the parse.c file generated by lemon and the
136955 ** tokenize.c file are concatenated. In that case, sqlite3RunParser()
136956 ** has access to the the size of the yyParser object and so the parser
136957 ** engine can be allocated from stack. In that case, only the
136958 ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
136959 ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
136960 ** omitted.
136962 #ifdef SQLITE_AMALGAMATION
136963 # define sqlite3Parser_ENGINEALWAYSONSTACK 1
136964 #endif
136967 ** Alternative datatype for the argument to the malloc() routine passed
136968 ** into sqlite3ParserAlloc(). The default is size_t.
136970 #define YYMALLOCARGTYPE u64
136973 ** An instance of this structure holds information about the
136974 ** LIMIT clause of a SELECT statement.
136976 struct LimitVal {
136977 Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
136978 Expr *pOffset; /* The OFFSET expression. NULL if there is none */
136982 ** An instance of the following structure describes the event of a
136983 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
136984 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
136986 ** UPDATE ON (a,b,c)
136988 ** Then the "b" IdList records the list "a,b,c".
136990 struct TrigEvent { int a; IdList * b; };
136993 ** Disable lookaside memory allocation for objects that might be
136994 ** shared across database connections.
136996 static void disableLookaside(Parse *pParse){
136997 pParse->disableLookaside++;
136998 pParse->db->lookaside.bDisable++;
137003 ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
137004 ** all elements in the list. And make sure list length does not exceed
137005 ** SQLITE_LIMIT_COMPOUND_SELECT.
137007 static void parserDoubleLinkSelect(Parse *pParse, Select *p){
137008 if( p->pPrior ){
137009 Select *pNext = 0, *pLoop;
137010 int mxSelect, cnt = 0;
137011 for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
137012 pLoop->pNext = pNext;
137013 pLoop->selFlags |= SF_Compound;
137015 if( (p->selFlags & SF_MultiValue)==0 &&
137016 (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
137017 cnt>mxSelect
137019 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
137024 /* This is a utility routine used to set the ExprSpan.zStart and
137025 ** ExprSpan.zEnd values of pOut so that the span covers the complete
137026 ** range of text beginning with pStart and going to the end of pEnd.
137028 static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
137029 pOut->zStart = pStart->z;
137030 pOut->zEnd = &pEnd->z[pEnd->n];
137033 /* Construct a new Expr object from a single identifier. Use the
137034 ** new Expr to populate pOut. Set the span of pOut to be the identifier
137035 ** that created the expression.
137037 static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
137038 Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
137039 if( p ){
137040 memset(p, 0, sizeof(Expr));
137041 p->op = (u8)op;
137042 p->flags = EP_Leaf;
137043 p->iAgg = -1;
137044 p->u.zToken = (char*)&p[1];
137045 memcpy(p->u.zToken, t.z, t.n);
137046 p->u.zToken[t.n] = 0;
137047 if( sqlite3Isquote(p->u.zToken[0]) ){
137048 if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
137049 sqlite3Dequote(p->u.zToken);
137051 #if SQLITE_MAX_EXPR_DEPTH>0
137052 p->nHeight = 1;
137053 #endif
137055 pOut->pExpr = p;
137056 pOut->zStart = t.z;
137057 pOut->zEnd = &t.z[t.n];
137060 /* This routine constructs a binary expression node out of two ExprSpan
137061 ** objects and uses the result to populate a new ExprSpan object.
137063 static void spanBinaryExpr(
137064 Parse *pParse, /* The parsing context. Errors accumulate here */
137065 int op, /* The binary operation */
137066 ExprSpan *pLeft, /* The left operand, and output */
137067 ExprSpan *pRight /* The right operand */
137069 pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr);
137070 pLeft->zEnd = pRight->zEnd;
137073 /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
137074 ** outside of *ppExpr.
137076 static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
137077 if( doNot ){
137078 pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0);
137082 /* Construct an expression node for a unary postfix operator
137084 static void spanUnaryPostfix(
137085 Parse *pParse, /* Parsing context to record errors */
137086 int op, /* The operator */
137087 ExprSpan *pOperand, /* The operand, and output */
137088 Token *pPostOp /* The operand token for setting the span */
137090 pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
137091 pOperand->zEnd = &pPostOp->z[pPostOp->n];
137094 /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
137095 ** unary TK_ISNULL or TK_NOTNULL expression. */
137096 static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
137097 sqlite3 *db = pParse->db;
137098 if( pA && pY && pY->op==TK_NULL ){
137099 pA->op = (u8)op;
137100 sqlite3ExprDelete(db, pA->pRight);
137101 pA->pRight = 0;
137105 /* Construct an expression node for a unary prefix operator
137107 static void spanUnaryPrefix(
137108 ExprSpan *pOut, /* Write the new expression node here */
137109 Parse *pParse, /* Parsing context to record errors */
137110 int op, /* The operator */
137111 ExprSpan *pOperand, /* The operand */
137112 Token *pPreOp /* The operand token for setting the span */
137114 pOut->zStart = pPreOp->z;
137115 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
137116 pOut->zEnd = pOperand->zEnd;
137119 /* Add a single new term to an ExprList that is used to store a
137120 ** list of identifiers. Report an error if the ID list contains
137121 ** a COLLATE clause or an ASC or DESC keyword, except ignore the
137122 ** error while parsing a legacy schema.
137124 static ExprList *parserAddExprIdListTerm(
137125 Parse *pParse,
137126 ExprList *pPrior,
137127 Token *pIdToken,
137128 int hasCollate,
137129 int sortOrder
137131 ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
137132 if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
137133 && pParse->db->init.busy==0
137135 sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
137136 pIdToken->n, pIdToken->z);
137138 sqlite3ExprListSetName(pParse, p, pIdToken, 1);
137139 return p;
137141 /**************** End of %include directives **********************************/
137142 /* These constants specify the various numeric values for terminal symbols
137143 ** in a format understandable to "makeheaders". This section is blank unless
137144 ** "lemon" is run with the "-m" command-line option.
137145 ***************** Begin makeheaders token definitions *************************/
137146 /**************** End makeheaders token definitions ***************************/
137148 /* The next sections is a series of control #defines.
137149 ** various aspects of the generated parser.
137150 ** YYCODETYPE is the data type used to store the integer codes
137151 ** that represent terminal and non-terminal symbols.
137152 ** "unsigned char" is used if there are fewer than
137153 ** 256 symbols. Larger types otherwise.
137154 ** YYNOCODE is a number of type YYCODETYPE that is not used for
137155 ** any terminal or nonterminal symbol.
137156 ** YYFALLBACK If defined, this indicates that one or more tokens
137157 ** (also known as: "terminal symbols") have fall-back
137158 ** values which should be used if the original symbol
137159 ** would not parse. This permits keywords to sometimes
137160 ** be used as identifiers, for example.
137161 ** YYACTIONTYPE is the data type used for "action codes" - numbers
137162 ** that indicate what to do in response to the next
137163 ** token.
137164 ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
137165 ** symbols. Background: A "minor type" is a semantic
137166 ** value associated with a terminal or non-terminal
137167 ** symbols. For example, for an "ID" terminal symbol,
137168 ** the minor type might be the name of the identifier.
137169 ** Each non-terminal can have a different minor type.
137170 ** Terminal symbols all have the same minor type, though.
137171 ** This macros defines the minor type for terminal
137172 ** symbols.
137173 ** YYMINORTYPE is the data type used for all minor types.
137174 ** This is typically a union of many types, one of
137175 ** which is sqlite3ParserTOKENTYPE. The entry in the union
137176 ** for terminal symbols is called "yy0".
137177 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
137178 ** zero the stack is dynamically sized using realloc()
137179 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
137180 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
137181 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
137182 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
137183 ** YYERRORSYMBOL is the code number of the error symbol. If not
137184 ** defined, then do no error processing.
137185 ** YYNSTATE the combined number of states.
137186 ** YYNRULE the number of rules in the grammar
137187 ** YY_MAX_SHIFT Maximum value for shift actions
137188 ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
137189 ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
137190 ** YY_MIN_REDUCE Minimum value for reduce actions
137191 ** YY_MAX_REDUCE Maximum value for reduce actions
137192 ** YY_ERROR_ACTION The yy_action[] code for syntax error
137193 ** YY_ACCEPT_ACTION The yy_action[] code for accept
137194 ** YY_NO_ACTION The yy_action[] code for no-op
137196 #ifndef INTERFACE
137197 # define INTERFACE 1
137198 #endif
137199 /************* Begin control #defines *****************************************/
137200 #define YYCODETYPE unsigned char
137201 #define YYNOCODE 252
137202 #define YYACTIONTYPE unsigned short int
137203 #define YYWILDCARD 83
137204 #define sqlite3ParserTOKENTYPE Token
137205 typedef union {
137206 int yyinit;
137207 sqlite3ParserTOKENTYPE yy0;
137208 Expr* yy72;
137209 TriggerStep* yy145;
137210 ExprList* yy148;
137211 SrcList* yy185;
137212 ExprSpan yy190;
137213 int yy194;
137214 Select* yy243;
137215 IdList* yy254;
137216 With* yy285;
137217 struct TrigEvent yy332;
137218 struct LimitVal yy354;
137219 struct {int value; int mask;} yy497;
137220 } YYMINORTYPE;
137221 #ifndef YYSTACKDEPTH
137222 #define YYSTACKDEPTH 100
137223 #endif
137224 #define sqlite3ParserARG_SDECL Parse *pParse;
137225 #define sqlite3ParserARG_PDECL ,Parse *pParse
137226 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
137227 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
137228 #define YYFALLBACK 1
137229 #define YYNSTATE 455
137230 #define YYNRULE 329
137231 #define YY_MAX_SHIFT 454
137232 #define YY_MIN_SHIFTREDUCE 664
137233 #define YY_MAX_SHIFTREDUCE 992
137234 #define YY_MIN_REDUCE 993
137235 #define YY_MAX_REDUCE 1321
137236 #define YY_ERROR_ACTION 1322
137237 #define YY_ACCEPT_ACTION 1323
137238 #define YY_NO_ACTION 1324
137239 /************* End control #defines *******************************************/
137241 /* Define the yytestcase() macro to be a no-op if is not already defined
137242 ** otherwise.
137244 ** Applications can choose to define yytestcase() in the %include section
137245 ** to a macro that can assist in verifying code coverage. For production
137246 ** code the yytestcase() macro should be turned off. But it is useful
137247 ** for testing.
137249 #ifndef yytestcase
137250 # define yytestcase(X)
137251 #endif
137254 /* Next are the tables used to determine what action to take based on the
137255 ** current state and lookahead token. These tables are used to implement
137256 ** functions that take a state number and lookahead value and return an
137257 ** action integer.
137259 ** Suppose the action integer is N. Then the action is determined as
137260 ** follows
137262 ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
137263 ** token onto the stack and goto state N.
137265 ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
137266 ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
137268 ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
137269 ** and YY_MAX_REDUCE
137271 ** N == YY_ERROR_ACTION A syntax error has occurred.
137273 ** N == YY_ACCEPT_ACTION The parser accepts its input.
137275 ** N == YY_NO_ACTION No such action. Denotes unused
137276 ** slots in the yy_action[] table.
137278 ** The action table is constructed as a single large table named yy_action[].
137279 ** Given state S and lookahead X, the action is computed as either:
137281 ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
137282 ** (B) N = yy_default[S]
137284 ** The (A) formula is preferred. The B formula is used instead if:
137285 ** (1) The yy_shift_ofst[S]+X value is out of range, or
137286 ** (2) yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or
137287 ** (3) yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT.
137288 ** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that
137289 ** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
137290 ** Hence only tests (1) and (2) need to be evaluated.)
137292 ** The formulas above are for computing the action when the lookahead is
137293 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
137294 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
137295 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
137296 ** YY_SHIFT_USE_DFLT.
137298 ** The following are the tables generated in this section:
137300 ** yy_action[] A single table containing all actions.
137301 ** yy_lookahead[] A table containing the lookahead for each entry in
137302 ** yy_action. Used to detect hash collisions.
137303 ** yy_shift_ofst[] For each state, the offset into yy_action for
137304 ** shifting terminals.
137305 ** yy_reduce_ofst[] For each state, the offset into yy_action for
137306 ** shifting non-terminals after a reduce.
137307 ** yy_default[] Default action for each state.
137309 *********** Begin parsing tables **********************************************/
137310 #define YY_ACTTAB_COUNT (1566)
137311 static const YYACTIONTYPE yy_action[] = {
137312 /* 0 */ 324, 1323, 155, 155, 2, 203, 94, 94, 94, 93,
137313 /* 10 */ 350, 98, 98, 98, 98, 91, 95, 95, 94, 94,
137314 /* 20 */ 94, 93, 350, 268, 99, 100, 90, 971, 971, 847,
137315 /* 30 */ 850, 839, 839, 97, 97, 98, 98, 98, 98, 350,
137316 /* 40 */ 969, 96, 96, 96, 96, 95, 95, 94, 94, 94,
137317 /* 50 */ 93, 350, 950, 96, 96, 96, 96, 95, 95, 94,
137318 /* 60 */ 94, 94, 93, 350, 250, 96, 96, 96, 96, 95,
137319 /* 70 */ 95, 94, 94, 94, 93, 350, 224, 224, 969, 132,
137320 /* 80 */ 888, 348, 347, 415, 172, 324, 1286, 449, 414, 950,
137321 /* 90 */ 951, 952, 808, 977, 1032, 950, 300, 786, 428, 132,
137322 /* 100 */ 975, 362, 976, 9, 9, 787, 132, 52, 52, 99,
137323 /* 110 */ 100, 90, 971, 971, 847, 850, 839, 839, 97, 97,
137324 /* 120 */ 98, 98, 98, 98, 372, 978, 241, 978, 262, 369,
137325 /* 130 */ 261, 120, 950, 951, 952, 194, 58, 324, 401, 398,
137326 /* 140 */ 397, 808, 427, 429, 75, 808, 1260, 1260, 132, 396,
137327 /* 150 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
137328 /* 160 */ 350, 99, 100, 90, 971, 971, 847, 850, 839, 839,
137329 /* 170 */ 97, 97, 98, 98, 98, 98, 786, 262, 369, 261,
137330 /* 180 */ 826, 262, 364, 251, 787, 1084, 101, 1114, 72, 324,
137331 /* 190 */ 227, 1113, 242, 411, 442, 819, 92, 89, 178, 818,
137332 /* 200 */ 1022, 268, 96, 96, 96, 96, 95, 95, 94, 94,
137333 /* 210 */ 94, 93, 350, 99, 100, 90, 971, 971, 847, 850,
137334 /* 220 */ 839, 839, 97, 97, 98, 98, 98, 98, 449, 372,
137335 /* 230 */ 818, 818, 820, 92, 89, 178, 60, 92, 89, 178,
137336 /* 240 */ 1025, 324, 357, 930, 1316, 300, 61, 1316, 52, 52,
137337 /* 250 */ 836, 836, 848, 851, 96, 96, 96, 96, 95, 95,
137338 /* 260 */ 94, 94, 94, 93, 350, 99, 100, 90, 971, 971,
137339 /* 270 */ 847, 850, 839, 839, 97, 97, 98, 98, 98, 98,
137340 /* 280 */ 92, 89, 178, 427, 412, 198, 930, 1317, 454, 995,
137341 /* 290 */ 1317, 355, 1024, 324, 243, 231, 114, 277, 348, 347,
137342 /* 300 */ 1242, 950, 416, 1071, 928, 840, 96, 96, 96, 96,
137343 /* 310 */ 95, 95, 94, 94, 94, 93, 350, 99, 100, 90,
137344 /* 320 */ 971, 971, 847, 850, 839, 839, 97, 97, 98, 98,
137345 /* 330 */ 98, 98, 449, 328, 449, 120, 23, 256, 950, 951,
137346 /* 340 */ 952, 968, 978, 438, 978, 324, 329, 928, 954, 701,
137347 /* 350 */ 200, 175, 52, 52, 52, 52, 939, 353, 96, 96,
137348 /* 360 */ 96, 96, 95, 95, 94, 94, 94, 93, 350, 99,
137349 /* 370 */ 100, 90, 971, 971, 847, 850, 839, 839, 97, 97,
137350 /* 380 */ 98, 98, 98, 98, 354, 449, 954, 427, 417, 427,
137351 /* 390 */ 426, 1290, 92, 89, 178, 268, 253, 324, 255, 1058,
137352 /* 400 */ 1037, 694, 93, 350, 383, 52, 52, 380, 1058, 374,
137353 /* 410 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
137354 /* 420 */ 350, 99, 100, 90, 971, 971, 847, 850, 839, 839,
137355 /* 430 */ 97, 97, 98, 98, 98, 98, 228, 449, 167, 449,
137356 /* 440 */ 427, 407, 157, 446, 446, 446, 349, 349, 349, 324,
137357 /* 450 */ 310, 316, 991, 827, 320, 242, 411, 51, 51, 36,
137358 /* 460 */ 36, 254, 96, 96, 96, 96, 95, 95, 94, 94,
137359 /* 470 */ 94, 93, 350, 99, 100, 90, 971, 971, 847, 850,
137360 /* 480 */ 839, 839, 97, 97, 98, 98, 98, 98, 194, 316,
137361 /* 490 */ 929, 401, 398, 397, 224, 224, 1265, 939, 353, 1318,
137362 /* 500 */ 317, 324, 396, 1063, 1063, 813, 414, 1061, 1061, 950,
137363 /* 510 */ 299, 448, 992, 268, 96, 96, 96, 96, 95, 95,
137364 /* 520 */ 94, 94, 94, 93, 350, 99, 100, 90, 971, 971,
137365 /* 530 */ 847, 850, 839, 839, 97, 97, 98, 98, 98, 98,
137366 /* 540 */ 757, 1041, 449, 893, 893, 386, 950, 951, 952, 410,
137367 /* 550 */ 992, 747, 747, 324, 229, 268, 221, 296, 268, 771,
137368 /* 560 */ 890, 378, 52, 52, 890, 421, 96, 96, 96, 96,
137369 /* 570 */ 95, 95, 94, 94, 94, 93, 350, 99, 100, 90,
137370 /* 580 */ 971, 971, 847, 850, 839, 839, 97, 97, 98, 98,
137371 /* 590 */ 98, 98, 103, 449, 275, 384, 1241, 343, 157, 1207,
137372 /* 600 */ 909, 669, 670, 671, 176, 197, 196, 195, 324, 298,
137373 /* 610 */ 319, 1266, 2, 37, 37, 910, 1134, 1040, 96, 96,
137374 /* 620 */ 96, 96, 95, 95, 94, 94, 94, 93, 350, 697,
137375 /* 630 */ 911, 177, 99, 100, 90, 971, 971, 847, 850, 839,
137376 /* 640 */ 839, 97, 97, 98, 98, 98, 98, 230, 146, 120,
137377 /* 650 */ 735, 1235, 826, 270, 1141, 273, 1141, 771, 171, 170,
137378 /* 660 */ 736, 1141, 82, 324, 80, 268, 697, 819, 158, 268,
137379 /* 670 */ 378, 818, 78, 96, 96, 96, 96, 95, 95, 94,
137380 /* 680 */ 94, 94, 93, 350, 120, 950, 393, 99, 100, 90,
137381 /* 690 */ 971, 971, 847, 850, 839, 839, 97, 97, 98, 98,
137382 /* 700 */ 98, 98, 818, 818, 820, 1141, 1070, 370, 331, 133,
137383 /* 710 */ 1066, 1141, 1250, 198, 268, 324, 1016, 330, 245, 333,
137384 /* 720 */ 24, 334, 950, 951, 952, 368, 335, 81, 96, 96,
137385 /* 730 */ 96, 96, 95, 95, 94, 94, 94, 93, 350, 99,
137386 /* 740 */ 100, 90, 971, 971, 847, 850, 839, 839, 97, 97,
137387 /* 750 */ 98, 98, 98, 98, 132, 267, 260, 445, 330, 223,
137388 /* 760 */ 175, 1289, 925, 752, 724, 318, 1073, 324, 751, 246,
137389 /* 770 */ 385, 301, 301, 378, 329, 361, 344, 414, 1233, 280,
137390 /* 780 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
137391 /* 790 */ 350, 99, 88, 90, 971, 971, 847, 850, 839, 839,
137392 /* 800 */ 97, 97, 98, 98, 98, 98, 337, 346, 721, 722,
137393 /* 810 */ 449, 120, 118, 887, 162, 887, 810, 371, 324, 202,
137394 /* 820 */ 202, 373, 249, 263, 202, 394, 74, 704, 208, 1069,
137395 /* 830 */ 12, 12, 96, 96, 96, 96, 95, 95, 94, 94,
137396 /* 840 */ 94, 93, 350, 100, 90, 971, 971, 847, 850, 839,
137397 /* 850 */ 839, 97, 97, 98, 98, 98, 98, 449, 771, 232,
137398 /* 860 */ 449, 278, 120, 286, 74, 704, 714, 713, 324, 342,
137399 /* 870 */ 749, 877, 1209, 77, 285, 1255, 780, 52, 52, 202,
137400 /* 880 */ 27, 27, 418, 96, 96, 96, 96, 95, 95, 94,
137401 /* 890 */ 94, 94, 93, 350, 90, 971, 971, 847, 850, 839,
137402 /* 900 */ 839, 97, 97, 98, 98, 98, 98, 86, 444, 877,
137403 /* 910 */ 3, 1193, 422, 1013, 873, 435, 886, 208, 886, 689,
137404 /* 920 */ 1091, 257, 116, 822, 447, 1230, 117, 1229, 86, 444,
137405 /* 930 */ 177, 3, 381, 96, 96, 96, 96, 95, 95, 94,
137406 /* 940 */ 94, 94, 93, 350, 339, 447, 120, 351, 120, 212,
137407 /* 950 */ 169, 287, 404, 282, 403, 199, 771, 950, 433, 419,
137408 /* 960 */ 439, 822, 280, 691, 1039, 264, 269, 132, 351, 153,
137409 /* 970 */ 826, 376, 74, 272, 274, 276, 83, 84, 1054, 433,
137410 /* 980 */ 147, 1038, 443, 85, 351, 451, 450, 281, 132, 818,
137411 /* 990 */ 25, 826, 449, 120, 950, 951, 952, 83, 84, 86,
137412 /* 1000 */ 444, 691, 3, 408, 85, 351, 451, 450, 449, 5,
137413 /* 1010 */ 818, 203, 32, 32, 1107, 120, 447, 950, 225, 1140,
137414 /* 1020 */ 818, 818, 820, 821, 19, 203, 226, 950, 38, 38,
137415 /* 1030 */ 1087, 314, 314, 313, 215, 311, 120, 449, 678, 351,
137416 /* 1040 */ 237, 818, 818, 820, 821, 19, 969, 409, 377, 1,
137417 /* 1050 */ 433, 180, 706, 248, 950, 951, 952, 10, 10, 449,
137418 /* 1060 */ 969, 247, 826, 1098, 950, 951, 952, 430, 83, 84,
137419 /* 1070 */ 756, 336, 950, 20, 431, 85, 351, 451, 450, 10,
137420 /* 1080 */ 10, 818, 86, 444, 969, 3, 950, 449, 302, 303,
137421 /* 1090 */ 182, 950, 1146, 338, 1021, 1015, 1004, 183, 969, 447,
137422 /* 1100 */ 132, 181, 76, 444, 21, 3, 449, 10, 10, 950,
137423 /* 1110 */ 951, 952, 818, 818, 820, 821, 19, 715, 1279, 447,
137424 /* 1120 */ 389, 233, 351, 950, 951, 952, 10, 10, 950, 951,
137425 /* 1130 */ 952, 1003, 218, 433, 1005, 325, 1273, 773, 289, 291,
137426 /* 1140 */ 424, 293, 351, 7, 159, 826, 363, 402, 315, 360,
137427 /* 1150 */ 1129, 83, 84, 433, 1232, 716, 772, 259, 85, 351,
137428 /* 1160 */ 451, 450, 358, 375, 818, 826, 360, 359, 399, 1211,
137429 /* 1170 */ 157, 83, 84, 681, 98, 98, 98, 98, 85, 351,
137430 /* 1180 */ 451, 450, 323, 252, 818, 295, 1211, 1213, 1235, 173,
137431 /* 1190 */ 1037, 284, 434, 340, 1204, 818, 818, 820, 821, 19,
137432 /* 1200 */ 308, 234, 449, 234, 96, 96, 96, 96, 95, 95,
137433 /* 1210 */ 94, 94, 94, 93, 350, 818, 818, 820, 821, 19,
137434 /* 1220 */ 909, 120, 39, 39, 1203, 449, 168, 360, 449, 1276,
137435 /* 1230 */ 367, 449, 135, 449, 986, 910, 449, 1249, 449, 1247,
137436 /* 1240 */ 449, 205, 983, 449, 370, 40, 40, 1211, 41, 41,
137437 /* 1250 */ 911, 42, 42, 28, 28, 870, 29, 29, 31, 31,
137438 /* 1260 */ 43, 43, 379, 44, 44, 449, 59, 449, 332, 449,
137439 /* 1270 */ 432, 62, 144, 156, 449, 130, 449, 72, 449, 137,
137440 /* 1280 */ 449, 365, 449, 392, 139, 45, 45, 11, 11, 46,
137441 /* 1290 */ 46, 140, 1200, 449, 105, 105, 47, 47, 48, 48,
137442 /* 1300 */ 33, 33, 49, 49, 1126, 449, 141, 366, 449, 185,
137443 /* 1310 */ 142, 449, 1234, 50, 50, 449, 160, 449, 148, 449,
137444 /* 1320 */ 1136, 382, 449, 67, 449, 34, 34, 449, 122, 122,
137445 /* 1330 */ 449, 123, 123, 449, 1198, 124, 124, 56, 56, 35,
137446 /* 1340 */ 35, 449, 106, 106, 53, 53, 449, 107, 107, 449,
137447 /* 1350 */ 108, 108, 449, 104, 104, 449, 406, 449, 388, 449,
137448 /* 1360 */ 189, 121, 121, 449, 190, 449, 119, 119, 449, 112,
137449 /* 1370 */ 112, 449, 111, 111, 1218, 109, 109, 110, 110, 55,
137450 /* 1380 */ 55, 266, 752, 57, 57, 54, 54, 751, 26, 26,
137451 /* 1390 */ 1099, 30, 30, 219, 154, 390, 271, 191, 321, 1006,
137452 /* 1400 */ 192, 405, 1057, 1056, 1055, 341, 1048, 706, 1047, 1029,
137453 /* 1410 */ 322, 420, 1028, 71, 1095, 283, 288, 1027, 1288, 204,
137454 /* 1420 */ 6, 297, 79, 1184, 437, 1096, 1094, 290, 345, 292,
137455 /* 1430 */ 441, 1093, 294, 102, 425, 73, 423, 213, 1012, 22,
137456 /* 1440 */ 452, 945, 214, 1077, 216, 217, 238, 453, 306, 304,
137457 /* 1450 */ 307, 239, 240, 1001, 305, 125, 996, 126, 115, 235,
137458 /* 1460 */ 127, 665, 352, 166, 244, 179, 356, 113, 885, 883,
137459 /* 1470 */ 806, 136, 128, 738, 326, 138, 327, 258, 184, 899,
137460 /* 1480 */ 143, 129, 145, 63, 64, 65, 66, 902, 186, 187,
137461 /* 1490 */ 898, 8, 13, 188, 134, 265, 891, 202, 980, 387,
137462 /* 1500 */ 150, 149, 680, 161, 391, 193, 285, 279, 395, 151,
137463 /* 1510 */ 68, 717, 14, 15, 400, 69, 16, 131, 236, 825,
137464 /* 1520 */ 824, 853, 746, 750, 4, 70, 174, 413, 220, 222,
137465 /* 1530 */ 152, 779, 774, 77, 868, 74, 854, 201, 17, 852,
137466 /* 1540 */ 908, 206, 907, 207, 18, 857, 934, 163, 436, 210,
137467 /* 1550 */ 935, 164, 209, 165, 440, 856, 823, 312, 690, 87,
137468 /* 1560 */ 211, 309, 1281, 940, 995, 1280,
137470 static const YYCODETYPE yy_lookahead[] = {
137471 /* 0 */ 19, 144, 145, 146, 147, 24, 90, 91, 92, 93,
137472 /* 10 */ 94, 54, 55, 56, 57, 58, 88, 89, 90, 91,
137473 /* 20 */ 92, 93, 94, 152, 43, 44, 45, 46, 47, 48,
137474 /* 30 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 94,
137475 /* 40 */ 59, 84, 85, 86, 87, 88, 89, 90, 91, 92,
137476 /* 50 */ 93, 94, 59, 84, 85, 86, 87, 88, 89, 90,
137477 /* 60 */ 91, 92, 93, 94, 193, 84, 85, 86, 87, 88,
137478 /* 70 */ 89, 90, 91, 92, 93, 94, 194, 195, 97, 79,
137479 /* 80 */ 11, 88, 89, 152, 26, 19, 171, 152, 206, 96,
137480 /* 90 */ 97, 98, 72, 100, 179, 59, 152, 31, 163, 79,
137481 /* 100 */ 107, 219, 109, 172, 173, 39, 79, 172, 173, 43,
137482 /* 110 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
137483 /* 120 */ 54, 55, 56, 57, 152, 132, 199, 134, 108, 109,
137484 /* 130 */ 110, 196, 96, 97, 98, 99, 209, 19, 102, 103,
137485 /* 140 */ 104, 72, 207, 208, 26, 72, 119, 120, 79, 113,
137486 /* 150 */ 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
137487 /* 160 */ 94, 43, 44, 45, 46, 47, 48, 49, 50, 51,
137488 /* 170 */ 52, 53, 54, 55, 56, 57, 31, 108, 109, 110,
137489 /* 180 */ 82, 108, 109, 110, 39, 210, 68, 175, 130, 19,
137490 /* 190 */ 218, 175, 119, 120, 250, 97, 221, 222, 223, 101,
137491 /* 200 */ 172, 152, 84, 85, 86, 87, 88, 89, 90, 91,
137492 /* 210 */ 92, 93, 94, 43, 44, 45, 46, 47, 48, 49,
137493 /* 220 */ 50, 51, 52, 53, 54, 55, 56, 57, 152, 152,
137494 /* 230 */ 132, 133, 134, 221, 222, 223, 66, 221, 222, 223,
137495 /* 240 */ 172, 19, 193, 22, 23, 152, 24, 26, 172, 173,
137496 /* 250 */ 46, 47, 48, 49, 84, 85, 86, 87, 88, 89,
137497 /* 260 */ 90, 91, 92, 93, 94, 43, 44, 45, 46, 47,
137498 /* 270 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
137499 /* 280 */ 221, 222, 223, 207, 208, 46, 22, 23, 148, 149,
137500 /* 290 */ 26, 242, 172, 19, 154, 218, 156, 23, 88, 89,
137501 /* 300 */ 241, 59, 163, 163, 83, 101, 84, 85, 86, 87,
137502 /* 310 */ 88, 89, 90, 91, 92, 93, 94, 43, 44, 45,
137503 /* 320 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
137504 /* 330 */ 56, 57, 152, 157, 152, 196, 196, 16, 96, 97,
137505 /* 340 */ 98, 26, 132, 250, 134, 19, 107, 83, 59, 23,
137506 /* 350 */ 211, 212, 172, 173, 172, 173, 1, 2, 84, 85,
137507 /* 360 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 43,
137508 /* 370 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
137509 /* 380 */ 54, 55, 56, 57, 244, 152, 97, 207, 208, 207,
137510 /* 390 */ 208, 185, 221, 222, 223, 152, 75, 19, 77, 179,
137511 /* 400 */ 180, 23, 93, 94, 228, 172, 173, 231, 188, 152,
137512 /* 410 */ 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
137513 /* 420 */ 94, 43, 44, 45, 46, 47, 48, 49, 50, 51,
137514 /* 430 */ 52, 53, 54, 55, 56, 57, 193, 152, 123, 152,
137515 /* 440 */ 207, 208, 152, 168, 169, 170, 168, 169, 170, 19,
137516 /* 450 */ 160, 22, 23, 23, 164, 119, 120, 172, 173, 172,
137517 /* 460 */ 173, 140, 84, 85, 86, 87, 88, 89, 90, 91,
137518 /* 470 */ 92, 93, 94, 43, 44, 45, 46, 47, 48, 49,
137519 /* 480 */ 50, 51, 52, 53, 54, 55, 56, 57, 99, 22,
137520 /* 490 */ 23, 102, 103, 104, 194, 195, 0, 1, 2, 247,
137521 /* 500 */ 248, 19, 113, 190, 191, 23, 206, 190, 191, 59,
137522 /* 510 */ 225, 152, 83, 152, 84, 85, 86, 87, 88, 89,
137523 /* 520 */ 90, 91, 92, 93, 94, 43, 44, 45, 46, 47,
137524 /* 530 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
137525 /* 540 */ 90, 181, 152, 108, 109, 110, 96, 97, 98, 115,
137526 /* 550 */ 83, 117, 118, 19, 193, 152, 23, 152, 152, 26,
137527 /* 560 */ 29, 152, 172, 173, 33, 152, 84, 85, 86, 87,
137528 /* 570 */ 88, 89, 90, 91, 92, 93, 94, 43, 44, 45,
137529 /* 580 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
137530 /* 590 */ 56, 57, 22, 152, 16, 64, 193, 207, 152, 193,
137531 /* 600 */ 12, 7, 8, 9, 152, 108, 109, 110, 19, 152,
137532 /* 610 */ 164, 146, 147, 172, 173, 27, 163, 181, 84, 85,
137533 /* 620 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 59,
137534 /* 630 */ 42, 98, 43, 44, 45, 46, 47, 48, 49, 50,
137535 /* 640 */ 51, 52, 53, 54, 55, 56, 57, 238, 22, 196,
137536 /* 650 */ 62, 163, 82, 75, 152, 77, 152, 124, 88, 89,
137537 /* 660 */ 72, 152, 137, 19, 139, 152, 96, 97, 24, 152,
137538 /* 670 */ 152, 101, 138, 84, 85, 86, 87, 88, 89, 90,
137539 /* 680 */ 91, 92, 93, 94, 196, 59, 19, 43, 44, 45,
137540 /* 690 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
137541 /* 700 */ 56, 57, 132, 133, 134, 152, 193, 219, 245, 246,
137542 /* 710 */ 193, 152, 152, 46, 152, 19, 166, 167, 152, 217,
137543 /* 720 */ 232, 217, 96, 97, 98, 237, 217, 138, 84, 85,
137544 /* 730 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 43,
137545 /* 740 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
137546 /* 750 */ 54, 55, 56, 57, 79, 193, 238, 166, 167, 211,
137547 /* 760 */ 212, 23, 23, 116, 26, 26, 195, 19, 121, 152,
137548 /* 770 */ 217, 152, 152, 152, 107, 100, 217, 206, 163, 112,
137549 /* 780 */ 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
137550 /* 790 */ 94, 43, 44, 45, 46, 47, 48, 49, 50, 51,
137551 /* 800 */ 52, 53, 54, 55, 56, 57, 187, 187, 7, 8,
137552 /* 810 */ 152, 196, 22, 132, 24, 134, 23, 23, 19, 26,
137553 /* 820 */ 26, 23, 152, 23, 26, 23, 26, 59, 26, 163,
137554 /* 830 */ 172, 173, 84, 85, 86, 87, 88, 89, 90, 91,
137555 /* 840 */ 92, 93, 94, 44, 45, 46, 47, 48, 49, 50,
137556 /* 850 */ 51, 52, 53, 54, 55, 56, 57, 152, 26, 238,
137557 /* 860 */ 152, 23, 196, 101, 26, 97, 100, 101, 19, 19,
137558 /* 870 */ 23, 59, 152, 26, 112, 152, 23, 172, 173, 26,
137559 /* 880 */ 172, 173, 19, 84, 85, 86, 87, 88, 89, 90,
137560 /* 890 */ 91, 92, 93, 94, 45, 46, 47, 48, 49, 50,
137561 /* 900 */ 51, 52, 53, 54, 55, 56, 57, 19, 20, 97,
137562 /* 910 */ 22, 23, 207, 163, 23, 163, 132, 26, 134, 23,
137563 /* 920 */ 213, 152, 26, 59, 36, 152, 22, 152, 19, 20,
137564 /* 930 */ 98, 22, 152, 84, 85, 86, 87, 88, 89, 90,
137565 /* 940 */ 91, 92, 93, 94, 94, 36, 196, 59, 196, 99,
137566 /* 950 */ 100, 101, 102, 103, 104, 105, 124, 59, 70, 96,
137567 /* 960 */ 163, 97, 112, 59, 181, 152, 152, 79, 59, 71,
137568 /* 970 */ 82, 19, 26, 152, 152, 152, 88, 89, 152, 70,
137569 /* 980 */ 22, 152, 163, 95, 96, 97, 98, 152, 79, 101,
137570 /* 990 */ 22, 82, 152, 196, 96, 97, 98, 88, 89, 19,
137571 /* 1000 */ 20, 97, 22, 163, 95, 96, 97, 98, 152, 22,
137572 /* 1010 */ 101, 24, 172, 173, 152, 196, 36, 59, 22, 152,
137573 /* 1020 */ 132, 133, 134, 135, 136, 24, 5, 59, 172, 173,
137574 /* 1030 */ 152, 10, 11, 12, 13, 14, 196, 152, 17, 59,
137575 /* 1040 */ 210, 132, 133, 134, 135, 136, 59, 207, 96, 22,
137576 /* 1050 */ 70, 30, 106, 32, 96, 97, 98, 172, 173, 152,
137577 /* 1060 */ 59, 40, 82, 152, 96, 97, 98, 152, 88, 89,
137578 /* 1070 */ 90, 186, 59, 22, 191, 95, 96, 97, 98, 172,
137579 /* 1080 */ 173, 101, 19, 20, 97, 22, 59, 152, 152, 152,
137580 /* 1090 */ 69, 59, 152, 186, 152, 152, 152, 76, 97, 36,
137581 /* 1100 */ 79, 80, 19, 20, 53, 22, 152, 172, 173, 96,
137582 /* 1110 */ 97, 98, 132, 133, 134, 135, 136, 35, 122, 36,
137583 /* 1120 */ 234, 186, 59, 96, 97, 98, 172, 173, 96, 97,
137584 /* 1130 */ 98, 152, 233, 70, 152, 114, 152, 124, 210, 210,
137585 /* 1140 */ 186, 210, 59, 198, 197, 82, 214, 65, 150, 152,
137586 /* 1150 */ 201, 88, 89, 70, 201, 73, 124, 239, 95, 96,
137587 /* 1160 */ 97, 98, 141, 239, 101, 82, 169, 170, 176, 152,
137588 /* 1170 */ 152, 88, 89, 21, 54, 55, 56, 57, 95, 96,
137589 /* 1180 */ 97, 98, 164, 214, 101, 214, 169, 170, 163, 184,
137590 /* 1190 */ 180, 175, 227, 111, 175, 132, 133, 134, 135, 136,
137591 /* 1200 */ 200, 183, 152, 185, 84, 85, 86, 87, 88, 89,
137592 /* 1210 */ 90, 91, 92, 93, 94, 132, 133, 134, 135, 136,
137593 /* 1220 */ 12, 196, 172, 173, 175, 152, 198, 230, 152, 155,
137594 /* 1230 */ 78, 152, 243, 152, 60, 27, 152, 159, 152, 159,
137595 /* 1240 */ 152, 122, 38, 152, 219, 172, 173, 230, 172, 173,
137596 /* 1250 */ 42, 172, 173, 172, 173, 103, 172, 173, 172, 173,
137597 /* 1260 */ 172, 173, 237, 172, 173, 152, 240, 152, 159, 152,
137598 /* 1270 */ 62, 240, 22, 220, 152, 43, 152, 130, 152, 189,
137599 /* 1280 */ 152, 18, 152, 18, 192, 172, 173, 172, 173, 172,
137600 /* 1290 */ 173, 192, 140, 152, 172, 173, 172, 173, 172, 173,
137601 /* 1300 */ 172, 173, 172, 173, 201, 152, 192, 159, 152, 158,
137602 /* 1310 */ 192, 152, 201, 172, 173, 152, 220, 152, 189, 152,
137603 /* 1320 */ 189, 159, 152, 137, 152, 172, 173, 152, 172, 173,
137604 /* 1330 */ 152, 172, 173, 152, 201, 172, 173, 172, 173, 172,
137605 /* 1340 */ 173, 152, 172, 173, 172, 173, 152, 172, 173, 152,
137606 /* 1350 */ 172, 173, 152, 172, 173, 152, 90, 152, 61, 152,
137607 /* 1360 */ 158, 172, 173, 152, 158, 152, 172, 173, 152, 172,
137608 /* 1370 */ 173, 152, 172, 173, 236, 172, 173, 172, 173, 172,
137609 /* 1380 */ 173, 235, 116, 172, 173, 172, 173, 121, 172, 173,
137610 /* 1390 */ 159, 172, 173, 159, 22, 177, 159, 158, 177, 159,
137611 /* 1400 */ 158, 107, 174, 174, 174, 63, 182, 106, 182, 174,
137612 /* 1410 */ 177, 125, 176, 107, 216, 174, 215, 174, 174, 159,
137613 /* 1420 */ 22, 159, 137, 224, 177, 216, 216, 215, 94, 215,
137614 /* 1430 */ 177, 216, 215, 129, 126, 128, 127, 25, 162, 26,
137615 /* 1440 */ 161, 13, 153, 205, 153, 6, 226, 151, 202, 204,
137616 /* 1450 */ 201, 229, 229, 151, 203, 165, 151, 165, 178, 178,
137617 /* 1460 */ 165, 4, 3, 22, 142, 15, 81, 16, 23, 23,
137618 /* 1470 */ 120, 131, 111, 20, 249, 123, 249, 16, 125, 1,
137619 /* 1480 */ 123, 111, 131, 53, 53, 53, 53, 96, 34, 122,
137620 /* 1490 */ 1, 5, 22, 107, 246, 140, 67, 26, 74, 41,
137621 /* 1500 */ 107, 67, 20, 24, 19, 105, 112, 23, 66, 22,
137622 /* 1510 */ 22, 28, 22, 22, 66, 22, 22, 37, 66, 23,
137623 /* 1520 */ 23, 23, 116, 23, 22, 26, 122, 26, 23, 23,
137624 /* 1530 */ 22, 96, 124, 26, 23, 26, 23, 34, 34, 23,
137625 /* 1540 */ 23, 26, 23, 22, 34, 11, 23, 22, 24, 122,
137626 /* 1550 */ 23, 22, 26, 22, 24, 23, 23, 15, 23, 22,
137627 /* 1560 */ 122, 23, 122, 1, 251, 122,
137629 #define YY_SHIFT_USE_DFLT (1566)
137630 #define YY_SHIFT_COUNT (454)
137631 #define YY_SHIFT_MIN (-84)
137632 #define YY_SHIFT_MAX (1562)
137633 static const short yy_shift_ofst[] = {
137634 /* 0 */ 355, 888, 1021, 909, 1063, 1063, 1063, 1063, 20, -19,
137635 /* 10 */ 66, 66, 170, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
137636 /* 20 */ -7, -7, 36, 73, 69, 27, 118, 222, 274, 326,
137637 /* 30 */ 378, 430, 482, 534, 589, 644, 696, 696, 696, 696,
137638 /* 40 */ 696, 696, 696, 696, 696, 696, 696, 696, 696, 696,
137639 /* 50 */ 696, 696, 696, 748, 696, 799, 849, 849, 980, 1063,
137640 /* 60 */ 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
137641 /* 70 */ 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
137642 /* 80 */ 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
137643 /* 90 */ 1083, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063,
137644 /* 100 */ 1063, 1063, 1063, 1063, -43, 1120, 1120, 1120, 1120, 1120,
137645 /* 110 */ -31, -72, -84, 242, 1152, 667, 210, 210, 242, 309,
137646 /* 120 */ 336, -55, 1566, 1566, 1566, 850, 850, 850, 626, 626,
137647 /* 130 */ 588, 588, 898, 221, 264, 242, 242, 242, 242, 242,
137648 /* 140 */ 242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
137649 /* 150 */ 242, 242, 242, 242, 242, 496, 675, 289, 289, 336,
137650 /* 160 */ 0, 0, 0, 0, 0, 0, 1566, 1566, 1566, 570,
137651 /* 170 */ 98, 98, 958, 389, 450, 968, 1013, 1032, 1027, 242,
137652 /* 180 */ 242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
137653 /* 190 */ 242, 242, 242, 242, 242, 1082, 1082, 1082, 242, 242,
137654 /* 200 */ 533, 242, 242, 242, 987, 242, 242, 1208, 242, 242,
137655 /* 210 */ 242, 242, 242, 242, 242, 242, 242, 242, 435, 531,
137656 /* 220 */ 1001, 1001, 1001, 832, 434, 1266, 594, 58, 863, 863,
137657 /* 230 */ 952, 58, 952, 946, 738, 239, 145, 863, 525, 145,
137658 /* 240 */ 145, 315, 647, 790, 1174, 1119, 1119, 1204, 1204, 1119,
137659 /* 250 */ 1250, 1232, 1147, 1263, 1263, 1263, 1263, 1119, 1265, 1147,
137660 /* 260 */ 1250, 1232, 1232, 1147, 1119, 1265, 1186, 1297, 1119, 1119,
137661 /* 270 */ 1265, 1372, 1119, 1265, 1119, 1265, 1372, 1294, 1294, 1294,
137662 /* 280 */ 1342, 1372, 1294, 1301, 1294, 1342, 1294, 1294, 1286, 1306,
137663 /* 290 */ 1286, 1306, 1286, 1306, 1286, 1306, 1119, 1398, 1119, 1285,
137664 /* 300 */ 1372, 1334, 1334, 1372, 1304, 1308, 1307, 1309, 1147, 1412,
137665 /* 310 */ 1413, 1428, 1428, 1439, 1439, 1439, 1566, 1566, 1566, 1566,
137666 /* 320 */ 1566, 1566, 1566, 1566, 204, 321, 429, 467, 578, 497,
137667 /* 330 */ 904, 739, 1051, 793, 794, 798, 800, 802, 838, 768,
137668 /* 340 */ 766, 801, 762, 847, 853, 812, 891, 681, 784, 896,
137669 /* 350 */ 864, 996, 1457, 1459, 1441, 1322, 1450, 1385, 1451, 1445,
137670 /* 360 */ 1446, 1350, 1340, 1361, 1352, 1453, 1353, 1461, 1478, 1357,
137671 /* 370 */ 1351, 1430, 1431, 1432, 1433, 1370, 1391, 1454, 1367, 1489,
137672 /* 380 */ 1486, 1470, 1386, 1355, 1429, 1471, 1434, 1424, 1458, 1393,
137673 /* 390 */ 1479, 1482, 1485, 1394, 1400, 1487, 1442, 1488, 1490, 1484,
137674 /* 400 */ 1491, 1448, 1483, 1493, 1452, 1480, 1496, 1497, 1498, 1499,
137675 /* 410 */ 1406, 1494, 1500, 1502, 1501, 1404, 1505, 1506, 1435, 1503,
137676 /* 420 */ 1508, 1408, 1507, 1504, 1509, 1510, 1511, 1507, 1513, 1516,
137677 /* 430 */ 1517, 1515, 1519, 1521, 1534, 1523, 1525, 1524, 1526, 1527,
137678 /* 440 */ 1529, 1530, 1526, 1532, 1531, 1533, 1535, 1537, 1427, 1438,
137679 /* 450 */ 1440, 1443, 1538, 1542, 1562,
137681 #define YY_REDUCE_USE_DFLT (-144)
137682 #define YY_REDUCE_COUNT (323)
137683 #define YY_REDUCE_MIN (-143)
137684 #define YY_REDUCE_MAX (1305)
137685 static const short yy_reduce_ofst[] = {
137686 /* 0 */ -143, -65, 140, 840, 76, 180, 182, 233, 488, -25,
137687 /* 10 */ 12, 16, 59, 885, 907, 935, 390, 705, 954, 285,
137688 /* 20 */ 997, 1017, 1018, -118, 1025, 139, 171, 171, 171, 171,
137689 /* 30 */ 171, 171, 171, 171, 171, 171, 171, 171, 171, 171,
137690 /* 40 */ 171, 171, 171, 171, 171, 171, 171, 171, 171, 171,
137691 /* 50 */ 171, 171, 171, 171, 171, 171, 171, 171, -69, 287,
137692 /* 60 */ 441, 658, 708, 856, 1050, 1073, 1076, 1079, 1081, 1084,
137693 /* 70 */ 1086, 1088, 1091, 1113, 1115, 1117, 1122, 1124, 1126, 1128,
137694 /* 80 */ 1130, 1141, 1153, 1156, 1159, 1163, 1165, 1167, 1170, 1172,
137695 /* 90 */ 1175, 1178, 1181, 1189, 1194, 1197, 1200, 1203, 1205, 1207,
137696 /* 100 */ 1211, 1213, 1216, 1219, 171, 171, 171, 171, 171, 171,
137697 /* 110 */ 171, 171, 171, 49, 176, 220, 275, 278, 290, 171,
137698 /* 120 */ 300, 171, 171, 171, 171, -85, -85, -85, -28, 77,
137699 /* 130 */ 313, 317, -56, 252, 252, 446, -129, 243, 361, 403,
137700 /* 140 */ 406, 513, 517, 409, 502, 518, 504, 509, 621, 553,
137701 /* 150 */ 562, 619, 559, 93, 620, 465, 453, 550, 591, 571,
137702 /* 160 */ 615, 666, 750, 752, 797, 819, 463, 548, -73, 28,
137703 /* 170 */ 68, 120, 257, 206, 359, 405, 413, 452, 457, 560,
137704 /* 180 */ 566, 617, 670, 720, 723, 769, 773, 775, 780, 813,
137705 /* 190 */ 814, 821, 822, 823, 826, 360, 436, 783, 829, 835,
137706 /* 200 */ 707, 862, 867, 878, 830, 911, 915, 883, 936, 937,
137707 /* 210 */ 940, 359, 942, 943, 944, 979, 982, 984, 886, 899,
137708 /* 220 */ 928, 929, 931, 707, 947, 945, 998, 949, 932, 969,
137709 /* 230 */ 918, 953, 924, 992, 1005, 1010, 1016, 971, 965, 1019,
137710 /* 240 */ 1049, 1000, 1028, 1074, 989, 1078, 1080, 1026, 1031, 1109,
137711 /* 250 */ 1053, 1090, 1103, 1092, 1099, 1114, 1118, 1148, 1151, 1111,
137712 /* 260 */ 1096, 1129, 1131, 1133, 1162, 1202, 1138, 1146, 1231, 1234,
137713 /* 270 */ 1206, 1218, 1237, 1239, 1240, 1242, 1221, 1228, 1229, 1230,
137714 /* 280 */ 1224, 1233, 1235, 1236, 1241, 1226, 1243, 1244, 1198, 1201,
137715 /* 290 */ 1209, 1212, 1210, 1214, 1215, 1217, 1260, 1199, 1262, 1220,
137716 /* 300 */ 1247, 1222, 1223, 1253, 1238, 1245, 1251, 1246, 1249, 1276,
137717 /* 310 */ 1279, 1289, 1291, 1296, 1302, 1305, 1225, 1227, 1248, 1290,
137718 /* 320 */ 1292, 1280, 1281, 1295,
137720 static const YYACTIONTYPE yy_default[] = {
137721 /* 0 */ 1270, 1260, 1260, 1260, 1193, 1193, 1193, 1193, 1260, 1088,
137722 /* 10 */ 1117, 1117, 1244, 1322, 1322, 1322, 1322, 1322, 1322, 1192,
137723 /* 20 */ 1322, 1322, 1322, 1322, 1260, 1092, 1123, 1322, 1322, 1322,
137724 /* 30 */ 1322, 1194, 1195, 1322, 1322, 1322, 1243, 1245, 1133, 1132,
137725 /* 40 */ 1131, 1130, 1226, 1104, 1128, 1121, 1125, 1194, 1188, 1189,
137726 /* 50 */ 1187, 1191, 1195, 1322, 1124, 1158, 1172, 1157, 1322, 1322,
137727 /* 60 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137728 /* 70 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137729 /* 80 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137730 /* 90 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137731 /* 100 */ 1322, 1322, 1322, 1322, 1166, 1171, 1178, 1170, 1167, 1160,
137732 /* 110 */ 1159, 1161, 1162, 1322, 1011, 1059, 1322, 1322, 1322, 1163,
137733 /* 120 */ 1322, 1164, 1175, 1174, 1173, 1251, 1278, 1277, 1322, 1322,
137734 /* 130 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137735 /* 140 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137736 /* 150 */ 1322, 1322, 1322, 1322, 1322, 1270, 1260, 1017, 1017, 1322,
137737 /* 160 */ 1260, 1260, 1260, 1260, 1260, 1260, 1256, 1092, 1083, 1322,
137738 /* 170 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137739 /* 180 */ 1248, 1246, 1322, 1208, 1322, 1322, 1322, 1322, 1322, 1322,
137740 /* 190 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137741 /* 200 */ 1322, 1322, 1322, 1322, 1088, 1322, 1322, 1322, 1322, 1322,
137742 /* 210 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1272, 1322, 1221,
137743 /* 220 */ 1088, 1088, 1088, 1090, 1072, 1082, 997, 1127, 1106, 1106,
137744 /* 230 */ 1311, 1127, 1311, 1034, 1292, 1031, 1117, 1106, 1190, 1117,
137745 /* 240 */ 1117, 1089, 1082, 1322, 1314, 1097, 1097, 1313, 1313, 1097,
137746 /* 250 */ 1138, 1062, 1127, 1068, 1068, 1068, 1068, 1097, 1008, 1127,
137747 /* 260 */ 1138, 1062, 1062, 1127, 1097, 1008, 1225, 1308, 1097, 1097,
137748 /* 270 */ 1008, 1201, 1097, 1008, 1097, 1008, 1201, 1060, 1060, 1060,
137749 /* 280 */ 1049, 1201, 1060, 1034, 1060, 1049, 1060, 1060, 1110, 1105,
137750 /* 290 */ 1110, 1105, 1110, 1105, 1110, 1105, 1097, 1196, 1097, 1322,
137751 /* 300 */ 1201, 1205, 1205, 1201, 1122, 1111, 1120, 1118, 1127, 1014,
137752 /* 310 */ 1052, 1275, 1275, 1271, 1271, 1271, 1319, 1319, 1256, 1287,
137753 /* 320 */ 1287, 1036, 1036, 1287, 1322, 1322, 1322, 1322, 1322, 1322,
137754 /* 330 */ 1282, 1322, 1210, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137755 /* 340 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137756 /* 350 */ 1322, 1143, 1322, 993, 1253, 1322, 1322, 1252, 1322, 1322,
137757 /* 360 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137758 /* 370 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1310, 1322,
137759 /* 380 */ 1322, 1322, 1322, 1322, 1322, 1224, 1223, 1322, 1322, 1322,
137760 /* 390 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137761 /* 400 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137762 /* 410 */ 1074, 1322, 1322, 1322, 1296, 1322, 1322, 1322, 1322, 1322,
137763 /* 420 */ 1322, 1322, 1119, 1322, 1112, 1322, 1322, 1301, 1322, 1322,
137764 /* 430 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1262, 1322,
137765 /* 440 */ 1322, 1322, 1261, 1322, 1322, 1322, 1322, 1322, 1145, 1322,
137766 /* 450 */ 1144, 1148, 1322, 1002, 1322,
137768 /********** End of lemon-generated parsing tables *****************************/
137770 /* The next table maps tokens (terminal symbols) into fallback tokens.
137771 ** If a construct like the following:
137773 ** %fallback ID X Y Z.
137775 ** appears in the grammar, then ID becomes a fallback token for X, Y,
137776 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
137777 ** but it does not parse, the type of the token is changed to ID and
137778 ** the parse is retried before an error is thrown.
137780 ** This feature can be used, for example, to cause some keywords in a language
137781 ** to revert to identifiers if they keyword does not apply in the context where
137782 ** it appears.
137784 #ifdef YYFALLBACK
137785 static const YYCODETYPE yyFallback[] = {
137786 0, /* $ => nothing */
137787 0, /* SEMI => nothing */
137788 59, /* EXPLAIN => ID */
137789 59, /* QUERY => ID */
137790 59, /* PLAN => ID */
137791 59, /* BEGIN => ID */
137792 0, /* TRANSACTION => nothing */
137793 59, /* DEFERRED => ID */
137794 59, /* IMMEDIATE => ID */
137795 59, /* EXCLUSIVE => ID */
137796 0, /* COMMIT => nothing */
137797 59, /* END => ID */
137798 59, /* ROLLBACK => ID */
137799 59, /* SAVEPOINT => ID */
137800 59, /* RELEASE => ID */
137801 0, /* TO => nothing */
137802 0, /* TABLE => nothing */
137803 0, /* CREATE => nothing */
137804 59, /* IF => ID */
137805 0, /* NOT => nothing */
137806 0, /* EXISTS => nothing */
137807 59, /* TEMP => ID */
137808 0, /* LP => nothing */
137809 0, /* RP => nothing */
137810 0, /* AS => nothing */
137811 59, /* WITHOUT => ID */
137812 0, /* COMMA => nothing */
137813 59, /* ABORT => ID */
137814 59, /* ACTION => ID */
137815 59, /* AFTER => ID */
137816 59, /* ANALYZE => ID */
137817 59, /* ASC => ID */
137818 59, /* ATTACH => ID */
137819 59, /* BEFORE => ID */
137820 59, /* BY => ID */
137821 59, /* CASCADE => ID */
137822 59, /* CAST => ID */
137823 59, /* CONFLICT => ID */
137824 59, /* DATABASE => ID */
137825 59, /* DESC => ID */
137826 59, /* DETACH => ID */
137827 59, /* EACH => ID */
137828 59, /* FAIL => ID */
137829 0, /* OR => nothing */
137830 0, /* AND => nothing */
137831 0, /* IS => nothing */
137832 59, /* MATCH => ID */
137833 59, /* LIKE_KW => ID */
137834 0, /* BETWEEN => nothing */
137835 0, /* IN => nothing */
137836 0, /* ISNULL => nothing */
137837 0, /* NOTNULL => nothing */
137838 0, /* NE => nothing */
137839 0, /* EQ => nothing */
137840 0, /* GT => nothing */
137841 0, /* LE => nothing */
137842 0, /* LT => nothing */
137843 0, /* GE => nothing */
137844 0, /* ESCAPE => nothing */
137845 0, /* ID => nothing */
137846 59, /* COLUMNKW => ID */
137847 59, /* FOR => ID */
137848 59, /* IGNORE => ID */
137849 59, /* INITIALLY => ID */
137850 59, /* INSTEAD => ID */
137851 59, /* NO => ID */
137852 59, /* KEY => ID */
137853 59, /* OF => ID */
137854 59, /* OFFSET => ID */
137855 59, /* PRAGMA => ID */
137856 59, /* RAISE => ID */
137857 59, /* RECURSIVE => ID */
137858 59, /* REPLACE => ID */
137859 59, /* RESTRICT => ID */
137860 59, /* ROW => ID */
137861 59, /* TRIGGER => ID */
137862 59, /* VACUUM => ID */
137863 59, /* VIEW => ID */
137864 59, /* VIRTUAL => ID */
137865 59, /* WITH => ID */
137866 59, /* REINDEX => ID */
137867 59, /* RENAME => ID */
137868 59, /* CTIME_KW => ID */
137870 #endif /* YYFALLBACK */
137872 /* The following structure represents a single element of the
137873 ** parser's stack. Information stored includes:
137875 ** + The state number for the parser at this level of the stack.
137877 ** + The value of the token stored at this level of the stack.
137878 ** (In other words, the "major" token.)
137880 ** + The semantic value stored at this level of the stack. This is
137881 ** the information used by the action routines in the grammar.
137882 ** It is sometimes called the "minor" token.
137884 ** After the "shift" half of a SHIFTREDUCE action, the stateno field
137885 ** actually contains the reduce action for the second half of the
137886 ** SHIFTREDUCE.
137888 struct yyStackEntry {
137889 YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
137890 YYCODETYPE major; /* The major token value. This is the code
137891 ** number for the token at this stack level */
137892 YYMINORTYPE minor; /* The user-supplied minor token value. This
137893 ** is the value of the token */
137895 typedef struct yyStackEntry yyStackEntry;
137897 /* The state of the parser is completely contained in an instance of
137898 ** the following structure */
137899 struct yyParser {
137900 yyStackEntry *yytos; /* Pointer to top element of the stack */
137901 #ifdef YYTRACKMAXSTACKDEPTH
137902 int yyhwm; /* High-water mark of the stack */
137903 #endif
137904 #ifndef YYNOERRORRECOVERY
137905 int yyerrcnt; /* Shifts left before out of the error */
137906 #endif
137907 sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
137908 #if YYSTACKDEPTH<=0
137909 int yystksz; /* Current side of the stack */
137910 yyStackEntry *yystack; /* The parser's stack */
137911 yyStackEntry yystk0; /* First stack entry */
137912 #else
137913 yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
137914 yyStackEntry *yystackEnd; /* Last entry in the stack */
137915 #endif
137917 typedef struct yyParser yyParser;
137919 #ifndef NDEBUG
137920 /* #include <stdio.h> */
137921 static FILE *yyTraceFILE = 0;
137922 static char *yyTracePrompt = 0;
137923 #endif /* NDEBUG */
137925 #ifndef NDEBUG
137927 ** Turn parser tracing on by giving a stream to which to write the trace
137928 ** and a prompt to preface each trace message. Tracing is turned off
137929 ** by making either argument NULL
137931 ** Inputs:
137932 ** <ul>
137933 ** <li> A FILE* to which trace output should be written.
137934 ** If NULL, then tracing is turned off.
137935 ** <li> A prefix string written at the beginning of every
137936 ** line of trace output. If NULL, then tracing is
137937 ** turned off.
137938 ** </ul>
137940 ** Outputs:
137941 ** None.
137943 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
137944 yyTraceFILE = TraceFILE;
137945 yyTracePrompt = zTracePrompt;
137946 if( yyTraceFILE==0 ) yyTracePrompt = 0;
137947 else if( yyTracePrompt==0 ) yyTraceFILE = 0;
137949 #endif /* NDEBUG */
137951 #ifndef NDEBUG
137952 /* For tracing shifts, the names of all terminals and nonterminals
137953 ** are required. The following table supplies these names */
137954 static const char *const yyTokenName[] = {
137955 "$", "SEMI", "EXPLAIN", "QUERY",
137956 "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
137957 "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
137958 "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
137959 "TABLE", "CREATE", "IF", "NOT",
137960 "EXISTS", "TEMP", "LP", "RP",
137961 "AS", "WITHOUT", "COMMA", "ABORT",
137962 "ACTION", "AFTER", "ANALYZE", "ASC",
137963 "ATTACH", "BEFORE", "BY", "CASCADE",
137964 "CAST", "CONFLICT", "DATABASE", "DESC",
137965 "DETACH", "EACH", "FAIL", "OR",
137966 "AND", "IS", "MATCH", "LIKE_KW",
137967 "BETWEEN", "IN", "ISNULL", "NOTNULL",
137968 "NE", "EQ", "GT", "LE",
137969 "LT", "GE", "ESCAPE", "ID",
137970 "COLUMNKW", "FOR", "IGNORE", "INITIALLY",
137971 "INSTEAD", "NO", "KEY", "OF",
137972 "OFFSET", "PRAGMA", "RAISE", "RECURSIVE",
137973 "REPLACE", "RESTRICT", "ROW", "TRIGGER",
137974 "VACUUM", "VIEW", "VIRTUAL", "WITH",
137975 "REINDEX", "RENAME", "CTIME_KW", "ANY",
137976 "BITAND", "BITOR", "LSHIFT", "RSHIFT",
137977 "PLUS", "MINUS", "STAR", "SLASH",
137978 "REM", "CONCAT", "COLLATE", "BITNOT",
137979 "INDEXED", "STRING", "JOIN_KW", "CONSTRAINT",
137980 "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
137981 "CHECK", "REFERENCES", "AUTOINCR", "ON",
137982 "INSERT", "DELETE", "UPDATE", "SET",
137983 "DEFERRABLE", "FOREIGN", "DROP", "UNION",
137984 "ALL", "EXCEPT", "INTERSECT", "SELECT",
137985 "VALUES", "DISTINCT", "DOT", "FROM",
137986 "JOIN", "USING", "ORDER", "GROUP",
137987 "HAVING", "LIMIT", "WHERE", "INTO",
137988 "FLOAT", "BLOB", "INTEGER", "VARIABLE",
137989 "CASE", "WHEN", "THEN", "ELSE",
137990 "INDEX", "ALTER", "ADD", "error",
137991 "input", "cmdlist", "ecmd", "explain",
137992 "cmdx", "cmd", "transtype", "trans_opt",
137993 "nm", "savepoint_opt", "create_table", "create_table_args",
137994 "createkw", "temp", "ifnotexists", "dbnm",
137995 "columnlist", "conslist_opt", "table_options", "select",
137996 "columnname", "carglist", "typetoken", "typename",
137997 "signed", "plus_num", "minus_num", "ccons",
137998 "term", "expr", "onconf", "sortorder",
137999 "autoinc", "eidlist_opt", "refargs", "defer_subclause",
138000 "refarg", "refact", "init_deferred_pred_opt", "conslist",
138001 "tconscomma", "tcons", "sortlist", "eidlist",
138002 "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
138003 "ifexists", "fullname", "selectnowith", "oneselect",
138004 "with", "multiselect_op", "distinct", "selcollist",
138005 "from", "where_opt", "groupby_opt", "having_opt",
138006 "orderby_opt", "limit_opt", "values", "nexprlist",
138007 "exprlist", "sclp", "as", "seltablist",
138008 "stl_prefix", "joinop", "indexed_opt", "on_opt",
138009 "using_opt", "idlist", "setlist", "insert_cmd",
138010 "idlist_opt", "likeop", "between_op", "in_op",
138011 "paren_exprlist", "case_operand", "case_exprlist", "case_else",
138012 "uniqueflag", "collate", "nmnum", "trigger_decl",
138013 "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
138014 "when_clause", "trigger_cmd", "trnm", "tridxby",
138015 "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
138016 "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
138017 "lp", "anylist", "wqlist",
138019 #endif /* NDEBUG */
138021 #ifndef NDEBUG
138022 /* For tracing reduce actions, the names of all rules are required.
138024 static const char *const yyRuleName[] = {
138025 /* 0 */ "explain ::= EXPLAIN",
138026 /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
138027 /* 2 */ "cmdx ::= cmd",
138028 /* 3 */ "cmd ::= BEGIN transtype trans_opt",
138029 /* 4 */ "transtype ::=",
138030 /* 5 */ "transtype ::= DEFERRED",
138031 /* 6 */ "transtype ::= IMMEDIATE",
138032 /* 7 */ "transtype ::= EXCLUSIVE",
138033 /* 8 */ "cmd ::= COMMIT|END trans_opt",
138034 /* 9 */ "cmd ::= ROLLBACK trans_opt",
138035 /* 10 */ "cmd ::= SAVEPOINT nm",
138036 /* 11 */ "cmd ::= RELEASE savepoint_opt nm",
138037 /* 12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
138038 /* 13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
138039 /* 14 */ "createkw ::= CREATE",
138040 /* 15 */ "ifnotexists ::=",
138041 /* 16 */ "ifnotexists ::= IF NOT EXISTS",
138042 /* 17 */ "temp ::= TEMP",
138043 /* 18 */ "temp ::=",
138044 /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
138045 /* 20 */ "create_table_args ::= AS select",
138046 /* 21 */ "table_options ::=",
138047 /* 22 */ "table_options ::= WITHOUT nm",
138048 /* 23 */ "columnname ::= nm typetoken",
138049 /* 24 */ "typetoken ::=",
138050 /* 25 */ "typetoken ::= typename LP signed RP",
138051 /* 26 */ "typetoken ::= typename LP signed COMMA signed RP",
138052 /* 27 */ "typename ::= typename ID|STRING",
138053 /* 28 */ "ccons ::= CONSTRAINT nm",
138054 /* 29 */ "ccons ::= DEFAULT term",
138055 /* 30 */ "ccons ::= DEFAULT LP expr RP",
138056 /* 31 */ "ccons ::= DEFAULT PLUS term",
138057 /* 32 */ "ccons ::= DEFAULT MINUS term",
138058 /* 33 */ "ccons ::= DEFAULT ID|INDEXED",
138059 /* 34 */ "ccons ::= NOT NULL onconf",
138060 /* 35 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
138061 /* 36 */ "ccons ::= UNIQUE onconf",
138062 /* 37 */ "ccons ::= CHECK LP expr RP",
138063 /* 38 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
138064 /* 39 */ "ccons ::= defer_subclause",
138065 /* 40 */ "ccons ::= COLLATE ID|STRING",
138066 /* 41 */ "autoinc ::=",
138067 /* 42 */ "autoinc ::= AUTOINCR",
138068 /* 43 */ "refargs ::=",
138069 /* 44 */ "refargs ::= refargs refarg",
138070 /* 45 */ "refarg ::= MATCH nm",
138071 /* 46 */ "refarg ::= ON INSERT refact",
138072 /* 47 */ "refarg ::= ON DELETE refact",
138073 /* 48 */ "refarg ::= ON UPDATE refact",
138074 /* 49 */ "refact ::= SET NULL",
138075 /* 50 */ "refact ::= SET DEFAULT",
138076 /* 51 */ "refact ::= CASCADE",
138077 /* 52 */ "refact ::= RESTRICT",
138078 /* 53 */ "refact ::= NO ACTION",
138079 /* 54 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
138080 /* 55 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
138081 /* 56 */ "init_deferred_pred_opt ::=",
138082 /* 57 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
138083 /* 58 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
138084 /* 59 */ "conslist_opt ::=",
138085 /* 60 */ "tconscomma ::= COMMA",
138086 /* 61 */ "tcons ::= CONSTRAINT nm",
138087 /* 62 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
138088 /* 63 */ "tcons ::= UNIQUE LP sortlist RP onconf",
138089 /* 64 */ "tcons ::= CHECK LP expr RP onconf",
138090 /* 65 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
138091 /* 66 */ "defer_subclause_opt ::=",
138092 /* 67 */ "onconf ::=",
138093 /* 68 */ "onconf ::= ON CONFLICT resolvetype",
138094 /* 69 */ "orconf ::=",
138095 /* 70 */ "orconf ::= OR resolvetype",
138096 /* 71 */ "resolvetype ::= IGNORE",
138097 /* 72 */ "resolvetype ::= REPLACE",
138098 /* 73 */ "cmd ::= DROP TABLE ifexists fullname",
138099 /* 74 */ "ifexists ::= IF EXISTS",
138100 /* 75 */ "ifexists ::=",
138101 /* 76 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
138102 /* 77 */ "cmd ::= DROP VIEW ifexists fullname",
138103 /* 78 */ "cmd ::= select",
138104 /* 79 */ "select ::= with selectnowith",
138105 /* 80 */ "selectnowith ::= selectnowith multiselect_op oneselect",
138106 /* 81 */ "multiselect_op ::= UNION",
138107 /* 82 */ "multiselect_op ::= UNION ALL",
138108 /* 83 */ "multiselect_op ::= EXCEPT|INTERSECT",
138109 /* 84 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
138110 /* 85 */ "values ::= VALUES LP nexprlist RP",
138111 /* 86 */ "values ::= values COMMA LP exprlist RP",
138112 /* 87 */ "distinct ::= DISTINCT",
138113 /* 88 */ "distinct ::= ALL",
138114 /* 89 */ "distinct ::=",
138115 /* 90 */ "sclp ::=",
138116 /* 91 */ "selcollist ::= sclp expr as",
138117 /* 92 */ "selcollist ::= sclp STAR",
138118 /* 93 */ "selcollist ::= sclp nm DOT STAR",
138119 /* 94 */ "as ::= AS nm",
138120 /* 95 */ "as ::=",
138121 /* 96 */ "from ::=",
138122 /* 97 */ "from ::= FROM seltablist",
138123 /* 98 */ "stl_prefix ::= seltablist joinop",
138124 /* 99 */ "stl_prefix ::=",
138125 /* 100 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
138126 /* 101 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
138127 /* 102 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
138128 /* 103 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
138129 /* 104 */ "dbnm ::=",
138130 /* 105 */ "dbnm ::= DOT nm",
138131 /* 106 */ "fullname ::= nm dbnm",
138132 /* 107 */ "joinop ::= COMMA|JOIN",
138133 /* 108 */ "joinop ::= JOIN_KW JOIN",
138134 /* 109 */ "joinop ::= JOIN_KW nm JOIN",
138135 /* 110 */ "joinop ::= JOIN_KW nm nm JOIN",
138136 /* 111 */ "on_opt ::= ON expr",
138137 /* 112 */ "on_opt ::=",
138138 /* 113 */ "indexed_opt ::=",
138139 /* 114 */ "indexed_opt ::= INDEXED BY nm",
138140 /* 115 */ "indexed_opt ::= NOT INDEXED",
138141 /* 116 */ "using_opt ::= USING LP idlist RP",
138142 /* 117 */ "using_opt ::=",
138143 /* 118 */ "orderby_opt ::=",
138144 /* 119 */ "orderby_opt ::= ORDER BY sortlist",
138145 /* 120 */ "sortlist ::= sortlist COMMA expr sortorder",
138146 /* 121 */ "sortlist ::= expr sortorder",
138147 /* 122 */ "sortorder ::= ASC",
138148 /* 123 */ "sortorder ::= DESC",
138149 /* 124 */ "sortorder ::=",
138150 /* 125 */ "groupby_opt ::=",
138151 /* 126 */ "groupby_opt ::= GROUP BY nexprlist",
138152 /* 127 */ "having_opt ::=",
138153 /* 128 */ "having_opt ::= HAVING expr",
138154 /* 129 */ "limit_opt ::=",
138155 /* 130 */ "limit_opt ::= LIMIT expr",
138156 /* 131 */ "limit_opt ::= LIMIT expr OFFSET expr",
138157 /* 132 */ "limit_opt ::= LIMIT expr COMMA expr",
138158 /* 133 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
138159 /* 134 */ "where_opt ::=",
138160 /* 135 */ "where_opt ::= WHERE expr",
138161 /* 136 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
138162 /* 137 */ "setlist ::= setlist COMMA nm EQ expr",
138163 /* 138 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
138164 /* 139 */ "setlist ::= nm EQ expr",
138165 /* 140 */ "setlist ::= LP idlist RP EQ expr",
138166 /* 141 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
138167 /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
138168 /* 143 */ "insert_cmd ::= INSERT orconf",
138169 /* 144 */ "insert_cmd ::= REPLACE",
138170 /* 145 */ "idlist_opt ::=",
138171 /* 146 */ "idlist_opt ::= LP idlist RP",
138172 /* 147 */ "idlist ::= idlist COMMA nm",
138173 /* 148 */ "idlist ::= nm",
138174 /* 149 */ "expr ::= LP expr RP",
138175 /* 150 */ "expr ::= ID|INDEXED",
138176 /* 151 */ "expr ::= JOIN_KW",
138177 /* 152 */ "expr ::= nm DOT nm",
138178 /* 153 */ "expr ::= nm DOT nm DOT nm",
138179 /* 154 */ "term ::= NULL|FLOAT|BLOB",
138180 /* 155 */ "term ::= STRING",
138181 /* 156 */ "term ::= INTEGER",
138182 /* 157 */ "expr ::= VARIABLE",
138183 /* 158 */ "expr ::= expr COLLATE ID|STRING",
138184 /* 159 */ "expr ::= CAST LP expr AS typetoken RP",
138185 /* 160 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
138186 /* 161 */ "expr ::= ID|INDEXED LP STAR RP",
138187 /* 162 */ "term ::= CTIME_KW",
138188 /* 163 */ "expr ::= LP nexprlist COMMA expr RP",
138189 /* 164 */ "expr ::= expr AND expr",
138190 /* 165 */ "expr ::= expr OR expr",
138191 /* 166 */ "expr ::= expr LT|GT|GE|LE expr",
138192 /* 167 */ "expr ::= expr EQ|NE expr",
138193 /* 168 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
138194 /* 169 */ "expr ::= expr PLUS|MINUS expr",
138195 /* 170 */ "expr ::= expr STAR|SLASH|REM expr",
138196 /* 171 */ "expr ::= expr CONCAT expr",
138197 /* 172 */ "likeop ::= NOT LIKE_KW|MATCH",
138198 /* 173 */ "expr ::= expr likeop expr",
138199 /* 174 */ "expr ::= expr likeop expr ESCAPE expr",
138200 /* 175 */ "expr ::= expr ISNULL|NOTNULL",
138201 /* 176 */ "expr ::= expr NOT NULL",
138202 /* 177 */ "expr ::= expr IS expr",
138203 /* 178 */ "expr ::= expr IS NOT expr",
138204 /* 179 */ "expr ::= NOT expr",
138205 /* 180 */ "expr ::= BITNOT expr",
138206 /* 181 */ "expr ::= MINUS expr",
138207 /* 182 */ "expr ::= PLUS expr",
138208 /* 183 */ "between_op ::= BETWEEN",
138209 /* 184 */ "between_op ::= NOT BETWEEN",
138210 /* 185 */ "expr ::= expr between_op expr AND expr",
138211 /* 186 */ "in_op ::= IN",
138212 /* 187 */ "in_op ::= NOT IN",
138213 /* 188 */ "expr ::= expr in_op LP exprlist RP",
138214 /* 189 */ "expr ::= LP select RP",
138215 /* 190 */ "expr ::= expr in_op LP select RP",
138216 /* 191 */ "expr ::= expr in_op nm dbnm paren_exprlist",
138217 /* 192 */ "expr ::= EXISTS LP select RP",
138218 /* 193 */ "expr ::= CASE case_operand case_exprlist case_else END",
138219 /* 194 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
138220 /* 195 */ "case_exprlist ::= WHEN expr THEN expr",
138221 /* 196 */ "case_else ::= ELSE expr",
138222 /* 197 */ "case_else ::=",
138223 /* 198 */ "case_operand ::= expr",
138224 /* 199 */ "case_operand ::=",
138225 /* 200 */ "exprlist ::=",
138226 /* 201 */ "nexprlist ::= nexprlist COMMA expr",
138227 /* 202 */ "nexprlist ::= expr",
138228 /* 203 */ "paren_exprlist ::=",
138229 /* 204 */ "paren_exprlist ::= LP exprlist RP",
138230 /* 205 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
138231 /* 206 */ "uniqueflag ::= UNIQUE",
138232 /* 207 */ "uniqueflag ::=",
138233 /* 208 */ "eidlist_opt ::=",
138234 /* 209 */ "eidlist_opt ::= LP eidlist RP",
138235 /* 210 */ "eidlist ::= eidlist COMMA nm collate sortorder",
138236 /* 211 */ "eidlist ::= nm collate sortorder",
138237 /* 212 */ "collate ::=",
138238 /* 213 */ "collate ::= COLLATE ID|STRING",
138239 /* 214 */ "cmd ::= DROP INDEX ifexists fullname",
138240 /* 215 */ "cmd ::= VACUUM",
138241 /* 216 */ "cmd ::= VACUUM nm",
138242 /* 217 */ "cmd ::= PRAGMA nm dbnm",
138243 /* 218 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
138244 /* 219 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
138245 /* 220 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
138246 /* 221 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
138247 /* 222 */ "plus_num ::= PLUS INTEGER|FLOAT",
138248 /* 223 */ "minus_num ::= MINUS INTEGER|FLOAT",
138249 /* 224 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
138250 /* 225 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
138251 /* 226 */ "trigger_time ::= BEFORE|AFTER",
138252 /* 227 */ "trigger_time ::= INSTEAD OF",
138253 /* 228 */ "trigger_time ::=",
138254 /* 229 */ "trigger_event ::= DELETE|INSERT",
138255 /* 230 */ "trigger_event ::= UPDATE",
138256 /* 231 */ "trigger_event ::= UPDATE OF idlist",
138257 /* 232 */ "when_clause ::=",
138258 /* 233 */ "when_clause ::= WHEN expr",
138259 /* 234 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
138260 /* 235 */ "trigger_cmd_list ::= trigger_cmd SEMI",
138261 /* 236 */ "trnm ::= nm DOT nm",
138262 /* 237 */ "tridxby ::= INDEXED BY nm",
138263 /* 238 */ "tridxby ::= NOT INDEXED",
138264 /* 239 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
138265 /* 240 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
138266 /* 241 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
138267 /* 242 */ "trigger_cmd ::= select",
138268 /* 243 */ "expr ::= RAISE LP IGNORE RP",
138269 /* 244 */ "expr ::= RAISE LP raisetype COMMA nm RP",
138270 /* 245 */ "raisetype ::= ROLLBACK",
138271 /* 246 */ "raisetype ::= ABORT",
138272 /* 247 */ "raisetype ::= FAIL",
138273 /* 248 */ "cmd ::= DROP TRIGGER ifexists fullname",
138274 /* 249 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
138275 /* 250 */ "cmd ::= DETACH database_kw_opt expr",
138276 /* 251 */ "key_opt ::=",
138277 /* 252 */ "key_opt ::= KEY expr",
138278 /* 253 */ "cmd ::= REINDEX",
138279 /* 254 */ "cmd ::= REINDEX nm dbnm",
138280 /* 255 */ "cmd ::= ANALYZE",
138281 /* 256 */ "cmd ::= ANALYZE nm dbnm",
138282 /* 257 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
138283 /* 258 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
138284 /* 259 */ "add_column_fullname ::= fullname",
138285 /* 260 */ "cmd ::= create_vtab",
138286 /* 261 */ "cmd ::= create_vtab LP vtabarglist RP",
138287 /* 262 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
138288 /* 263 */ "vtabarg ::=",
138289 /* 264 */ "vtabargtoken ::= ANY",
138290 /* 265 */ "vtabargtoken ::= lp anylist RP",
138291 /* 266 */ "lp ::= LP",
138292 /* 267 */ "with ::=",
138293 /* 268 */ "with ::= WITH wqlist",
138294 /* 269 */ "with ::= WITH RECURSIVE wqlist",
138295 /* 270 */ "wqlist ::= nm eidlist_opt AS LP select RP",
138296 /* 271 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
138297 /* 272 */ "input ::= cmdlist",
138298 /* 273 */ "cmdlist ::= cmdlist ecmd",
138299 /* 274 */ "cmdlist ::= ecmd",
138300 /* 275 */ "ecmd ::= SEMI",
138301 /* 276 */ "ecmd ::= explain cmdx SEMI",
138302 /* 277 */ "explain ::=",
138303 /* 278 */ "trans_opt ::=",
138304 /* 279 */ "trans_opt ::= TRANSACTION",
138305 /* 280 */ "trans_opt ::= TRANSACTION nm",
138306 /* 281 */ "savepoint_opt ::= SAVEPOINT",
138307 /* 282 */ "savepoint_opt ::=",
138308 /* 283 */ "cmd ::= create_table create_table_args",
138309 /* 284 */ "columnlist ::= columnlist COMMA columnname carglist",
138310 /* 285 */ "columnlist ::= columnname carglist",
138311 /* 286 */ "nm ::= ID|INDEXED",
138312 /* 287 */ "nm ::= STRING",
138313 /* 288 */ "nm ::= JOIN_KW",
138314 /* 289 */ "typetoken ::= typename",
138315 /* 290 */ "typename ::= ID|STRING",
138316 /* 291 */ "signed ::= plus_num",
138317 /* 292 */ "signed ::= minus_num",
138318 /* 293 */ "carglist ::= carglist ccons",
138319 /* 294 */ "carglist ::=",
138320 /* 295 */ "ccons ::= NULL onconf",
138321 /* 296 */ "conslist_opt ::= COMMA conslist",
138322 /* 297 */ "conslist ::= conslist tconscomma tcons",
138323 /* 298 */ "conslist ::= tcons",
138324 /* 299 */ "tconscomma ::=",
138325 /* 300 */ "defer_subclause_opt ::= defer_subclause",
138326 /* 301 */ "resolvetype ::= raisetype",
138327 /* 302 */ "selectnowith ::= oneselect",
138328 /* 303 */ "oneselect ::= values",
138329 /* 304 */ "sclp ::= selcollist COMMA",
138330 /* 305 */ "as ::= ID|STRING",
138331 /* 306 */ "expr ::= term",
138332 /* 307 */ "likeop ::= LIKE_KW|MATCH",
138333 /* 308 */ "exprlist ::= nexprlist",
138334 /* 309 */ "nmnum ::= plus_num",
138335 /* 310 */ "nmnum ::= nm",
138336 /* 311 */ "nmnum ::= ON",
138337 /* 312 */ "nmnum ::= DELETE",
138338 /* 313 */ "nmnum ::= DEFAULT",
138339 /* 314 */ "plus_num ::= INTEGER|FLOAT",
138340 /* 315 */ "foreach_clause ::=",
138341 /* 316 */ "foreach_clause ::= FOR EACH ROW",
138342 /* 317 */ "trnm ::= nm",
138343 /* 318 */ "tridxby ::=",
138344 /* 319 */ "database_kw_opt ::= DATABASE",
138345 /* 320 */ "database_kw_opt ::=",
138346 /* 321 */ "kwcolumn_opt ::=",
138347 /* 322 */ "kwcolumn_opt ::= COLUMNKW",
138348 /* 323 */ "vtabarglist ::= vtabarg",
138349 /* 324 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
138350 /* 325 */ "vtabarg ::= vtabarg vtabargtoken",
138351 /* 326 */ "anylist ::=",
138352 /* 327 */ "anylist ::= anylist LP anylist RP",
138353 /* 328 */ "anylist ::= anylist ANY",
138355 #endif /* NDEBUG */
138358 #if YYSTACKDEPTH<=0
138360 ** Try to increase the size of the parser stack. Return the number
138361 ** of errors. Return 0 on success.
138363 static int yyGrowStack(yyParser *p){
138364 int newSize;
138365 int idx;
138366 yyStackEntry *pNew;
138368 newSize = p->yystksz*2 + 100;
138369 idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
138370 if( p->yystack==&p->yystk0 ){
138371 pNew = malloc(newSize*sizeof(pNew[0]));
138372 if( pNew ) pNew[0] = p->yystk0;
138373 }else{
138374 pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
138376 if( pNew ){
138377 p->yystack = pNew;
138378 p->yytos = &p->yystack[idx];
138379 #ifndef NDEBUG
138380 if( yyTraceFILE ){
138381 fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
138382 yyTracePrompt, p->yystksz, newSize);
138384 #endif
138385 p->yystksz = newSize;
138387 return pNew==0;
138389 #endif
138391 /* Datatype of the argument to the memory allocated passed as the
138392 ** second argument to sqlite3ParserAlloc() below. This can be changed by
138393 ** putting an appropriate #define in the %include section of the input
138394 ** grammar.
138396 #ifndef YYMALLOCARGTYPE
138397 # define YYMALLOCARGTYPE size_t
138398 #endif
138400 /* Initialize a new parser that has already been allocated.
138402 SQLITE_PRIVATE void sqlite3ParserInit(void *yypParser){
138403 yyParser *pParser = (yyParser*)yypParser;
138404 #ifdef YYTRACKMAXSTACKDEPTH
138405 pParser->yyhwm = 0;
138406 #endif
138407 #if YYSTACKDEPTH<=0
138408 pParser->yytos = NULL;
138409 pParser->yystack = NULL;
138410 pParser->yystksz = 0;
138411 if( yyGrowStack(pParser) ){
138412 pParser->yystack = &pParser->yystk0;
138413 pParser->yystksz = 1;
138415 #endif
138416 #ifndef YYNOERRORRECOVERY
138417 pParser->yyerrcnt = -1;
138418 #endif
138419 pParser->yytos = pParser->yystack;
138420 pParser->yystack[0].stateno = 0;
138421 pParser->yystack[0].major = 0;
138422 #if YYSTACKDEPTH>0
138423 pParser->yystackEnd = &pParser->yystack[YYSTACKDEPTH-1];
138424 #endif
138427 #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
138429 ** This function allocates a new parser.
138430 ** The only argument is a pointer to a function which works like
138431 ** malloc.
138433 ** Inputs:
138434 ** A pointer to the function used to allocate memory.
138436 ** Outputs:
138437 ** A pointer to a parser. This pointer is used in subsequent calls
138438 ** to sqlite3Parser and sqlite3ParserFree.
138440 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
138441 yyParser *pParser;
138442 pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
138443 if( pParser ) sqlite3ParserInit(pParser);
138444 return pParser;
138446 #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
138449 /* The following function deletes the "minor type" or semantic value
138450 ** associated with a symbol. The symbol can be either a terminal
138451 ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
138452 ** a pointer to the value to be deleted. The code used to do the
138453 ** deletions is derived from the %destructor and/or %token_destructor
138454 ** directives of the input grammar.
138456 static void yy_destructor(
138457 yyParser *yypParser, /* The parser */
138458 YYCODETYPE yymajor, /* Type code for object to destroy */
138459 YYMINORTYPE *yypminor /* The object to be destroyed */
138461 sqlite3ParserARG_FETCH;
138462 switch( yymajor ){
138463 /* Here is inserted the actions which take place when a
138464 ** terminal or non-terminal is destroyed. This can happen
138465 ** when the symbol is popped from the stack during a
138466 ** reduce or during error processing or when a parser is
138467 ** being destroyed before it is finished parsing.
138469 ** Note: during a reduce, the only symbols destroyed are those
138470 ** which appear on the RHS of the rule, but which are *not* used
138471 ** inside the C code.
138473 /********* Begin destructor definitions ***************************************/
138474 case 163: /* select */
138475 case 194: /* selectnowith */
138476 case 195: /* oneselect */
138477 case 206: /* values */
138479 sqlite3SelectDelete(pParse->db, (yypminor->yy243));
138481 break;
138482 case 172: /* term */
138483 case 173: /* expr */
138485 sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
138487 break;
138488 case 177: /* eidlist_opt */
138489 case 186: /* sortlist */
138490 case 187: /* eidlist */
138491 case 199: /* selcollist */
138492 case 202: /* groupby_opt */
138493 case 204: /* orderby_opt */
138494 case 207: /* nexprlist */
138495 case 208: /* exprlist */
138496 case 209: /* sclp */
138497 case 218: /* setlist */
138498 case 224: /* paren_exprlist */
138499 case 226: /* case_exprlist */
138501 sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
138503 break;
138504 case 193: /* fullname */
138505 case 200: /* from */
138506 case 211: /* seltablist */
138507 case 212: /* stl_prefix */
138509 sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
138511 break;
138512 case 196: /* with */
138513 case 250: /* wqlist */
138515 sqlite3WithDelete(pParse->db, (yypminor->yy285));
138517 break;
138518 case 201: /* where_opt */
138519 case 203: /* having_opt */
138520 case 215: /* on_opt */
138521 case 225: /* case_operand */
138522 case 227: /* case_else */
138523 case 236: /* when_clause */
138524 case 241: /* key_opt */
138526 sqlite3ExprDelete(pParse->db, (yypminor->yy72));
138528 break;
138529 case 216: /* using_opt */
138530 case 217: /* idlist */
138531 case 220: /* idlist_opt */
138533 sqlite3IdListDelete(pParse->db, (yypminor->yy254));
138535 break;
138536 case 232: /* trigger_cmd_list */
138537 case 237: /* trigger_cmd */
138539 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
138541 break;
138542 case 234: /* trigger_event */
138544 sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
138546 break;
138547 /********* End destructor definitions *****************************************/
138548 default: break; /* If no destructor action specified: do nothing */
138553 ** Pop the parser's stack once.
138555 ** If there is a destructor routine associated with the token which
138556 ** is popped from the stack, then call it.
138558 static void yy_pop_parser_stack(yyParser *pParser){
138559 yyStackEntry *yytos;
138560 assert( pParser->yytos!=0 );
138561 assert( pParser->yytos > pParser->yystack );
138562 yytos = pParser->yytos--;
138563 #ifndef NDEBUG
138564 if( yyTraceFILE ){
138565 fprintf(yyTraceFILE,"%sPopping %s\n",
138566 yyTracePrompt,
138567 yyTokenName[yytos->major]);
138569 #endif
138570 yy_destructor(pParser, yytos->major, &yytos->minor);
138574 ** Clear all secondary memory allocations from the parser
138576 SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
138577 yyParser *pParser = (yyParser*)p;
138578 while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
138579 #if YYSTACKDEPTH<=0
138580 if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
138581 #endif
138584 #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
138586 ** Deallocate and destroy a parser. Destructors are called for
138587 ** all stack elements before shutting the parser down.
138589 ** If the YYPARSEFREENEVERNULL macro exists (for example because it
138590 ** is defined in a %include section of the input grammar) then it is
138591 ** assumed that the input pointer is never NULL.
138593 SQLITE_PRIVATE void sqlite3ParserFree(
138594 void *p, /* The parser to be deleted */
138595 void (*freeProc)(void*) /* Function used to reclaim memory */
138597 #ifndef YYPARSEFREENEVERNULL
138598 if( p==0 ) return;
138599 #endif
138600 sqlite3ParserFinalize(p);
138601 (*freeProc)(p);
138603 #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
138606 ** Return the peak depth of the stack for a parser.
138608 #ifdef YYTRACKMAXSTACKDEPTH
138609 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
138610 yyParser *pParser = (yyParser*)p;
138611 return pParser->yyhwm;
138613 #endif
138616 ** Find the appropriate action for a parser given the terminal
138617 ** look-ahead token iLookAhead.
138619 static unsigned int yy_find_shift_action(
138620 yyParser *pParser, /* The parser */
138621 YYCODETYPE iLookAhead /* The look-ahead token */
138623 int i;
138624 int stateno = pParser->yytos->stateno;
138626 if( stateno>=YY_MIN_REDUCE ) return stateno;
138627 assert( stateno <= YY_SHIFT_COUNT );
138629 i = yy_shift_ofst[stateno];
138630 assert( iLookAhead!=YYNOCODE );
138631 i += iLookAhead;
138632 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
138633 #ifdef YYFALLBACK
138634 YYCODETYPE iFallback; /* Fallback token */
138635 if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
138636 && (iFallback = yyFallback[iLookAhead])!=0 ){
138637 #ifndef NDEBUG
138638 if( yyTraceFILE ){
138639 fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
138640 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
138642 #endif
138643 assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
138644 iLookAhead = iFallback;
138645 continue;
138647 #endif
138648 #ifdef YYWILDCARD
138650 int j = i - iLookAhead + YYWILDCARD;
138652 #if YY_SHIFT_MIN+YYWILDCARD<0
138653 j>=0 &&
138654 #endif
138655 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
138656 j<YY_ACTTAB_COUNT &&
138657 #endif
138658 yy_lookahead[j]==YYWILDCARD && iLookAhead>0
138660 #ifndef NDEBUG
138661 if( yyTraceFILE ){
138662 fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
138663 yyTracePrompt, yyTokenName[iLookAhead],
138664 yyTokenName[YYWILDCARD]);
138666 #endif /* NDEBUG */
138667 return yy_action[j];
138670 #endif /* YYWILDCARD */
138671 return yy_default[stateno];
138672 }else{
138673 return yy_action[i];
138675 }while(1);
138679 ** Find the appropriate action for a parser given the non-terminal
138680 ** look-ahead token iLookAhead.
138682 static int yy_find_reduce_action(
138683 int stateno, /* Current state number */
138684 YYCODETYPE iLookAhead /* The look-ahead token */
138686 int i;
138687 #ifdef YYERRORSYMBOL
138688 if( stateno>YY_REDUCE_COUNT ){
138689 return yy_default[stateno];
138691 #else
138692 assert( stateno<=YY_REDUCE_COUNT );
138693 #endif
138694 i = yy_reduce_ofst[stateno];
138695 assert( i!=YY_REDUCE_USE_DFLT );
138696 assert( iLookAhead!=YYNOCODE );
138697 i += iLookAhead;
138698 #ifdef YYERRORSYMBOL
138699 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
138700 return yy_default[stateno];
138702 #else
138703 assert( i>=0 && i<YY_ACTTAB_COUNT );
138704 assert( yy_lookahead[i]==iLookAhead );
138705 #endif
138706 return yy_action[i];
138710 ** The following routine is called if the stack overflows.
138712 static void yyStackOverflow(yyParser *yypParser){
138713 sqlite3ParserARG_FETCH;
138714 #ifndef NDEBUG
138715 if( yyTraceFILE ){
138716 fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
138718 #endif
138719 while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
138720 /* Here code is inserted which will execute if the parser
138721 ** stack every overflows */
138722 /******** Begin %stack_overflow code ******************************************/
138724 sqlite3ErrorMsg(pParse, "parser stack overflow");
138725 /******** End %stack_overflow code ********************************************/
138726 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
138730 ** Print tracing information for a SHIFT action
138732 #ifndef NDEBUG
138733 static void yyTraceShift(yyParser *yypParser, int yyNewState){
138734 if( yyTraceFILE ){
138735 if( yyNewState<YYNSTATE ){
138736 fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
138737 yyTracePrompt,yyTokenName[yypParser->yytos->major],
138738 yyNewState);
138739 }else{
138740 fprintf(yyTraceFILE,"%sShift '%s'\n",
138741 yyTracePrompt,yyTokenName[yypParser->yytos->major]);
138745 #else
138746 # define yyTraceShift(X,Y)
138747 #endif
138750 ** Perform a shift action.
138752 static void yy_shift(
138753 yyParser *yypParser, /* The parser to be shifted */
138754 int yyNewState, /* The new state to shift in */
138755 int yyMajor, /* The major token to shift in */
138756 sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
138758 yyStackEntry *yytos;
138759 yypParser->yytos++;
138760 #ifdef YYTRACKMAXSTACKDEPTH
138761 if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
138762 yypParser->yyhwm++;
138763 assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
138765 #endif
138766 #if YYSTACKDEPTH>0
138767 if( yypParser->yytos>yypParser->yystackEnd ){
138768 yypParser->yytos--;
138769 yyStackOverflow(yypParser);
138770 return;
138772 #else
138773 if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
138774 if( yyGrowStack(yypParser) ){
138775 yypParser->yytos--;
138776 yyStackOverflow(yypParser);
138777 return;
138780 #endif
138781 if( yyNewState > YY_MAX_SHIFT ){
138782 yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
138784 yytos = yypParser->yytos;
138785 yytos->stateno = (YYACTIONTYPE)yyNewState;
138786 yytos->major = (YYCODETYPE)yyMajor;
138787 yytos->minor.yy0 = yyMinor;
138788 yyTraceShift(yypParser, yyNewState);
138791 /* The following table contains information about every rule that
138792 ** is used during the reduce.
138794 static const struct {
138795 YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
138796 signed char nrhs; /* Negative of the number of RHS symbols in the rule */
138797 } yyRuleInfo[] = {
138798 { 147, -1 },
138799 { 147, -3 },
138800 { 148, -1 },
138801 { 149, -3 },
138802 { 150, 0 },
138803 { 150, -1 },
138804 { 150, -1 },
138805 { 150, -1 },
138806 { 149, -2 },
138807 { 149, -2 },
138808 { 149, -2 },
138809 { 149, -3 },
138810 { 149, -5 },
138811 { 154, -6 },
138812 { 156, -1 },
138813 { 158, 0 },
138814 { 158, -3 },
138815 { 157, -1 },
138816 { 157, 0 },
138817 { 155, -5 },
138818 { 155, -2 },
138819 { 162, 0 },
138820 { 162, -2 },
138821 { 164, -2 },
138822 { 166, 0 },
138823 { 166, -4 },
138824 { 166, -6 },
138825 { 167, -2 },
138826 { 171, -2 },
138827 { 171, -2 },
138828 { 171, -4 },
138829 { 171, -3 },
138830 { 171, -3 },
138831 { 171, -2 },
138832 { 171, -3 },
138833 { 171, -5 },
138834 { 171, -2 },
138835 { 171, -4 },
138836 { 171, -4 },
138837 { 171, -1 },
138838 { 171, -2 },
138839 { 176, 0 },
138840 { 176, -1 },
138841 { 178, 0 },
138842 { 178, -2 },
138843 { 180, -2 },
138844 { 180, -3 },
138845 { 180, -3 },
138846 { 180, -3 },
138847 { 181, -2 },
138848 { 181, -2 },
138849 { 181, -1 },
138850 { 181, -1 },
138851 { 181, -2 },
138852 { 179, -3 },
138853 { 179, -2 },
138854 { 182, 0 },
138855 { 182, -2 },
138856 { 182, -2 },
138857 { 161, 0 },
138858 { 184, -1 },
138859 { 185, -2 },
138860 { 185, -7 },
138861 { 185, -5 },
138862 { 185, -5 },
138863 { 185, -10 },
138864 { 188, 0 },
138865 { 174, 0 },
138866 { 174, -3 },
138867 { 189, 0 },
138868 { 189, -2 },
138869 { 190, -1 },
138870 { 190, -1 },
138871 { 149, -4 },
138872 { 192, -2 },
138873 { 192, 0 },
138874 { 149, -9 },
138875 { 149, -4 },
138876 { 149, -1 },
138877 { 163, -2 },
138878 { 194, -3 },
138879 { 197, -1 },
138880 { 197, -2 },
138881 { 197, -1 },
138882 { 195, -9 },
138883 { 206, -4 },
138884 { 206, -5 },
138885 { 198, -1 },
138886 { 198, -1 },
138887 { 198, 0 },
138888 { 209, 0 },
138889 { 199, -3 },
138890 { 199, -2 },
138891 { 199, -4 },
138892 { 210, -2 },
138893 { 210, 0 },
138894 { 200, 0 },
138895 { 200, -2 },
138896 { 212, -2 },
138897 { 212, 0 },
138898 { 211, -7 },
138899 { 211, -9 },
138900 { 211, -7 },
138901 { 211, -7 },
138902 { 159, 0 },
138903 { 159, -2 },
138904 { 193, -2 },
138905 { 213, -1 },
138906 { 213, -2 },
138907 { 213, -3 },
138908 { 213, -4 },
138909 { 215, -2 },
138910 { 215, 0 },
138911 { 214, 0 },
138912 { 214, -3 },
138913 { 214, -2 },
138914 { 216, -4 },
138915 { 216, 0 },
138916 { 204, 0 },
138917 { 204, -3 },
138918 { 186, -4 },
138919 { 186, -2 },
138920 { 175, -1 },
138921 { 175, -1 },
138922 { 175, 0 },
138923 { 202, 0 },
138924 { 202, -3 },
138925 { 203, 0 },
138926 { 203, -2 },
138927 { 205, 0 },
138928 { 205, -2 },
138929 { 205, -4 },
138930 { 205, -4 },
138931 { 149, -6 },
138932 { 201, 0 },
138933 { 201, -2 },
138934 { 149, -8 },
138935 { 218, -5 },
138936 { 218, -7 },
138937 { 218, -3 },
138938 { 218, -5 },
138939 { 149, -6 },
138940 { 149, -7 },
138941 { 219, -2 },
138942 { 219, -1 },
138943 { 220, 0 },
138944 { 220, -3 },
138945 { 217, -3 },
138946 { 217, -1 },
138947 { 173, -3 },
138948 { 173, -1 },
138949 { 173, -1 },
138950 { 173, -3 },
138951 { 173, -5 },
138952 { 172, -1 },
138953 { 172, -1 },
138954 { 172, -1 },
138955 { 173, -1 },
138956 { 173, -3 },
138957 { 173, -6 },
138958 { 173, -5 },
138959 { 173, -4 },
138960 { 172, -1 },
138961 { 173, -5 },
138962 { 173, -3 },
138963 { 173, -3 },
138964 { 173, -3 },
138965 { 173, -3 },
138966 { 173, -3 },
138967 { 173, -3 },
138968 { 173, -3 },
138969 { 173, -3 },
138970 { 221, -2 },
138971 { 173, -3 },
138972 { 173, -5 },
138973 { 173, -2 },
138974 { 173, -3 },
138975 { 173, -3 },
138976 { 173, -4 },
138977 { 173, -2 },
138978 { 173, -2 },
138979 { 173, -2 },
138980 { 173, -2 },
138981 { 222, -1 },
138982 { 222, -2 },
138983 { 173, -5 },
138984 { 223, -1 },
138985 { 223, -2 },
138986 { 173, -5 },
138987 { 173, -3 },
138988 { 173, -5 },
138989 { 173, -5 },
138990 { 173, -4 },
138991 { 173, -5 },
138992 { 226, -5 },
138993 { 226, -4 },
138994 { 227, -2 },
138995 { 227, 0 },
138996 { 225, -1 },
138997 { 225, 0 },
138998 { 208, 0 },
138999 { 207, -3 },
139000 { 207, -1 },
139001 { 224, 0 },
139002 { 224, -3 },
139003 { 149, -12 },
139004 { 228, -1 },
139005 { 228, 0 },
139006 { 177, 0 },
139007 { 177, -3 },
139008 { 187, -5 },
139009 { 187, -3 },
139010 { 229, 0 },
139011 { 229, -2 },
139012 { 149, -4 },
139013 { 149, -1 },
139014 { 149, -2 },
139015 { 149, -3 },
139016 { 149, -5 },
139017 { 149, -6 },
139018 { 149, -5 },
139019 { 149, -6 },
139020 { 169, -2 },
139021 { 170, -2 },
139022 { 149, -5 },
139023 { 231, -11 },
139024 { 233, -1 },
139025 { 233, -2 },
139026 { 233, 0 },
139027 { 234, -1 },
139028 { 234, -1 },
139029 { 234, -3 },
139030 { 236, 0 },
139031 { 236, -2 },
139032 { 232, -3 },
139033 { 232, -2 },
139034 { 238, -3 },
139035 { 239, -3 },
139036 { 239, -2 },
139037 { 237, -7 },
139038 { 237, -5 },
139039 { 237, -5 },
139040 { 237, -1 },
139041 { 173, -4 },
139042 { 173, -6 },
139043 { 191, -1 },
139044 { 191, -1 },
139045 { 191, -1 },
139046 { 149, -4 },
139047 { 149, -6 },
139048 { 149, -3 },
139049 { 241, 0 },
139050 { 241, -2 },
139051 { 149, -1 },
139052 { 149, -3 },
139053 { 149, -1 },
139054 { 149, -3 },
139055 { 149, -6 },
139056 { 149, -7 },
139057 { 242, -1 },
139058 { 149, -1 },
139059 { 149, -4 },
139060 { 244, -8 },
139061 { 246, 0 },
139062 { 247, -1 },
139063 { 247, -3 },
139064 { 248, -1 },
139065 { 196, 0 },
139066 { 196, -2 },
139067 { 196, -3 },
139068 { 250, -6 },
139069 { 250, -8 },
139070 { 144, -1 },
139071 { 145, -2 },
139072 { 145, -1 },
139073 { 146, -1 },
139074 { 146, -3 },
139075 { 147, 0 },
139076 { 151, 0 },
139077 { 151, -1 },
139078 { 151, -2 },
139079 { 153, -1 },
139080 { 153, 0 },
139081 { 149, -2 },
139082 { 160, -4 },
139083 { 160, -2 },
139084 { 152, -1 },
139085 { 152, -1 },
139086 { 152, -1 },
139087 { 166, -1 },
139088 { 167, -1 },
139089 { 168, -1 },
139090 { 168, -1 },
139091 { 165, -2 },
139092 { 165, 0 },
139093 { 171, -2 },
139094 { 161, -2 },
139095 { 183, -3 },
139096 { 183, -1 },
139097 { 184, 0 },
139098 { 188, -1 },
139099 { 190, -1 },
139100 { 194, -1 },
139101 { 195, -1 },
139102 { 209, -2 },
139103 { 210, -1 },
139104 { 173, -1 },
139105 { 221, -1 },
139106 { 208, -1 },
139107 { 230, -1 },
139108 { 230, -1 },
139109 { 230, -1 },
139110 { 230, -1 },
139111 { 230, -1 },
139112 { 169, -1 },
139113 { 235, 0 },
139114 { 235, -3 },
139115 { 238, -1 },
139116 { 239, 0 },
139117 { 240, -1 },
139118 { 240, 0 },
139119 { 243, 0 },
139120 { 243, -1 },
139121 { 245, -1 },
139122 { 245, -3 },
139123 { 246, -2 },
139124 { 249, 0 },
139125 { 249, -4 },
139126 { 249, -2 },
139129 static void yy_accept(yyParser*); /* Forward Declaration */
139132 ** Perform a reduce action and the shift that must immediately
139133 ** follow the reduce.
139135 static void yy_reduce(
139136 yyParser *yypParser, /* The parser */
139137 unsigned int yyruleno /* Number of the rule by which to reduce */
139139 int yygoto; /* The next state */
139140 int yyact; /* The next action */
139141 yyStackEntry *yymsp; /* The top of the parser's stack */
139142 int yysize; /* Amount to pop the stack */
139143 sqlite3ParserARG_FETCH;
139144 yymsp = yypParser->yytos;
139145 #ifndef NDEBUG
139146 if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
139147 yysize = yyRuleInfo[yyruleno].nrhs;
139148 fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
139149 yyRuleName[yyruleno], yymsp[yysize].stateno);
139151 #endif /* NDEBUG */
139153 /* Check that the stack is large enough to grow by a single entry
139154 ** if the RHS of the rule is empty. This ensures that there is room
139155 ** enough on the stack to push the LHS value */
139156 if( yyRuleInfo[yyruleno].nrhs==0 ){
139157 #ifdef YYTRACKMAXSTACKDEPTH
139158 if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
139159 yypParser->yyhwm++;
139160 assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
139162 #endif
139163 #if YYSTACKDEPTH>0
139164 if( yypParser->yytos>=yypParser->yystackEnd ){
139165 yyStackOverflow(yypParser);
139166 return;
139168 #else
139169 if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
139170 if( yyGrowStack(yypParser) ){
139171 yyStackOverflow(yypParser);
139172 return;
139174 yymsp = yypParser->yytos;
139176 #endif
139179 switch( yyruleno ){
139180 /* Beginning here are the reduction cases. A typical example
139181 ** follows:
139182 ** case 0:
139183 ** #line <lineno> <grammarfile>
139184 ** { ... } // User supplied code
139185 ** #line <lineno> <thisfile>
139186 ** break;
139188 /********** Begin reduce actions **********************************************/
139189 YYMINORTYPE yylhsminor;
139190 case 0: /* explain ::= EXPLAIN */
139191 { pParse->explain = 1; }
139192 break;
139193 case 1: /* explain ::= EXPLAIN QUERY PLAN */
139194 { pParse->explain = 2; }
139195 break;
139196 case 2: /* cmdx ::= cmd */
139197 { sqlite3FinishCoding(pParse); }
139198 break;
139199 case 3: /* cmd ::= BEGIN transtype trans_opt */
139200 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
139201 break;
139202 case 4: /* transtype ::= */
139203 {yymsp[1].minor.yy194 = TK_DEFERRED;}
139204 break;
139205 case 5: /* transtype ::= DEFERRED */
139206 case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
139207 case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
139208 {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
139209 break;
139210 case 8: /* cmd ::= COMMIT|END trans_opt */
139211 case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
139212 {sqlite3EndTransaction(pParse,yymsp[-1].major);}
139213 break;
139214 case 10: /* cmd ::= SAVEPOINT nm */
139216 sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
139218 break;
139219 case 11: /* cmd ::= RELEASE savepoint_opt nm */
139221 sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
139223 break;
139224 case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
139226 sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
139228 break;
139229 case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
139231 sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
139233 break;
139234 case 14: /* createkw ::= CREATE */
139235 {disableLookaside(pParse);}
139236 break;
139237 case 15: /* ifnotexists ::= */
139238 case 18: /* temp ::= */ yytestcase(yyruleno==18);
139239 case 21: /* table_options ::= */ yytestcase(yyruleno==21);
139240 case 41: /* autoinc ::= */ yytestcase(yyruleno==41);
139241 case 56: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==56);
139242 case 66: /* defer_subclause_opt ::= */ yytestcase(yyruleno==66);
139243 case 75: /* ifexists ::= */ yytestcase(yyruleno==75);
139244 case 89: /* distinct ::= */ yytestcase(yyruleno==89);
139245 case 212: /* collate ::= */ yytestcase(yyruleno==212);
139246 {yymsp[1].minor.yy194 = 0;}
139247 break;
139248 case 16: /* ifnotexists ::= IF NOT EXISTS */
139249 {yymsp[-2].minor.yy194 = 1;}
139250 break;
139251 case 17: /* temp ::= TEMP */
139252 case 42: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==42);
139253 {yymsp[0].minor.yy194 = 1;}
139254 break;
139255 case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
139257 sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
139259 break;
139260 case 20: /* create_table_args ::= AS select */
139262 sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
139263 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
139265 break;
139266 case 22: /* table_options ::= WITHOUT nm */
139268 if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
139269 yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid;
139270 }else{
139271 yymsp[-1].minor.yy194 = 0;
139272 sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
139275 break;
139276 case 23: /* columnname ::= nm typetoken */
139277 {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
139278 break;
139279 case 24: /* typetoken ::= */
139280 case 59: /* conslist_opt ::= */ yytestcase(yyruleno==59);
139281 case 95: /* as ::= */ yytestcase(yyruleno==95);
139282 {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
139283 break;
139284 case 25: /* typetoken ::= typename LP signed RP */
139286 yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
139288 break;
139289 case 26: /* typetoken ::= typename LP signed COMMA signed RP */
139291 yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
139293 break;
139294 case 27: /* typename ::= typename ID|STRING */
139295 {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
139296 break;
139297 case 28: /* ccons ::= CONSTRAINT nm */
139298 case 61: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==61);
139299 {pParse->constraintName = yymsp[0].minor.yy0;}
139300 break;
139301 case 29: /* ccons ::= DEFAULT term */
139302 case 31: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==31);
139303 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
139304 break;
139305 case 30: /* ccons ::= DEFAULT LP expr RP */
139306 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
139307 break;
139308 case 32: /* ccons ::= DEFAULT MINUS term */
139310 ExprSpan v;
139311 v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0);
139312 v.zStart = yymsp[-1].minor.yy0.z;
139313 v.zEnd = yymsp[0].minor.yy190.zEnd;
139314 sqlite3AddDefaultValue(pParse,&v);
139316 break;
139317 case 33: /* ccons ::= DEFAULT ID|INDEXED */
139319 ExprSpan v;
139320 spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
139321 sqlite3AddDefaultValue(pParse,&v);
139323 break;
139324 case 34: /* ccons ::= NOT NULL onconf */
139325 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
139326 break;
139327 case 35: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
139328 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
139329 break;
139330 case 36: /* ccons ::= UNIQUE onconf */
139331 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
139332 SQLITE_IDXTYPE_UNIQUE);}
139333 break;
139334 case 37: /* ccons ::= CHECK LP expr RP */
139335 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
139336 break;
139337 case 38: /* ccons ::= REFERENCES nm eidlist_opt refargs */
139338 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
139339 break;
139340 case 39: /* ccons ::= defer_subclause */
139341 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
139342 break;
139343 case 40: /* ccons ::= COLLATE ID|STRING */
139344 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
139345 break;
139346 case 43: /* refargs ::= */
139347 { yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
139348 break;
139349 case 44: /* refargs ::= refargs refarg */
139350 { yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
139351 break;
139352 case 45: /* refarg ::= MATCH nm */
139353 { yymsp[-1].minor.yy497.value = 0; yymsp[-1].minor.yy497.mask = 0x000000; }
139354 break;
139355 case 46: /* refarg ::= ON INSERT refact */
139356 { yymsp[-2].minor.yy497.value = 0; yymsp[-2].minor.yy497.mask = 0x000000; }
139357 break;
139358 case 47: /* refarg ::= ON DELETE refact */
139359 { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194; yymsp[-2].minor.yy497.mask = 0x0000ff; }
139360 break;
139361 case 48: /* refarg ::= ON UPDATE refact */
139362 { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8; yymsp[-2].minor.yy497.mask = 0x00ff00; }
139363 break;
139364 case 49: /* refact ::= SET NULL */
139365 { yymsp[-1].minor.yy194 = OE_SetNull; /* EV: R-33326-45252 */}
139366 break;
139367 case 50: /* refact ::= SET DEFAULT */
139368 { yymsp[-1].minor.yy194 = OE_SetDflt; /* EV: R-33326-45252 */}
139369 break;
139370 case 51: /* refact ::= CASCADE */
139371 { yymsp[0].minor.yy194 = OE_Cascade; /* EV: R-33326-45252 */}
139372 break;
139373 case 52: /* refact ::= RESTRICT */
139374 { yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
139375 break;
139376 case 53: /* refact ::= NO ACTION */
139377 { yymsp[-1].minor.yy194 = OE_None; /* EV: R-33326-45252 */}
139378 break;
139379 case 54: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
139380 {yymsp[-2].minor.yy194 = 0;}
139381 break;
139382 case 55: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
139383 case 70: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==70);
139384 case 143: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==143);
139385 {yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
139386 break;
139387 case 57: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
139388 case 74: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==74);
139389 case 184: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==184);
139390 case 187: /* in_op ::= NOT IN */ yytestcase(yyruleno==187);
139391 case 213: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==213);
139392 {yymsp[-1].minor.yy194 = 1;}
139393 break;
139394 case 58: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
139395 {yymsp[-1].minor.yy194 = 0;}
139396 break;
139397 case 60: /* tconscomma ::= COMMA */
139398 {pParse->constraintName.n = 0;}
139399 break;
139400 case 62: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
139401 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
139402 break;
139403 case 63: /* tcons ::= UNIQUE LP sortlist RP onconf */
139404 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
139405 SQLITE_IDXTYPE_UNIQUE);}
139406 break;
139407 case 64: /* tcons ::= CHECK LP expr RP onconf */
139408 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
139409 break;
139410 case 65: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
139412 sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
139413 sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
139415 break;
139416 case 67: /* onconf ::= */
139417 case 69: /* orconf ::= */ yytestcase(yyruleno==69);
139418 {yymsp[1].minor.yy194 = OE_Default;}
139419 break;
139420 case 68: /* onconf ::= ON CONFLICT resolvetype */
139421 {yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
139422 break;
139423 case 71: /* resolvetype ::= IGNORE */
139424 {yymsp[0].minor.yy194 = OE_Ignore;}
139425 break;
139426 case 72: /* resolvetype ::= REPLACE */
139427 case 144: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==144);
139428 {yymsp[0].minor.yy194 = OE_Replace;}
139429 break;
139430 case 73: /* cmd ::= DROP TABLE ifexists fullname */
139432 sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
139434 break;
139435 case 76: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
139437 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);
139439 break;
139440 case 77: /* cmd ::= DROP VIEW ifexists fullname */
139442 sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
139444 break;
139445 case 78: /* cmd ::= select */
139447 SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
139448 sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
139449 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
139451 break;
139452 case 79: /* select ::= with selectnowith */
139454 Select *p = yymsp[0].minor.yy243;
139455 if( p ){
139456 p->pWith = yymsp[-1].minor.yy285;
139457 parserDoubleLinkSelect(pParse, p);
139458 }else{
139459 sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
139461 yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
139463 break;
139464 case 80: /* selectnowith ::= selectnowith multiselect_op oneselect */
139466 Select *pRhs = yymsp[0].minor.yy243;
139467 Select *pLhs = yymsp[-2].minor.yy243;
139468 if( pRhs && pRhs->pPrior ){
139469 SrcList *pFrom;
139470 Token x;
139471 x.n = 0;
139472 parserDoubleLinkSelect(pParse, pRhs);
139473 pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
139474 pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
139476 if( pRhs ){
139477 pRhs->op = (u8)yymsp[-1].minor.yy194;
139478 pRhs->pPrior = pLhs;
139479 if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
139480 pRhs->selFlags &= ~SF_MultiValue;
139481 if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
139482 }else{
139483 sqlite3SelectDelete(pParse->db, pLhs);
139485 yymsp[-2].minor.yy243 = pRhs;
139487 break;
139488 case 81: /* multiselect_op ::= UNION */
139489 case 83: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==83);
139490 {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
139491 break;
139492 case 82: /* multiselect_op ::= UNION ALL */
139493 {yymsp[-1].minor.yy194 = TK_ALL;}
139494 break;
139495 case 84: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
139497 #if SELECTTRACE_ENABLED
139498 Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
139499 #endif
139500 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);
139501 #if SELECTTRACE_ENABLED
139502 /* Populate the Select.zSelName[] string that is used to help with
139503 ** query planner debugging, to differentiate between multiple Select
139504 ** objects in a complex query.
139506 ** If the SELECT keyword is immediately followed by a C-style comment
139507 ** then extract the first few alphanumeric characters from within that
139508 ** comment to be the zSelName value. Otherwise, the label is #N where
139509 ** is an integer that is incremented with each SELECT statement seen.
139511 if( yymsp[-8].minor.yy243!=0 ){
139512 const char *z = s.z+6;
139513 int i;
139514 sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
139515 ++pParse->nSelect);
139516 while( z[0]==' ' ) z++;
139517 if( z[0]=='/' && z[1]=='*' ){
139518 z += 2;
139519 while( z[0]==' ' ) z++;
139520 for(i=0; sqlite3Isalnum(z[i]); i++){}
139521 sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
139524 #endif /* SELECTRACE_ENABLED */
139526 break;
139527 case 85: /* values ::= VALUES LP nexprlist RP */
139529 yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
139531 break;
139532 case 86: /* values ::= values COMMA LP exprlist RP */
139534 Select *pRight, *pLeft = yymsp[-4].minor.yy243;
139535 pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
139536 if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
139537 if( pRight ){
139538 pRight->op = TK_ALL;
139539 pRight->pPrior = pLeft;
139540 yymsp[-4].minor.yy243 = pRight;
139541 }else{
139542 yymsp[-4].minor.yy243 = pLeft;
139545 break;
139546 case 87: /* distinct ::= DISTINCT */
139547 {yymsp[0].minor.yy194 = SF_Distinct;}
139548 break;
139549 case 88: /* distinct ::= ALL */
139550 {yymsp[0].minor.yy194 = SF_All;}
139551 break;
139552 case 90: /* sclp ::= */
139553 case 118: /* orderby_opt ::= */ yytestcase(yyruleno==118);
139554 case 125: /* groupby_opt ::= */ yytestcase(yyruleno==125);
139555 case 200: /* exprlist ::= */ yytestcase(yyruleno==200);
139556 case 203: /* paren_exprlist ::= */ yytestcase(yyruleno==203);
139557 case 208: /* eidlist_opt ::= */ yytestcase(yyruleno==208);
139558 {yymsp[1].minor.yy148 = 0;}
139559 break;
139560 case 91: /* selcollist ::= sclp expr as */
139562 yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
139563 if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
139564 sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
139566 break;
139567 case 92: /* selcollist ::= sclp STAR */
139569 Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
139570 yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
139572 break;
139573 case 93: /* selcollist ::= sclp nm DOT STAR */
139575 Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
139576 Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
139577 Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
139578 yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
139580 break;
139581 case 94: /* as ::= AS nm */
139582 case 105: /* dbnm ::= DOT nm */ yytestcase(yyruleno==105);
139583 case 222: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==222);
139584 case 223: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==223);
139585 {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
139586 break;
139587 case 96: /* from ::= */
139588 {yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
139589 break;
139590 case 97: /* from ::= FROM seltablist */
139592 yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
139593 sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
139595 break;
139596 case 98: /* stl_prefix ::= seltablist joinop */
139598 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;
139600 break;
139601 case 99: /* stl_prefix ::= */
139602 {yymsp[1].minor.yy185 = 0;}
139603 break;
139604 case 100: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
139606 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);
139607 sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
139609 break;
139610 case 101: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
139612 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);
139613 sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
139615 break;
139616 case 102: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
139618 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);
139620 break;
139621 case 103: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
139623 if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
139624 yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
139625 }else if( yymsp[-4].minor.yy185->nSrc==1 ){
139626 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);
139627 if( yymsp[-6].minor.yy185 ){
139628 struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
139629 struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
139630 pNew->zName = pOld->zName;
139631 pNew->zDatabase = pOld->zDatabase;
139632 pNew->pSelect = pOld->pSelect;
139633 pOld->zName = pOld->zDatabase = 0;
139634 pOld->pSelect = 0;
139636 sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
139637 }else{
139638 Select *pSubquery;
139639 sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
139640 pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
139641 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);
139644 break;
139645 case 104: /* dbnm ::= */
139646 case 113: /* indexed_opt ::= */ yytestcase(yyruleno==113);
139647 {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
139648 break;
139649 case 106: /* fullname ::= nm dbnm */
139650 {yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
139651 break;
139652 case 107: /* joinop ::= COMMA|JOIN */
139653 { yymsp[0].minor.yy194 = JT_INNER; }
139654 break;
139655 case 108: /* joinop ::= JOIN_KW JOIN */
139656 {yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
139657 break;
139658 case 109: /* joinop ::= JOIN_KW nm JOIN */
139659 {yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
139660 break;
139661 case 110: /* joinop ::= JOIN_KW nm nm JOIN */
139662 {yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
139663 break;
139664 case 111: /* on_opt ::= ON expr */
139665 case 128: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==128);
139666 case 135: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==135);
139667 case 196: /* case_else ::= ELSE expr */ yytestcase(yyruleno==196);
139668 {yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
139669 break;
139670 case 112: /* on_opt ::= */
139671 case 127: /* having_opt ::= */ yytestcase(yyruleno==127);
139672 case 134: /* where_opt ::= */ yytestcase(yyruleno==134);
139673 case 197: /* case_else ::= */ yytestcase(yyruleno==197);
139674 case 199: /* case_operand ::= */ yytestcase(yyruleno==199);
139675 {yymsp[1].minor.yy72 = 0;}
139676 break;
139677 case 114: /* indexed_opt ::= INDEXED BY nm */
139678 {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
139679 break;
139680 case 115: /* indexed_opt ::= NOT INDEXED */
139681 {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
139682 break;
139683 case 116: /* using_opt ::= USING LP idlist RP */
139684 {yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
139685 break;
139686 case 117: /* using_opt ::= */
139687 case 145: /* idlist_opt ::= */ yytestcase(yyruleno==145);
139688 {yymsp[1].minor.yy254 = 0;}
139689 break;
139690 case 119: /* orderby_opt ::= ORDER BY sortlist */
139691 case 126: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==126);
139692 {yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
139693 break;
139694 case 120: /* sortlist ::= sortlist COMMA expr sortorder */
139696 yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
139697 sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
139699 break;
139700 case 121: /* sortlist ::= expr sortorder */
139702 yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
139703 sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
139705 break;
139706 case 122: /* sortorder ::= ASC */
139707 {yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
139708 break;
139709 case 123: /* sortorder ::= DESC */
139710 {yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
139711 break;
139712 case 124: /* sortorder ::= */
139713 {yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
139714 break;
139715 case 129: /* limit_opt ::= */
139716 {yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
139717 break;
139718 case 130: /* limit_opt ::= LIMIT expr */
139719 {yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
139720 break;
139721 case 131: /* limit_opt ::= LIMIT expr OFFSET expr */
139722 {yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
139723 break;
139724 case 132: /* limit_opt ::= LIMIT expr COMMA expr */
139725 {yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
139726 break;
139727 case 133: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
139729 sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
139730 sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
139731 sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
139733 break;
139734 case 136: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
139736 sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
139737 sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
139738 sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list");
139739 sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
139741 break;
139742 case 137: /* setlist ::= setlist COMMA nm EQ expr */
139744 yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
139745 sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
139747 break;
139748 case 138: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
139750 yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
139752 break;
139753 case 139: /* setlist ::= nm EQ expr */
139755 yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
139756 sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
139758 yymsp[-2].minor.yy148 = yylhsminor.yy148;
139759 break;
139760 case 140: /* setlist ::= LP idlist RP EQ expr */
139762 yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
139764 break;
139765 case 141: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
139767 sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
139768 sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
139770 break;
139771 case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
139773 sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
139774 sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
139776 break;
139777 case 146: /* idlist_opt ::= LP idlist RP */
139778 {yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
139779 break;
139780 case 147: /* idlist ::= idlist COMMA nm */
139781 {yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
139782 break;
139783 case 148: /* idlist ::= nm */
139784 {yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
139785 break;
139786 case 149: /* expr ::= LP expr RP */
139787 {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;}
139788 break;
139789 case 150: /* expr ::= ID|INDEXED */
139790 case 151: /* expr ::= JOIN_KW */ yytestcase(yyruleno==151);
139791 {spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
139792 break;
139793 case 152: /* expr ::= nm DOT nm */
139795 Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
139796 Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
139797 spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
139798 yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
139800 break;
139801 case 153: /* expr ::= nm DOT nm DOT nm */
139803 Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
139804 Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
139805 Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
139806 Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
139807 spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
139808 yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
139810 break;
139811 case 154: /* term ::= NULL|FLOAT|BLOB */
139812 case 155: /* term ::= STRING */ yytestcase(yyruleno==155);
139813 {spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
139814 break;
139815 case 156: /* term ::= INTEGER */
139817 yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
139818 yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z;
139819 yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n;
139821 yymsp[0].minor.yy190 = yylhsminor.yy190;
139822 break;
139823 case 157: /* expr ::= VARIABLE */
139825 if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
139826 u32 n = yymsp[0].minor.yy0.n;
139827 spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
139828 sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n);
139829 }else{
139830 /* When doing a nested parse, one can include terms in an expression
139831 ** that look like this: #1 #2 ... These terms refer to registers
139832 ** in the virtual machine. #N is the N-th register. */
139833 Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
139834 assert( t.n>=2 );
139835 spanSet(&yymsp[0].minor.yy190, &t, &t);
139836 if( pParse->nested==0 ){
139837 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
139838 yymsp[0].minor.yy190.pExpr = 0;
139839 }else{
139840 yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
139841 if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
139845 break;
139846 case 158: /* expr ::= expr COLLATE ID|STRING */
139848 yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
139849 yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
139851 break;
139852 case 159: /* expr ::= CAST LP expr AS typetoken RP */
139854 spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
139855 yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
139856 sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, 0);
139858 break;
139859 case 160: /* expr ::= ID|INDEXED LP distinct exprlist RP */
139861 if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
139862 sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
139864 yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
139865 spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
139866 if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
139867 yylhsminor.yy190.pExpr->flags |= EP_Distinct;
139870 yymsp[-4].minor.yy190 = yylhsminor.yy190;
139871 break;
139872 case 161: /* expr ::= ID|INDEXED LP STAR RP */
139874 yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
139875 spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
139877 yymsp[-3].minor.yy190 = yylhsminor.yy190;
139878 break;
139879 case 162: /* term ::= CTIME_KW */
139881 yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
139882 spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
139884 yymsp[0].minor.yy190 = yylhsminor.yy190;
139885 break;
139886 case 163: /* expr ::= LP nexprlist COMMA expr RP */
139888 ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr);
139889 yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
139890 if( yylhsminor.yy190.pExpr ){
139891 yylhsminor.yy190.pExpr->x.pList = pList;
139892 spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
139893 }else{
139894 sqlite3ExprListDelete(pParse->db, pList);
139897 yymsp[-4].minor.yy190 = yylhsminor.yy190;
139898 break;
139899 case 164: /* expr ::= expr AND expr */
139900 case 165: /* expr ::= expr OR expr */ yytestcase(yyruleno==165);
139901 case 166: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==166);
139902 case 167: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==167);
139903 case 168: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==168);
139904 case 169: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==169);
139905 case 170: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==170);
139906 case 171: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==171);
139907 {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
139908 break;
139909 case 172: /* likeop ::= NOT LIKE_KW|MATCH */
139910 {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
139911 break;
139912 case 173: /* expr ::= expr likeop expr */
139914 ExprList *pList;
139915 int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
139916 yymsp[-1].minor.yy0.n &= 0x7fffffff;
139917 pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
139918 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
139919 yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
139920 exprNot(pParse, bNot, &yymsp[-2].minor.yy190);
139921 yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
139922 if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
139924 break;
139925 case 174: /* expr ::= expr likeop expr ESCAPE expr */
139927 ExprList *pList;
139928 int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
139929 yymsp[-3].minor.yy0.n &= 0x7fffffff;
139930 pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
139931 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
139932 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
139933 yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
139934 exprNot(pParse, bNot, &yymsp[-4].minor.yy190);
139935 yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
139936 if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
139938 break;
139939 case 175: /* expr ::= expr ISNULL|NOTNULL */
139940 {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
139941 break;
139942 case 176: /* expr ::= expr NOT NULL */
139943 {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
139944 break;
139945 case 177: /* expr ::= expr IS expr */
139947 spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
139948 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
139950 break;
139951 case 178: /* expr ::= expr IS NOT expr */
139953 spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
139954 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
139956 break;
139957 case 179: /* expr ::= NOT expr */
139958 case 180: /* expr ::= BITNOT expr */ yytestcase(yyruleno==180);
139959 {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
139960 break;
139961 case 181: /* expr ::= MINUS expr */
139962 {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
139963 break;
139964 case 182: /* expr ::= PLUS expr */
139965 {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
139966 break;
139967 case 183: /* between_op ::= BETWEEN */
139968 case 186: /* in_op ::= IN */ yytestcase(yyruleno==186);
139969 {yymsp[0].minor.yy194 = 0;}
139970 break;
139971 case 185: /* expr ::= expr between_op expr AND expr */
139973 ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
139974 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
139975 yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0);
139976 if( yymsp[-4].minor.yy190.pExpr ){
139977 yymsp[-4].minor.yy190.pExpr->x.pList = pList;
139978 }else{
139979 sqlite3ExprListDelete(pParse->db, pList);
139981 exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
139982 yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
139984 break;
139985 case 188: /* expr ::= expr in_op LP exprlist RP */
139987 if( yymsp[-1].minor.yy148==0 ){
139988 /* Expressions of the form
139990 ** expr1 IN ()
139991 ** expr1 NOT IN ()
139993 ** simplify to constants 0 (false) and 1 (true), respectively,
139994 ** regardless of the value of expr1.
139996 sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
139997 yymsp[-4].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy194],1);
139998 }else if( yymsp[-1].minor.yy148->nExpr==1 ){
139999 /* Expressions of the form:
140001 ** expr1 IN (?1)
140002 ** expr1 NOT IN (?2)
140004 ** with exactly one value on the RHS can be simplified to something
140005 ** like this:
140007 ** expr1 == ?1
140008 ** expr1 <> ?2
140010 ** But, the RHS of the == or <> is marked with the EP_Generic flag
140011 ** so that it may not contribute to the computation of comparison
140012 ** affinity or the collating sequence to use for comparison. Otherwise,
140013 ** the semantics would be subtly different from IN or NOT IN.
140015 Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
140016 yymsp[-1].minor.yy148->a[0].pExpr = 0;
140017 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
140018 /* pRHS cannot be NULL because a malloc error would have been detected
140019 ** before now and control would have never reached this point */
140020 if( ALWAYS(pRHS) ){
140021 pRHS->flags &= ~EP_Collate;
140022 pRHS->flags |= EP_Generic;
140024 yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS);
140025 }else{
140026 yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
140027 if( yymsp[-4].minor.yy190.pExpr ){
140028 yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
140029 sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
140030 }else{
140031 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
140033 exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
140035 yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
140037 break;
140038 case 189: /* expr ::= LP select RP */
140040 spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
140041 yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
140042 sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
140044 break;
140045 case 190: /* expr ::= expr in_op LP select RP */
140047 yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
140048 sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
140049 exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
140050 yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
140052 break;
140053 case 191: /* expr ::= expr in_op nm dbnm paren_exprlist */
140055 SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
140056 Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
140057 if( yymsp[0].minor.yy148 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
140058 yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
140059 sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
140060 exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
140061 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];
140063 break;
140064 case 192: /* expr ::= EXISTS LP select RP */
140066 Expr *p;
140067 spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
140068 p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
140069 sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
140071 break;
140072 case 193: /* expr ::= CASE case_operand case_exprlist case_else END */
140074 spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/
140075 yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0);
140076 if( yymsp[-4].minor.yy190.pExpr ){
140077 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;
140078 sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
140079 }else{
140080 sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
140081 sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
140084 break;
140085 case 194: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
140087 yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
140088 yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
140090 break;
140091 case 195: /* case_exprlist ::= WHEN expr THEN expr */
140093 yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
140094 yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
140096 break;
140097 case 198: /* case_operand ::= expr */
140098 {yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
140099 break;
140100 case 201: /* nexprlist ::= nexprlist COMMA expr */
140101 {yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
140102 break;
140103 case 202: /* nexprlist ::= expr */
140104 {yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
140105 break;
140106 case 204: /* paren_exprlist ::= LP exprlist RP */
140107 case 209: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==209);
140108 {yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
140109 break;
140110 case 205: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
140112 sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
140113 sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
140114 &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
140116 break;
140117 case 206: /* uniqueflag ::= UNIQUE */
140118 case 246: /* raisetype ::= ABORT */ yytestcase(yyruleno==246);
140119 {yymsp[0].minor.yy194 = OE_Abort;}
140120 break;
140121 case 207: /* uniqueflag ::= */
140122 {yymsp[1].minor.yy194 = OE_None;}
140123 break;
140124 case 210: /* eidlist ::= eidlist COMMA nm collate sortorder */
140126 yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
140128 break;
140129 case 211: /* eidlist ::= nm collate sortorder */
140131 yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
140133 break;
140134 case 214: /* cmd ::= DROP INDEX ifexists fullname */
140135 {sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
140136 break;
140137 case 215: /* cmd ::= VACUUM */
140138 {sqlite3Vacuum(pParse,0);}
140139 break;
140140 case 216: /* cmd ::= VACUUM nm */
140141 {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
140142 break;
140143 case 217: /* cmd ::= PRAGMA nm dbnm */
140144 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
140145 break;
140146 case 218: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
140147 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
140148 break;
140149 case 219: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
140150 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
140151 break;
140152 case 220: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
140153 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
140154 break;
140155 case 221: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
140156 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
140157 break;
140158 case 224: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
140160 Token all;
140161 all.z = yymsp[-3].minor.yy0.z;
140162 all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
140163 sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
140165 break;
140166 case 225: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
140168 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);
140169 yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
140171 break;
140172 case 226: /* trigger_time ::= BEFORE|AFTER */
140173 { yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/ }
140174 break;
140175 case 227: /* trigger_time ::= INSTEAD OF */
140176 { yymsp[-1].minor.yy194 = TK_INSTEAD;}
140177 break;
140178 case 228: /* trigger_time ::= */
140179 { yymsp[1].minor.yy194 = TK_BEFORE; }
140180 break;
140181 case 229: /* trigger_event ::= DELETE|INSERT */
140182 case 230: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==230);
140183 {yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
140184 break;
140185 case 231: /* trigger_event ::= UPDATE OF idlist */
140186 {yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
140187 break;
140188 case 232: /* when_clause ::= */
140189 case 251: /* key_opt ::= */ yytestcase(yyruleno==251);
140190 { yymsp[1].minor.yy72 = 0; }
140191 break;
140192 case 233: /* when_clause ::= WHEN expr */
140193 case 252: /* key_opt ::= KEY expr */ yytestcase(yyruleno==252);
140194 { yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
140195 break;
140196 case 234: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
140198 assert( yymsp[-2].minor.yy145!=0 );
140199 yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
140200 yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
140202 break;
140203 case 235: /* trigger_cmd_list ::= trigger_cmd SEMI */
140205 assert( yymsp[-1].minor.yy145!=0 );
140206 yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
140208 break;
140209 case 236: /* trnm ::= nm DOT nm */
140211 yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
140212 sqlite3ErrorMsg(pParse,
140213 "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
140214 "statements within triggers");
140216 break;
140217 case 237: /* tridxby ::= INDEXED BY nm */
140219 sqlite3ErrorMsg(pParse,
140220 "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
140221 "within triggers");
140223 break;
140224 case 238: /* tridxby ::= NOT INDEXED */
140226 sqlite3ErrorMsg(pParse,
140227 "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
140228 "within triggers");
140230 break;
140231 case 239: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
140232 {yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
140233 break;
140234 case 240: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
140235 {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*/}
140236 break;
140237 case 241: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
140238 {yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
140239 break;
140240 case 242: /* trigger_cmd ::= select */
140241 {yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
140242 break;
140243 case 243: /* expr ::= RAISE LP IGNORE RP */
140245 spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
140246 yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
140247 if( yymsp[-3].minor.yy190.pExpr ){
140248 yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
140251 break;
140252 case 244: /* expr ::= RAISE LP raisetype COMMA nm RP */
140254 spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
140255 yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
140256 if( yymsp[-5].minor.yy190.pExpr ) {
140257 yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
140260 break;
140261 case 245: /* raisetype ::= ROLLBACK */
140262 {yymsp[0].minor.yy194 = OE_Rollback;}
140263 break;
140264 case 247: /* raisetype ::= FAIL */
140265 {yymsp[0].minor.yy194 = OE_Fail;}
140266 break;
140267 case 248: /* cmd ::= DROP TRIGGER ifexists fullname */
140269 sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
140271 break;
140272 case 249: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
140274 sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
140276 break;
140277 case 250: /* cmd ::= DETACH database_kw_opt expr */
140279 sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
140281 break;
140282 case 253: /* cmd ::= REINDEX */
140283 {sqlite3Reindex(pParse, 0, 0);}
140284 break;
140285 case 254: /* cmd ::= REINDEX nm dbnm */
140286 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
140287 break;
140288 case 255: /* cmd ::= ANALYZE */
140289 {sqlite3Analyze(pParse, 0, 0);}
140290 break;
140291 case 256: /* cmd ::= ANALYZE nm dbnm */
140292 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
140293 break;
140294 case 257: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
140296 sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
140298 break;
140299 case 258: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
140301 yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
140302 sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
140304 break;
140305 case 259: /* add_column_fullname ::= fullname */
140307 disableLookaside(pParse);
140308 sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
140310 break;
140311 case 260: /* cmd ::= create_vtab */
140312 {sqlite3VtabFinishParse(pParse,0);}
140313 break;
140314 case 261: /* cmd ::= create_vtab LP vtabarglist RP */
140315 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
140316 break;
140317 case 262: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
140319 sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
140321 break;
140322 case 263: /* vtabarg ::= */
140323 {sqlite3VtabArgInit(pParse);}
140324 break;
140325 case 264: /* vtabargtoken ::= ANY */
140326 case 265: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==265);
140327 case 266: /* lp ::= LP */ yytestcase(yyruleno==266);
140328 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
140329 break;
140330 case 267: /* with ::= */
140331 {yymsp[1].minor.yy285 = 0;}
140332 break;
140333 case 268: /* with ::= WITH wqlist */
140334 { yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
140335 break;
140336 case 269: /* with ::= WITH RECURSIVE wqlist */
140337 { yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
140338 break;
140339 case 270: /* wqlist ::= nm eidlist_opt AS LP select RP */
140341 yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
140343 break;
140344 case 271: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
140346 yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
140348 break;
140349 default:
140350 /* (272) input ::= cmdlist */ yytestcase(yyruleno==272);
140351 /* (273) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==273);
140352 /* (274) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=274);
140353 /* (275) ecmd ::= SEMI */ yytestcase(yyruleno==275);
140354 /* (276) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==276);
140355 /* (277) explain ::= */ yytestcase(yyruleno==277);
140356 /* (278) trans_opt ::= */ yytestcase(yyruleno==278);
140357 /* (279) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==279);
140358 /* (280) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==280);
140359 /* (281) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==281);
140360 /* (282) savepoint_opt ::= */ yytestcase(yyruleno==282);
140361 /* (283) cmd ::= create_table create_table_args */ yytestcase(yyruleno==283);
140362 /* (284) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==284);
140363 /* (285) columnlist ::= columnname carglist */ yytestcase(yyruleno==285);
140364 /* (286) nm ::= ID|INDEXED */ yytestcase(yyruleno==286);
140365 /* (287) nm ::= STRING */ yytestcase(yyruleno==287);
140366 /* (288) nm ::= JOIN_KW */ yytestcase(yyruleno==288);
140367 /* (289) typetoken ::= typename */ yytestcase(yyruleno==289);
140368 /* (290) typename ::= ID|STRING */ yytestcase(yyruleno==290);
140369 /* (291) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=291);
140370 /* (292) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=292);
140371 /* (293) carglist ::= carglist ccons */ yytestcase(yyruleno==293);
140372 /* (294) carglist ::= */ yytestcase(yyruleno==294);
140373 /* (295) ccons ::= NULL onconf */ yytestcase(yyruleno==295);
140374 /* (296) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==296);
140375 /* (297) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==297);
140376 /* (298) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=298);
140377 /* (299) tconscomma ::= */ yytestcase(yyruleno==299);
140378 /* (300) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=300);
140379 /* (301) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=301);
140380 /* (302) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=302);
140381 /* (303) oneselect ::= values */ yytestcase(yyruleno==303);
140382 /* (304) sclp ::= selcollist COMMA */ yytestcase(yyruleno==304);
140383 /* (305) as ::= ID|STRING */ yytestcase(yyruleno==305);
140384 /* (306) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=306);
140385 /* (307) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==307);
140386 /* (308) exprlist ::= nexprlist */ yytestcase(yyruleno==308);
140387 /* (309) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=309);
140388 /* (310) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=310);
140389 /* (311) nmnum ::= ON */ yytestcase(yyruleno==311);
140390 /* (312) nmnum ::= DELETE */ yytestcase(yyruleno==312);
140391 /* (313) nmnum ::= DEFAULT */ yytestcase(yyruleno==313);
140392 /* (314) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==314);
140393 /* (315) foreach_clause ::= */ yytestcase(yyruleno==315);
140394 /* (316) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==316);
140395 /* (317) trnm ::= nm */ yytestcase(yyruleno==317);
140396 /* (318) tridxby ::= */ yytestcase(yyruleno==318);
140397 /* (319) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==319);
140398 /* (320) database_kw_opt ::= */ yytestcase(yyruleno==320);
140399 /* (321) kwcolumn_opt ::= */ yytestcase(yyruleno==321);
140400 /* (322) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==322);
140401 /* (323) vtabarglist ::= vtabarg */ yytestcase(yyruleno==323);
140402 /* (324) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==324);
140403 /* (325) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==325);
140404 /* (326) anylist ::= */ yytestcase(yyruleno==326);
140405 /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
140406 /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
140407 break;
140408 /********** End reduce actions ************************************************/
140410 assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
140411 yygoto = yyRuleInfo[yyruleno].lhs;
140412 yysize = yyRuleInfo[yyruleno].nrhs;
140413 yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
140415 /* There are no SHIFTREDUCE actions on nonterminals because the table
140416 ** generator has simplified them to pure REDUCE actions. */
140417 assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
140419 /* It is not possible for a REDUCE to be followed by an error */
140420 assert( yyact!=YY_ERROR_ACTION );
140422 if( yyact==YY_ACCEPT_ACTION ){
140423 yypParser->yytos += yysize;
140424 yy_accept(yypParser);
140425 }else{
140426 yymsp += yysize+1;
140427 yypParser->yytos = yymsp;
140428 yymsp->stateno = (YYACTIONTYPE)yyact;
140429 yymsp->major = (YYCODETYPE)yygoto;
140430 yyTraceShift(yypParser, yyact);
140435 ** The following code executes when the parse fails
140437 #ifndef YYNOERRORRECOVERY
140438 static void yy_parse_failed(
140439 yyParser *yypParser /* The parser */
140441 sqlite3ParserARG_FETCH;
140442 #ifndef NDEBUG
140443 if( yyTraceFILE ){
140444 fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
140446 #endif
140447 while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
140448 /* Here code is inserted which will be executed whenever the
140449 ** parser fails */
140450 /************ Begin %parse_failure code ***************************************/
140451 /************ End %parse_failure code *****************************************/
140452 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
140454 #endif /* YYNOERRORRECOVERY */
140457 ** The following code executes when a syntax error first occurs.
140459 static void yy_syntax_error(
140460 yyParser *yypParser, /* The parser */
140461 int yymajor, /* The major type of the error token */
140462 sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
140464 sqlite3ParserARG_FETCH;
140465 #define TOKEN yyminor
140466 /************ Begin %syntax_error code ****************************************/
140468 UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
140469 assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
140470 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
140471 /************ End %syntax_error code ******************************************/
140472 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
140476 ** The following is executed when the parser accepts
140478 static void yy_accept(
140479 yyParser *yypParser /* The parser */
140481 sqlite3ParserARG_FETCH;
140482 #ifndef NDEBUG
140483 if( yyTraceFILE ){
140484 fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
140486 #endif
140487 #ifndef YYNOERRORRECOVERY
140488 yypParser->yyerrcnt = -1;
140489 #endif
140490 assert( yypParser->yytos==yypParser->yystack );
140491 /* Here code is inserted which will be executed whenever the
140492 ** parser accepts */
140493 /*********** Begin %parse_accept code *****************************************/
140494 /*********** End %parse_accept code *******************************************/
140495 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
140498 /* The main parser program.
140499 ** The first argument is a pointer to a structure obtained from
140500 ** "sqlite3ParserAlloc" which describes the current state of the parser.
140501 ** The second argument is the major token number. The third is
140502 ** the minor token. The fourth optional argument is whatever the
140503 ** user wants (and specified in the grammar) and is available for
140504 ** use by the action routines.
140506 ** Inputs:
140507 ** <ul>
140508 ** <li> A pointer to the parser (an opaque structure.)
140509 ** <li> The major token number.
140510 ** <li> The minor token number.
140511 ** <li> An option argument of a grammar-specified type.
140512 ** </ul>
140514 ** Outputs:
140515 ** None.
140517 SQLITE_PRIVATE void sqlite3Parser(
140518 void *yyp, /* The parser */
140519 int yymajor, /* The major token code number */
140520 sqlite3ParserTOKENTYPE yyminor /* The value for the token */
140521 sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
140523 YYMINORTYPE yyminorunion;
140524 unsigned int yyact; /* The parser action. */
140525 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
140526 int yyendofinput; /* True if we are at the end of input */
140527 #endif
140528 #ifdef YYERRORSYMBOL
140529 int yyerrorhit = 0; /* True if yymajor has invoked an error */
140530 #endif
140531 yyParser *yypParser; /* The parser */
140533 yypParser = (yyParser*)yyp;
140534 assert( yypParser->yytos!=0 );
140535 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
140536 yyendofinput = (yymajor==0);
140537 #endif
140538 sqlite3ParserARG_STORE;
140540 #ifndef NDEBUG
140541 if( yyTraceFILE ){
140542 fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
140544 #endif
140547 yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
140548 if( yyact <= YY_MAX_SHIFTREDUCE ){
140549 yy_shift(yypParser,yyact,yymajor,yyminor);
140550 #ifndef YYNOERRORRECOVERY
140551 yypParser->yyerrcnt--;
140552 #endif
140553 yymajor = YYNOCODE;
140554 }else if( yyact <= YY_MAX_REDUCE ){
140555 yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
140556 }else{
140557 assert( yyact == YY_ERROR_ACTION );
140558 yyminorunion.yy0 = yyminor;
140559 #ifdef YYERRORSYMBOL
140560 int yymx;
140561 #endif
140562 #ifndef NDEBUG
140563 if( yyTraceFILE ){
140564 fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
140566 #endif
140567 #ifdef YYERRORSYMBOL
140568 /* A syntax error has occurred.
140569 ** The response to an error depends upon whether or not the
140570 ** grammar defines an error token "ERROR".
140572 ** This is what we do if the grammar does define ERROR:
140574 ** * Call the %syntax_error function.
140576 ** * Begin popping the stack until we enter a state where
140577 ** it is legal to shift the error symbol, then shift
140578 ** the error symbol.
140580 ** * Set the error count to three.
140582 ** * Begin accepting and shifting new tokens. No new error
140583 ** processing will occur until three tokens have been
140584 ** shifted successfully.
140587 if( yypParser->yyerrcnt<0 ){
140588 yy_syntax_error(yypParser,yymajor,yyminor);
140590 yymx = yypParser->yytos->major;
140591 if( yymx==YYERRORSYMBOL || yyerrorhit ){
140592 #ifndef NDEBUG
140593 if( yyTraceFILE ){
140594 fprintf(yyTraceFILE,"%sDiscard input token %s\n",
140595 yyTracePrompt,yyTokenName[yymajor]);
140597 #endif
140598 yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
140599 yymajor = YYNOCODE;
140600 }else{
140601 while( yypParser->yytos >= yypParser->yystack
140602 && yymx != YYERRORSYMBOL
140603 && (yyact = yy_find_reduce_action(
140604 yypParser->yytos->stateno,
140605 YYERRORSYMBOL)) >= YY_MIN_REDUCE
140607 yy_pop_parser_stack(yypParser);
140609 if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
140610 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
140611 yy_parse_failed(yypParser);
140612 #ifndef YYNOERRORRECOVERY
140613 yypParser->yyerrcnt = -1;
140614 #endif
140615 yymajor = YYNOCODE;
140616 }else if( yymx!=YYERRORSYMBOL ){
140617 yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
140620 yypParser->yyerrcnt = 3;
140621 yyerrorhit = 1;
140622 #elif defined(YYNOERRORRECOVERY)
140623 /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
140624 ** do any kind of error recovery. Instead, simply invoke the syntax
140625 ** error routine and continue going as if nothing had happened.
140627 ** Applications can set this macro (for example inside %include) if
140628 ** they intend to abandon the parse upon the first syntax error seen.
140630 yy_syntax_error(yypParser,yymajor, yyminor);
140631 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
140632 yymajor = YYNOCODE;
140634 #else /* YYERRORSYMBOL is not defined */
140635 /* This is what we do if the grammar does not define ERROR:
140637 ** * Report an error message, and throw away the input token.
140639 ** * If the input token is $, then fail the parse.
140641 ** As before, subsequent error messages are suppressed until
140642 ** three input tokens have been successfully shifted.
140644 if( yypParser->yyerrcnt<=0 ){
140645 yy_syntax_error(yypParser,yymajor, yyminor);
140647 yypParser->yyerrcnt = 3;
140648 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
140649 if( yyendofinput ){
140650 yy_parse_failed(yypParser);
140651 #ifndef YYNOERRORRECOVERY
140652 yypParser->yyerrcnt = -1;
140653 #endif
140655 yymajor = YYNOCODE;
140656 #endif
140658 }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
140659 #ifndef NDEBUG
140660 if( yyTraceFILE ){
140661 yyStackEntry *i;
140662 char cDiv = '[';
140663 fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
140664 for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
140665 fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
140666 cDiv = ' ';
140668 fprintf(yyTraceFILE,"]\n");
140670 #endif
140671 return;
140674 /************** End of parse.c ***********************************************/
140675 /************** Begin file tokenize.c ****************************************/
140677 ** 2001 September 15
140679 ** The author disclaims copyright to this source code. In place of
140680 ** a legal notice, here is a blessing:
140682 ** May you do good and not evil.
140683 ** May you find forgiveness for yourself and forgive others.
140684 ** May you share freely, never taking more than you give.
140686 *************************************************************************
140687 ** An tokenizer for SQL
140689 ** This file contains C code that splits an SQL input string up into
140690 ** individual tokens and sends those tokens one-by-one over to the
140691 ** parser for analysis.
140693 /* #include "sqliteInt.h" */
140694 /* #include <stdlib.h> */
140696 /* Character classes for tokenizing
140698 ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
140699 ** using a lookup table, whereas a switch() directly on c uses a binary search.
140700 ** The lookup table is much faster. To maximize speed, and to ensure that
140701 ** a lookup table is used, all of the classes need to be small integers and
140702 ** all of them need to be used within the switch.
140704 #define CC_X 0 /* The letter 'x', or start of BLOB literal */
140705 #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
140706 #define CC_ID 2 /* unicode characters usable in IDs */
140707 #define CC_DIGIT 3 /* Digits */
140708 #define CC_DOLLAR 4 /* '$' */
140709 #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
140710 #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
140711 #define CC_SPACE 7 /* Space characters */
140712 #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
140713 #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
140714 #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
140715 #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
140716 #define CC_LT 12 /* '<'. Part of < or <= or <> */
140717 #define CC_GT 13 /* '>'. Part of > or >= */
140718 #define CC_EQ 14 /* '='. Part of = or == */
140719 #define CC_BANG 15 /* '!'. Part of != */
140720 #define CC_SLASH 16 /* '/'. / or c-style comment */
140721 #define CC_LP 17 /* '(' */
140722 #define CC_RP 18 /* ')' */
140723 #define CC_SEMI 19 /* ';' */
140724 #define CC_PLUS 20 /* '+' */
140725 #define CC_STAR 21 /* '*' */
140726 #define CC_PERCENT 22 /* '%' */
140727 #define CC_COMMA 23 /* ',' */
140728 #define CC_AND 24 /* '&' */
140729 #define CC_TILDA 25 /* '~' */
140730 #define CC_DOT 26 /* '.' */
140731 #define CC_ILLEGAL 27 /* Illegal character */
140733 static const unsigned char aiClass[] = {
140734 #ifdef SQLITE_ASCII
140735 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
140736 /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
140737 /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140738 /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
140739 /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
140740 /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
140741 /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
140742 /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
140743 /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
140744 /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
140745 /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
140746 /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
140747 /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
140748 /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
140749 /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
140750 /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
140751 /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
140752 #endif
140753 #ifdef SQLITE_EBCDIC
140754 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
140755 /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
140756 /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140757 /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140758 /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140759 /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
140760 /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
140761 /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6,
140762 /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
140763 /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
140764 /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
140765 /* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
140766 /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
140767 /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
140768 /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
140769 /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
140770 /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
140771 #endif
140775 ** The charMap() macro maps alphabetic characters (only) into their
140776 ** lower-case ASCII equivalent. On ASCII machines, this is just
140777 ** an upper-to-lower case map. On EBCDIC machines we also need
140778 ** to adjust the encoding. The mapping is only valid for alphabetics
140779 ** which are the only characters for which this feature is used.
140781 ** Used by keywordhash.h
140783 #ifdef SQLITE_ASCII
140784 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
140785 #endif
140786 #ifdef SQLITE_EBCDIC
140787 # define charMap(X) ebcdicToAscii[(unsigned char)X]
140788 const unsigned char ebcdicToAscii[] = {
140789 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
140790 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
140791 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
140792 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
140793 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
140794 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
140795 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
140796 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
140797 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
140798 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
140799 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
140800 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
140801 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
140802 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
140803 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
140804 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
140805 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
140807 #endif
140810 ** The sqlite3KeywordCode function looks up an identifier to determine if
140811 ** it is a keyword. If it is a keyword, the token code of that keyword is
140812 ** returned. If the input is not a keyword, TK_ID is returned.
140814 ** The implementation of this routine was generated by a program,
140815 ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
140816 ** The output of the mkkeywordhash.c program is written into a file
140817 ** named keywordhash.h and then included into this source file by
140818 ** the #include below.
140820 /************** Include keywordhash.h in the middle of tokenize.c ************/
140821 /************** Begin file keywordhash.h *************************************/
140822 /***** This file contains automatically generated code ******
140824 ** The code in this file has been automatically generated by
140826 ** sqlite/tool/mkkeywordhash.c
140828 ** The code in this file implements a function that determines whether
140829 ** or not a given identifier is really an SQL keyword. The same thing
140830 ** might be implemented more directly using a hand-written hash table.
140831 ** But by using this automatically generated code, the size of the code
140832 ** is substantially reduced. This is important for embedded applications
140833 ** on platforms with limited memory.
140835 /* Hash score: 182 */
140836 /* zKWText[] encodes 834 bytes of keyword text in 554 bytes */
140837 /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
140838 /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
140839 /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
140840 /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
140841 /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
140842 /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
140843 /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
140844 /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
140845 /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
140846 /* VACUUMVIEWINITIALLY */
140847 static const char zKWText[553] = {
140848 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
140849 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
140850 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
140851 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
140852 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
140853 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
140854 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
140855 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
140856 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
140857 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
140858 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
140859 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
140860 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
140861 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
140862 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
140863 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
140864 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
140865 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
140866 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
140867 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
140868 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
140869 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
140870 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
140871 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
140872 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
140873 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
140874 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
140875 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
140876 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
140877 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
140878 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
140880 /* aKWHash[i] is the hash value for the i-th keyword */
140881 static const unsigned char aKWHash[127] = {
140882 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
140883 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
140884 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
140885 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
140886 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
140887 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
140888 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
140889 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
140890 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
140891 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
140893 /* aKWNext[] forms the hash collision chain. If aKWHash[i]==0
140894 ** then the i-th keyword has no more hash collisions. Otherwise,
140895 ** the next keyword with the same hash is aKWHash[i]-1. */
140896 static const unsigned char aKWNext[124] = {
140897 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
140898 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
140899 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
140900 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
140901 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
140902 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
140903 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
140904 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
140905 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
140906 73, 83, 0, 35, 68, 0, 0,
140908 /* aKWLen[i] is the length (in bytes) of the i-th keyword */
140909 static const unsigned char aKWLen[124] = {
140910 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
140911 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
140912 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
140913 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
140914 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
140915 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
140916 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
140917 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
140918 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
140919 3, 5, 5, 6, 4, 9, 3,
140921 /* aKWOffset[i] is the index into zKWText[] of the start of
140922 ** the text for the i-th keyword. */
140923 static const unsigned short int aKWOffset[124] = {
140924 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
140925 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
140926 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
140927 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
140928 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
140929 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
140930 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
140931 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
140932 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
140933 521, 524, 529, 534, 540, 544, 549,
140935 /* aKWCode[i] is the parser symbol code for the i-th keyword */
140936 static const unsigned char aKWCode[124] = {
140937 TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
140938 TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
140939 TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
140940 TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
140941 TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
140942 TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
140943 TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
140944 TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
140945 TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
140946 TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
140947 TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
140948 TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
140949 TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
140950 TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
140951 TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
140952 TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
140953 TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
140954 TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
140955 TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
140956 TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
140957 TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
140958 TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
140959 TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
140960 TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
140961 TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
140963 /* Check to see if z[0..n-1] is a keyword. If it is, write the
140964 ** parser symbol code for that keyword into *pType. Always
140965 ** return the integer n (the length of the token). */
140966 static int keywordCode(const char *z, int n, int *pType){
140967 int i, j;
140968 const char *zKW;
140969 if( n>=2 ){
140970 i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
140971 for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
140972 if( aKWLen[i]!=n ) continue;
140973 j = 0;
140974 zKW = &zKWText[aKWOffset[i]];
140975 #ifdef SQLITE_ASCII
140976 while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
140977 #endif
140978 #ifdef SQLITE_EBCDIC
140979 while( j<n && toupper(z[j])==zKW[j] ){ j++; }
140980 #endif
140981 if( j<n ) continue;
140982 testcase( i==0 ); /* REINDEX */
140983 testcase( i==1 ); /* INDEXED */
140984 testcase( i==2 ); /* INDEX */
140985 testcase( i==3 ); /* DESC */
140986 testcase( i==4 ); /* ESCAPE */
140987 testcase( i==5 ); /* EACH */
140988 testcase( i==6 ); /* CHECK */
140989 testcase( i==7 ); /* KEY */
140990 testcase( i==8 ); /* BEFORE */
140991 testcase( i==9 ); /* FOREIGN */
140992 testcase( i==10 ); /* FOR */
140993 testcase( i==11 ); /* IGNORE */
140994 testcase( i==12 ); /* REGEXP */
140995 testcase( i==13 ); /* EXPLAIN */
140996 testcase( i==14 ); /* INSTEAD */
140997 testcase( i==15 ); /* ADD */
140998 testcase( i==16 ); /* DATABASE */
140999 testcase( i==17 ); /* AS */
141000 testcase( i==18 ); /* SELECT */
141001 testcase( i==19 ); /* TABLE */
141002 testcase( i==20 ); /* LEFT */
141003 testcase( i==21 ); /* THEN */
141004 testcase( i==22 ); /* END */
141005 testcase( i==23 ); /* DEFERRABLE */
141006 testcase( i==24 ); /* ELSE */
141007 testcase( i==25 ); /* EXCEPT */
141008 testcase( i==26 ); /* TRANSACTION */
141009 testcase( i==27 ); /* ACTION */
141010 testcase( i==28 ); /* ON */
141011 testcase( i==29 ); /* NATURAL */
141012 testcase( i==30 ); /* ALTER */
141013 testcase( i==31 ); /* RAISE */
141014 testcase( i==32 ); /* EXCLUSIVE */
141015 testcase( i==33 ); /* EXISTS */
141016 testcase( i==34 ); /* SAVEPOINT */
141017 testcase( i==35 ); /* INTERSECT */
141018 testcase( i==36 ); /* TRIGGER */
141019 testcase( i==37 ); /* REFERENCES */
141020 testcase( i==38 ); /* CONSTRAINT */
141021 testcase( i==39 ); /* INTO */
141022 testcase( i==40 ); /* OFFSET */
141023 testcase( i==41 ); /* OF */
141024 testcase( i==42 ); /* SET */
141025 testcase( i==43 ); /* TEMPORARY */
141026 testcase( i==44 ); /* TEMP */
141027 testcase( i==45 ); /* OR */
141028 testcase( i==46 ); /* UNIQUE */
141029 testcase( i==47 ); /* QUERY */
141030 testcase( i==48 ); /* WITHOUT */
141031 testcase( i==49 ); /* WITH */
141032 testcase( i==50 ); /* OUTER */
141033 testcase( i==51 ); /* RELEASE */
141034 testcase( i==52 ); /* ATTACH */
141035 testcase( i==53 ); /* HAVING */
141036 testcase( i==54 ); /* GROUP */
141037 testcase( i==55 ); /* UPDATE */
141038 testcase( i==56 ); /* BEGIN */
141039 testcase( i==57 ); /* INNER */
141040 testcase( i==58 ); /* RECURSIVE */
141041 testcase( i==59 ); /* BETWEEN */
141042 testcase( i==60 ); /* NOTNULL */
141043 testcase( i==61 ); /* NOT */
141044 testcase( i==62 ); /* NO */
141045 testcase( i==63 ); /* NULL */
141046 testcase( i==64 ); /* LIKE */
141047 testcase( i==65 ); /* CASCADE */
141048 testcase( i==66 ); /* ASC */
141049 testcase( i==67 ); /* DELETE */
141050 testcase( i==68 ); /* CASE */
141051 testcase( i==69 ); /* COLLATE */
141052 testcase( i==70 ); /* CREATE */
141053 testcase( i==71 ); /* CURRENT_DATE */
141054 testcase( i==72 ); /* DETACH */
141055 testcase( i==73 ); /* IMMEDIATE */
141056 testcase( i==74 ); /* JOIN */
141057 testcase( i==75 ); /* INSERT */
141058 testcase( i==76 ); /* MATCH */
141059 testcase( i==77 ); /* PLAN */
141060 testcase( i==78 ); /* ANALYZE */
141061 testcase( i==79 ); /* PRAGMA */
141062 testcase( i==80 ); /* ABORT */
141063 testcase( i==81 ); /* VALUES */
141064 testcase( i==82 ); /* VIRTUAL */
141065 testcase( i==83 ); /* LIMIT */
141066 testcase( i==84 ); /* WHEN */
141067 testcase( i==85 ); /* WHERE */
141068 testcase( i==86 ); /* RENAME */
141069 testcase( i==87 ); /* AFTER */
141070 testcase( i==88 ); /* REPLACE */
141071 testcase( i==89 ); /* AND */
141072 testcase( i==90 ); /* DEFAULT */
141073 testcase( i==91 ); /* AUTOINCREMENT */
141074 testcase( i==92 ); /* TO */
141075 testcase( i==93 ); /* IN */
141076 testcase( i==94 ); /* CAST */
141077 testcase( i==95 ); /* COLUMN */
141078 testcase( i==96 ); /* COMMIT */
141079 testcase( i==97 ); /* CONFLICT */
141080 testcase( i==98 ); /* CROSS */
141081 testcase( i==99 ); /* CURRENT_TIMESTAMP */
141082 testcase( i==100 ); /* CURRENT_TIME */
141083 testcase( i==101 ); /* PRIMARY */
141084 testcase( i==102 ); /* DEFERRED */
141085 testcase( i==103 ); /* DISTINCT */
141086 testcase( i==104 ); /* IS */
141087 testcase( i==105 ); /* DROP */
141088 testcase( i==106 ); /* FAIL */
141089 testcase( i==107 ); /* FROM */
141090 testcase( i==108 ); /* FULL */
141091 testcase( i==109 ); /* GLOB */
141092 testcase( i==110 ); /* BY */
141093 testcase( i==111 ); /* IF */
141094 testcase( i==112 ); /* ISNULL */
141095 testcase( i==113 ); /* ORDER */
141096 testcase( i==114 ); /* RESTRICT */
141097 testcase( i==115 ); /* RIGHT */
141098 testcase( i==116 ); /* ROLLBACK */
141099 testcase( i==117 ); /* ROW */
141100 testcase( i==118 ); /* UNION */
141101 testcase( i==119 ); /* USING */
141102 testcase( i==120 ); /* VACUUM */
141103 testcase( i==121 ); /* VIEW */
141104 testcase( i==122 ); /* INITIALLY */
141105 testcase( i==123 ); /* ALL */
141106 *pType = aKWCode[i];
141107 break;
141110 return n;
141112 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
141113 int id = TK_ID;
141114 keywordCode((char*)z, n, &id);
141115 return id;
141117 #define SQLITE_N_KEYWORD 124
141119 /************** End of keywordhash.h *****************************************/
141120 /************** Continuing where we left off in tokenize.c *******************/
141124 ** If X is a character that can be used in an identifier then
141125 ** IdChar(X) will be true. Otherwise it is false.
141127 ** For ASCII, any character with the high-order bit set is
141128 ** allowed in an identifier. For 7-bit characters,
141129 ** sqlite3IsIdChar[X] must be 1.
141131 ** For EBCDIC, the rules are more complex but have the same
141132 ** end result.
141134 ** Ticket #1066. the SQL standard does not allow '$' in the
141135 ** middle of identifiers. But many SQL implementations do.
141136 ** SQLite will allow '$' in identifiers for compatibility.
141137 ** But the feature is undocumented.
141139 #ifdef SQLITE_ASCII
141140 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
141141 #endif
141142 #ifdef SQLITE_EBCDIC
141143 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
141144 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
141145 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
141146 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
141147 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
141148 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
141149 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
141150 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
141151 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
141152 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
141153 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
141154 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
141155 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
141156 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
141158 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
141159 #endif
141161 /* Make the IdChar function accessible from ctime.c */
141162 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
141163 SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
141164 #endif
141168 ** Return the length (in bytes) of the token that begins at z[0].
141169 ** Store the token type in *tokenType before returning.
141171 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
141172 int i, c;
141173 switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
141174 ** of the token. See the comment on the CC_ defines
141175 ** above. */
141176 case CC_SPACE: {
141177 testcase( z[0]==' ' );
141178 testcase( z[0]=='\t' );
141179 testcase( z[0]=='\n' );
141180 testcase( z[0]=='\f' );
141181 testcase( z[0]=='\r' );
141182 for(i=1; sqlite3Isspace(z[i]); i++){}
141183 *tokenType = TK_SPACE;
141184 return i;
141186 case CC_MINUS: {
141187 if( z[1]=='-' ){
141188 for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
141189 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
141190 return i;
141192 *tokenType = TK_MINUS;
141193 return 1;
141195 case CC_LP: {
141196 *tokenType = TK_LP;
141197 return 1;
141199 case CC_RP: {
141200 *tokenType = TK_RP;
141201 return 1;
141203 case CC_SEMI: {
141204 *tokenType = TK_SEMI;
141205 return 1;
141207 case CC_PLUS: {
141208 *tokenType = TK_PLUS;
141209 return 1;
141211 case CC_STAR: {
141212 *tokenType = TK_STAR;
141213 return 1;
141215 case CC_SLASH: {
141216 if( z[1]!='*' || z[2]==0 ){
141217 *tokenType = TK_SLASH;
141218 return 1;
141220 for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
141221 if( c ) i++;
141222 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
141223 return i;
141225 case CC_PERCENT: {
141226 *tokenType = TK_REM;
141227 return 1;
141229 case CC_EQ: {
141230 *tokenType = TK_EQ;
141231 return 1 + (z[1]=='=');
141233 case CC_LT: {
141234 if( (c=z[1])=='=' ){
141235 *tokenType = TK_LE;
141236 return 2;
141237 }else if( c=='>' ){
141238 *tokenType = TK_NE;
141239 return 2;
141240 }else if( c=='<' ){
141241 *tokenType = TK_LSHIFT;
141242 return 2;
141243 }else{
141244 *tokenType = TK_LT;
141245 return 1;
141248 case CC_GT: {
141249 if( (c=z[1])=='=' ){
141250 *tokenType = TK_GE;
141251 return 2;
141252 }else if( c=='>' ){
141253 *tokenType = TK_RSHIFT;
141254 return 2;
141255 }else{
141256 *tokenType = TK_GT;
141257 return 1;
141260 case CC_BANG: {
141261 if( z[1]!='=' ){
141262 *tokenType = TK_ILLEGAL;
141263 return 1;
141264 }else{
141265 *tokenType = TK_NE;
141266 return 2;
141269 case CC_PIPE: {
141270 if( z[1]!='|' ){
141271 *tokenType = TK_BITOR;
141272 return 1;
141273 }else{
141274 *tokenType = TK_CONCAT;
141275 return 2;
141278 case CC_COMMA: {
141279 *tokenType = TK_COMMA;
141280 return 1;
141282 case CC_AND: {
141283 *tokenType = TK_BITAND;
141284 return 1;
141286 case CC_TILDA: {
141287 *tokenType = TK_BITNOT;
141288 return 1;
141290 case CC_QUOTE: {
141291 int delim = z[0];
141292 testcase( delim=='`' );
141293 testcase( delim=='\'' );
141294 testcase( delim=='"' );
141295 for(i=1; (c=z[i])!=0; i++){
141296 if( c==delim ){
141297 if( z[i+1]==delim ){
141299 }else{
141300 break;
141304 if( c=='\'' ){
141305 *tokenType = TK_STRING;
141306 return i+1;
141307 }else if( c!=0 ){
141308 *tokenType = TK_ID;
141309 return i+1;
141310 }else{
141311 *tokenType = TK_ILLEGAL;
141312 return i;
141315 case CC_DOT: {
141316 #ifndef SQLITE_OMIT_FLOATING_POINT
141317 if( !sqlite3Isdigit(z[1]) )
141318 #endif
141320 *tokenType = TK_DOT;
141321 return 1;
141323 /* If the next character is a digit, this is a floating point
141324 ** number that begins with ".". Fall thru into the next case */
141326 case CC_DIGIT: {
141327 testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
141328 testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
141329 testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
141330 testcase( z[0]=='9' );
141331 *tokenType = TK_INTEGER;
141332 #ifndef SQLITE_OMIT_HEX_INTEGER
141333 if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
141334 for(i=3; sqlite3Isxdigit(z[i]); i++){}
141335 return i;
141337 #endif
141338 for(i=0; sqlite3Isdigit(z[i]); i++){}
141339 #ifndef SQLITE_OMIT_FLOATING_POINT
141340 if( z[i]=='.' ){
141342 while( sqlite3Isdigit(z[i]) ){ i++; }
141343 *tokenType = TK_FLOAT;
141345 if( (z[i]=='e' || z[i]=='E') &&
141346 ( sqlite3Isdigit(z[i+1])
141347 || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
141350 i += 2;
141351 while( sqlite3Isdigit(z[i]) ){ i++; }
141352 *tokenType = TK_FLOAT;
141354 #endif
141355 while( IdChar(z[i]) ){
141356 *tokenType = TK_ILLEGAL;
141359 return i;
141361 case CC_QUOTE2: {
141362 for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
141363 *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
141364 return i;
141366 case CC_VARNUM: {
141367 *tokenType = TK_VARIABLE;
141368 for(i=1; sqlite3Isdigit(z[i]); i++){}
141369 return i;
141371 case CC_DOLLAR:
141372 case CC_VARALPHA: {
141373 int n = 0;
141374 testcase( z[0]=='$' ); testcase( z[0]=='@' );
141375 testcase( z[0]==':' ); testcase( z[0]=='#' );
141376 *tokenType = TK_VARIABLE;
141377 for(i=1; (c=z[i])!=0; i++){
141378 if( IdChar(c) ){
141380 #ifndef SQLITE_OMIT_TCL_VARIABLE
141381 }else if( c=='(' && n>0 ){
141384 }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
141385 if( c==')' ){
141387 }else{
141388 *tokenType = TK_ILLEGAL;
141390 break;
141391 }else if( c==':' && z[i+1]==':' ){
141393 #endif
141394 }else{
141395 break;
141398 if( n==0 ) *tokenType = TK_ILLEGAL;
141399 return i;
141401 case CC_KYWD: {
141402 for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
141403 if( IdChar(z[i]) ){
141404 /* This token started out using characters that can appear in keywords,
141405 ** but z[i] is a character not allowed within keywords, so this must
141406 ** be an identifier instead */
141408 break;
141410 *tokenType = TK_ID;
141411 return keywordCode((char*)z, i, tokenType);
141413 case CC_X: {
141414 #ifndef SQLITE_OMIT_BLOB_LITERAL
141415 testcase( z[0]=='x' ); testcase( z[0]=='X' );
141416 if( z[1]=='\'' ){
141417 *tokenType = TK_BLOB;
141418 for(i=2; sqlite3Isxdigit(z[i]); i++){}
141419 if( z[i]!='\'' || i%2 ){
141420 *tokenType = TK_ILLEGAL;
141421 while( z[i] && z[i]!='\'' ){ i++; }
141423 if( z[i] ) i++;
141424 return i;
141426 #endif
141427 /* If it is not a BLOB literal, then it must be an ID, since no
141428 ** SQL keywords start with the letter 'x'. Fall through */
141430 case CC_ID: {
141431 i = 1;
141432 break;
141434 default: {
141435 *tokenType = TK_ILLEGAL;
141436 return 1;
141439 while( IdChar(z[i]) ){ i++; }
141440 *tokenType = TK_ID;
141441 return i;
141445 ** Run the parser on the given SQL string. The parser structure is
141446 ** passed in. An SQLITE_ status code is returned. If an error occurs
141447 ** then an and attempt is made to write an error message into
141448 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
141449 ** error message.
141451 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
141452 int nErr = 0; /* Number of errors encountered */
141453 void *pEngine; /* The LEMON-generated LALR(1) parser */
141454 int n = 0; /* Length of the next token token */
141455 int tokenType; /* type of the next token */
141456 int lastTokenParsed = -1; /* type of the previous token */
141457 sqlite3 *db = pParse->db; /* The database connection */
141458 int mxSqlLen; /* Max length of an SQL string */
141459 #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
141460 yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
141461 #endif
141463 assert( zSql!=0 );
141464 mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
141465 if( db->nVdbeActive==0 ){
141466 db->u1.isInterrupted = 0;
141468 pParse->rc = SQLITE_OK;
141469 pParse->zTail = zSql;
141470 assert( pzErrMsg!=0 );
141471 /* sqlite3ParserTrace(stdout, "parser: "); */
141472 #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
141473 pEngine = &sEngine;
141474 sqlite3ParserInit(pEngine);
141475 #else
141476 pEngine = sqlite3ParserAlloc(sqlite3Malloc);
141477 if( pEngine==0 ){
141478 sqlite3OomFault(db);
141479 return SQLITE_NOMEM_BKPT;
141481 #endif
141482 assert( pParse->pNewTable==0 );
141483 assert( pParse->pNewTrigger==0 );
141484 assert( pParse->nVar==0 );
141485 assert( pParse->pVList==0 );
141486 while( 1 ){
141487 if( zSql[0]!=0 ){
141488 n = sqlite3GetToken((u8*)zSql, &tokenType);
141489 mxSqlLen -= n;
141490 if( mxSqlLen<0 ){
141491 pParse->rc = SQLITE_TOOBIG;
141492 break;
141494 }else{
141495 /* Upon reaching the end of input, call the parser two more times
141496 ** with tokens TK_SEMI and 0, in that order. */
141497 if( lastTokenParsed==TK_SEMI ){
141498 tokenType = 0;
141499 }else if( lastTokenParsed==0 ){
141500 break;
141501 }else{
141502 tokenType = TK_SEMI;
141504 zSql -= n;
141506 if( tokenType>=TK_SPACE ){
141507 assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
141508 if( db->u1.isInterrupted ){
141509 pParse->rc = SQLITE_INTERRUPT;
141510 break;
141512 if( tokenType==TK_ILLEGAL ){
141513 sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
141514 break;
141516 zSql += n;
141517 }else{
141518 pParse->sLastToken.z = zSql;
141519 pParse->sLastToken.n = n;
141520 sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
141521 lastTokenParsed = tokenType;
141522 zSql += n;
141523 if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
141526 assert( nErr==0 );
141527 pParse->zTail = zSql;
141528 #ifdef YYTRACKMAXSTACKDEPTH
141529 sqlite3_mutex_enter(sqlite3MallocMutex());
141530 sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
141531 sqlite3ParserStackPeak(pEngine)
141533 sqlite3_mutex_leave(sqlite3MallocMutex());
141534 #endif /* YYDEBUG */
141535 #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
141536 sqlite3ParserFinalize(pEngine);
141537 #else
141538 sqlite3ParserFree(pEngine, sqlite3_free);
141539 #endif
141540 if( db->mallocFailed ){
141541 pParse->rc = SQLITE_NOMEM_BKPT;
141543 if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
141544 pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
141546 assert( pzErrMsg!=0 );
141547 if( pParse->zErrMsg ){
141548 *pzErrMsg = pParse->zErrMsg;
141549 sqlite3_log(pParse->rc, "%s", *pzErrMsg);
141550 pParse->zErrMsg = 0;
141551 nErr++;
141553 if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
141554 sqlite3VdbeDelete(pParse->pVdbe);
141555 pParse->pVdbe = 0;
141557 #ifndef SQLITE_OMIT_SHARED_CACHE
141558 if( pParse->nested==0 ){
141559 sqlite3DbFree(db, pParse->aTableLock);
141560 pParse->aTableLock = 0;
141561 pParse->nTableLock = 0;
141563 #endif
141564 #ifndef SQLITE_OMIT_VIRTUALTABLE
141565 sqlite3_free(pParse->apVtabLock);
141566 #endif
141568 if( !IN_DECLARE_VTAB ){
141569 /* If the pParse->declareVtab flag is set, do not delete any table
141570 ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
141571 ** will take responsibility for freeing the Table structure.
141573 sqlite3DeleteTable(db, pParse->pNewTable);
141576 if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
141577 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
141578 sqlite3DbFree(db, pParse->pVList);
141579 while( pParse->pAinc ){
141580 AutoincInfo *p = pParse->pAinc;
141581 pParse->pAinc = p->pNext;
141582 sqlite3DbFreeNN(db, p);
141584 while( pParse->pZombieTab ){
141585 Table *p = pParse->pZombieTab;
141586 pParse->pZombieTab = p->pNextZombie;
141587 sqlite3DeleteTable(db, p);
141589 assert( nErr==0 || pParse->rc!=SQLITE_OK );
141590 return nErr;
141593 /************** End of tokenize.c ********************************************/
141594 /************** Begin file complete.c ****************************************/
141596 ** 2001 September 15
141598 ** The author disclaims copyright to this source code. In place of
141599 ** a legal notice, here is a blessing:
141601 ** May you do good and not evil.
141602 ** May you find forgiveness for yourself and forgive others.
141603 ** May you share freely, never taking more than you give.
141605 *************************************************************************
141606 ** An tokenizer for SQL
141608 ** This file contains C code that implements the sqlite3_complete() API.
141609 ** This code used to be part of the tokenizer.c source file. But by
141610 ** separating it out, the code will be automatically omitted from
141611 ** static links that do not use it.
141613 /* #include "sqliteInt.h" */
141614 #ifndef SQLITE_OMIT_COMPLETE
141617 ** This is defined in tokenize.c. We just have to import the definition.
141619 #ifndef SQLITE_AMALGAMATION
141620 #ifdef SQLITE_ASCII
141621 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
141622 #endif
141623 #ifdef SQLITE_EBCDIC
141624 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
141625 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
141626 #endif
141627 #endif /* SQLITE_AMALGAMATION */
141631 ** Token types used by the sqlite3_complete() routine. See the header
141632 ** comments on that procedure for additional information.
141634 #define tkSEMI 0
141635 #define tkWS 1
141636 #define tkOTHER 2
141637 #ifndef SQLITE_OMIT_TRIGGER
141638 #define tkEXPLAIN 3
141639 #define tkCREATE 4
141640 #define tkTEMP 5
141641 #define tkTRIGGER 6
141642 #define tkEND 7
141643 #endif
141646 ** Return TRUE if the given SQL string ends in a semicolon.
141648 ** Special handling is require for CREATE TRIGGER statements.
141649 ** Whenever the CREATE TRIGGER keywords are seen, the statement
141650 ** must end with ";END;".
141652 ** This implementation uses a state machine with 8 states:
141654 ** (0) INVALID We have not yet seen a non-whitespace character.
141656 ** (1) START At the beginning or end of an SQL statement. This routine
141657 ** returns 1 if it ends in the START state and 0 if it ends
141658 ** in any other state.
141660 ** (2) NORMAL We are in the middle of statement which ends with a single
141661 ** semicolon.
141663 ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
141664 ** a statement.
141666 ** (4) CREATE The keyword CREATE has been seen at the beginning of a
141667 ** statement, possibly preceded by EXPLAIN and/or followed by
141668 ** TEMP or TEMPORARY
141670 ** (5) TRIGGER We are in the middle of a trigger definition that must be
141671 ** ended by a semicolon, the keyword END, and another semicolon.
141673 ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
141674 ** the end of a trigger definition.
141676 ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
141677 ** of a trigger definition.
141679 ** Transitions between states above are determined by tokens extracted
141680 ** from the input. The following tokens are significant:
141682 ** (0) tkSEMI A semicolon.
141683 ** (1) tkWS Whitespace.
141684 ** (2) tkOTHER Any other SQL token.
141685 ** (3) tkEXPLAIN The "explain" keyword.
141686 ** (4) tkCREATE The "create" keyword.
141687 ** (5) tkTEMP The "temp" or "temporary" keyword.
141688 ** (6) tkTRIGGER The "trigger" keyword.
141689 ** (7) tkEND The "end" keyword.
141691 ** Whitespace never causes a state transition and is always ignored.
141692 ** This means that a SQL string of all whitespace is invalid.
141694 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
141695 ** to recognize the end of a trigger can be omitted. All we have to do
141696 ** is look for a semicolon that is not part of an string or comment.
141698 SQLITE_API int sqlite3_complete(const char *zSql){
141699 u8 state = 0; /* Current state, using numbers defined in header comment */
141700 u8 token; /* Value of the next token */
141702 #ifndef SQLITE_OMIT_TRIGGER
141703 /* A complex statement machine used to detect the end of a CREATE TRIGGER
141704 ** statement. This is the normal case.
141706 static const u8 trans[8][8] = {
141707 /* Token: */
141708 /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
141709 /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
141710 /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
141711 /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
141712 /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
141713 /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
141714 /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
141715 /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
141716 /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
141718 #else
141719 /* If triggers are not supported by this compile then the statement machine
141720 ** used to detect the end of a statement is much simpler
141722 static const u8 trans[3][3] = {
141723 /* Token: */
141724 /* State: ** SEMI WS OTHER */
141725 /* 0 INVALID: */ { 1, 0, 2, },
141726 /* 1 START: */ { 1, 1, 2, },
141727 /* 2 NORMAL: */ { 1, 2, 2, },
141729 #endif /* SQLITE_OMIT_TRIGGER */
141731 #ifdef SQLITE_ENABLE_API_ARMOR
141732 if( zSql==0 ){
141733 (void)SQLITE_MISUSE_BKPT;
141734 return 0;
141736 #endif
141738 while( *zSql ){
141739 switch( *zSql ){
141740 case ';': { /* A semicolon */
141741 token = tkSEMI;
141742 break;
141744 case ' ':
141745 case '\r':
141746 case '\t':
141747 case '\n':
141748 case '\f': { /* White space is ignored */
141749 token = tkWS;
141750 break;
141752 case '/': { /* C-style comments */
141753 if( zSql[1]!='*' ){
141754 token = tkOTHER;
141755 break;
141757 zSql += 2;
141758 while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
141759 if( zSql[0]==0 ) return 0;
141760 zSql++;
141761 token = tkWS;
141762 break;
141764 case '-': { /* SQL-style comments from "--" to end of line */
141765 if( zSql[1]!='-' ){
141766 token = tkOTHER;
141767 break;
141769 while( *zSql && *zSql!='\n' ){ zSql++; }
141770 if( *zSql==0 ) return state==1;
141771 token = tkWS;
141772 break;
141774 case '[': { /* Microsoft-style identifiers in [...] */
141775 zSql++;
141776 while( *zSql && *zSql!=']' ){ zSql++; }
141777 if( *zSql==0 ) return 0;
141778 token = tkOTHER;
141779 break;
141781 case '`': /* Grave-accent quoted symbols used by MySQL */
141782 case '"': /* single- and double-quoted strings */
141783 case '\'': {
141784 int c = *zSql;
141785 zSql++;
141786 while( *zSql && *zSql!=c ){ zSql++; }
141787 if( *zSql==0 ) return 0;
141788 token = tkOTHER;
141789 break;
141791 default: {
141792 #ifdef SQLITE_EBCDIC
141793 unsigned char c;
141794 #endif
141795 if( IdChar((u8)*zSql) ){
141796 /* Keywords and unquoted identifiers */
141797 int nId;
141798 for(nId=1; IdChar(zSql[nId]); nId++){}
141799 #ifdef SQLITE_OMIT_TRIGGER
141800 token = tkOTHER;
141801 #else
141802 switch( *zSql ){
141803 case 'c': case 'C': {
141804 if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
141805 token = tkCREATE;
141806 }else{
141807 token = tkOTHER;
141809 break;
141811 case 't': case 'T': {
141812 if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
141813 token = tkTRIGGER;
141814 }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
141815 token = tkTEMP;
141816 }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
141817 token = tkTEMP;
141818 }else{
141819 token = tkOTHER;
141821 break;
141823 case 'e': case 'E': {
141824 if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
141825 token = tkEND;
141826 }else
141827 #ifndef SQLITE_OMIT_EXPLAIN
141828 if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
141829 token = tkEXPLAIN;
141830 }else
141831 #endif
141833 token = tkOTHER;
141835 break;
141837 default: {
141838 token = tkOTHER;
141839 break;
141842 #endif /* SQLITE_OMIT_TRIGGER */
141843 zSql += nId-1;
141844 }else{
141845 /* Operators and special symbols */
141846 token = tkOTHER;
141848 break;
141851 state = trans[state][token];
141852 zSql++;
141854 return state==1;
141857 #ifndef SQLITE_OMIT_UTF16
141859 ** This routine is the same as the sqlite3_complete() routine described
141860 ** above, except that the parameter is required to be UTF-16 encoded, not
141861 ** UTF-8.
141863 SQLITE_API int sqlite3_complete16(const void *zSql){
141864 sqlite3_value *pVal;
141865 char const *zSql8;
141866 int rc;
141868 #ifndef SQLITE_OMIT_AUTOINIT
141869 rc = sqlite3_initialize();
141870 if( rc ) return rc;
141871 #endif
141872 pVal = sqlite3ValueNew(0);
141873 sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
141874 zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
141875 if( zSql8 ){
141876 rc = sqlite3_complete(zSql8);
141877 }else{
141878 rc = SQLITE_NOMEM_BKPT;
141880 sqlite3ValueFree(pVal);
141881 return rc & 0xff;
141883 #endif /* SQLITE_OMIT_UTF16 */
141884 #endif /* SQLITE_OMIT_COMPLETE */
141886 /************** End of complete.c ********************************************/
141887 /************** Begin file main.c ********************************************/
141889 ** 2001 September 15
141891 ** The author disclaims copyright to this source code. In place of
141892 ** a legal notice, here is a blessing:
141894 ** May you do good and not evil.
141895 ** May you find forgiveness for yourself and forgive others.
141896 ** May you share freely, never taking more than you give.
141898 *************************************************************************
141899 ** Main file for the SQLite library. The routines in this file
141900 ** implement the programmer interface to the library. Routines in
141901 ** other files are for internal use by SQLite and should not be
141902 ** accessed by users of the library.
141904 /* #include "sqliteInt.h" */
141906 #ifdef SQLITE_ENABLE_FTS3
141907 /************** Include fts3.h in the middle of main.c ***********************/
141908 /************** Begin file fts3.h ********************************************/
141910 ** 2006 Oct 10
141912 ** The author disclaims copyright to this source code. In place of
141913 ** a legal notice, here is a blessing:
141915 ** May you do good and not evil.
141916 ** May you find forgiveness for yourself and forgive others.
141917 ** May you share freely, never taking more than you give.
141919 ******************************************************************************
141921 ** This header file is used by programs that want to link against the
141922 ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
141924 /* #include "sqlite3.h" */
141926 #if 0
141927 extern "C" {
141928 #endif /* __cplusplus */
141930 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
141932 #if 0
141933 } /* extern "C" */
141934 #endif /* __cplusplus */
141936 /************** End of fts3.h ************************************************/
141937 /************** Continuing where we left off in main.c ***********************/
141938 #endif
141939 #ifdef SQLITE_ENABLE_RTREE
141940 /************** Include rtree.h in the middle of main.c **********************/
141941 /************** Begin file rtree.h *******************************************/
141943 ** 2008 May 26
141945 ** The author disclaims copyright to this source code. In place of
141946 ** a legal notice, here is a blessing:
141948 ** May you do good and not evil.
141949 ** May you find forgiveness for yourself and forgive others.
141950 ** May you share freely, never taking more than you give.
141952 ******************************************************************************
141954 ** This header file is used by programs that want to link against the
141955 ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
141957 /* #include "sqlite3.h" */
141959 #if 0
141960 extern "C" {
141961 #endif /* __cplusplus */
141963 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
141965 #if 0
141966 } /* extern "C" */
141967 #endif /* __cplusplus */
141969 /************** End of rtree.h ***********************************************/
141970 /************** Continuing where we left off in main.c ***********************/
141971 #endif
141972 #ifdef SQLITE_ENABLE_ICU
141973 /************** Include sqliteicu.h in the middle of main.c ******************/
141974 /************** Begin file sqliteicu.h ***************************************/
141976 ** 2008 May 26
141978 ** The author disclaims copyright to this source code. In place of
141979 ** a legal notice, here is a blessing:
141981 ** May you do good and not evil.
141982 ** May you find forgiveness for yourself and forgive others.
141983 ** May you share freely, never taking more than you give.
141985 ******************************************************************************
141987 ** This header file is used by programs that want to link against the
141988 ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
141990 /* #include "sqlite3.h" */
141992 #if 0
141993 extern "C" {
141994 #endif /* __cplusplus */
141996 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
141998 #if 0
141999 } /* extern "C" */
142000 #endif /* __cplusplus */
142003 /************** End of sqliteicu.h *******************************************/
142004 /************** Continuing where we left off in main.c ***********************/
142005 #endif
142006 #ifdef SQLITE_ENABLE_JSON1
142007 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
142008 #endif
142009 #ifdef SQLITE_ENABLE_STMTVTAB
142010 SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
142011 #endif
142012 #ifdef SQLITE_ENABLE_FTS5
142013 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
142014 #endif
142016 #ifndef SQLITE_AMALGAMATION
142017 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
142018 ** contains the text of SQLITE_VERSION macro.
142020 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
142021 #endif
142023 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
142024 ** a pointer to the to the sqlite3_version[] string constant.
142026 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
142028 /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
142029 ** pointer to a string constant whose value is the same as the
142030 ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
142031 ** an edited copy of the amalgamation, then the last four characters of
142032 ** the hash might be different from SQLITE_SOURCE_ID.
142034 /* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
142036 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
142037 ** returns an integer equal to SQLITE_VERSION_NUMBER.
142039 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
142041 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
142042 ** zero if and only if SQLite was compiled with mutexing code omitted due to
142043 ** the SQLITE_THREADSAFE compile-time option being set to 0.
142045 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
142048 ** When compiling the test fixture or with debugging enabled (on Win32),
142049 ** this variable being set to non-zero will cause OSTRACE macros to emit
142050 ** extra diagnostic information.
142052 #ifdef SQLITE_HAVE_OS_TRACE
142053 # ifndef SQLITE_DEBUG_OS_TRACE
142054 # define SQLITE_DEBUG_OS_TRACE 0
142055 # endif
142056 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
142057 #endif
142059 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
142061 ** If the following function pointer is not NULL and if
142062 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
142063 ** I/O active are written using this function. These messages
142064 ** are intended for debugging activity only.
142066 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
142067 #endif
142070 ** If the following global variable points to a string which is the
142071 ** name of a directory, then that directory will be used to store
142072 ** temporary files.
142074 ** See also the "PRAGMA temp_store_directory" SQL command.
142076 SQLITE_API char *sqlite3_temp_directory = 0;
142079 ** If the following global variable points to a string which is the
142080 ** name of a directory, then that directory will be used to store
142081 ** all database files specified with a relative pathname.
142083 ** See also the "PRAGMA data_store_directory" SQL command.
142085 SQLITE_API char *sqlite3_data_directory = 0;
142088 ** Initialize SQLite.
142090 ** This routine must be called to initialize the memory allocation,
142091 ** VFS, and mutex subsystems prior to doing any serious work with
142092 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
142093 ** this routine will be called automatically by key routines such as
142094 ** sqlite3_open().
142096 ** This routine is a no-op except on its very first call for the process,
142097 ** or for the first call after a call to sqlite3_shutdown.
142099 ** The first thread to call this routine runs the initialization to
142100 ** completion. If subsequent threads call this routine before the first
142101 ** thread has finished the initialization process, then the subsequent
142102 ** threads must block until the first thread finishes with the initialization.
142104 ** The first thread might call this routine recursively. Recursive
142105 ** calls to this routine should not block, of course. Otherwise the
142106 ** initialization process would never complete.
142108 ** Let X be the first thread to enter this routine. Let Y be some other
142109 ** thread. Then while the initial invocation of this routine by X is
142110 ** incomplete, it is required that:
142112 ** * Calls to this routine from Y must block until the outer-most
142113 ** call by X completes.
142115 ** * Recursive calls to this routine from thread X return immediately
142116 ** without blocking.
142118 SQLITE_API int sqlite3_initialize(void){
142119 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
142120 int rc; /* Result code */
142121 #ifdef SQLITE_EXTRA_INIT
142122 int bRunExtraInit = 0; /* Extra initialization needed */
142123 #endif
142125 #ifdef SQLITE_OMIT_WSD
142126 rc = sqlite3_wsd_init(4096, 24);
142127 if( rc!=SQLITE_OK ){
142128 return rc;
142130 #endif
142132 /* If the following assert() fails on some obscure processor/compiler
142133 ** combination, the work-around is to set the correct pointer
142134 ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
142135 assert( SQLITE_PTRSIZE==sizeof(char*) );
142137 /* If SQLite is already completely initialized, then this call
142138 ** to sqlite3_initialize() should be a no-op. But the initialization
142139 ** must be complete. So isInit must not be set until the very end
142140 ** of this routine.
142142 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
142144 /* Make sure the mutex subsystem is initialized. If unable to
142145 ** initialize the mutex subsystem, return early with the error.
142146 ** If the system is so sick that we are unable to allocate a mutex,
142147 ** there is not much SQLite is going to be able to do.
142149 ** The mutex subsystem must take care of serializing its own
142150 ** initialization.
142152 rc = sqlite3MutexInit();
142153 if( rc ) return rc;
142155 /* Initialize the malloc() system and the recursive pInitMutex mutex.
142156 ** This operation is protected by the STATIC_MASTER mutex. Note that
142157 ** MutexAlloc() is called for a static mutex prior to initializing the
142158 ** malloc subsystem - this implies that the allocation of a static
142159 ** mutex must not require support from the malloc subsystem.
142161 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
142162 sqlite3_mutex_enter(pMaster);
142163 sqlite3GlobalConfig.isMutexInit = 1;
142164 if( !sqlite3GlobalConfig.isMallocInit ){
142165 rc = sqlite3MallocInit();
142167 if( rc==SQLITE_OK ){
142168 sqlite3GlobalConfig.isMallocInit = 1;
142169 if( !sqlite3GlobalConfig.pInitMutex ){
142170 sqlite3GlobalConfig.pInitMutex =
142171 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
142172 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
142173 rc = SQLITE_NOMEM_BKPT;
142177 if( rc==SQLITE_OK ){
142178 sqlite3GlobalConfig.nRefInitMutex++;
142180 sqlite3_mutex_leave(pMaster);
142182 /* If rc is not SQLITE_OK at this point, then either the malloc
142183 ** subsystem could not be initialized or the system failed to allocate
142184 ** the pInitMutex mutex. Return an error in either case. */
142185 if( rc!=SQLITE_OK ){
142186 return rc;
142189 /* Do the rest of the initialization under the recursive mutex so
142190 ** that we will be able to handle recursive calls into
142191 ** sqlite3_initialize(). The recursive calls normally come through
142192 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
142193 ** recursive calls might also be possible.
142195 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
142196 ** to the xInit method, so the xInit method need not be threadsafe.
142198 ** The following mutex is what serializes access to the appdef pcache xInit
142199 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
142200 ** call to sqlite3PcacheInitialize().
142202 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
142203 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
142204 sqlite3GlobalConfig.inProgress = 1;
142205 #ifdef SQLITE_ENABLE_SQLLOG
142207 extern void sqlite3_init_sqllog(void);
142208 sqlite3_init_sqllog();
142210 #endif
142211 memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
142212 sqlite3RegisterBuiltinFunctions();
142213 if( sqlite3GlobalConfig.isPCacheInit==0 ){
142214 rc = sqlite3PcacheInitialize();
142216 if( rc==SQLITE_OK ){
142217 sqlite3GlobalConfig.isPCacheInit = 1;
142218 rc = sqlite3OsInit();
142220 if( rc==SQLITE_OK ){
142221 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
142222 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
142223 sqlite3GlobalConfig.isInit = 1;
142224 #ifdef SQLITE_EXTRA_INIT
142225 bRunExtraInit = 1;
142226 #endif
142228 sqlite3GlobalConfig.inProgress = 0;
142230 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
142232 /* Go back under the static mutex and clean up the recursive
142233 ** mutex to prevent a resource leak.
142235 sqlite3_mutex_enter(pMaster);
142236 sqlite3GlobalConfig.nRefInitMutex--;
142237 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
142238 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
142239 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
142240 sqlite3GlobalConfig.pInitMutex = 0;
142242 sqlite3_mutex_leave(pMaster);
142244 /* The following is just a sanity check to make sure SQLite has
142245 ** been compiled correctly. It is important to run this code, but
142246 ** we don't want to run it too often and soak up CPU cycles for no
142247 ** reason. So we run it once during initialization.
142249 #ifndef NDEBUG
142250 #ifndef SQLITE_OMIT_FLOATING_POINT
142251 /* This section of code's only "output" is via assert() statements. */
142252 if ( rc==SQLITE_OK ){
142253 u64 x = (((u64)1)<<63)-1;
142254 double y;
142255 assert(sizeof(x)==8);
142256 assert(sizeof(x)==sizeof(y));
142257 memcpy(&y, &x, 8);
142258 assert( sqlite3IsNaN(y) );
142260 #endif
142261 #endif
142263 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
142264 ** compile-time option.
142266 #ifdef SQLITE_EXTRA_INIT
142267 if( bRunExtraInit ){
142268 int SQLITE_EXTRA_INIT(const char*);
142269 rc = SQLITE_EXTRA_INIT(0);
142271 #endif
142273 return rc;
142277 ** Undo the effects of sqlite3_initialize(). Must not be called while
142278 ** there are outstanding database connections or memory allocations or
142279 ** while any part of SQLite is otherwise in use in any thread. This
142280 ** routine is not threadsafe. But it is safe to invoke this routine
142281 ** on when SQLite is already shut down. If SQLite is already shut down
142282 ** when this routine is invoked, then this routine is a harmless no-op.
142284 SQLITE_API int sqlite3_shutdown(void){
142285 #ifdef SQLITE_OMIT_WSD
142286 int rc = sqlite3_wsd_init(4096, 24);
142287 if( rc!=SQLITE_OK ){
142288 return rc;
142290 #endif
142292 if( sqlite3GlobalConfig.isInit ){
142293 #ifdef SQLITE_EXTRA_SHUTDOWN
142294 void SQLITE_EXTRA_SHUTDOWN(void);
142295 SQLITE_EXTRA_SHUTDOWN();
142296 #endif
142297 sqlite3_os_end();
142298 sqlite3_reset_auto_extension();
142299 sqlite3GlobalConfig.isInit = 0;
142301 if( sqlite3GlobalConfig.isPCacheInit ){
142302 sqlite3PcacheShutdown();
142303 sqlite3GlobalConfig.isPCacheInit = 0;
142305 if( sqlite3GlobalConfig.isMallocInit ){
142306 sqlite3MallocEnd();
142307 sqlite3GlobalConfig.isMallocInit = 0;
142309 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
142310 /* The heap subsystem has now been shutdown and these values are supposed
142311 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
142312 ** which would rely on that heap subsystem; therefore, make sure these
142313 ** values cannot refer to heap memory that was just invalidated when the
142314 ** heap subsystem was shutdown. This is only done if the current call to
142315 ** this function resulted in the heap subsystem actually being shutdown.
142317 sqlite3_data_directory = 0;
142318 sqlite3_temp_directory = 0;
142319 #endif
142321 if( sqlite3GlobalConfig.isMutexInit ){
142322 sqlite3MutexEnd();
142323 sqlite3GlobalConfig.isMutexInit = 0;
142326 return SQLITE_OK;
142330 ** This API allows applications to modify the global configuration of
142331 ** the SQLite library at run-time.
142333 ** This routine should only be called when there are no outstanding
142334 ** database connections or memory allocations. This routine is not
142335 ** threadsafe. Failure to heed these warnings can lead to unpredictable
142336 ** behavior.
142338 SQLITE_API int sqlite3_config(int op, ...){
142339 va_list ap;
142340 int rc = SQLITE_OK;
142342 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
142343 ** the SQLite library is in use. */
142344 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
142346 va_start(ap, op);
142347 switch( op ){
142349 /* Mutex configuration options are only available in a threadsafe
142350 ** compile.
142352 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
142353 case SQLITE_CONFIG_SINGLETHREAD: {
142354 /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
142355 ** Single-thread. */
142356 sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
142357 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
142358 break;
142360 #endif
142361 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
142362 case SQLITE_CONFIG_MULTITHREAD: {
142363 /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
142364 ** Multi-thread. */
142365 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
142366 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
142367 break;
142369 #endif
142370 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
142371 case SQLITE_CONFIG_SERIALIZED: {
142372 /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
142373 ** Serialized. */
142374 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
142375 sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
142376 break;
142378 #endif
142379 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
142380 case SQLITE_CONFIG_MUTEX: {
142381 /* Specify an alternative mutex implementation */
142382 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
142383 break;
142385 #endif
142386 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
142387 case SQLITE_CONFIG_GETMUTEX: {
142388 /* Retrieve the current mutex implementation */
142389 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
142390 break;
142392 #endif
142394 case SQLITE_CONFIG_MALLOC: {
142395 /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
142396 ** single argument which is a pointer to an instance of the
142397 ** sqlite3_mem_methods structure. The argument specifies alternative
142398 ** low-level memory allocation routines to be used in place of the memory
142399 ** allocation routines built into SQLite. */
142400 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
142401 break;
142403 case SQLITE_CONFIG_GETMALLOC: {
142404 /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
142405 ** single argument which is a pointer to an instance of the
142406 ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
142407 ** filled with the currently defined memory allocation routines. */
142408 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
142409 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
142410 break;
142412 case SQLITE_CONFIG_MEMSTATUS: {
142413 /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
142414 ** single argument of type int, interpreted as a boolean, which enables
142415 ** or disables the collection of memory allocation statistics. */
142416 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
142417 break;
142419 case SQLITE_CONFIG_SMALL_MALLOC: {
142420 sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
142421 break;
142423 case SQLITE_CONFIG_PAGECACHE: {
142424 /* EVIDENCE-OF: R-18761-36601 There are three arguments to
142425 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
142426 ** the size of each page cache line (sz), and the number of cache lines
142427 ** (N). */
142428 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
142429 sqlite3GlobalConfig.szPage = va_arg(ap, int);
142430 sqlite3GlobalConfig.nPage = va_arg(ap, int);
142431 break;
142433 case SQLITE_CONFIG_PCACHE_HDRSZ: {
142434 /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
142435 ** a single parameter which is a pointer to an integer and writes into
142436 ** that integer the number of extra bytes per page required for each page
142437 ** in SQLITE_CONFIG_PAGECACHE. */
142438 *va_arg(ap, int*) =
142439 sqlite3HeaderSizeBtree() +
142440 sqlite3HeaderSizePcache() +
142441 sqlite3HeaderSizePcache1();
142442 break;
142445 case SQLITE_CONFIG_PCACHE: {
142446 /* no-op */
142447 break;
142449 case SQLITE_CONFIG_GETPCACHE: {
142450 /* now an error */
142451 rc = SQLITE_ERROR;
142452 break;
142455 case SQLITE_CONFIG_PCACHE2: {
142456 /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
142457 ** single argument which is a pointer to an sqlite3_pcache_methods2
142458 ** object. This object specifies the interface to a custom page cache
142459 ** implementation. */
142460 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
142461 break;
142463 case SQLITE_CONFIG_GETPCACHE2: {
142464 /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
142465 ** single argument which is a pointer to an sqlite3_pcache_methods2
142466 ** object. SQLite copies of the current page cache implementation into
142467 ** that object. */
142468 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
142469 sqlite3PCacheSetDefault();
142471 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
142472 break;
142475 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
142476 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
142477 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
142478 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
142479 case SQLITE_CONFIG_HEAP: {
142480 /* EVIDENCE-OF: R-19854-42126 There are three arguments to
142481 ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
142482 ** number of bytes in the memory buffer, and the minimum allocation size.
142484 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
142485 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
142486 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
142488 if( sqlite3GlobalConfig.mnReq<1 ){
142489 sqlite3GlobalConfig.mnReq = 1;
142490 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
142491 /* cap min request size at 2^12 */
142492 sqlite3GlobalConfig.mnReq = (1<<12);
142495 if( sqlite3GlobalConfig.pHeap==0 ){
142496 /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
142497 ** is NULL, then SQLite reverts to using its default memory allocator
142498 ** (the system malloc() implementation), undoing any prior invocation of
142499 ** SQLITE_CONFIG_MALLOC.
142501 ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
142502 ** revert to its default implementation when sqlite3_initialize() is run
142504 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
142505 }else{
142506 /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
142507 ** alternative memory allocator is engaged to handle all of SQLites
142508 ** memory allocation needs. */
142509 #ifdef SQLITE_ENABLE_MEMSYS3
142510 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
142511 #endif
142512 #ifdef SQLITE_ENABLE_MEMSYS5
142513 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
142514 #endif
142516 break;
142518 #endif
142520 case SQLITE_CONFIG_LOOKASIDE: {
142521 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
142522 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
142523 break;
142526 /* Record a pointer to the logger function and its first argument.
142527 ** The default is NULL. Logging is disabled if the function pointer is
142528 ** NULL.
142530 case SQLITE_CONFIG_LOG: {
142531 /* MSVC is picky about pulling func ptrs from va lists.
142532 ** http://support.microsoft.com/kb/47961
142533 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
142535 typedef void(*LOGFUNC_t)(void*,int,const char*);
142536 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
142537 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
142538 break;
142541 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
142542 ** can be changed at start-time using the
142543 ** sqlite3_config(SQLITE_CONFIG_URI,1) or
142544 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
142546 case SQLITE_CONFIG_URI: {
142547 /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
142548 ** argument of type int. If non-zero, then URI handling is globally
142549 ** enabled. If the parameter is zero, then URI handling is globally
142550 ** disabled. */
142551 sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
142552 break;
142555 case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
142556 /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
142557 ** option takes a single integer argument which is interpreted as a
142558 ** boolean in order to enable or disable the use of covering indices for
142559 ** full table scans in the query optimizer. */
142560 sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
142561 break;
142564 #ifdef SQLITE_ENABLE_SQLLOG
142565 case SQLITE_CONFIG_SQLLOG: {
142566 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
142567 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
142568 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
142569 break;
142571 #endif
142573 case SQLITE_CONFIG_MMAP_SIZE: {
142574 /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
142575 ** integer (sqlite3_int64) values that are the default mmap size limit
142576 ** (the default setting for PRAGMA mmap_size) and the maximum allowed
142577 ** mmap size limit. */
142578 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
142579 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
142580 /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
142581 ** negative, then that argument is changed to its compile-time default.
142583 ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
142584 ** silently truncated if necessary so that it does not exceed the
142585 ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
142586 ** compile-time option.
142588 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
142589 mxMmap = SQLITE_MAX_MMAP_SIZE;
142591 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
142592 if( szMmap>mxMmap) szMmap = mxMmap;
142593 sqlite3GlobalConfig.mxMmap = mxMmap;
142594 sqlite3GlobalConfig.szMmap = szMmap;
142595 break;
142598 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
142599 case SQLITE_CONFIG_WIN32_HEAPSIZE: {
142600 /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
142601 ** unsigned integer value that specifies the maximum size of the created
142602 ** heap. */
142603 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
142604 break;
142606 #endif
142608 case SQLITE_CONFIG_PMASZ: {
142609 sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
142610 break;
142613 case SQLITE_CONFIG_STMTJRNL_SPILL: {
142614 sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
142615 break;
142618 default: {
142619 rc = SQLITE_ERROR;
142620 break;
142623 va_end(ap);
142624 return rc;
142628 ** Set up the lookaside buffers for a database connection.
142629 ** Return SQLITE_OK on success.
142630 ** If lookaside is already active, return SQLITE_BUSY.
142632 ** The sz parameter is the number of bytes in each lookaside slot.
142633 ** The cnt parameter is the number of slots. If pStart is NULL the
142634 ** space for the lookaside memory is obtained from sqlite3_malloc().
142635 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
142636 ** the lookaside memory.
142638 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
142639 #ifndef SQLITE_OMIT_LOOKASIDE
142640 void *pStart;
142642 if( sqlite3LookasideUsed(db,0)>0 ){
142643 return SQLITE_BUSY;
142645 /* Free any existing lookaside buffer for this handle before
142646 ** allocating a new one so we don't have to have space for
142647 ** both at the same time.
142649 if( db->lookaside.bMalloced ){
142650 sqlite3_free(db->lookaside.pStart);
142652 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
142653 ** than a pointer to be useful.
142655 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
142656 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
142657 if( cnt<0 ) cnt = 0;
142658 if( sz==0 || cnt==0 ){
142659 sz = 0;
142660 pStart = 0;
142661 }else if( pBuf==0 ){
142662 sqlite3BeginBenignMalloc();
142663 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
142664 sqlite3EndBenignMalloc();
142665 if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
142666 }else{
142667 pStart = pBuf;
142669 db->lookaside.pStart = pStart;
142670 db->lookaside.pInit = 0;
142671 db->lookaside.pFree = 0;
142672 db->lookaside.sz = (u16)sz;
142673 if( pStart ){
142674 int i;
142675 LookasideSlot *p;
142676 assert( sz > (int)sizeof(LookasideSlot*) );
142677 db->lookaside.nSlot = cnt;
142678 p = (LookasideSlot*)pStart;
142679 for(i=cnt-1; i>=0; i--){
142680 p->pNext = db->lookaside.pInit;
142681 db->lookaside.pInit = p;
142682 p = (LookasideSlot*)&((u8*)p)[sz];
142684 db->lookaside.pEnd = p;
142685 db->lookaside.bDisable = 0;
142686 db->lookaside.bMalloced = pBuf==0 ?1:0;
142687 }else{
142688 db->lookaside.pStart = db;
142689 db->lookaside.pEnd = db;
142690 db->lookaside.bDisable = 1;
142691 db->lookaside.bMalloced = 0;
142692 db->lookaside.nSlot = 0;
142694 #endif /* SQLITE_OMIT_LOOKASIDE */
142695 return SQLITE_OK;
142699 ** Return the mutex associated with a database connection.
142701 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
142702 #ifdef SQLITE_ENABLE_API_ARMOR
142703 if( !sqlite3SafetyCheckOk(db) ){
142704 (void)SQLITE_MISUSE_BKPT;
142705 return 0;
142707 #endif
142708 return db->mutex;
142712 ** Free up as much memory as we can from the given database
142713 ** connection.
142715 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
142716 int i;
142718 #ifdef SQLITE_ENABLE_API_ARMOR
142719 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
142720 #endif
142721 sqlite3_mutex_enter(db->mutex);
142722 sqlite3BtreeEnterAll(db);
142723 for(i=0; i<db->nDb; i++){
142724 Btree *pBt = db->aDb[i].pBt;
142725 if( pBt ){
142726 Pager *pPager = sqlite3BtreePager(pBt);
142727 sqlite3PagerShrink(pPager);
142730 sqlite3BtreeLeaveAll(db);
142731 sqlite3_mutex_leave(db->mutex);
142732 return SQLITE_OK;
142736 ** Flush any dirty pages in the pager-cache for any attached database
142737 ** to disk.
142739 SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
142740 int i;
142741 int rc = SQLITE_OK;
142742 int bSeenBusy = 0;
142744 #ifdef SQLITE_ENABLE_API_ARMOR
142745 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
142746 #endif
142747 sqlite3_mutex_enter(db->mutex);
142748 sqlite3BtreeEnterAll(db);
142749 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
142750 Btree *pBt = db->aDb[i].pBt;
142751 if( pBt && sqlite3BtreeIsInTrans(pBt) ){
142752 Pager *pPager = sqlite3BtreePager(pBt);
142753 rc = sqlite3PagerFlush(pPager);
142754 if( rc==SQLITE_BUSY ){
142755 bSeenBusy = 1;
142756 rc = SQLITE_OK;
142760 sqlite3BtreeLeaveAll(db);
142761 sqlite3_mutex_leave(db->mutex);
142762 return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
142766 ** Configuration settings for an individual database connection
142768 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
142769 va_list ap;
142770 int rc;
142771 va_start(ap, op);
142772 switch( op ){
142773 case SQLITE_DBCONFIG_MAINDBNAME: {
142774 /* IMP: R-06824-28531 */
142775 /* IMP: R-36257-52125 */
142776 db->aDb[0].zDbSName = va_arg(ap,char*);
142777 rc = SQLITE_OK;
142778 break;
142780 case SQLITE_DBCONFIG_LOOKASIDE: {
142781 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
142782 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
142783 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
142784 rc = setupLookaside(db, pBuf, sz, cnt);
142785 break;
142787 default: {
142788 static const struct {
142789 int op; /* The opcode */
142790 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
142791 } aFlagOp[] = {
142792 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
142793 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
142794 { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
142795 { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
142796 { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
142797 { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
142799 unsigned int i;
142800 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
142801 for(i=0; i<ArraySize(aFlagOp); i++){
142802 if( aFlagOp[i].op==op ){
142803 int onoff = va_arg(ap, int);
142804 int *pRes = va_arg(ap, int*);
142805 u32 oldFlags = db->flags;
142806 if( onoff>0 ){
142807 db->flags |= aFlagOp[i].mask;
142808 }else if( onoff==0 ){
142809 db->flags &= ~aFlagOp[i].mask;
142811 if( oldFlags!=db->flags ){
142812 sqlite3ExpirePreparedStatements(db);
142814 if( pRes ){
142815 *pRes = (db->flags & aFlagOp[i].mask)!=0;
142817 rc = SQLITE_OK;
142818 break;
142821 break;
142824 va_end(ap);
142825 return rc;
142830 ** Return true if the buffer z[0..n-1] contains all spaces.
142832 static int allSpaces(const char *z, int n){
142833 while( n>0 && z[n-1]==' ' ){ n--; }
142834 return n==0;
142838 ** This is the default collating function named "BINARY" which is always
142839 ** available.
142841 ** If the padFlag argument is not NULL then space padding at the end
142842 ** of strings is ignored. This implements the RTRIM collation.
142844 static int binCollFunc(
142845 void *padFlag,
142846 int nKey1, const void *pKey1,
142847 int nKey2, const void *pKey2
142849 int rc, n;
142850 n = nKey1<nKey2 ? nKey1 : nKey2;
142851 /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
142852 ** strings byte by byte using the memcmp() function from the standard C
142853 ** library. */
142854 assert( pKey1 && pKey2 );
142855 rc = memcmp(pKey1, pKey2, n);
142856 if( rc==0 ){
142857 if( padFlag
142858 && allSpaces(((char*)pKey1)+n, nKey1-n)
142859 && allSpaces(((char*)pKey2)+n, nKey2-n)
142861 /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
142862 ** spaces at the end of either string do not change the result. In other
142863 ** words, strings will compare equal to one another as long as they
142864 ** differ only in the number of spaces at the end.
142866 }else{
142867 rc = nKey1 - nKey2;
142870 return rc;
142874 ** Another built-in collating sequence: NOCASE.
142876 ** This collating sequence is intended to be used for "case independent
142877 ** comparison". SQLite's knowledge of upper and lower case equivalents
142878 ** extends only to the 26 characters used in the English language.
142880 ** At the moment there is only a UTF-8 implementation.
142882 static int nocaseCollatingFunc(
142883 void *NotUsed,
142884 int nKey1, const void *pKey1,
142885 int nKey2, const void *pKey2
142887 int r = sqlite3StrNICmp(
142888 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
142889 UNUSED_PARAMETER(NotUsed);
142890 if( 0==r ){
142891 r = nKey1-nKey2;
142893 return r;
142897 ** Return the ROWID of the most recent insert
142899 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
142900 #ifdef SQLITE_ENABLE_API_ARMOR
142901 if( !sqlite3SafetyCheckOk(db) ){
142902 (void)SQLITE_MISUSE_BKPT;
142903 return 0;
142905 #endif
142906 return db->lastRowid;
142910 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
142912 SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
142913 #ifdef SQLITE_ENABLE_API_ARMOR
142914 if( !sqlite3SafetyCheckOk(db) ){
142915 (void)SQLITE_MISUSE_BKPT;
142916 return;
142918 #endif
142919 sqlite3_mutex_enter(db->mutex);
142920 db->lastRowid = iRowid;
142921 sqlite3_mutex_leave(db->mutex);
142925 ** Return the number of changes in the most recent call to sqlite3_exec().
142927 SQLITE_API int sqlite3_changes(sqlite3 *db){
142928 #ifdef SQLITE_ENABLE_API_ARMOR
142929 if( !sqlite3SafetyCheckOk(db) ){
142930 (void)SQLITE_MISUSE_BKPT;
142931 return 0;
142933 #endif
142934 return db->nChange;
142938 ** Return the number of changes since the database handle was opened.
142940 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
142941 #ifdef SQLITE_ENABLE_API_ARMOR
142942 if( !sqlite3SafetyCheckOk(db) ){
142943 (void)SQLITE_MISUSE_BKPT;
142944 return 0;
142946 #endif
142947 return db->nTotalChange;
142951 ** Close all open savepoints. This function only manipulates fields of the
142952 ** database handle object, it does not close any savepoints that may be open
142953 ** at the b-tree/pager level.
142955 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
142956 while( db->pSavepoint ){
142957 Savepoint *pTmp = db->pSavepoint;
142958 db->pSavepoint = pTmp->pNext;
142959 sqlite3DbFree(db, pTmp);
142961 db->nSavepoint = 0;
142962 db->nStatement = 0;
142963 db->isTransactionSavepoint = 0;
142967 ** Invoke the destructor function associated with FuncDef p, if any. Except,
142968 ** if this is not the last copy of the function, do not invoke it. Multiple
142969 ** copies of a single function are created when create_function() is called
142970 ** with SQLITE_ANY as the encoding.
142972 static void functionDestroy(sqlite3 *db, FuncDef *p){
142973 FuncDestructor *pDestructor = p->u.pDestructor;
142974 if( pDestructor ){
142975 pDestructor->nRef--;
142976 if( pDestructor->nRef==0 ){
142977 pDestructor->xDestroy(pDestructor->pUserData);
142978 sqlite3DbFree(db, pDestructor);
142984 ** Disconnect all sqlite3_vtab objects that belong to database connection
142985 ** db. This is called when db is being closed.
142987 static void disconnectAllVtab(sqlite3 *db){
142988 #ifndef SQLITE_OMIT_VIRTUALTABLE
142989 int i;
142990 HashElem *p;
142991 sqlite3BtreeEnterAll(db);
142992 for(i=0; i<db->nDb; i++){
142993 Schema *pSchema = db->aDb[i].pSchema;
142994 if( db->aDb[i].pSchema ){
142995 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
142996 Table *pTab = (Table *)sqliteHashData(p);
142997 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
143001 for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
143002 Module *pMod = (Module *)sqliteHashData(p);
143003 if( pMod->pEpoTab ){
143004 sqlite3VtabDisconnect(db, pMod->pEpoTab);
143007 sqlite3VtabUnlockList(db);
143008 sqlite3BtreeLeaveAll(db);
143009 #else
143010 UNUSED_PARAMETER(db);
143011 #endif
143015 ** Return TRUE if database connection db has unfinalized prepared
143016 ** statements or unfinished sqlite3_backup objects.
143018 static int connectionIsBusy(sqlite3 *db){
143019 int j;
143020 assert( sqlite3_mutex_held(db->mutex) );
143021 if( db->pVdbe ) return 1;
143022 for(j=0; j<db->nDb; j++){
143023 Btree *pBt = db->aDb[j].pBt;
143024 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
143026 return 0;
143030 ** Close an existing SQLite database
143032 static int sqlite3Close(sqlite3 *db, int forceZombie){
143033 if( !db ){
143034 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
143035 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
143036 return SQLITE_OK;
143038 if( !sqlite3SafetyCheckSickOrOk(db) ){
143039 return SQLITE_MISUSE_BKPT;
143041 sqlite3_mutex_enter(db->mutex);
143042 if( db->mTrace & SQLITE_TRACE_CLOSE ){
143043 db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
143046 /* Force xDisconnect calls on all virtual tables */
143047 disconnectAllVtab(db);
143049 /* If a transaction is open, the disconnectAllVtab() call above
143050 ** will not have called the xDisconnect() method on any virtual
143051 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
143052 ** call will do so. We need to do this before the check for active
143053 ** SQL statements below, as the v-table implementation may be storing
143054 ** some prepared statements internally.
143056 sqlite3VtabRollback(db);
143058 /* Legacy behavior (sqlite3_close() behavior) is to return
143059 ** SQLITE_BUSY if the connection can not be closed immediately.
143061 if( !forceZombie && connectionIsBusy(db) ){
143062 sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
143063 "statements or unfinished backups");
143064 sqlite3_mutex_leave(db->mutex);
143065 return SQLITE_BUSY;
143068 #ifdef SQLITE_ENABLE_SQLLOG
143069 if( sqlite3GlobalConfig.xSqllog ){
143070 /* Closing the handle. Fourth parameter is passed the value 2. */
143071 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
143073 #endif
143075 /* Convert the connection into a zombie and then close it.
143077 db->magic = SQLITE_MAGIC_ZOMBIE;
143078 sqlite3LeaveMutexAndCloseZombie(db);
143079 return SQLITE_OK;
143083 ** Two variations on the public interface for closing a database
143084 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
143085 ** leaves the connection option if there are unfinalized prepared
143086 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
143087 ** version forces the connection to become a zombie if there are
143088 ** unclosed resources, and arranges for deallocation when the last
143089 ** prepare statement or sqlite3_backup closes.
143091 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
143092 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
143096 ** Close the mutex on database connection db.
143098 ** Furthermore, if database connection db is a zombie (meaning that there
143099 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
143100 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
143101 ** finished, then free all resources.
143103 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
143104 HashElem *i; /* Hash table iterator */
143105 int j;
143107 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
143108 ** or if the connection has not yet been closed by sqlite3_close_v2(),
143109 ** then just leave the mutex and return.
143111 if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
143112 sqlite3_mutex_leave(db->mutex);
143113 return;
143116 /* If we reach this point, it means that the database connection has
143117 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
143118 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
143119 ** go ahead and free all resources.
143122 /* If a transaction is open, roll it back. This also ensures that if
143123 ** any database schemas have been modified by an uncommitted transaction
143124 ** they are reset. And that the required b-tree mutex is held to make
143125 ** the pager rollback and schema reset an atomic operation. */
143126 sqlite3RollbackAll(db, SQLITE_OK);
143128 /* Free any outstanding Savepoint structures. */
143129 sqlite3CloseSavepoints(db);
143131 /* Close all database connections */
143132 for(j=0; j<db->nDb; j++){
143133 struct Db *pDb = &db->aDb[j];
143134 if( pDb->pBt ){
143135 sqlite3BtreeClose(pDb->pBt);
143136 pDb->pBt = 0;
143137 if( j!=1 ){
143138 pDb->pSchema = 0;
143142 /* Clear the TEMP schema separately and last */
143143 if( db->aDb[1].pSchema ){
143144 sqlite3SchemaClear(db->aDb[1].pSchema);
143146 sqlite3VtabUnlockList(db);
143148 /* Free up the array of auxiliary databases */
143149 sqlite3CollapseDatabaseArray(db);
143150 assert( db->nDb<=2 );
143151 assert( db->aDb==db->aDbStatic );
143153 /* Tell the code in notify.c that the connection no longer holds any
143154 ** locks and does not require any further unlock-notify callbacks.
143156 sqlite3ConnectionClosed(db);
143158 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
143159 FuncDef *pNext, *p;
143160 p = sqliteHashData(i);
143162 functionDestroy(db, p);
143163 pNext = p->pNext;
143164 sqlite3DbFree(db, p);
143165 p = pNext;
143166 }while( p );
143168 sqlite3HashClear(&db->aFunc);
143169 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
143170 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
143171 /* Invoke any destructors registered for collation sequence user data. */
143172 for(j=0; j<3; j++){
143173 if( pColl[j].xDel ){
143174 pColl[j].xDel(pColl[j].pUser);
143177 sqlite3DbFree(db, pColl);
143179 sqlite3HashClear(&db->aCollSeq);
143180 #ifndef SQLITE_OMIT_VIRTUALTABLE
143181 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
143182 Module *pMod = (Module *)sqliteHashData(i);
143183 if( pMod->xDestroy ){
143184 pMod->xDestroy(pMod->pAux);
143186 sqlite3VtabEponymousTableClear(db, pMod);
143187 sqlite3DbFree(db, pMod);
143189 sqlite3HashClear(&db->aModule);
143190 #endif
143192 sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
143193 sqlite3ValueFree(db->pErr);
143194 sqlite3CloseExtensions(db);
143195 #if SQLITE_USER_AUTHENTICATION
143196 sqlite3_free(db->auth.zAuthUser);
143197 sqlite3_free(db->auth.zAuthPW);
143198 #endif
143200 db->magic = SQLITE_MAGIC_ERROR;
143202 /* The temp-database schema is allocated differently from the other schema
143203 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
143204 ** So it needs to be freed here. Todo: Why not roll the temp schema into
143205 ** the same sqliteMalloc() as the one that allocates the database
143206 ** structure?
143208 sqlite3DbFree(db, db->aDb[1].pSchema);
143209 sqlite3_mutex_leave(db->mutex);
143210 db->magic = SQLITE_MAGIC_CLOSED;
143211 sqlite3_mutex_free(db->mutex);
143212 assert( sqlite3LookasideUsed(db,0)==0 );
143213 if( db->lookaside.bMalloced ){
143214 sqlite3_free(db->lookaside.pStart);
143216 sqlite3_free(db);
143220 ** Rollback all database files. If tripCode is not SQLITE_OK, then
143221 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
143222 ** breaker") and made to return tripCode if there are any further
143223 ** attempts to use that cursor. Read cursors remain open and valid
143224 ** but are "saved" in case the table pages are moved around.
143226 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
143227 int i;
143228 int inTrans = 0;
143229 int schemaChange;
143230 assert( sqlite3_mutex_held(db->mutex) );
143231 sqlite3BeginBenignMalloc();
143233 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
143234 ** This is important in case the transaction being rolled back has
143235 ** modified the database schema. If the b-tree mutexes are not taken
143236 ** here, then another shared-cache connection might sneak in between
143237 ** the database rollback and schema reset, which can cause false
143238 ** corruption reports in some cases. */
143239 sqlite3BtreeEnterAll(db);
143240 schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
143242 for(i=0; i<db->nDb; i++){
143243 Btree *p = db->aDb[i].pBt;
143244 if( p ){
143245 if( sqlite3BtreeIsInTrans(p) ){
143246 inTrans = 1;
143248 sqlite3BtreeRollback(p, tripCode, !schemaChange);
143251 sqlite3VtabRollback(db);
143252 sqlite3EndBenignMalloc();
143254 if( (db->mDbFlags&DBFLAG_SchemaChange)!=0 && db->init.busy==0 ){
143255 sqlite3ExpirePreparedStatements(db);
143256 sqlite3ResetAllSchemasOfConnection(db);
143258 sqlite3BtreeLeaveAll(db);
143260 /* Any deferred constraint violations have now been resolved. */
143261 db->nDeferredCons = 0;
143262 db->nDeferredImmCons = 0;
143263 db->flags &= ~SQLITE_DeferFKs;
143265 /* If one has been configured, invoke the rollback-hook callback */
143266 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
143267 db->xRollbackCallback(db->pRollbackArg);
143272 ** Return a static string containing the name corresponding to the error code
143273 ** specified in the argument.
143275 #if defined(SQLITE_NEED_ERR_NAME)
143276 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
143277 const char *zName = 0;
143278 int i, origRc = rc;
143279 for(i=0; i<2 && zName==0; i++, rc &= 0xff){
143280 switch( rc ){
143281 case SQLITE_OK: zName = "SQLITE_OK"; break;
143282 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
143283 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
143284 case SQLITE_PERM: zName = "SQLITE_PERM"; break;
143285 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
143286 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
143287 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
143288 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
143289 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
143290 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
143291 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
143292 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
143293 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
143294 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
143295 case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
143296 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
143297 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
143298 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
143299 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
143300 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
143301 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
143302 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
143303 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
143304 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
143305 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
143306 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
143307 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
143308 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
143309 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
143310 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
143311 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
143312 case SQLITE_IOERR_CHECKRESERVEDLOCK:
143313 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
143314 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
143315 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
143316 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
143317 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
143318 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
143319 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
143320 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
143321 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
143322 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
143323 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
143324 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
143325 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
143326 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
143327 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
143328 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
143329 case SQLITE_FULL: zName = "SQLITE_FULL"; break;
143330 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
143331 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
143332 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
143333 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
143334 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
143335 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
143336 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
143337 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
143338 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
143339 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
143340 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
143341 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
143342 case SQLITE_CONSTRAINT_FOREIGNKEY:
143343 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
143344 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
143345 case SQLITE_CONSTRAINT_PRIMARYKEY:
143346 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
143347 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
143348 case SQLITE_CONSTRAINT_COMMITHOOK:
143349 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
143350 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
143351 case SQLITE_CONSTRAINT_FUNCTION:
143352 zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
143353 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
143354 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
143355 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
143356 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
143357 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
143358 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
143359 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
143360 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
143361 case SQLITE_ROW: zName = "SQLITE_ROW"; break;
143362 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
143363 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
143364 case SQLITE_NOTICE_RECOVER_ROLLBACK:
143365 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
143366 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
143367 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
143368 case SQLITE_DONE: zName = "SQLITE_DONE"; break;
143371 if( zName==0 ){
143372 static char zBuf[50];
143373 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
143374 zName = zBuf;
143376 return zName;
143378 #endif
143381 ** Return a static string that describes the kind of error specified in the
143382 ** argument.
143384 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
143385 static const char* const aMsg[] = {
143386 /* SQLITE_OK */ "not an error",
143387 /* SQLITE_ERROR */ "SQL logic error",
143388 /* SQLITE_INTERNAL */ 0,
143389 /* SQLITE_PERM */ "access permission denied",
143390 /* SQLITE_ABORT */ "query aborted",
143391 /* SQLITE_BUSY */ "database is locked",
143392 /* SQLITE_LOCKED */ "database table is locked",
143393 /* SQLITE_NOMEM */ "out of memory",
143394 /* SQLITE_READONLY */ "attempt to write a readonly database",
143395 /* SQLITE_INTERRUPT */ "interrupted",
143396 /* SQLITE_IOERR */ "disk I/O error",
143397 /* SQLITE_CORRUPT */ "database disk image is malformed",
143398 /* SQLITE_NOTFOUND */ "unknown operation",
143399 /* SQLITE_FULL */ "database or disk is full",
143400 /* SQLITE_CANTOPEN */ "unable to open database file",
143401 /* SQLITE_PROTOCOL */ "locking protocol",
143402 /* SQLITE_EMPTY */ 0,
143403 /* SQLITE_SCHEMA */ "database schema has changed",
143404 /* SQLITE_TOOBIG */ "string or blob too big",
143405 /* SQLITE_CONSTRAINT */ "constraint failed",
143406 /* SQLITE_MISMATCH */ "datatype mismatch",
143407 /* SQLITE_MISUSE */ "bad parameter or other API misuse",
143408 #ifdef SQLITE_DISABLE_LFS
143409 /* SQLITE_NOLFS */ "large file support is disabled",
143410 #else
143411 /* SQLITE_NOLFS */ 0,
143412 #endif
143413 /* SQLITE_AUTH */ "authorization denied",
143414 /* SQLITE_FORMAT */ 0,
143415 /* SQLITE_RANGE */ "column index out of range",
143416 /* SQLITE_NOTADB */ "file is not a database",
143418 const char *zErr = "unknown error";
143419 switch( rc ){
143420 case SQLITE_ABORT_ROLLBACK: {
143421 zErr = "abort due to ROLLBACK";
143422 break;
143424 default: {
143425 rc &= 0xff;
143426 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
143427 zErr = aMsg[rc];
143429 break;
143432 return zErr;
143436 ** This routine implements a busy callback that sleeps and tries
143437 ** again until a timeout value is reached. The timeout value is
143438 ** an integer number of milliseconds passed in as the first
143439 ** argument.
143441 static int sqliteDefaultBusyCallback(
143442 void *ptr, /* Database connection */
143443 int count /* Number of times table has been busy */
143445 #if SQLITE_OS_WIN || HAVE_USLEEP
143446 static const u8 delays[] =
143447 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
143448 static const u8 totals[] =
143449 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
143450 # define NDELAY ArraySize(delays)
143451 sqlite3 *db = (sqlite3 *)ptr;
143452 int timeout = db->busyTimeout;
143453 int delay, prior;
143455 assert( count>=0 );
143456 if( count < NDELAY ){
143457 delay = delays[count];
143458 prior = totals[count];
143459 }else{
143460 delay = delays[NDELAY-1];
143461 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
143463 if( prior + delay > timeout ){
143464 delay = timeout - prior;
143465 if( delay<=0 ) return 0;
143467 sqlite3OsSleep(db->pVfs, delay*1000);
143468 return 1;
143469 #else
143470 sqlite3 *db = (sqlite3 *)ptr;
143471 int timeout = ((sqlite3 *)ptr)->busyTimeout;
143472 if( (count+1)*1000 > timeout ){
143473 return 0;
143475 sqlite3OsSleep(db->pVfs, 1000000);
143476 return 1;
143477 #endif
143481 ** Invoke the given busy handler.
143483 ** This routine is called when an operation failed with a lock.
143484 ** If this routine returns non-zero, the lock is retried. If it
143485 ** returns 0, the operation aborts with an SQLITE_BUSY error.
143487 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
143488 int rc;
143489 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
143490 rc = p->xFunc(p->pArg, p->nBusy);
143491 if( rc==0 ){
143492 p->nBusy = -1;
143493 }else{
143494 p->nBusy++;
143496 return rc;
143500 ** This routine sets the busy callback for an Sqlite database to the
143501 ** given callback function with the given argument.
143503 SQLITE_API int sqlite3_busy_handler(
143504 sqlite3 *db,
143505 int (*xBusy)(void*,int),
143506 void *pArg
143508 #ifdef SQLITE_ENABLE_API_ARMOR
143509 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143510 #endif
143511 sqlite3_mutex_enter(db->mutex);
143512 db->busyHandler.xFunc = xBusy;
143513 db->busyHandler.pArg = pArg;
143514 db->busyHandler.nBusy = 0;
143515 db->busyTimeout = 0;
143516 sqlite3_mutex_leave(db->mutex);
143517 return SQLITE_OK;
143520 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
143522 ** This routine sets the progress callback for an Sqlite database to the
143523 ** given callback function with the given argument. The progress callback will
143524 ** be invoked every nOps opcodes.
143526 SQLITE_API void sqlite3_progress_handler(
143527 sqlite3 *db,
143528 int nOps,
143529 int (*xProgress)(void*),
143530 void *pArg
143532 #ifdef SQLITE_ENABLE_API_ARMOR
143533 if( !sqlite3SafetyCheckOk(db) ){
143534 (void)SQLITE_MISUSE_BKPT;
143535 return;
143537 #endif
143538 sqlite3_mutex_enter(db->mutex);
143539 if( nOps>0 ){
143540 db->xProgress = xProgress;
143541 db->nProgressOps = (unsigned)nOps;
143542 db->pProgressArg = pArg;
143543 }else{
143544 db->xProgress = 0;
143545 db->nProgressOps = 0;
143546 db->pProgressArg = 0;
143548 sqlite3_mutex_leave(db->mutex);
143550 #endif
143554 ** This routine installs a default busy handler that waits for the
143555 ** specified number of milliseconds before returning 0.
143557 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
143558 #ifdef SQLITE_ENABLE_API_ARMOR
143559 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143560 #endif
143561 if( ms>0 ){
143562 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
143563 db->busyTimeout = ms;
143564 }else{
143565 sqlite3_busy_handler(db, 0, 0);
143567 return SQLITE_OK;
143571 ** Cause any pending operation to stop at its earliest opportunity.
143573 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
143574 #ifdef SQLITE_ENABLE_API_ARMOR
143575 if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
143576 (void)SQLITE_MISUSE_BKPT;
143577 return;
143579 #endif
143580 db->u1.isInterrupted = 1;
143585 ** This function is exactly the same as sqlite3_create_function(), except
143586 ** that it is designed to be called by internal code. The difference is
143587 ** that if a malloc() fails in sqlite3_create_function(), an error code
143588 ** is returned and the mallocFailed flag cleared.
143590 SQLITE_PRIVATE int sqlite3CreateFunc(
143591 sqlite3 *db,
143592 const char *zFunctionName,
143593 int nArg,
143594 int enc,
143595 void *pUserData,
143596 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
143597 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
143598 void (*xFinal)(sqlite3_context*),
143599 FuncDestructor *pDestructor
143601 FuncDef *p;
143602 int nName;
143603 int extraFlags;
143605 assert( sqlite3_mutex_held(db->mutex) );
143606 if( zFunctionName==0 ||
143607 (xSFunc && (xFinal || xStep)) ||
143608 (!xSFunc && (xFinal && !xStep)) ||
143609 (!xSFunc && (!xFinal && xStep)) ||
143610 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
143611 (255<(nName = sqlite3Strlen30( zFunctionName))) ){
143612 return SQLITE_MISUSE_BKPT;
143615 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
143616 extraFlags = enc & SQLITE_DETERMINISTIC;
143617 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
143619 #ifndef SQLITE_OMIT_UTF16
143620 /* If SQLITE_UTF16 is specified as the encoding type, transform this
143621 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
143622 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
143624 ** If SQLITE_ANY is specified, add three versions of the function
143625 ** to the hash table.
143627 if( enc==SQLITE_UTF16 ){
143628 enc = SQLITE_UTF16NATIVE;
143629 }else if( enc==SQLITE_ANY ){
143630 int rc;
143631 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
143632 pUserData, xSFunc, xStep, xFinal, pDestructor);
143633 if( rc==SQLITE_OK ){
143634 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
143635 pUserData, xSFunc, xStep, xFinal, pDestructor);
143637 if( rc!=SQLITE_OK ){
143638 return rc;
143640 enc = SQLITE_UTF16BE;
143642 #else
143643 enc = SQLITE_UTF8;
143644 #endif
143646 /* Check if an existing function is being overridden or deleted. If so,
143647 ** and there are active VMs, then return SQLITE_BUSY. If a function
143648 ** is being overridden/deleted but there are no active VMs, allow the
143649 ** operation to continue but invalidate all precompiled statements.
143651 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
143652 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
143653 if( db->nVdbeActive ){
143654 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
143655 "unable to delete/modify user-function due to active statements");
143656 assert( !db->mallocFailed );
143657 return SQLITE_BUSY;
143658 }else{
143659 sqlite3ExpirePreparedStatements(db);
143663 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
143664 assert(p || db->mallocFailed);
143665 if( !p ){
143666 return SQLITE_NOMEM_BKPT;
143669 /* If an older version of the function with a configured destructor is
143670 ** being replaced invoke the destructor function here. */
143671 functionDestroy(db, p);
143673 if( pDestructor ){
143674 pDestructor->nRef++;
143676 p->u.pDestructor = pDestructor;
143677 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
143678 testcase( p->funcFlags & SQLITE_DETERMINISTIC );
143679 p->xSFunc = xSFunc ? xSFunc : xStep;
143680 p->xFinalize = xFinal;
143681 p->pUserData = pUserData;
143682 p->nArg = (u16)nArg;
143683 return SQLITE_OK;
143687 ** Create new user functions.
143689 SQLITE_API int sqlite3_create_function(
143690 sqlite3 *db,
143691 const char *zFunc,
143692 int nArg,
143693 int enc,
143694 void *p,
143695 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
143696 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
143697 void (*xFinal)(sqlite3_context*)
143699 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
143700 xFinal, 0);
143703 SQLITE_API int sqlite3_create_function_v2(
143704 sqlite3 *db,
143705 const char *zFunc,
143706 int nArg,
143707 int enc,
143708 void *p,
143709 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
143710 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
143711 void (*xFinal)(sqlite3_context*),
143712 void (*xDestroy)(void *)
143714 int rc = SQLITE_ERROR;
143715 FuncDestructor *pArg = 0;
143717 #ifdef SQLITE_ENABLE_API_ARMOR
143718 if( !sqlite3SafetyCheckOk(db) ){
143719 return SQLITE_MISUSE_BKPT;
143721 #endif
143722 sqlite3_mutex_enter(db->mutex);
143723 if( xDestroy ){
143724 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
143725 if( !pArg ){
143726 xDestroy(p);
143727 goto out;
143729 pArg->xDestroy = xDestroy;
143730 pArg->pUserData = p;
143732 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
143733 if( pArg && pArg->nRef==0 ){
143734 assert( rc!=SQLITE_OK );
143735 xDestroy(p);
143736 sqlite3DbFree(db, pArg);
143740 rc = sqlite3ApiExit(db, rc);
143741 sqlite3_mutex_leave(db->mutex);
143742 return rc;
143745 #ifndef SQLITE_OMIT_UTF16
143746 SQLITE_API int sqlite3_create_function16(
143747 sqlite3 *db,
143748 const void *zFunctionName,
143749 int nArg,
143750 int eTextRep,
143751 void *p,
143752 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
143753 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
143754 void (*xFinal)(sqlite3_context*)
143756 int rc;
143757 char *zFunc8;
143759 #ifdef SQLITE_ENABLE_API_ARMOR
143760 if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
143761 #endif
143762 sqlite3_mutex_enter(db->mutex);
143763 assert( !db->mallocFailed );
143764 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
143765 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
143766 sqlite3DbFree(db, zFunc8);
143767 rc = sqlite3ApiExit(db, rc);
143768 sqlite3_mutex_leave(db->mutex);
143769 return rc;
143771 #endif
143775 ** Declare that a function has been overloaded by a virtual table.
143777 ** If the function already exists as a regular global function, then
143778 ** this routine is a no-op. If the function does not exist, then create
143779 ** a new one that always throws a run-time error.
143781 ** When virtual tables intend to provide an overloaded function, they
143782 ** should call this routine to make sure the global function exists.
143783 ** A global function must exist in order for name resolution to work
143784 ** properly.
143786 SQLITE_API int sqlite3_overload_function(
143787 sqlite3 *db,
143788 const char *zName,
143789 int nArg
143791 int rc = SQLITE_OK;
143793 #ifdef SQLITE_ENABLE_API_ARMOR
143794 if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
143795 return SQLITE_MISUSE_BKPT;
143797 #endif
143798 sqlite3_mutex_enter(db->mutex);
143799 if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
143800 rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
143801 0, sqlite3InvalidFunction, 0, 0, 0);
143803 rc = sqlite3ApiExit(db, rc);
143804 sqlite3_mutex_leave(db->mutex);
143805 return rc;
143808 #ifndef SQLITE_OMIT_TRACE
143810 ** Register a trace function. The pArg from the previously registered trace
143811 ** is returned.
143813 ** A NULL trace function means that no tracing is executes. A non-NULL
143814 ** trace is a pointer to a function that is invoked at the start of each
143815 ** SQL statement.
143817 #ifndef SQLITE_OMIT_DEPRECATED
143818 SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
143819 void *pOld;
143821 #ifdef SQLITE_ENABLE_API_ARMOR
143822 if( !sqlite3SafetyCheckOk(db) ){
143823 (void)SQLITE_MISUSE_BKPT;
143824 return 0;
143826 #endif
143827 sqlite3_mutex_enter(db->mutex);
143828 pOld = db->pTraceArg;
143829 db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
143830 db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
143831 db->pTraceArg = pArg;
143832 sqlite3_mutex_leave(db->mutex);
143833 return pOld;
143835 #endif /* SQLITE_OMIT_DEPRECATED */
143837 /* Register a trace callback using the version-2 interface.
143839 SQLITE_API int sqlite3_trace_v2(
143840 sqlite3 *db, /* Trace this connection */
143841 unsigned mTrace, /* Mask of events to be traced */
143842 int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
143843 void *pArg /* Context */
143845 #ifdef SQLITE_ENABLE_API_ARMOR
143846 if( !sqlite3SafetyCheckOk(db) ){
143847 return SQLITE_MISUSE_BKPT;
143849 #endif
143850 sqlite3_mutex_enter(db->mutex);
143851 if( mTrace==0 ) xTrace = 0;
143852 if( xTrace==0 ) mTrace = 0;
143853 db->mTrace = mTrace;
143854 db->xTrace = xTrace;
143855 db->pTraceArg = pArg;
143856 sqlite3_mutex_leave(db->mutex);
143857 return SQLITE_OK;
143860 #ifndef SQLITE_OMIT_DEPRECATED
143862 ** Register a profile function. The pArg from the previously registered
143863 ** profile function is returned.
143865 ** A NULL profile function means that no profiling is executes. A non-NULL
143866 ** profile is a pointer to a function that is invoked at the conclusion of
143867 ** each SQL statement that is run.
143869 SQLITE_API void *sqlite3_profile(
143870 sqlite3 *db,
143871 void (*xProfile)(void*,const char*,sqlite_uint64),
143872 void *pArg
143874 void *pOld;
143876 #ifdef SQLITE_ENABLE_API_ARMOR
143877 if( !sqlite3SafetyCheckOk(db) ){
143878 (void)SQLITE_MISUSE_BKPT;
143879 return 0;
143881 #endif
143882 sqlite3_mutex_enter(db->mutex);
143883 pOld = db->pProfileArg;
143884 db->xProfile = xProfile;
143885 db->pProfileArg = pArg;
143886 sqlite3_mutex_leave(db->mutex);
143887 return pOld;
143889 #endif /* SQLITE_OMIT_DEPRECATED */
143890 #endif /* SQLITE_OMIT_TRACE */
143893 ** Register a function to be invoked when a transaction commits.
143894 ** If the invoked function returns non-zero, then the commit becomes a
143895 ** rollback.
143897 SQLITE_API void *sqlite3_commit_hook(
143898 sqlite3 *db, /* Attach the hook to this database */
143899 int (*xCallback)(void*), /* Function to invoke on each commit */
143900 void *pArg /* Argument to the function */
143902 void *pOld;
143904 #ifdef SQLITE_ENABLE_API_ARMOR
143905 if( !sqlite3SafetyCheckOk(db) ){
143906 (void)SQLITE_MISUSE_BKPT;
143907 return 0;
143909 #endif
143910 sqlite3_mutex_enter(db->mutex);
143911 pOld = db->pCommitArg;
143912 db->xCommitCallback = xCallback;
143913 db->pCommitArg = pArg;
143914 sqlite3_mutex_leave(db->mutex);
143915 return pOld;
143919 ** Register a callback to be invoked each time a row is updated,
143920 ** inserted or deleted using this database connection.
143922 SQLITE_API void *sqlite3_update_hook(
143923 sqlite3 *db, /* Attach the hook to this database */
143924 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
143925 void *pArg /* Argument to the function */
143927 void *pRet;
143929 #ifdef SQLITE_ENABLE_API_ARMOR
143930 if( !sqlite3SafetyCheckOk(db) ){
143931 (void)SQLITE_MISUSE_BKPT;
143932 return 0;
143934 #endif
143935 sqlite3_mutex_enter(db->mutex);
143936 pRet = db->pUpdateArg;
143937 db->xUpdateCallback = xCallback;
143938 db->pUpdateArg = pArg;
143939 sqlite3_mutex_leave(db->mutex);
143940 return pRet;
143944 ** Register a callback to be invoked each time a transaction is rolled
143945 ** back by this database connection.
143947 SQLITE_API void *sqlite3_rollback_hook(
143948 sqlite3 *db, /* Attach the hook to this database */
143949 void (*xCallback)(void*), /* Callback function */
143950 void *pArg /* Argument to the function */
143952 void *pRet;
143954 #ifdef SQLITE_ENABLE_API_ARMOR
143955 if( !sqlite3SafetyCheckOk(db) ){
143956 (void)SQLITE_MISUSE_BKPT;
143957 return 0;
143959 #endif
143960 sqlite3_mutex_enter(db->mutex);
143961 pRet = db->pRollbackArg;
143962 db->xRollbackCallback = xCallback;
143963 db->pRollbackArg = pArg;
143964 sqlite3_mutex_leave(db->mutex);
143965 return pRet;
143968 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
143970 ** Register a callback to be invoked each time a row is updated,
143971 ** inserted or deleted using this database connection.
143973 SQLITE_API void *sqlite3_preupdate_hook(
143974 sqlite3 *db, /* Attach the hook to this database */
143975 void(*xCallback)( /* Callback function */
143976 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
143977 void *pArg /* First callback argument */
143979 void *pRet;
143980 sqlite3_mutex_enter(db->mutex);
143981 pRet = db->pPreUpdateArg;
143982 db->xPreUpdateCallback = xCallback;
143983 db->pPreUpdateArg = pArg;
143984 sqlite3_mutex_leave(db->mutex);
143985 return pRet;
143987 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
143989 #ifndef SQLITE_OMIT_WAL
143991 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
143992 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
143993 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
143994 ** wal_autocheckpoint()).
143996 SQLITE_PRIVATE int sqlite3WalDefaultHook(
143997 void *pClientData, /* Argument */
143998 sqlite3 *db, /* Connection */
143999 const char *zDb, /* Database */
144000 int nFrame /* Size of WAL */
144002 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
144003 sqlite3BeginBenignMalloc();
144004 sqlite3_wal_checkpoint(db, zDb);
144005 sqlite3EndBenignMalloc();
144007 return SQLITE_OK;
144009 #endif /* SQLITE_OMIT_WAL */
144012 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
144013 ** a database after committing a transaction if there are nFrame or
144014 ** more frames in the log file. Passing zero or a negative value as the
144015 ** nFrame parameter disables automatic checkpoints entirely.
144017 ** The callback registered by this function replaces any existing callback
144018 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
144019 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
144020 ** configured by this function.
144022 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
144023 #ifdef SQLITE_OMIT_WAL
144024 UNUSED_PARAMETER(db);
144025 UNUSED_PARAMETER(nFrame);
144026 #else
144027 #ifdef SQLITE_ENABLE_API_ARMOR
144028 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
144029 #endif
144030 if( nFrame>0 ){
144031 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
144032 }else{
144033 sqlite3_wal_hook(db, 0, 0);
144035 #endif
144036 return SQLITE_OK;
144040 ** Register a callback to be invoked each time a transaction is written
144041 ** into the write-ahead-log by this database connection.
144043 SQLITE_API void *sqlite3_wal_hook(
144044 sqlite3 *db, /* Attach the hook to this db handle */
144045 int(*xCallback)(void *, sqlite3*, const char*, int),
144046 void *pArg /* First argument passed to xCallback() */
144048 #ifndef SQLITE_OMIT_WAL
144049 void *pRet;
144050 #ifdef SQLITE_ENABLE_API_ARMOR
144051 if( !sqlite3SafetyCheckOk(db) ){
144052 (void)SQLITE_MISUSE_BKPT;
144053 return 0;
144055 #endif
144056 sqlite3_mutex_enter(db->mutex);
144057 pRet = db->pWalArg;
144058 db->xWalCallback = xCallback;
144059 db->pWalArg = pArg;
144060 sqlite3_mutex_leave(db->mutex);
144061 return pRet;
144062 #else
144063 return 0;
144064 #endif
144068 ** Checkpoint database zDb.
144070 SQLITE_API int sqlite3_wal_checkpoint_v2(
144071 sqlite3 *db, /* Database handle */
144072 const char *zDb, /* Name of attached database (or NULL) */
144073 int eMode, /* SQLITE_CHECKPOINT_* value */
144074 int *pnLog, /* OUT: Size of WAL log in frames */
144075 int *pnCkpt /* OUT: Total number of frames checkpointed */
144077 #ifdef SQLITE_OMIT_WAL
144078 return SQLITE_OK;
144079 #else
144080 int rc; /* Return code */
144081 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
144083 #ifdef SQLITE_ENABLE_API_ARMOR
144084 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
144085 #endif
144087 /* Initialize the output variables to -1 in case an error occurs. */
144088 if( pnLog ) *pnLog = -1;
144089 if( pnCkpt ) *pnCkpt = -1;
144091 assert( SQLITE_CHECKPOINT_PASSIVE==0 );
144092 assert( SQLITE_CHECKPOINT_FULL==1 );
144093 assert( SQLITE_CHECKPOINT_RESTART==2 );
144094 assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
144095 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
144096 /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
144097 ** mode: */
144098 return SQLITE_MISUSE;
144101 sqlite3_mutex_enter(db->mutex);
144102 if( zDb && zDb[0] ){
144103 iDb = sqlite3FindDbName(db, zDb);
144105 if( iDb<0 ){
144106 rc = SQLITE_ERROR;
144107 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
144108 }else{
144109 db->busyHandler.nBusy = 0;
144110 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
144111 sqlite3Error(db, rc);
144113 rc = sqlite3ApiExit(db, rc);
144115 /* If there are no active statements, clear the interrupt flag at this
144116 ** point. */
144117 if( db->nVdbeActive==0 ){
144118 db->u1.isInterrupted = 0;
144121 sqlite3_mutex_leave(db->mutex);
144122 return rc;
144123 #endif
144128 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
144129 ** to contains a zero-length string, all attached databases are
144130 ** checkpointed.
144132 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
144133 /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
144134 ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
144135 return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
144138 #ifndef SQLITE_OMIT_WAL
144140 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
144141 ** not currently open in WAL mode.
144143 ** If a transaction is open on the database being checkpointed, this
144144 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
144145 ** an error occurs while running the checkpoint, an SQLite error code is
144146 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
144148 ** The mutex on database handle db should be held by the caller. The mutex
144149 ** associated with the specific b-tree being checkpointed is taken by
144150 ** this function while the checkpoint is running.
144152 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
144153 ** checkpointed. If an error is encountered it is returned immediately -
144154 ** no attempt is made to checkpoint any remaining databases.
144156 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
144157 ** or TRUNCATE.
144159 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
144160 int rc = SQLITE_OK; /* Return code */
144161 int i; /* Used to iterate through attached dbs */
144162 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
144164 assert( sqlite3_mutex_held(db->mutex) );
144165 assert( !pnLog || *pnLog==-1 );
144166 assert( !pnCkpt || *pnCkpt==-1 );
144168 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
144169 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
144170 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
144171 pnLog = 0;
144172 pnCkpt = 0;
144173 if( rc==SQLITE_BUSY ){
144174 bBusy = 1;
144175 rc = SQLITE_OK;
144180 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
144182 #endif /* SQLITE_OMIT_WAL */
144185 ** This function returns true if main-memory should be used instead of
144186 ** a temporary file for transient pager files and statement journals.
144187 ** The value returned depends on the value of db->temp_store (runtime
144188 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
144189 ** following table describes the relationship between these two values
144190 ** and this functions return value.
144192 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
144193 ** ----------------- -------------- ------------------------------
144194 ** 0 any file (return 0)
144195 ** 1 1 file (return 0)
144196 ** 1 2 memory (return 1)
144197 ** 1 0 file (return 0)
144198 ** 2 1 file (return 0)
144199 ** 2 2 memory (return 1)
144200 ** 2 0 memory (return 1)
144201 ** 3 any memory (return 1)
144203 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
144204 #if SQLITE_TEMP_STORE==1
144205 return ( db->temp_store==2 );
144206 #endif
144207 #if SQLITE_TEMP_STORE==2
144208 return ( db->temp_store!=1 );
144209 #endif
144210 #if SQLITE_TEMP_STORE==3
144211 UNUSED_PARAMETER(db);
144212 return 1;
144213 #endif
144214 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
144215 UNUSED_PARAMETER(db);
144216 return 0;
144217 #endif
144221 ** Return UTF-8 encoded English language explanation of the most recent
144222 ** error.
144224 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
144225 const char *z;
144226 if( !db ){
144227 return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
144229 if( !sqlite3SafetyCheckSickOrOk(db) ){
144230 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
144232 sqlite3_mutex_enter(db->mutex);
144233 if( db->mallocFailed ){
144234 z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
144235 }else{
144236 testcase( db->pErr==0 );
144237 z = (char*)sqlite3_value_text(db->pErr);
144238 assert( !db->mallocFailed );
144239 if( z==0 ){
144240 z = sqlite3ErrStr(db->errCode);
144243 sqlite3_mutex_leave(db->mutex);
144244 return z;
144247 #ifndef SQLITE_OMIT_UTF16
144249 ** Return UTF-16 encoded English language explanation of the most recent
144250 ** error.
144252 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
144253 static const u16 outOfMem[] = {
144254 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
144256 static const u16 misuse[] = {
144257 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
144258 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
144259 'm', 'i', 's', 'u', 's', 'e', 0
144262 const void *z;
144263 if( !db ){
144264 return (void *)outOfMem;
144266 if( !sqlite3SafetyCheckSickOrOk(db) ){
144267 return (void *)misuse;
144269 sqlite3_mutex_enter(db->mutex);
144270 if( db->mallocFailed ){
144271 z = (void *)outOfMem;
144272 }else{
144273 z = sqlite3_value_text16(db->pErr);
144274 if( z==0 ){
144275 sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
144276 z = sqlite3_value_text16(db->pErr);
144278 /* A malloc() may have failed within the call to sqlite3_value_text16()
144279 ** above. If this is the case, then the db->mallocFailed flag needs to
144280 ** be cleared before returning. Do this directly, instead of via
144281 ** sqlite3ApiExit(), to avoid setting the database handle error message.
144283 sqlite3OomClear(db);
144285 sqlite3_mutex_leave(db->mutex);
144286 return z;
144288 #endif /* SQLITE_OMIT_UTF16 */
144291 ** Return the most recent error code generated by an SQLite routine. If NULL is
144292 ** passed to this function, we assume a malloc() failed during sqlite3_open().
144294 SQLITE_API int sqlite3_errcode(sqlite3 *db){
144295 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
144296 return SQLITE_MISUSE_BKPT;
144298 if( !db || db->mallocFailed ){
144299 return SQLITE_NOMEM_BKPT;
144301 return db->errCode & db->errMask;
144303 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
144304 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
144305 return SQLITE_MISUSE_BKPT;
144307 if( !db || db->mallocFailed ){
144308 return SQLITE_NOMEM_BKPT;
144310 return db->errCode;
144312 SQLITE_API int sqlite3_system_errno(sqlite3 *db){
144313 return db ? db->iSysErrno : 0;
144317 ** Return a string that describes the kind of error specified in the
144318 ** argument. For now, this simply calls the internal sqlite3ErrStr()
144319 ** function.
144321 SQLITE_API const char *sqlite3_errstr(int rc){
144322 return sqlite3ErrStr(rc);
144326 ** Create a new collating function for database "db". The name is zName
144327 ** and the encoding is enc.
144329 static int createCollation(
144330 sqlite3* db,
144331 const char *zName,
144332 u8 enc,
144333 void* pCtx,
144334 int(*xCompare)(void*,int,const void*,int,const void*),
144335 void(*xDel)(void*)
144337 CollSeq *pColl;
144338 int enc2;
144340 assert( sqlite3_mutex_held(db->mutex) );
144342 /* If SQLITE_UTF16 is specified as the encoding type, transform this
144343 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
144344 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
144346 enc2 = enc;
144347 testcase( enc2==SQLITE_UTF16 );
144348 testcase( enc2==SQLITE_UTF16_ALIGNED );
144349 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
144350 enc2 = SQLITE_UTF16NATIVE;
144352 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
144353 return SQLITE_MISUSE_BKPT;
144356 /* Check if this call is removing or replacing an existing collation
144357 ** sequence. If so, and there are active VMs, return busy. If there
144358 ** are no active VMs, invalidate any pre-compiled statements.
144360 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
144361 if( pColl && pColl->xCmp ){
144362 if( db->nVdbeActive ){
144363 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
144364 "unable to delete/modify collation sequence due to active statements");
144365 return SQLITE_BUSY;
144367 sqlite3ExpirePreparedStatements(db);
144369 /* If collation sequence pColl was created directly by a call to
144370 ** sqlite3_create_collation, and not generated by synthCollSeq(),
144371 ** then any copies made by synthCollSeq() need to be invalidated.
144372 ** Also, collation destructor - CollSeq.xDel() - function may need
144373 ** to be called.
144375 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
144376 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
144377 int j;
144378 for(j=0; j<3; j++){
144379 CollSeq *p = &aColl[j];
144380 if( p->enc==pColl->enc ){
144381 if( p->xDel ){
144382 p->xDel(p->pUser);
144384 p->xCmp = 0;
144390 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
144391 if( pColl==0 ) return SQLITE_NOMEM_BKPT;
144392 pColl->xCmp = xCompare;
144393 pColl->pUser = pCtx;
144394 pColl->xDel = xDel;
144395 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
144396 sqlite3Error(db, SQLITE_OK);
144397 return SQLITE_OK;
144402 ** This array defines hard upper bounds on limit values. The
144403 ** initializer must be kept in sync with the SQLITE_LIMIT_*
144404 ** #defines in sqlite3.h.
144406 static const int aHardLimit[] = {
144407 SQLITE_MAX_LENGTH,
144408 SQLITE_MAX_SQL_LENGTH,
144409 SQLITE_MAX_COLUMN,
144410 SQLITE_MAX_EXPR_DEPTH,
144411 SQLITE_MAX_COMPOUND_SELECT,
144412 SQLITE_MAX_VDBE_OP,
144413 SQLITE_MAX_FUNCTION_ARG,
144414 SQLITE_MAX_ATTACHED,
144415 SQLITE_MAX_LIKE_PATTERN_LENGTH,
144416 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
144417 SQLITE_MAX_TRIGGER_DEPTH,
144418 SQLITE_MAX_WORKER_THREADS,
144422 ** Make sure the hard limits are set to reasonable values
144424 #if SQLITE_MAX_LENGTH<100
144425 # error SQLITE_MAX_LENGTH must be at least 100
144426 #endif
144427 #if SQLITE_MAX_SQL_LENGTH<100
144428 # error SQLITE_MAX_SQL_LENGTH must be at least 100
144429 #endif
144430 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
144431 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
144432 #endif
144433 #if SQLITE_MAX_COMPOUND_SELECT<2
144434 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
144435 #endif
144436 #if SQLITE_MAX_VDBE_OP<40
144437 # error SQLITE_MAX_VDBE_OP must be at least 40
144438 #endif
144439 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
144440 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
144441 #endif
144442 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
144443 # error SQLITE_MAX_ATTACHED must be between 0 and 125
144444 #endif
144445 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
144446 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
144447 #endif
144448 #if SQLITE_MAX_COLUMN>32767
144449 # error SQLITE_MAX_COLUMN must not exceed 32767
144450 #endif
144451 #if SQLITE_MAX_TRIGGER_DEPTH<1
144452 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
144453 #endif
144454 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
144455 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
144456 #endif
144460 ** Change the value of a limit. Report the old value.
144461 ** If an invalid limit index is supplied, report -1.
144462 ** Make no changes but still report the old value if the
144463 ** new limit is negative.
144465 ** A new lower limit does not shrink existing constructs.
144466 ** It merely prevents new constructs that exceed the limit
144467 ** from forming.
144469 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
144470 int oldLimit;
144472 #ifdef SQLITE_ENABLE_API_ARMOR
144473 if( !sqlite3SafetyCheckOk(db) ){
144474 (void)SQLITE_MISUSE_BKPT;
144475 return -1;
144477 #endif
144479 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
144480 ** there is a hard upper bound set at compile-time by a C preprocessor
144481 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
144482 ** "_MAX_".)
144484 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
144485 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
144486 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
144487 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
144488 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
144489 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
144490 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
144491 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
144492 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
144493 SQLITE_MAX_LIKE_PATTERN_LENGTH );
144494 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
144495 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
144496 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
144497 assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
144500 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
144501 return -1;
144503 oldLimit = db->aLimit[limitId];
144504 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
144505 if( newLimit>aHardLimit[limitId] ){
144506 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
144508 db->aLimit[limitId] = newLimit;
144510 return oldLimit; /* IMP: R-53341-35419 */
144514 ** This function is used to parse both URIs and non-URI filenames passed by the
144515 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
144516 ** URIs specified as part of ATTACH statements.
144518 ** The first argument to this function is the name of the VFS to use (or
144519 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
144520 ** query parameter. The second argument contains the URI (or non-URI filename)
144521 ** itself. When this function is called the *pFlags variable should contain
144522 ** the default flags to open the database handle with. The value stored in
144523 ** *pFlags may be updated before returning if the URI filename contains
144524 ** "cache=xxx" or "mode=xxx" query parameters.
144526 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
144527 ** the VFS that should be used to open the database file. *pzFile is set to
144528 ** point to a buffer containing the name of the file to open. It is the
144529 ** responsibility of the caller to eventually call sqlite3_free() to release
144530 ** this buffer.
144532 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
144533 ** may be set to point to a buffer containing an English language error
144534 ** message. It is the responsibility of the caller to eventually release
144535 ** this buffer by calling sqlite3_free().
144537 SQLITE_PRIVATE int sqlite3ParseUri(
144538 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
144539 const char *zUri, /* Nul-terminated URI to parse */
144540 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
144541 sqlite3_vfs **ppVfs, /* OUT: VFS to use */
144542 char **pzFile, /* OUT: Filename component of URI */
144543 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
144545 int rc = SQLITE_OK;
144546 unsigned int flags = *pFlags;
144547 const char *zVfs = zDefaultVfs;
144548 char *zFile;
144549 char c;
144550 int nUri = sqlite3Strlen30(zUri);
144552 assert( *pzErrMsg==0 );
144554 if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
144555 || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
144556 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
144558 char *zOpt;
144559 int eState; /* Parser state when parsing URI */
144560 int iIn; /* Input character index */
144561 int iOut = 0; /* Output character index */
144562 u64 nByte = nUri+2; /* Bytes of space to allocate */
144564 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
144565 ** method that there may be extra parameters following the file-name. */
144566 flags |= SQLITE_OPEN_URI;
144568 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
144569 zFile = sqlite3_malloc64(nByte);
144570 if( !zFile ) return SQLITE_NOMEM_BKPT;
144572 iIn = 5;
144573 #ifdef SQLITE_ALLOW_URI_AUTHORITY
144574 if( strncmp(zUri+5, "///", 3)==0 ){
144575 iIn = 7;
144576 /* The following condition causes URIs with five leading / characters
144577 ** like file://///host/path to be converted into UNCs like //host/path.
144578 ** The correct URI for that UNC has only two or four leading / characters
144579 ** file://host/path or file:////host/path. But 5 leading slashes is a
144580 ** common error, we are told, so we handle it as a special case. */
144581 if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
144582 }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
144583 iIn = 16;
144585 #else
144586 /* Discard the scheme and authority segments of the URI. */
144587 if( zUri[5]=='/' && zUri[6]=='/' ){
144588 iIn = 7;
144589 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
144590 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
144591 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
144592 iIn-7, &zUri[7]);
144593 rc = SQLITE_ERROR;
144594 goto parse_uri_out;
144597 #endif
144599 /* Copy the filename and any query parameters into the zFile buffer.
144600 ** Decode %HH escape codes along the way.
144602 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
144603 ** on the parsing context. As follows:
144605 ** 0: Parsing file-name.
144606 ** 1: Parsing name section of a name=value query parameter.
144607 ** 2: Parsing value section of a name=value query parameter.
144609 eState = 0;
144610 while( (c = zUri[iIn])!=0 && c!='#' ){
144611 iIn++;
144612 if( c=='%'
144613 && sqlite3Isxdigit(zUri[iIn])
144614 && sqlite3Isxdigit(zUri[iIn+1])
144616 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
144617 octet += sqlite3HexToInt(zUri[iIn++]);
144619 assert( octet>=0 && octet<256 );
144620 if( octet==0 ){
144621 #ifndef SQLITE_ENABLE_URI_00_ERROR
144622 /* This branch is taken when "%00" appears within the URI. In this
144623 ** case we ignore all text in the remainder of the path, name or
144624 ** value currently being parsed. So ignore the current character
144625 ** and skip to the next "?", "=" or "&", as appropriate. */
144626 while( (c = zUri[iIn])!=0 && c!='#'
144627 && (eState!=0 || c!='?')
144628 && (eState!=1 || (c!='=' && c!='&'))
144629 && (eState!=2 || c!='&')
144631 iIn++;
144633 continue;
144634 #else
144635 /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
144636 *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
144637 rc = SQLITE_ERROR;
144638 goto parse_uri_out;
144639 #endif
144641 c = octet;
144642 }else if( eState==1 && (c=='&' || c=='=') ){
144643 if( zFile[iOut-1]==0 ){
144644 /* An empty option name. Ignore this option altogether. */
144645 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
144646 continue;
144648 if( c=='&' ){
144649 zFile[iOut++] = '\0';
144650 }else{
144651 eState = 2;
144653 c = 0;
144654 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
144655 c = 0;
144656 eState = 1;
144658 zFile[iOut++] = c;
144660 if( eState==1 ) zFile[iOut++] = '\0';
144661 zFile[iOut++] = '\0';
144662 zFile[iOut++] = '\0';
144664 /* Check if there were any options specified that should be interpreted
144665 ** here. Options that are interpreted here include "vfs" and those that
144666 ** correspond to flags that may be passed to the sqlite3_open_v2()
144667 ** method. */
144668 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
144669 while( zOpt[0] ){
144670 int nOpt = sqlite3Strlen30(zOpt);
144671 char *zVal = &zOpt[nOpt+1];
144672 int nVal = sqlite3Strlen30(zVal);
144674 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
144675 zVfs = zVal;
144676 }else{
144677 struct OpenMode {
144678 const char *z;
144679 int mode;
144680 } *aMode = 0;
144681 char *zModeType = 0;
144682 int mask = 0;
144683 int limit = 0;
144685 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
144686 static struct OpenMode aCacheMode[] = {
144687 { "shared", SQLITE_OPEN_SHAREDCACHE },
144688 { "private", SQLITE_OPEN_PRIVATECACHE },
144689 { 0, 0 }
144692 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
144693 aMode = aCacheMode;
144694 limit = mask;
144695 zModeType = "cache";
144697 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
144698 static struct OpenMode aOpenMode[] = {
144699 { "ro", SQLITE_OPEN_READONLY },
144700 { "rw", SQLITE_OPEN_READWRITE },
144701 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
144702 { "memory", SQLITE_OPEN_MEMORY },
144703 { 0, 0 }
144706 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
144707 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
144708 aMode = aOpenMode;
144709 limit = mask & flags;
144710 zModeType = "access";
144713 if( aMode ){
144714 int i;
144715 int mode = 0;
144716 for(i=0; aMode[i].z; i++){
144717 const char *z = aMode[i].z;
144718 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
144719 mode = aMode[i].mode;
144720 break;
144723 if( mode==0 ){
144724 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
144725 rc = SQLITE_ERROR;
144726 goto parse_uri_out;
144728 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
144729 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
144730 zModeType, zVal);
144731 rc = SQLITE_PERM;
144732 goto parse_uri_out;
144734 flags = (flags & ~mask) | mode;
144738 zOpt = &zVal[nVal+1];
144741 }else{
144742 zFile = sqlite3_malloc64(nUri+2);
144743 if( !zFile ) return SQLITE_NOMEM_BKPT;
144744 if( nUri ){
144745 memcpy(zFile, zUri, nUri);
144747 zFile[nUri] = '\0';
144748 zFile[nUri+1] = '\0';
144749 flags &= ~SQLITE_OPEN_URI;
144752 *ppVfs = sqlite3_vfs_find(zVfs);
144753 if( *ppVfs==0 ){
144754 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
144755 rc = SQLITE_ERROR;
144757 parse_uri_out:
144758 if( rc!=SQLITE_OK ){
144759 sqlite3_free(zFile);
144760 zFile = 0;
144762 *pFlags = flags;
144763 *pzFile = zFile;
144764 return rc;
144769 ** This routine does the work of opening a database on behalf of
144770 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
144771 ** is UTF-8 encoded.
144773 static int openDatabase(
144774 const char *zFilename, /* Database filename UTF-8 encoded */
144775 sqlite3 **ppDb, /* OUT: Returned database handle */
144776 unsigned int flags, /* Operational flags */
144777 const char *zVfs /* Name of the VFS to use */
144779 sqlite3 *db; /* Store allocated handle here */
144780 int rc; /* Return code */
144781 int isThreadsafe; /* True for threadsafe connections */
144782 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
144783 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
144785 #ifdef SQLITE_ENABLE_API_ARMOR
144786 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
144787 #endif
144788 *ppDb = 0;
144789 #ifndef SQLITE_OMIT_AUTOINIT
144790 rc = sqlite3_initialize();
144791 if( rc ) return rc;
144792 #endif
144794 if( sqlite3GlobalConfig.bCoreMutex==0 ){
144795 isThreadsafe = 0;
144796 }else if( flags & SQLITE_OPEN_NOMUTEX ){
144797 isThreadsafe = 0;
144798 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
144799 isThreadsafe = 1;
144800 }else{
144801 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
144803 if( flags & SQLITE_OPEN_PRIVATECACHE ){
144804 flags &= ~SQLITE_OPEN_SHAREDCACHE;
144805 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
144806 flags |= SQLITE_OPEN_SHAREDCACHE;
144809 /* Remove harmful bits from the flags parameter
144811 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
144812 ** dealt with in the previous code block. Besides these, the only
144813 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
144814 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
144815 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
144816 ** off all other flags.
144818 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
144819 SQLITE_OPEN_EXCLUSIVE |
144820 SQLITE_OPEN_MAIN_DB |
144821 SQLITE_OPEN_TEMP_DB |
144822 SQLITE_OPEN_TRANSIENT_DB |
144823 SQLITE_OPEN_MAIN_JOURNAL |
144824 SQLITE_OPEN_TEMP_JOURNAL |
144825 SQLITE_OPEN_SUBJOURNAL |
144826 SQLITE_OPEN_MASTER_JOURNAL |
144827 SQLITE_OPEN_NOMUTEX |
144828 SQLITE_OPEN_FULLMUTEX |
144829 SQLITE_OPEN_WAL
144832 /* Allocate the sqlite data structure */
144833 db = sqlite3MallocZero( sizeof(sqlite3) );
144834 if( db==0 ) goto opendb_out;
144835 if( isThreadsafe ){
144836 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
144837 if( db->mutex==0 ){
144838 sqlite3_free(db);
144839 db = 0;
144840 goto opendb_out;
144843 sqlite3_mutex_enter(db->mutex);
144844 db->errMask = 0xff;
144845 db->nDb = 2;
144846 db->magic = SQLITE_MAGIC_BUSY;
144847 db->aDb = db->aDbStatic;
144849 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
144850 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
144851 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
144852 db->autoCommit = 1;
144853 db->nextAutovac = -1;
144854 db->szMmap = sqlite3GlobalConfig.szMmap;
144855 db->nextPagesize = 0;
144856 db->nMaxSorterMmap = 0x7FFFFFFF;
144857 db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
144858 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
144859 | SQLITE_AutoIndex
144860 #endif
144861 #if SQLITE_DEFAULT_CKPTFULLFSYNC
144862 | SQLITE_CkptFullFSync
144863 #endif
144864 #if SQLITE_DEFAULT_FILE_FORMAT<4
144865 | SQLITE_LegacyFileFmt
144866 #endif
144867 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
144868 | SQLITE_LoadExtension
144869 #endif
144870 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
144871 | SQLITE_RecTriggers
144872 #endif
144873 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
144874 | SQLITE_ForeignKeys
144875 #endif
144876 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
144877 | SQLITE_ReverseOrder
144878 #endif
144879 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
144880 | SQLITE_CellSizeCk
144881 #endif
144882 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
144883 | SQLITE_Fts3Tokenizer
144884 #endif
144885 #if defined(SQLITE_ENABLE_QPSG)
144886 | SQLITE_EnableQPSG
144887 #endif
144889 sqlite3HashInit(&db->aCollSeq);
144890 #ifndef SQLITE_OMIT_VIRTUALTABLE
144891 sqlite3HashInit(&db->aModule);
144892 #endif
144894 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
144895 ** and UTF-16, so add a version for each to avoid any unnecessary
144896 ** conversions. The only error that can occur here is a malloc() failure.
144898 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
144899 ** functions:
144901 createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
144902 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
144903 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
144904 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
144905 createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
144906 if( db->mallocFailed ){
144907 goto opendb_out;
144909 /* EVIDENCE-OF: R-08308-17224 The default collating function for all
144910 ** strings is BINARY.
144912 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
144913 assert( db->pDfltColl!=0 );
144915 /* Parse the filename/URI argument
144917 ** Only allow sensible combinations of bits in the flags argument.
144918 ** Throw an error if any non-sense combination is used. If we
144919 ** do not block illegal combinations here, it could trigger
144920 ** assert() statements in deeper layers. Sensible combinations
144921 ** are:
144923 ** 1: SQLITE_OPEN_READONLY
144924 ** 2: SQLITE_OPEN_READWRITE
144925 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
144927 db->openFlags = flags;
144928 assert( SQLITE_OPEN_READONLY == 0x01 );
144929 assert( SQLITE_OPEN_READWRITE == 0x02 );
144930 assert( SQLITE_OPEN_CREATE == 0x04 );
144931 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
144932 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
144933 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
144934 if( ((1<<(flags&7)) & 0x46)==0 ){
144935 rc = SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
144936 }else{
144937 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
144939 if( rc!=SQLITE_OK ){
144940 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
144941 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
144942 sqlite3_free(zErrMsg);
144943 goto opendb_out;
144946 /* Open the backend database driver */
144947 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
144948 flags | SQLITE_OPEN_MAIN_DB);
144949 if( rc!=SQLITE_OK ){
144950 if( rc==SQLITE_IOERR_NOMEM ){
144951 rc = SQLITE_NOMEM_BKPT;
144953 sqlite3Error(db, rc);
144954 goto opendb_out;
144956 sqlite3BtreeEnter(db->aDb[0].pBt);
144957 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
144958 if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
144959 sqlite3BtreeLeave(db->aDb[0].pBt);
144960 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
144962 /* The default safety_level for the main database is FULL; for the temp
144963 ** database it is OFF. This matches the pager layer defaults.
144965 db->aDb[0].zDbSName = "main";
144966 db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
144967 db->aDb[1].zDbSName = "temp";
144968 db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
144970 db->magic = SQLITE_MAGIC_OPEN;
144971 if( db->mallocFailed ){
144972 goto opendb_out;
144975 /* Register all built-in functions, but do not attempt to read the
144976 ** database schema yet. This is delayed until the first time the database
144977 ** is accessed.
144979 sqlite3Error(db, SQLITE_OK);
144980 sqlite3RegisterPerConnectionBuiltinFunctions(db);
144981 rc = sqlite3_errcode(db);
144983 #ifdef SQLITE_ENABLE_FTS5
144984 /* Register any built-in FTS5 module before loading the automatic
144985 ** extensions. This allows automatic extensions to register FTS5
144986 ** tokenizers and auxiliary functions. */
144987 if( !db->mallocFailed && rc==SQLITE_OK ){
144988 rc = sqlite3Fts5Init(db);
144990 #endif
144992 /* Load automatic extensions - extensions that have been registered
144993 ** using the sqlite3_automatic_extension() API.
144995 if( rc==SQLITE_OK ){
144996 sqlite3AutoLoadExtensions(db);
144997 rc = sqlite3_errcode(db);
144998 if( rc!=SQLITE_OK ){
144999 goto opendb_out;
145003 #ifdef SQLITE_ENABLE_FTS1
145004 if( !db->mallocFailed ){
145005 extern int sqlite3Fts1Init(sqlite3*);
145006 rc = sqlite3Fts1Init(db);
145008 #endif
145010 #ifdef SQLITE_ENABLE_FTS2
145011 if( !db->mallocFailed && rc==SQLITE_OK ){
145012 extern int sqlite3Fts2Init(sqlite3*);
145013 rc = sqlite3Fts2Init(db);
145015 #endif
145017 #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
145018 if( !db->mallocFailed && rc==SQLITE_OK ){
145019 rc = sqlite3Fts3Init(db);
145021 #endif
145023 #ifdef SQLITE_ENABLE_ICU
145024 if( !db->mallocFailed && rc==SQLITE_OK ){
145025 rc = sqlite3IcuInit(db);
145027 #endif
145029 #ifdef SQLITE_ENABLE_RTREE
145030 if( !db->mallocFailed && rc==SQLITE_OK){
145031 rc = sqlite3RtreeInit(db);
145033 #endif
145035 #ifdef SQLITE_ENABLE_DBPAGE_VTAB
145036 if( !db->mallocFailed && rc==SQLITE_OK){
145037 rc = sqlite3DbpageRegister(db);
145039 #endif
145041 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
145042 if( !db->mallocFailed && rc==SQLITE_OK){
145043 rc = sqlite3DbstatRegister(db);
145045 #endif
145047 #ifdef SQLITE_ENABLE_JSON1
145048 if( !db->mallocFailed && rc==SQLITE_OK){
145049 rc = sqlite3Json1Init(db);
145051 #endif
145053 #ifdef SQLITE_ENABLE_STMTVTAB
145054 if( !db->mallocFailed && rc==SQLITE_OK){
145055 rc = sqlite3StmtVtabInit(db);
145057 #endif
145059 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
145060 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
145061 ** mode. Doing nothing at all also makes NORMAL the default.
145063 #ifdef SQLITE_DEFAULT_LOCKING_MODE
145064 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
145065 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
145066 SQLITE_DEFAULT_LOCKING_MODE);
145067 #endif
145069 if( rc ) sqlite3Error(db, rc);
145071 /* Enable the lookaside-malloc subsystem */
145072 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
145073 sqlite3GlobalConfig.nLookaside);
145075 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
145077 opendb_out:
145078 if( db ){
145079 assert( db->mutex!=0 || isThreadsafe==0
145080 || sqlite3GlobalConfig.bFullMutex==0 );
145081 sqlite3_mutex_leave(db->mutex);
145083 rc = sqlite3_errcode(db);
145084 assert( db!=0 || rc==SQLITE_NOMEM );
145085 if( rc==SQLITE_NOMEM ){
145086 sqlite3_close(db);
145087 db = 0;
145088 }else if( rc!=SQLITE_OK ){
145089 db->magic = SQLITE_MAGIC_SICK;
145091 *ppDb = db;
145092 #ifdef SQLITE_ENABLE_SQLLOG
145093 if( sqlite3GlobalConfig.xSqllog ){
145094 /* Opening a db handle. Fourth parameter is passed 0. */
145095 void *pArg = sqlite3GlobalConfig.pSqllogArg;
145096 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
145098 #endif
145099 #if defined(SQLITE_HAS_CODEC)
145100 if( rc==SQLITE_OK ){
145101 const char *zKey;
145102 if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
145103 u8 iByte;
145104 int i;
145105 char zDecoded[40];
145106 for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
145107 iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
145108 if( (i&1)!=0 ) zDecoded[i/2] = iByte;
145110 sqlite3_key_v2(db, 0, zDecoded, i/2);
145111 }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
145112 sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
145115 #endif
145116 sqlite3_free(zOpen);
145117 return rc & 0xff;
145121 ** Open a new database handle.
145123 SQLITE_API int sqlite3_open(
145124 const char *zFilename,
145125 sqlite3 **ppDb
145127 return openDatabase(zFilename, ppDb,
145128 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
145130 SQLITE_API int sqlite3_open_v2(
145131 const char *filename, /* Database filename (UTF-8) */
145132 sqlite3 **ppDb, /* OUT: SQLite db handle */
145133 int flags, /* Flags */
145134 const char *zVfs /* Name of VFS module to use */
145136 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
145139 #ifndef SQLITE_OMIT_UTF16
145141 ** Open a new database handle.
145143 SQLITE_API int sqlite3_open16(
145144 const void *zFilename,
145145 sqlite3 **ppDb
145147 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
145148 sqlite3_value *pVal;
145149 int rc;
145151 #ifdef SQLITE_ENABLE_API_ARMOR
145152 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
145153 #endif
145154 *ppDb = 0;
145155 #ifndef SQLITE_OMIT_AUTOINIT
145156 rc = sqlite3_initialize();
145157 if( rc ) return rc;
145158 #endif
145159 if( zFilename==0 ) zFilename = "\000\000";
145160 pVal = sqlite3ValueNew(0);
145161 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
145162 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
145163 if( zFilename8 ){
145164 rc = openDatabase(zFilename8, ppDb,
145165 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
145166 assert( *ppDb || rc==SQLITE_NOMEM );
145167 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
145168 SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
145170 }else{
145171 rc = SQLITE_NOMEM_BKPT;
145173 sqlite3ValueFree(pVal);
145175 return rc & 0xff;
145177 #endif /* SQLITE_OMIT_UTF16 */
145180 ** Register a new collation sequence with the database handle db.
145182 SQLITE_API int sqlite3_create_collation(
145183 sqlite3* db,
145184 const char *zName,
145185 int enc,
145186 void* pCtx,
145187 int(*xCompare)(void*,int,const void*,int,const void*)
145189 return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
145193 ** Register a new collation sequence with the database handle db.
145195 SQLITE_API int sqlite3_create_collation_v2(
145196 sqlite3* db,
145197 const char *zName,
145198 int enc,
145199 void* pCtx,
145200 int(*xCompare)(void*,int,const void*,int,const void*),
145201 void(*xDel)(void*)
145203 int rc;
145205 #ifdef SQLITE_ENABLE_API_ARMOR
145206 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
145207 #endif
145208 sqlite3_mutex_enter(db->mutex);
145209 assert( !db->mallocFailed );
145210 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
145211 rc = sqlite3ApiExit(db, rc);
145212 sqlite3_mutex_leave(db->mutex);
145213 return rc;
145216 #ifndef SQLITE_OMIT_UTF16
145218 ** Register a new collation sequence with the database handle db.
145220 SQLITE_API int sqlite3_create_collation16(
145221 sqlite3* db,
145222 const void *zName,
145223 int enc,
145224 void* pCtx,
145225 int(*xCompare)(void*,int,const void*,int,const void*)
145227 int rc = SQLITE_OK;
145228 char *zName8;
145230 #ifdef SQLITE_ENABLE_API_ARMOR
145231 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
145232 #endif
145233 sqlite3_mutex_enter(db->mutex);
145234 assert( !db->mallocFailed );
145235 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
145236 if( zName8 ){
145237 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
145238 sqlite3DbFree(db, zName8);
145240 rc = sqlite3ApiExit(db, rc);
145241 sqlite3_mutex_leave(db->mutex);
145242 return rc;
145244 #endif /* SQLITE_OMIT_UTF16 */
145247 ** Register a collation sequence factory callback with the database handle
145248 ** db. Replace any previously installed collation sequence factory.
145250 SQLITE_API int sqlite3_collation_needed(
145251 sqlite3 *db,
145252 void *pCollNeededArg,
145253 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
145255 #ifdef SQLITE_ENABLE_API_ARMOR
145256 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
145257 #endif
145258 sqlite3_mutex_enter(db->mutex);
145259 db->xCollNeeded = xCollNeeded;
145260 db->xCollNeeded16 = 0;
145261 db->pCollNeededArg = pCollNeededArg;
145262 sqlite3_mutex_leave(db->mutex);
145263 return SQLITE_OK;
145266 #ifndef SQLITE_OMIT_UTF16
145268 ** Register a collation sequence factory callback with the database handle
145269 ** db. Replace any previously installed collation sequence factory.
145271 SQLITE_API int sqlite3_collation_needed16(
145272 sqlite3 *db,
145273 void *pCollNeededArg,
145274 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
145276 #ifdef SQLITE_ENABLE_API_ARMOR
145277 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
145278 #endif
145279 sqlite3_mutex_enter(db->mutex);
145280 db->xCollNeeded = 0;
145281 db->xCollNeeded16 = xCollNeeded16;
145282 db->pCollNeededArg = pCollNeededArg;
145283 sqlite3_mutex_leave(db->mutex);
145284 return SQLITE_OK;
145286 #endif /* SQLITE_OMIT_UTF16 */
145288 #ifndef SQLITE_OMIT_DEPRECATED
145290 ** This function is now an anachronism. It used to be used to recover from a
145291 ** malloc() failure, but SQLite now does this automatically.
145293 SQLITE_API int sqlite3_global_recover(void){
145294 return SQLITE_OK;
145296 #endif
145299 ** Test to see whether or not the database connection is in autocommit
145300 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
145301 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
145302 ** by the next COMMIT or ROLLBACK.
145304 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
145305 #ifdef SQLITE_ENABLE_API_ARMOR
145306 if( !sqlite3SafetyCheckOk(db) ){
145307 (void)SQLITE_MISUSE_BKPT;
145308 return 0;
145310 #endif
145311 return db->autoCommit;
145315 ** The following routines are substitutes for constants SQLITE_CORRUPT,
145316 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
145317 ** constants. They serve two purposes:
145319 ** 1. Serve as a convenient place to set a breakpoint in a debugger
145320 ** to detect when version error conditions occurs.
145322 ** 2. Invoke sqlite3_log() to provide the source code location where
145323 ** a low-level error is first detected.
145325 static int reportError(int iErr, int lineno, const char *zType){
145326 sqlite3_log(iErr, "%s at line %d of [%.10s]",
145327 zType, lineno, 20+sqlite3_sourceid());
145328 return iErr;
145330 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
145331 testcase( sqlite3GlobalConfig.xLog!=0 );
145332 return reportError(SQLITE_CORRUPT, lineno, "database corruption");
145334 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
145335 testcase( sqlite3GlobalConfig.xLog!=0 );
145336 return reportError(SQLITE_MISUSE, lineno, "misuse");
145338 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
145339 testcase( sqlite3GlobalConfig.xLog!=0 );
145340 return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
145342 #ifdef SQLITE_DEBUG
145343 SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
145344 char zMsg[100];
145345 sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
145346 testcase( sqlite3GlobalConfig.xLog!=0 );
145347 return reportError(SQLITE_CORRUPT, lineno, zMsg);
145349 SQLITE_PRIVATE int sqlite3NomemError(int lineno){
145350 testcase( sqlite3GlobalConfig.xLog!=0 );
145351 return reportError(SQLITE_NOMEM, lineno, "OOM");
145353 SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
145354 testcase( sqlite3GlobalConfig.xLog!=0 );
145355 return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
145357 #endif
145359 #ifndef SQLITE_OMIT_DEPRECATED
145361 ** This is a convenience routine that makes sure that all thread-specific
145362 ** data for this thread has been deallocated.
145364 ** SQLite no longer uses thread-specific data so this routine is now a
145365 ** no-op. It is retained for historical compatibility.
145367 SQLITE_API void sqlite3_thread_cleanup(void){
145369 #endif
145372 ** Return meta information about a specific column of a database table.
145373 ** See comment in sqlite3.h (sqlite.h.in) for details.
145375 SQLITE_API int sqlite3_table_column_metadata(
145376 sqlite3 *db, /* Connection handle */
145377 const char *zDbName, /* Database name or NULL */
145378 const char *zTableName, /* Table name */
145379 const char *zColumnName, /* Column name */
145380 char const **pzDataType, /* OUTPUT: Declared data type */
145381 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
145382 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
145383 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
145384 int *pAutoinc /* OUTPUT: True if column is auto-increment */
145386 int rc;
145387 char *zErrMsg = 0;
145388 Table *pTab = 0;
145389 Column *pCol = 0;
145390 int iCol = 0;
145391 char const *zDataType = 0;
145392 char const *zCollSeq = 0;
145393 int notnull = 0;
145394 int primarykey = 0;
145395 int autoinc = 0;
145398 #ifdef SQLITE_ENABLE_API_ARMOR
145399 if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
145400 return SQLITE_MISUSE_BKPT;
145402 #endif
145404 /* Ensure the database schema has been loaded */
145405 sqlite3_mutex_enter(db->mutex);
145406 sqlite3BtreeEnterAll(db);
145407 rc = sqlite3Init(db, &zErrMsg);
145408 if( SQLITE_OK!=rc ){
145409 goto error_out;
145412 /* Locate the table in question */
145413 pTab = sqlite3FindTable(db, zTableName, zDbName);
145414 if( !pTab || pTab->pSelect ){
145415 pTab = 0;
145416 goto error_out;
145419 /* Find the column for which info is requested */
145420 if( zColumnName==0 ){
145421 /* Query for existance of table only */
145422 }else{
145423 for(iCol=0; iCol<pTab->nCol; iCol++){
145424 pCol = &pTab->aCol[iCol];
145425 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
145426 break;
145429 if( iCol==pTab->nCol ){
145430 if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
145431 iCol = pTab->iPKey;
145432 pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
145433 }else{
145434 pTab = 0;
145435 goto error_out;
145440 /* The following block stores the meta information that will be returned
145441 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
145442 ** and autoinc. At this point there are two possibilities:
145444 ** 1. The specified column name was rowid", "oid" or "_rowid_"
145445 ** and there is no explicitly declared IPK column.
145447 ** 2. The table is not a view and the column name identified an
145448 ** explicitly declared column. Copy meta information from *pCol.
145450 if( pCol ){
145451 zDataType = sqlite3ColumnType(pCol,0);
145452 zCollSeq = pCol->zColl;
145453 notnull = pCol->notNull!=0;
145454 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
145455 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
145456 }else{
145457 zDataType = "INTEGER";
145458 primarykey = 1;
145460 if( !zCollSeq ){
145461 zCollSeq = sqlite3StrBINARY;
145464 error_out:
145465 sqlite3BtreeLeaveAll(db);
145467 /* Whether the function call succeeded or failed, set the output parameters
145468 ** to whatever their local counterparts contain. If an error did occur,
145469 ** this has the effect of zeroing all output parameters.
145471 if( pzDataType ) *pzDataType = zDataType;
145472 if( pzCollSeq ) *pzCollSeq = zCollSeq;
145473 if( pNotNull ) *pNotNull = notnull;
145474 if( pPrimaryKey ) *pPrimaryKey = primarykey;
145475 if( pAutoinc ) *pAutoinc = autoinc;
145477 if( SQLITE_OK==rc && !pTab ){
145478 sqlite3DbFree(db, zErrMsg);
145479 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
145480 zColumnName);
145481 rc = SQLITE_ERROR;
145483 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
145484 sqlite3DbFree(db, zErrMsg);
145485 rc = sqlite3ApiExit(db, rc);
145486 sqlite3_mutex_leave(db->mutex);
145487 return rc;
145491 ** Sleep for a little while. Return the amount of time slept.
145493 SQLITE_API int sqlite3_sleep(int ms){
145494 sqlite3_vfs *pVfs;
145495 int rc;
145496 pVfs = sqlite3_vfs_find(0);
145497 if( pVfs==0 ) return 0;
145499 /* This function works in milliseconds, but the underlying OsSleep()
145500 ** API uses microseconds. Hence the 1000's.
145502 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
145503 return rc;
145507 ** Enable or disable the extended result codes.
145509 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
145510 #ifdef SQLITE_ENABLE_API_ARMOR
145511 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
145512 #endif
145513 sqlite3_mutex_enter(db->mutex);
145514 db->errMask = onoff ? 0xffffffff : 0xff;
145515 sqlite3_mutex_leave(db->mutex);
145516 return SQLITE_OK;
145520 ** Invoke the xFileControl method on a particular database.
145522 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
145523 int rc = SQLITE_ERROR;
145524 Btree *pBtree;
145526 #ifdef SQLITE_ENABLE_API_ARMOR
145527 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
145528 #endif
145529 sqlite3_mutex_enter(db->mutex);
145530 pBtree = sqlite3DbNameToBtree(db, zDbName);
145531 if( pBtree ){
145532 Pager *pPager;
145533 sqlite3_file *fd;
145534 sqlite3BtreeEnter(pBtree);
145535 pPager = sqlite3BtreePager(pBtree);
145536 assert( pPager!=0 );
145537 fd = sqlite3PagerFile(pPager);
145538 assert( fd!=0 );
145539 if( op==SQLITE_FCNTL_FILE_POINTER ){
145540 *(sqlite3_file**)pArg = fd;
145541 rc = SQLITE_OK;
145542 }else if( op==SQLITE_FCNTL_VFS_POINTER ){
145543 *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
145544 rc = SQLITE_OK;
145545 }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
145546 *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
145547 rc = SQLITE_OK;
145548 }else if( fd->pMethods ){
145549 rc = sqlite3OsFileControl(fd, op, pArg);
145550 }else{
145551 rc = SQLITE_NOTFOUND;
145553 sqlite3BtreeLeave(pBtree);
145555 sqlite3_mutex_leave(db->mutex);
145556 return rc;
145560 ** Interface to the testing logic.
145562 SQLITE_API int sqlite3_test_control(int op, ...){
145563 int rc = 0;
145564 #ifdef SQLITE_UNTESTABLE
145565 UNUSED_PARAMETER(op);
145566 #else
145567 va_list ap;
145568 va_start(ap, op);
145569 switch( op ){
145572 ** Save the current state of the PRNG.
145574 case SQLITE_TESTCTRL_PRNG_SAVE: {
145575 sqlite3PrngSaveState();
145576 break;
145580 ** Restore the state of the PRNG to the last state saved using
145581 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
145582 ** this verb acts like PRNG_RESET.
145584 case SQLITE_TESTCTRL_PRNG_RESTORE: {
145585 sqlite3PrngRestoreState();
145586 break;
145590 ** Reset the PRNG back to its uninitialized state. The next call
145591 ** to sqlite3_randomness() will reseed the PRNG using a single call
145592 ** to the xRandomness method of the default VFS.
145594 case SQLITE_TESTCTRL_PRNG_RESET: {
145595 sqlite3_randomness(0,0);
145596 break;
145600 ** sqlite3_test_control(BITVEC_TEST, size, program)
145602 ** Run a test against a Bitvec object of size. The program argument
145603 ** is an array of integers that defines the test. Return -1 on a
145604 ** memory allocation error, 0 on success, or non-zero for an error.
145605 ** See the sqlite3BitvecBuiltinTest() for additional information.
145607 case SQLITE_TESTCTRL_BITVEC_TEST: {
145608 int sz = va_arg(ap, int);
145609 int *aProg = va_arg(ap, int*);
145610 rc = sqlite3BitvecBuiltinTest(sz, aProg);
145611 break;
145615 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
145617 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
145618 ** if xCallback is not NULL.
145620 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
145621 ** is called immediately after installing the new callback and the return
145622 ** value from sqlite3FaultSim(0) becomes the return from
145623 ** sqlite3_test_control().
145625 case SQLITE_TESTCTRL_FAULT_INSTALL: {
145626 /* MSVC is picky about pulling func ptrs from va lists.
145627 ** http://support.microsoft.com/kb/47961
145628 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
145630 typedef int(*TESTCALLBACKFUNC_t)(int);
145631 sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
145632 rc = sqlite3FaultSim(0);
145633 break;
145637 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
145639 ** Register hooks to call to indicate which malloc() failures
145640 ** are benign.
145642 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
145643 typedef void (*void_function)(void);
145644 void_function xBenignBegin;
145645 void_function xBenignEnd;
145646 xBenignBegin = va_arg(ap, void_function);
145647 xBenignEnd = va_arg(ap, void_function);
145648 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
145649 break;
145653 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
145655 ** Set the PENDING byte to the value in the argument, if X>0.
145656 ** Make no changes if X==0. Return the value of the pending byte
145657 ** as it existing before this routine was called.
145659 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
145660 ** an incompatible database file format. Changing the PENDING byte
145661 ** while any database connection is open results in undefined and
145662 ** deleterious behavior.
145664 case SQLITE_TESTCTRL_PENDING_BYTE: {
145665 rc = PENDING_BYTE;
145666 #ifndef SQLITE_OMIT_WSD
145668 unsigned int newVal = va_arg(ap, unsigned int);
145669 if( newVal ) sqlite3PendingByte = newVal;
145671 #endif
145672 break;
145676 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
145678 ** This action provides a run-time test to see whether or not
145679 ** assert() was enabled at compile-time. If X is true and assert()
145680 ** is enabled, then the return value is true. If X is true and
145681 ** assert() is disabled, then the return value is zero. If X is
145682 ** false and assert() is enabled, then the assertion fires and the
145683 ** process aborts. If X is false and assert() is disabled, then the
145684 ** return value is zero.
145686 case SQLITE_TESTCTRL_ASSERT: {
145687 volatile int x = 0;
145688 assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
145689 rc = x;
145690 break;
145695 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
145697 ** This action provides a run-time test to see how the ALWAYS and
145698 ** NEVER macros were defined at compile-time.
145700 ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
145702 ** The recommended test is X==2. If the return value is 2, that means
145703 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
145704 ** default setting. If the return value is 1, then ALWAYS() is either
145705 ** hard-coded to true or else it asserts if its argument is false.
145706 ** The first behavior (hard-coded to true) is the case if
145707 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
145708 ** behavior (assert if the argument to ALWAYS() is false) is the case if
145709 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
145711 ** The run-time test procedure might look something like this:
145713 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
145714 ** // ALWAYS() and NEVER() are no-op pass-through macros
145715 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
145716 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
145717 ** }else{
145718 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
145721 case SQLITE_TESTCTRL_ALWAYS: {
145722 int x = va_arg(ap,int);
145723 rc = x ? ALWAYS(x) : 0;
145724 break;
145728 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
145730 ** The integer returned reveals the byte-order of the computer on which
145731 ** SQLite is running:
145733 ** 1 big-endian, determined at run-time
145734 ** 10 little-endian, determined at run-time
145735 ** 432101 big-endian, determined at compile-time
145736 ** 123410 little-endian, determined at compile-time
145738 case SQLITE_TESTCTRL_BYTEORDER: {
145739 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
145740 break;
145743 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
145745 ** Set the nReserve size to N for the main database on the database
145746 ** connection db.
145748 case SQLITE_TESTCTRL_RESERVE: {
145749 sqlite3 *db = va_arg(ap, sqlite3*);
145750 int x = va_arg(ap,int);
145751 sqlite3_mutex_enter(db->mutex);
145752 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
145753 sqlite3_mutex_leave(db->mutex);
145754 break;
145757 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
145759 ** Enable or disable various optimizations for testing purposes. The
145760 ** argument N is a bitmask of optimizations to be disabled. For normal
145761 ** operation N should be 0. The idea is that a test program (like the
145762 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
145763 ** with various optimizations disabled to verify that the same answer
145764 ** is obtained in every case.
145766 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
145767 sqlite3 *db = va_arg(ap, sqlite3*);
145768 db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
145769 break;
145772 #ifdef SQLITE_N_KEYWORD
145773 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
145775 ** If zWord is a keyword recognized by the parser, then return the
145776 ** number of keywords. Or if zWord is not a keyword, return 0.
145778 ** This test feature is only available in the amalgamation since
145779 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
145780 ** is built using separate source files.
145782 case SQLITE_TESTCTRL_ISKEYWORD: {
145783 const char *zWord = va_arg(ap, const char*);
145784 int n = sqlite3Strlen30(zWord);
145785 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
145786 break;
145788 #endif
145790 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
145792 ** If parameter onoff is non-zero, configure the wrappers so that all
145793 ** subsequent calls to localtime() and variants fail. If onoff is zero,
145794 ** undo this setting.
145796 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
145797 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
145798 break;
145801 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
145803 ** Set or clear a flag that indicates that the database file is always well-
145804 ** formed and never corrupt. This flag is clear by default, indicating that
145805 ** database files might have arbitrary corruption. Setting the flag during
145806 ** testing causes certain assert() statements in the code to be activated
145807 ** that demonstrat invariants on well-formed database files.
145809 case SQLITE_TESTCTRL_NEVER_CORRUPT: {
145810 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
145811 break;
145814 /* Set the threshold at which OP_Once counters reset back to zero.
145815 ** By default this is 0x7ffffffe (over 2 billion), but that value is
145816 ** too big to test in a reasonable amount of time, so this control is
145817 ** provided to set a small and easily reachable reset value.
145819 case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
145820 sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
145821 break;
145824 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
145826 ** Set the VDBE coverage callback function to xCallback with context
145827 ** pointer ptr.
145829 case SQLITE_TESTCTRL_VDBE_COVERAGE: {
145830 #ifdef SQLITE_VDBE_COVERAGE
145831 typedef void (*branch_callback)(void*,int,u8,u8);
145832 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
145833 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
145834 #endif
145835 break;
145838 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
145839 case SQLITE_TESTCTRL_SORTER_MMAP: {
145840 sqlite3 *db = va_arg(ap, sqlite3*);
145841 db->nMaxSorterMmap = va_arg(ap, int);
145842 break;
145845 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
145847 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
145848 ** not.
145850 case SQLITE_TESTCTRL_ISINIT: {
145851 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
145852 break;
145855 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
145857 ** This test control is used to create imposter tables. "db" is a pointer
145858 ** to the database connection. dbName is the database name (ex: "main" or
145859 ** "temp") which will receive the imposter. "onOff" turns imposter mode on
145860 ** or off. "tnum" is the root page of the b-tree to which the imposter
145861 ** table should connect.
145863 ** Enable imposter mode only when the schema has already been parsed. Then
145864 ** run a single CREATE TABLE statement to construct the imposter table in
145865 ** the parsed schema. Then turn imposter mode back off again.
145867 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
145868 ** the schema to be reparsed the next time it is needed. This has the
145869 ** effect of erasing all imposter tables.
145871 case SQLITE_TESTCTRL_IMPOSTER: {
145872 sqlite3 *db = va_arg(ap, sqlite3*);
145873 sqlite3_mutex_enter(db->mutex);
145874 db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
145875 db->init.busy = db->init.imposterTable = va_arg(ap,int);
145876 db->init.newTnum = va_arg(ap,int);
145877 if( db->init.busy==0 && db->init.newTnum>0 ){
145878 sqlite3ResetAllSchemasOfConnection(db);
145880 sqlite3_mutex_leave(db->mutex);
145881 break;
145884 va_end(ap);
145885 #endif /* SQLITE_UNTESTABLE */
145886 return rc;
145890 ** This is a utility routine, useful to VFS implementations, that checks
145891 ** to see if a database file was a URI that contained a specific query
145892 ** parameter, and if so obtains the value of the query parameter.
145894 ** The zFilename argument is the filename pointer passed into the xOpen()
145895 ** method of a VFS implementation. The zParam argument is the name of the
145896 ** query parameter we seek. This routine returns the value of the zParam
145897 ** parameter if it exists. If the parameter does not exist, this routine
145898 ** returns a NULL pointer.
145900 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
145901 if( zFilename==0 || zParam==0 ) return 0;
145902 zFilename += sqlite3Strlen30(zFilename) + 1;
145903 while( zFilename[0] ){
145904 int x = strcmp(zFilename, zParam);
145905 zFilename += sqlite3Strlen30(zFilename) + 1;
145906 if( x==0 ) return zFilename;
145907 zFilename += sqlite3Strlen30(zFilename) + 1;
145909 return 0;
145913 ** Return a boolean value for a query parameter.
145915 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
145916 const char *z = sqlite3_uri_parameter(zFilename, zParam);
145917 bDflt = bDflt!=0;
145918 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
145922 ** Return a 64-bit integer value for a query parameter.
145924 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
145925 const char *zFilename, /* Filename as passed to xOpen */
145926 const char *zParam, /* URI parameter sought */
145927 sqlite3_int64 bDflt /* return if parameter is missing */
145929 const char *z = sqlite3_uri_parameter(zFilename, zParam);
145930 sqlite3_int64 v;
145931 if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
145932 bDflt = v;
145934 return bDflt;
145938 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
145940 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
145941 int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
145942 return iDb<0 ? 0 : db->aDb[iDb].pBt;
145946 ** Return the filename of the database associated with a database
145947 ** connection.
145949 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
145950 Btree *pBt;
145951 #ifdef SQLITE_ENABLE_API_ARMOR
145952 if( !sqlite3SafetyCheckOk(db) ){
145953 (void)SQLITE_MISUSE_BKPT;
145954 return 0;
145956 #endif
145957 pBt = sqlite3DbNameToBtree(db, zDbName);
145958 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
145962 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
145963 ** no such database exists.
145965 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
145966 Btree *pBt;
145967 #ifdef SQLITE_ENABLE_API_ARMOR
145968 if( !sqlite3SafetyCheckOk(db) ){
145969 (void)SQLITE_MISUSE_BKPT;
145970 return -1;
145972 #endif
145973 pBt = sqlite3DbNameToBtree(db, zDbName);
145974 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
145977 #ifdef SQLITE_ENABLE_SNAPSHOT
145979 ** Obtain a snapshot handle for the snapshot of database zDb currently
145980 ** being read by handle db.
145982 SQLITE_API int sqlite3_snapshot_get(
145983 sqlite3 *db,
145984 const char *zDb,
145985 sqlite3_snapshot **ppSnapshot
145987 int rc = SQLITE_ERROR;
145988 #ifndef SQLITE_OMIT_WAL
145990 #ifdef SQLITE_ENABLE_API_ARMOR
145991 if( !sqlite3SafetyCheckOk(db) ){
145992 return SQLITE_MISUSE_BKPT;
145994 #endif
145995 sqlite3_mutex_enter(db->mutex);
145997 if( db->autoCommit==0 ){
145998 int iDb = sqlite3FindDbName(db, zDb);
145999 if( iDb==0 || iDb>1 ){
146000 Btree *pBt = db->aDb[iDb].pBt;
146001 if( 0==sqlite3BtreeIsInTrans(pBt) ){
146002 rc = sqlite3BtreeBeginTrans(pBt, 0);
146003 if( rc==SQLITE_OK ){
146004 rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
146010 sqlite3_mutex_leave(db->mutex);
146011 #endif /* SQLITE_OMIT_WAL */
146012 return rc;
146016 ** Open a read-transaction on the snapshot idendified by pSnapshot.
146018 SQLITE_API int sqlite3_snapshot_open(
146019 sqlite3 *db,
146020 const char *zDb,
146021 sqlite3_snapshot *pSnapshot
146023 int rc = SQLITE_ERROR;
146024 #ifndef SQLITE_OMIT_WAL
146026 #ifdef SQLITE_ENABLE_API_ARMOR
146027 if( !sqlite3SafetyCheckOk(db) ){
146028 return SQLITE_MISUSE_BKPT;
146030 #endif
146031 sqlite3_mutex_enter(db->mutex);
146032 if( db->autoCommit==0 ){
146033 int iDb;
146034 iDb = sqlite3FindDbName(db, zDb);
146035 if( iDb==0 || iDb>1 ){
146036 Btree *pBt = db->aDb[iDb].pBt;
146037 if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
146038 rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
146039 if( rc==SQLITE_OK ){
146040 rc = sqlite3BtreeBeginTrans(pBt, 0);
146041 sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
146047 sqlite3_mutex_leave(db->mutex);
146048 #endif /* SQLITE_OMIT_WAL */
146049 return rc;
146053 ** Recover as many snapshots as possible from the wal file associated with
146054 ** schema zDb of database db.
146056 SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
146057 int rc = SQLITE_ERROR;
146058 int iDb;
146059 #ifndef SQLITE_OMIT_WAL
146061 #ifdef SQLITE_ENABLE_API_ARMOR
146062 if( !sqlite3SafetyCheckOk(db) ){
146063 return SQLITE_MISUSE_BKPT;
146065 #endif
146067 sqlite3_mutex_enter(db->mutex);
146068 iDb = sqlite3FindDbName(db, zDb);
146069 if( iDb==0 || iDb>1 ){
146070 Btree *pBt = db->aDb[iDb].pBt;
146071 if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
146072 rc = sqlite3BtreeBeginTrans(pBt, 0);
146073 if( rc==SQLITE_OK ){
146074 rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
146075 sqlite3BtreeCommit(pBt);
146079 sqlite3_mutex_leave(db->mutex);
146080 #endif /* SQLITE_OMIT_WAL */
146081 return rc;
146085 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
146087 SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
146088 sqlite3_free(pSnapshot);
146090 #endif /* SQLITE_ENABLE_SNAPSHOT */
146092 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
146094 ** Given the name of a compile-time option, return true if that option
146095 ** was used and false if not.
146097 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
146098 ** is not required for a match.
146100 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
146101 int i, n;
146102 int nOpt;
146103 const char **azCompileOpt;
146105 #if SQLITE_ENABLE_API_ARMOR
146106 if( zOptName==0 ){
146107 (void)SQLITE_MISUSE_BKPT;
146108 return 0;
146110 #endif
146112 azCompileOpt = sqlite3CompileOptions(&nOpt);
146114 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
146115 n = sqlite3Strlen30(zOptName);
146117 /* Since nOpt is normally in single digits, a linear search is
146118 ** adequate. No need for a binary search. */
146119 for(i=0; i<nOpt; i++){
146120 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
146121 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
146123 return 1;
146126 return 0;
146130 ** Return the N-th compile-time option string. If N is out of range,
146131 ** return a NULL pointer.
146133 SQLITE_API const char *sqlite3_compileoption_get(int N){
146134 int nOpt;
146135 const char **azCompileOpt;
146136 azCompileOpt = sqlite3CompileOptions(&nOpt);
146137 if( N>=0 && N<nOpt ){
146138 return azCompileOpt[N];
146140 return 0;
146142 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
146144 /************** End of main.c ************************************************/
146145 /************** Begin file notify.c ******************************************/
146147 ** 2009 March 3
146149 ** The author disclaims copyright to this source code. In place of
146150 ** a legal notice, here is a blessing:
146152 ** May you do good and not evil.
146153 ** May you find forgiveness for yourself and forgive others.
146154 ** May you share freely, never taking more than you give.
146156 *************************************************************************
146158 ** This file contains the implementation of the sqlite3_unlock_notify()
146159 ** API method and its associated functionality.
146161 /* #include "sqliteInt.h" */
146162 /* #include "btreeInt.h" */
146164 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
146165 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
146168 ** Public interfaces:
146170 ** sqlite3ConnectionBlocked()
146171 ** sqlite3ConnectionUnlocked()
146172 ** sqlite3ConnectionClosed()
146173 ** sqlite3_unlock_notify()
146176 #define assertMutexHeld() \
146177 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
146180 ** Head of a linked list of all sqlite3 objects created by this process
146181 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
146182 ** is not NULL. This variable may only accessed while the STATIC_MASTER
146183 ** mutex is held.
146185 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
146187 #ifndef NDEBUG
146189 ** This function is a complex assert() that verifies the following
146190 ** properties of the blocked connections list:
146192 ** 1) Each entry in the list has a non-NULL value for either
146193 ** pUnlockConnection or pBlockingConnection, or both.
146195 ** 2) All entries in the list that share a common value for
146196 ** xUnlockNotify are grouped together.
146198 ** 3) If the argument db is not NULL, then none of the entries in the
146199 ** blocked connections list have pUnlockConnection or pBlockingConnection
146200 ** set to db. This is used when closing connection db.
146202 static void checkListProperties(sqlite3 *db){
146203 sqlite3 *p;
146204 for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
146205 int seen = 0;
146206 sqlite3 *p2;
146208 /* Verify property (1) */
146209 assert( p->pUnlockConnection || p->pBlockingConnection );
146211 /* Verify property (2) */
146212 for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
146213 if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
146214 assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
146215 assert( db==0 || p->pUnlockConnection!=db );
146216 assert( db==0 || p->pBlockingConnection!=db );
146220 #else
146221 # define checkListProperties(x)
146222 #endif
146225 ** Remove connection db from the blocked connections list. If connection
146226 ** db is not currently a part of the list, this function is a no-op.
146228 static void removeFromBlockedList(sqlite3 *db){
146229 sqlite3 **pp;
146230 assertMutexHeld();
146231 for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
146232 if( *pp==db ){
146233 *pp = (*pp)->pNextBlocked;
146234 break;
146240 ** Add connection db to the blocked connections list. It is assumed
146241 ** that it is not already a part of the list.
146243 static void addToBlockedList(sqlite3 *db){
146244 sqlite3 **pp;
146245 assertMutexHeld();
146247 pp=&sqlite3BlockedList;
146248 *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
146249 pp=&(*pp)->pNextBlocked
146251 db->pNextBlocked = *pp;
146252 *pp = db;
146256 ** Obtain the STATIC_MASTER mutex.
146258 static void enterMutex(void){
146259 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
146260 checkListProperties(0);
146264 ** Release the STATIC_MASTER mutex.
146266 static void leaveMutex(void){
146267 assertMutexHeld();
146268 checkListProperties(0);
146269 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
146273 ** Register an unlock-notify callback.
146275 ** This is called after connection "db" has attempted some operation
146276 ** but has received an SQLITE_LOCKED error because another connection
146277 ** (call it pOther) in the same process was busy using the same shared
146278 ** cache. pOther is found by looking at db->pBlockingConnection.
146280 ** If there is no blocking connection, the callback is invoked immediately,
146281 ** before this routine returns.
146283 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
146284 ** a deadlock.
146286 ** Otherwise, make arrangements to invoke xNotify when pOther drops
146287 ** its locks.
146289 ** Each call to this routine overrides any prior callbacks registered
146290 ** on the same "db". If xNotify==0 then any prior callbacks are immediately
146291 ** cancelled.
146293 SQLITE_API int sqlite3_unlock_notify(
146294 sqlite3 *db,
146295 void (*xNotify)(void **, int),
146296 void *pArg
146298 int rc = SQLITE_OK;
146300 sqlite3_mutex_enter(db->mutex);
146301 enterMutex();
146303 if( xNotify==0 ){
146304 removeFromBlockedList(db);
146305 db->pBlockingConnection = 0;
146306 db->pUnlockConnection = 0;
146307 db->xUnlockNotify = 0;
146308 db->pUnlockArg = 0;
146309 }else if( 0==db->pBlockingConnection ){
146310 /* The blocking transaction has been concluded. Or there never was a
146311 ** blocking transaction. In either case, invoke the notify callback
146312 ** immediately.
146314 xNotify(&pArg, 1);
146315 }else{
146316 sqlite3 *p;
146318 for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
146319 if( p ){
146320 rc = SQLITE_LOCKED; /* Deadlock detected. */
146321 }else{
146322 db->pUnlockConnection = db->pBlockingConnection;
146323 db->xUnlockNotify = xNotify;
146324 db->pUnlockArg = pArg;
146325 removeFromBlockedList(db);
146326 addToBlockedList(db);
146330 leaveMutex();
146331 assert( !db->mallocFailed );
146332 sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
146333 sqlite3_mutex_leave(db->mutex);
146334 return rc;
146338 ** This function is called while stepping or preparing a statement
146339 ** associated with connection db. The operation will return SQLITE_LOCKED
146340 ** to the user because it requires a lock that will not be available
146341 ** until connection pBlocker concludes its current transaction.
146343 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
146344 enterMutex();
146345 if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
146346 addToBlockedList(db);
146348 db->pBlockingConnection = pBlocker;
146349 leaveMutex();
146353 ** This function is called when
146354 ** the transaction opened by database db has just finished. Locks held
146355 ** by database connection db have been released.
146357 ** This function loops through each entry in the blocked connections
146358 ** list and does the following:
146360 ** 1) If the sqlite3.pBlockingConnection member of a list entry is
146361 ** set to db, then set pBlockingConnection=0.
146363 ** 2) If the sqlite3.pUnlockConnection member of a list entry is
146364 ** set to db, then invoke the configured unlock-notify callback and
146365 ** set pUnlockConnection=0.
146367 ** 3) If the two steps above mean that pBlockingConnection==0 and
146368 ** pUnlockConnection==0, remove the entry from the blocked connections
146369 ** list.
146371 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
146372 void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
146373 int nArg = 0; /* Number of entries in aArg[] */
146374 sqlite3 **pp; /* Iterator variable */
146375 void **aArg; /* Arguments to the unlock callback */
146376 void **aDyn = 0; /* Dynamically allocated space for aArg[] */
146377 void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
146379 aArg = aStatic;
146380 enterMutex(); /* Enter STATIC_MASTER mutex */
146382 /* This loop runs once for each entry in the blocked-connections list. */
146383 for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
146384 sqlite3 *p = *pp;
146386 /* Step 1. */
146387 if( p->pBlockingConnection==db ){
146388 p->pBlockingConnection = 0;
146391 /* Step 2. */
146392 if( p->pUnlockConnection==db ){
146393 assert( p->xUnlockNotify );
146394 if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
146395 xUnlockNotify(aArg, nArg);
146396 nArg = 0;
146399 sqlite3BeginBenignMalloc();
146400 assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
146401 assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
146402 if( (!aDyn && nArg==(int)ArraySize(aStatic))
146403 || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
146405 /* The aArg[] array needs to grow. */
146406 void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
146407 if( pNew ){
146408 memcpy(pNew, aArg, nArg*sizeof(void *));
146409 sqlite3_free(aDyn);
146410 aDyn = aArg = pNew;
146411 }else{
146412 /* This occurs when the array of context pointers that need to
146413 ** be passed to the unlock-notify callback is larger than the
146414 ** aStatic[] array allocated on the stack and the attempt to
146415 ** allocate a larger array from the heap has failed.
146417 ** This is a difficult situation to handle. Returning an error
146418 ** code to the caller is insufficient, as even if an error code
146419 ** is returned the transaction on connection db will still be
146420 ** closed and the unlock-notify callbacks on blocked connections
146421 ** will go unissued. This might cause the application to wait
146422 ** indefinitely for an unlock-notify callback that will never
146423 ** arrive.
146425 ** Instead, invoke the unlock-notify callback with the context
146426 ** array already accumulated. We can then clear the array and
146427 ** begin accumulating any further context pointers without
146428 ** requiring any dynamic allocation. This is sub-optimal because
146429 ** it means that instead of one callback with a large array of
146430 ** context pointers the application will receive two or more
146431 ** callbacks with smaller arrays of context pointers, which will
146432 ** reduce the applications ability to prioritize multiple
146433 ** connections. But it is the best that can be done under the
146434 ** circumstances.
146436 xUnlockNotify(aArg, nArg);
146437 nArg = 0;
146440 sqlite3EndBenignMalloc();
146442 aArg[nArg++] = p->pUnlockArg;
146443 xUnlockNotify = p->xUnlockNotify;
146444 p->pUnlockConnection = 0;
146445 p->xUnlockNotify = 0;
146446 p->pUnlockArg = 0;
146449 /* Step 3. */
146450 if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
146451 /* Remove connection p from the blocked connections list. */
146452 *pp = p->pNextBlocked;
146453 p->pNextBlocked = 0;
146454 }else{
146455 pp = &p->pNextBlocked;
146459 if( nArg!=0 ){
146460 xUnlockNotify(aArg, nArg);
146462 sqlite3_free(aDyn);
146463 leaveMutex(); /* Leave STATIC_MASTER mutex */
146467 ** This is called when the database connection passed as an argument is
146468 ** being closed. The connection is removed from the blocked list.
146470 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
146471 sqlite3ConnectionUnlocked(db);
146472 enterMutex();
146473 removeFromBlockedList(db);
146474 checkListProperties(db);
146475 leaveMutex();
146477 #endif
146479 /************** End of notify.c **********************************************/
146480 /************** Begin file fts3.c ********************************************/
146482 ** 2006 Oct 10
146484 ** The author disclaims copyright to this source code. In place of
146485 ** a legal notice, here is a blessing:
146487 ** May you do good and not evil.
146488 ** May you find forgiveness for yourself and forgive others.
146489 ** May you share freely, never taking more than you give.
146491 ******************************************************************************
146493 ** This is an SQLite module implementing full-text search.
146497 ** The code in this file is only compiled if:
146499 ** * The FTS3 module is being built as an extension
146500 ** (in which case SQLITE_CORE is not defined), or
146502 ** * The FTS3 module is being built into the core of
146503 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
146506 /* The full-text index is stored in a series of b+tree (-like)
146507 ** structures called segments which map terms to doclists. The
146508 ** structures are like b+trees in layout, but are constructed from the
146509 ** bottom up in optimal fashion and are not updatable. Since trees
146510 ** are built from the bottom up, things will be described from the
146511 ** bottom up.
146514 **** Varints ****
146515 ** The basic unit of encoding is a variable-length integer called a
146516 ** varint. We encode variable-length integers in little-endian order
146517 ** using seven bits * per byte as follows:
146519 ** KEY:
146520 ** A = 0xxxxxxx 7 bits of data and one flag bit
146521 ** B = 1xxxxxxx 7 bits of data and one flag bit
146523 ** 7 bits - A
146524 ** 14 bits - BA
146525 ** 21 bits - BBA
146526 ** and so on.
146528 ** This is similar in concept to how sqlite encodes "varints" but
146529 ** the encoding is not the same. SQLite varints are big-endian
146530 ** are are limited to 9 bytes in length whereas FTS3 varints are
146531 ** little-endian and can be up to 10 bytes in length (in theory).
146533 ** Example encodings:
146535 ** 1: 0x01
146536 ** 127: 0x7f
146537 ** 128: 0x81 0x00
146540 **** Document lists ****
146541 ** A doclist (document list) holds a docid-sorted list of hits for a
146542 ** given term. Doclists hold docids and associated token positions.
146543 ** A docid is the unique integer identifier for a single document.
146544 ** A position is the index of a word within the document. The first
146545 ** word of the document has a position of 0.
146547 ** FTS3 used to optionally store character offsets using a compile-time
146548 ** option. But that functionality is no longer supported.
146550 ** A doclist is stored like this:
146552 ** array {
146553 ** varint docid; (delta from previous doclist)
146554 ** array { (position list for column 0)
146555 ** varint position; (2 more than the delta from previous position)
146557 ** array {
146558 ** varint POS_COLUMN; (marks start of position list for new column)
146559 ** varint column; (index of new column)
146560 ** array {
146561 ** varint position; (2 more than the delta from previous position)
146564 ** varint POS_END; (marks end of positions for this document.
146567 ** Here, array { X } means zero or more occurrences of X, adjacent in
146568 ** memory. A "position" is an index of a token in the token stream
146569 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
146570 ** in the same logical place as the position element, and act as sentinals
146571 ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
146572 ** The positions numbers are not stored literally but rather as two more
146573 ** than the difference from the prior position, or the just the position plus
146574 ** 2 for the first position. Example:
146576 ** label: A B C D E F G H I J K
146577 ** value: 123 5 9 1 1 14 35 0 234 72 0
146579 ** The 123 value is the first docid. For column zero in this document
146580 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
146581 ** at D signals the start of a new column; the 1 at E indicates that the
146582 ** new column is column number 1. There are two positions at 12 and 45
146583 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
146584 ** 234 at I is the delta to next docid (357). It has one position 70
146585 ** (72-2) and then terminates with the 0 at K.
146587 ** A "position-list" is the list of positions for multiple columns for
146588 ** a single docid. A "column-list" is the set of positions for a single
146589 ** column. Hence, a position-list consists of one or more column-lists,
146590 ** a document record consists of a docid followed by a position-list and
146591 ** a doclist consists of one or more document records.
146593 ** A bare doclist omits the position information, becoming an
146594 ** array of varint-encoded docids.
146596 **** Segment leaf nodes ****
146597 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
146598 ** nodes are written using LeafWriter, and read using LeafReader (to
146599 ** iterate through a single leaf node's data) and LeavesReader (to
146600 ** iterate through a segment's entire leaf layer). Leaf nodes have
146601 ** the format:
146603 ** varint iHeight; (height from leaf level, always 0)
146604 ** varint nTerm; (length of first term)
146605 ** char pTerm[nTerm]; (content of first term)
146606 ** varint nDoclist; (length of term's associated doclist)
146607 ** char pDoclist[nDoclist]; (content of doclist)
146608 ** array {
146609 ** (further terms are delta-encoded)
146610 ** varint nPrefix; (length of prefix shared with previous term)
146611 ** varint nSuffix; (length of unshared suffix)
146612 ** char pTermSuffix[nSuffix];(unshared suffix of next term)
146613 ** varint nDoclist; (length of term's associated doclist)
146614 ** char pDoclist[nDoclist]; (content of doclist)
146617 ** Here, array { X } means zero or more occurrences of X, adjacent in
146618 ** memory.
146620 ** Leaf nodes are broken into blocks which are stored contiguously in
146621 ** the %_segments table in sorted order. This means that when the end
146622 ** of a node is reached, the next term is in the node with the next
146623 ** greater node id.
146625 ** New data is spilled to a new leaf node when the current node
146626 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
146627 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
146628 ** node (a leaf node with a single term and doclist). The goal of
146629 ** these settings is to pack together groups of small doclists while
146630 ** making it efficient to directly access large doclists. The
146631 ** assumption is that large doclists represent terms which are more
146632 ** likely to be query targets.
146634 ** TODO(shess) It may be useful for blocking decisions to be more
146635 ** dynamic. For instance, it may make more sense to have a 2.5k leaf
146636 ** node rather than splitting into 2k and .5k nodes. My intuition is
146637 ** that this might extend through 2x or 4x the pagesize.
146640 **** Segment interior nodes ****
146641 ** Segment interior nodes store blockids for subtree nodes and terms
146642 ** to describe what data is stored by the each subtree. Interior
146643 ** nodes are written using InteriorWriter, and read using
146644 ** InteriorReader. InteriorWriters are created as needed when
146645 ** SegmentWriter creates new leaf nodes, or when an interior node
146646 ** itself grows too big and must be split. The format of interior
146647 ** nodes:
146649 ** varint iHeight; (height from leaf level, always >0)
146650 ** varint iBlockid; (block id of node's leftmost subtree)
146651 ** optional {
146652 ** varint nTerm; (length of first term)
146653 ** char pTerm[nTerm]; (content of first term)
146654 ** array {
146655 ** (further terms are delta-encoded)
146656 ** varint nPrefix; (length of shared prefix with previous term)
146657 ** varint nSuffix; (length of unshared suffix)
146658 ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
146662 ** Here, optional { X } means an optional element, while array { X }
146663 ** means zero or more occurrences of X, adjacent in memory.
146665 ** An interior node encodes n terms separating n+1 subtrees. The
146666 ** subtree blocks are contiguous, so only the first subtree's blockid
146667 ** is encoded. The subtree at iBlockid will contain all terms less
146668 ** than the first term encoded (or all terms if no term is encoded).
146669 ** Otherwise, for terms greater than or equal to pTerm[i] but less
146670 ** than pTerm[i+1], the subtree for that term will be rooted at
146671 ** iBlockid+i. Interior nodes only store enough term data to
146672 ** distinguish adjacent children (if the rightmost term of the left
146673 ** child is "something", and the leftmost term of the right child is
146674 ** "wicked", only "w" is stored).
146676 ** New data is spilled to a new interior node at the same height when
146677 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
146678 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
146679 ** interior nodes and making the tree too skinny. The interior nodes
146680 ** at a given height are naturally tracked by interior nodes at
146681 ** height+1, and so on.
146684 **** Segment directory ****
146685 ** The segment directory in table %_segdir stores meta-information for
146686 ** merging and deleting segments, and also the root node of the
146687 ** segment's tree.
146689 ** The root node is the top node of the segment's tree after encoding
146690 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
146691 ** This could be either a leaf node or an interior node. If the top
146692 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
146693 ** and a new root interior node is generated (which should always fit
146694 ** within ROOT_MAX because it only needs space for 2 varints, the
146695 ** height and the blockid of the previous root).
146697 ** The meta-information in the segment directory is:
146698 ** level - segment level (see below)
146699 ** idx - index within level
146700 ** - (level,idx uniquely identify a segment)
146701 ** start_block - first leaf node
146702 ** leaves_end_block - last leaf node
146703 ** end_block - last block (including interior nodes)
146704 ** root - contents of root node
146706 ** If the root node is a leaf node, then start_block,
146707 ** leaves_end_block, and end_block are all 0.
146710 **** Segment merging ****
146711 ** To amortize update costs, segments are grouped into levels and
146712 ** merged in batches. Each increase in level represents exponentially
146713 ** more documents.
146715 ** New documents (actually, document updates) are tokenized and
146716 ** written individually (using LeafWriter) to a level 0 segment, with
146717 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
146718 ** level 0 segments are merged into a single level 1 segment. Level 1
146719 ** is populated like level 0, and eventually MERGE_COUNT level 1
146720 ** segments are merged to a single level 2 segment (representing
146721 ** MERGE_COUNT^2 updates), and so on.
146723 ** A segment merge traverses all segments at a given level in
146724 ** parallel, performing a straightforward sorted merge. Since segment
146725 ** leaf nodes are written in to the %_segments table in order, this
146726 ** merge traverses the underlying sqlite disk structures efficiently.
146727 ** After the merge, all segment blocks from the merged level are
146728 ** deleted.
146730 ** MERGE_COUNT controls how often we merge segments. 16 seems to be
146731 ** somewhat of a sweet spot for insertion performance. 32 and 64 show
146732 ** very similar performance numbers to 16 on insertion, though they're
146733 ** a tiny bit slower (perhaps due to more overhead in merge-time
146734 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
146735 ** 16, 2 about 66% slower than 16.
146737 ** At query time, high MERGE_COUNT increases the number of segments
146738 ** which need to be scanned and merged. For instance, with 100k docs
146739 ** inserted:
146741 ** MERGE_COUNT segments
146742 ** 16 25
146743 ** 8 12
146744 ** 4 10
146745 ** 2 6
146747 ** This appears to have only a moderate impact on queries for very
146748 ** frequent terms (which are somewhat dominated by segment merge
146749 ** costs), and infrequent and non-existent terms still seem to be fast
146750 ** even with many segments.
146752 ** TODO(shess) That said, it would be nice to have a better query-side
146753 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
146754 ** optimizations to things like doclist merging will swing the sweet
146755 ** spot around.
146759 **** Handling of deletions and updates ****
146760 ** Since we're using a segmented structure, with no docid-oriented
146761 ** index into the term index, we clearly cannot simply update the term
146762 ** index when a document is deleted or updated. For deletions, we
146763 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
146764 ** we simply write the new doclist. Segment merges overwrite older
146765 ** data for a particular docid with newer data, so deletes or updates
146766 ** will eventually overtake the earlier data and knock it out. The
146767 ** query logic likewise merges doclists so that newer data knocks out
146768 ** older data.
146771 /************** Include fts3Int.h in the middle of fts3.c ********************/
146772 /************** Begin file fts3Int.h *****************************************/
146774 ** 2009 Nov 12
146776 ** The author disclaims copyright to this source code. In place of
146777 ** a legal notice, here is a blessing:
146779 ** May you do good and not evil.
146780 ** May you find forgiveness for yourself and forgive others.
146781 ** May you share freely, never taking more than you give.
146783 ******************************************************************************
146786 #ifndef _FTSINT_H
146787 #define _FTSINT_H
146789 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
146790 # define NDEBUG 1
146791 #endif
146793 /* FTS3/FTS4 require virtual tables */
146794 #ifdef SQLITE_OMIT_VIRTUALTABLE
146795 # undef SQLITE_ENABLE_FTS3
146796 # undef SQLITE_ENABLE_FTS4
146797 #endif
146800 ** FTS4 is really an extension for FTS3. It is enabled using the
146801 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
146802 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
146804 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
146805 # define SQLITE_ENABLE_FTS3
146806 #endif
146808 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
146810 /* If not building as part of the core, include sqlite3ext.h. */
146811 #ifndef SQLITE_CORE
146812 /* # include "sqlite3ext.h" */
146813 SQLITE_EXTENSION_INIT3
146814 #endif
146816 /* #include "sqlite3.h" */
146817 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
146818 /************** Begin file fts3_tokenizer.h **********************************/
146820 ** 2006 July 10
146822 ** The author disclaims copyright to this source code.
146824 *************************************************************************
146825 ** Defines the interface to tokenizers used by fulltext-search. There
146826 ** are three basic components:
146828 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
146829 ** interface functions. This is essentially the class structure for
146830 ** tokenizers.
146832 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
146833 ** including customization information defined at creation time.
146835 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
146836 ** tokens from a particular input.
146838 #ifndef _FTS3_TOKENIZER_H_
146839 #define _FTS3_TOKENIZER_H_
146841 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
146842 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
146843 ** we will need a way to register the API consistently.
146845 /* #include "sqlite3.h" */
146848 ** Structures used by the tokenizer interface. When a new tokenizer
146849 ** implementation is registered, the caller provides a pointer to
146850 ** an sqlite3_tokenizer_module containing pointers to the callback
146851 ** functions that make up an implementation.
146853 ** When an fts3 table is created, it passes any arguments passed to
146854 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
146855 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
146856 ** implementation. The xCreate() function in turn returns an
146857 ** sqlite3_tokenizer structure representing the specific tokenizer to
146858 ** be used for the fts3 table (customized by the tokenizer clause arguments).
146860 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
146861 ** method is called. It returns an sqlite3_tokenizer_cursor object
146862 ** that may be used to tokenize a specific input buffer based on
146863 ** the tokenization rules supplied by a specific sqlite3_tokenizer
146864 ** object.
146866 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
146867 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
146868 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
146870 struct sqlite3_tokenizer_module {
146873 ** Structure version. Should always be set to 0 or 1.
146875 int iVersion;
146878 ** Create a new tokenizer. The values in the argv[] array are the
146879 ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
146880 ** TABLE statement that created the fts3 table. For example, if
146881 ** the following SQL is executed:
146883 ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
146885 ** then argc is set to 2, and the argv[] array contains pointers
146886 ** to the strings "arg1" and "arg2".
146888 ** This method should return either SQLITE_OK (0), or an SQLite error
146889 ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
146890 ** to point at the newly created tokenizer structure. The generic
146891 ** sqlite3_tokenizer.pModule variable should not be initialized by
146892 ** this callback. The caller will do so.
146894 int (*xCreate)(
146895 int argc, /* Size of argv array */
146896 const char *const*argv, /* Tokenizer argument strings */
146897 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
146901 ** Destroy an existing tokenizer. The fts3 module calls this method
146902 ** exactly once for each successful call to xCreate().
146904 int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
146907 ** Create a tokenizer cursor to tokenize an input buffer. The caller
146908 ** is responsible for ensuring that the input buffer remains valid
146909 ** until the cursor is closed (using the xClose() method).
146911 int (*xOpen)(
146912 sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
146913 const char *pInput, int nBytes, /* Input buffer */
146914 sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
146918 ** Destroy an existing tokenizer cursor. The fts3 module calls this
146919 ** method exactly once for each successful call to xOpen().
146921 int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
146924 ** Retrieve the next token from the tokenizer cursor pCursor. This
146925 ** method should either return SQLITE_OK and set the values of the
146926 ** "OUT" variables identified below, or SQLITE_DONE to indicate that
146927 ** the end of the buffer has been reached, or an SQLite error code.
146929 ** *ppToken should be set to point at a buffer containing the
146930 ** normalized version of the token (i.e. after any case-folding and/or
146931 ** stemming has been performed). *pnBytes should be set to the length
146932 ** of this buffer in bytes. The input text that generated the token is
146933 ** identified by the byte offsets returned in *piStartOffset and
146934 ** *piEndOffset. *piStartOffset should be set to the index of the first
146935 ** byte of the token in the input buffer. *piEndOffset should be set
146936 ** to the index of the first byte just past the end of the token in
146937 ** the input buffer.
146939 ** The buffer *ppToken is set to point at is managed by the tokenizer
146940 ** implementation. It is only required to be valid until the next call
146941 ** to xNext() or xClose().
146943 /* TODO(shess) current implementation requires pInput to be
146944 ** nul-terminated. This should either be fixed, or pInput/nBytes
146945 ** should be converted to zInput.
146947 int (*xNext)(
146948 sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
146949 const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
146950 int *piStartOffset, /* OUT: Byte offset of token in input buffer */
146951 int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
146952 int *piPosition /* OUT: Number of tokens returned before this one */
146955 /***********************************************************************
146956 ** Methods below this point are only available if iVersion>=1.
146960 ** Configure the language id of a tokenizer cursor.
146962 int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
146965 struct sqlite3_tokenizer {
146966 const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
146967 /* Tokenizer implementations will typically add additional fields */
146970 struct sqlite3_tokenizer_cursor {
146971 sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
146972 /* Tokenizer implementations will typically add additional fields */
146975 int fts3_global_term_cnt(int iTerm, int iCol);
146976 int fts3_term_cnt(int iTerm, int iCol);
146979 #endif /* _FTS3_TOKENIZER_H_ */
146981 /************** End of fts3_tokenizer.h **************************************/
146982 /************** Continuing where we left off in fts3Int.h ********************/
146983 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
146984 /************** Begin file fts3_hash.h ***************************************/
146986 ** 2001 September 22
146988 ** The author disclaims copyright to this source code. In place of
146989 ** a legal notice, here is a blessing:
146991 ** May you do good and not evil.
146992 ** May you find forgiveness for yourself and forgive others.
146993 ** May you share freely, never taking more than you give.
146995 *************************************************************************
146996 ** This is the header file for the generic hash-table implementation
146997 ** used in SQLite. We've modified it slightly to serve as a standalone
146998 ** hash table implementation for the full-text indexing module.
147001 #ifndef _FTS3_HASH_H_
147002 #define _FTS3_HASH_H_
147004 /* Forward declarations of structures. */
147005 typedef struct Fts3Hash Fts3Hash;
147006 typedef struct Fts3HashElem Fts3HashElem;
147008 /* A complete hash table is an instance of the following structure.
147009 ** The internals of this structure are intended to be opaque -- client
147010 ** code should not attempt to access or modify the fields of this structure
147011 ** directly. Change this structure only by using the routines below.
147012 ** However, many of the "procedures" and "functions" for modifying and
147013 ** accessing this structure are really macros, so we can't really make
147014 ** this structure opaque.
147016 struct Fts3Hash {
147017 char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
147018 char copyKey; /* True if copy of key made on insert */
147019 int count; /* Number of entries in this table */
147020 Fts3HashElem *first; /* The first element of the array */
147021 int htsize; /* Number of buckets in the hash table */
147022 struct _fts3ht { /* the hash table */
147023 int count; /* Number of entries with this hash */
147024 Fts3HashElem *chain; /* Pointer to first entry with this hash */
147025 } *ht;
147028 /* Each element in the hash table is an instance of the following
147029 ** structure. All elements are stored on a single doubly-linked list.
147031 ** Again, this structure is intended to be opaque, but it can't really
147032 ** be opaque because it is used by macros.
147034 struct Fts3HashElem {
147035 Fts3HashElem *next, *prev; /* Next and previous elements in the table */
147036 void *data; /* Data associated with this element */
147037 void *pKey; int nKey; /* Key associated with this element */
147041 ** There are 2 different modes of operation for a hash table:
147043 ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
147044 ** (including the null-terminator, if any). Case
147045 ** is respected in comparisons.
147047 ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
147048 ** memcmp() is used to compare keys.
147050 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
147052 #define FTS3_HASH_STRING 1
147053 #define FTS3_HASH_BINARY 2
147056 ** Access routines. To delete, insert a NULL pointer.
147058 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
147059 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
147060 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
147061 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
147062 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
147065 ** Shorthand for the functions above
147067 #define fts3HashInit sqlite3Fts3HashInit
147068 #define fts3HashInsert sqlite3Fts3HashInsert
147069 #define fts3HashFind sqlite3Fts3HashFind
147070 #define fts3HashClear sqlite3Fts3HashClear
147071 #define fts3HashFindElem sqlite3Fts3HashFindElem
147074 ** Macros for looping over all elements of a hash table. The idiom is
147075 ** like this:
147077 ** Fts3Hash h;
147078 ** Fts3HashElem *p;
147079 ** ...
147080 ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
147081 ** SomeStructure *pData = fts3HashData(p);
147082 ** // do something with pData
147085 #define fts3HashFirst(H) ((H)->first)
147086 #define fts3HashNext(E) ((E)->next)
147087 #define fts3HashData(E) ((E)->data)
147088 #define fts3HashKey(E) ((E)->pKey)
147089 #define fts3HashKeysize(E) ((E)->nKey)
147092 ** Number of entries in a hash table
147094 #define fts3HashCount(H) ((H)->count)
147096 #endif /* _FTS3_HASH_H_ */
147098 /************** End of fts3_hash.h *******************************************/
147099 /************** Continuing where we left off in fts3Int.h ********************/
147102 ** This constant determines the maximum depth of an FTS expression tree
147103 ** that the library will create and use. FTS uses recursion to perform
147104 ** various operations on the query tree, so the disadvantage of a large
147105 ** limit is that it may allow very large queries to use large amounts
147106 ** of stack space (perhaps causing a stack overflow).
147108 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
147109 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
147110 #endif
147114 ** This constant controls how often segments are merged. Once there are
147115 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
147116 ** segment of level N+1.
147118 #define FTS3_MERGE_COUNT 16
147121 ** This is the maximum amount of data (in bytes) to store in the
147122 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
147123 ** populated as documents are inserted/updated/deleted in a transaction
147124 ** and used to create a new segment when the transaction is committed.
147125 ** However if this limit is reached midway through a transaction, a new
147126 ** segment is created and the hash table cleared immediately.
147128 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
147131 ** Macro to return the number of elements in an array. SQLite has a
147132 ** similar macro called ArraySize(). Use a different name to avoid
147133 ** a collision when building an amalgamation with built-in FTS3.
147135 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
147138 #ifndef MIN
147139 # define MIN(x,y) ((x)<(y)?(x):(y))
147140 #endif
147141 #ifndef MAX
147142 # define MAX(x,y) ((x)>(y)?(x):(y))
147143 #endif
147146 ** Maximum length of a varint encoded integer. The varint format is different
147147 ** from that used by SQLite, so the maximum length is 10, not 9.
147149 #define FTS3_VARINT_MAX 10
147152 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
147153 ** in the document set and zero or more prefix indexes. All indexes are stored
147154 ** as one or more b+-trees in the %_segments and %_segdir tables.
147156 ** It is possible to determine which index a b+-tree belongs to based on the
147157 ** value stored in the "%_segdir.level" column. Given this value L, the index
147158 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
147159 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
147160 ** between 1024 and 2047 to index 1, and so on.
147162 ** It is considered impossible for an index to use more than 1024 levels. In
147163 ** theory though this may happen, but only after at least
147164 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
147166 #define FTS3_SEGDIR_MAXLEVEL 1024
147167 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
147170 ** The testcase() macro is only used by the amalgamation. If undefined,
147171 ** make it a no-op.
147173 #ifndef testcase
147174 # define testcase(X)
147175 #endif
147178 ** Terminator values for position-lists and column-lists.
147180 #define POS_COLUMN (1) /* Column-list terminator */
147181 #define POS_END (0) /* Position-list terminator */
147184 ** This section provides definitions to allow the
147185 ** FTS3 extension to be compiled outside of the
147186 ** amalgamation.
147188 #ifndef SQLITE_AMALGAMATION
147190 ** Macros indicating that conditional expressions are always true or
147191 ** false.
147193 #ifdef SQLITE_COVERAGE_TEST
147194 # define ALWAYS(x) (1)
147195 # define NEVER(X) (0)
147196 #elif defined(SQLITE_DEBUG)
147197 # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
147198 # define NEVER(x) sqlite3Fts3Never((x)!=0)
147199 SQLITE_PRIVATE int sqlite3Fts3Always(int b);
147200 SQLITE_PRIVATE int sqlite3Fts3Never(int b);
147201 #else
147202 # define ALWAYS(x) (x)
147203 # define NEVER(x) (x)
147204 #endif
147207 ** Internal types used by SQLite.
147209 typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
147210 typedef short int i16; /* 2-byte (or larger) signed integer */
147211 typedef unsigned int u32; /* 4-byte unsigned integer */
147212 typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
147213 typedef sqlite3_int64 i64; /* 8-byte signed integer */
147216 ** Macro used to suppress compiler warnings for unused parameters.
147218 #define UNUSED_PARAMETER(x) (void)(x)
147221 ** Activate assert() only if SQLITE_TEST is enabled.
147223 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
147224 # define NDEBUG 1
147225 #endif
147228 ** The TESTONLY macro is used to enclose variable declarations or
147229 ** other bits of code that are needed to support the arguments
147230 ** within testcase() and assert() macros.
147232 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
147233 # define TESTONLY(X) X
147234 #else
147235 # define TESTONLY(X)
147236 #endif
147238 #endif /* SQLITE_AMALGAMATION */
147240 #ifdef SQLITE_DEBUG
147241 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
147242 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
147243 #else
147244 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
147245 #endif
147247 typedef struct Fts3Table Fts3Table;
147248 typedef struct Fts3Cursor Fts3Cursor;
147249 typedef struct Fts3Expr Fts3Expr;
147250 typedef struct Fts3Phrase Fts3Phrase;
147251 typedef struct Fts3PhraseToken Fts3PhraseToken;
147253 typedef struct Fts3Doclist Fts3Doclist;
147254 typedef struct Fts3SegFilter Fts3SegFilter;
147255 typedef struct Fts3DeferredToken Fts3DeferredToken;
147256 typedef struct Fts3SegReader Fts3SegReader;
147257 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
147259 typedef struct MatchinfoBuffer MatchinfoBuffer;
147262 ** A connection to a fulltext index is an instance of the following
147263 ** structure. The xCreate and xConnect methods create an instance
147264 ** of this structure and xDestroy and xDisconnect free that instance.
147265 ** All other methods receive a pointer to the structure as one of their
147266 ** arguments.
147268 struct Fts3Table {
147269 sqlite3_vtab base; /* Base class used by SQLite core */
147270 sqlite3 *db; /* The database connection */
147271 const char *zDb; /* logical database name */
147272 const char *zName; /* virtual table name */
147273 int nColumn; /* number of named columns in virtual table */
147274 char **azColumn; /* column names. malloced */
147275 u8 *abNotindexed; /* True for 'notindexed' columns */
147276 sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
147277 char *zContentTbl; /* content=xxx option, or NULL */
147278 char *zLanguageid; /* languageid=xxx option, or NULL */
147279 int nAutoincrmerge; /* Value configured by 'automerge' */
147280 u32 nLeafAdd; /* Number of leaf blocks added this trans */
147282 /* Precompiled statements used by the implementation. Each of these
147283 ** statements is run and reset within a single virtual table API call.
147285 sqlite3_stmt *aStmt[40];
147286 sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */
147288 char *zReadExprlist;
147289 char *zWriteExprlist;
147291 int nNodeSize; /* Soft limit for node size */
147292 u8 bFts4; /* True for FTS4, false for FTS3 */
147293 u8 bHasStat; /* True if %_stat table exists (2==unknown) */
147294 u8 bHasDocsize; /* True if %_docsize table exists */
147295 u8 bDescIdx; /* True if doclists are in reverse order */
147296 u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
147297 int nPgsz; /* Page size for host database */
147298 char *zSegmentsTbl; /* Name of %_segments table */
147299 sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
147302 ** The following array of hash tables is used to buffer pending index
147303 ** updates during transactions. All pending updates buffered at any one
147304 ** time must share a common language-id (see the FTS4 langid= feature).
147305 ** The current language id is stored in variable iPrevLangid.
147307 ** A single FTS4 table may have multiple full-text indexes. For each index
147308 ** there is an entry in the aIndex[] array. Index 0 is an index of all the
147309 ** terms that appear in the document set. Each subsequent index in aIndex[]
147310 ** is an index of prefixes of a specific length.
147312 ** Variable nPendingData contains an estimate the memory consumed by the
147313 ** pending data structures, including hash table overhead, but not including
147314 ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
147315 ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
147316 ** recently inserted record.
147318 int nIndex; /* Size of aIndex[] */
147319 struct Fts3Index {
147320 int nPrefix; /* Prefix length (0 for main terms index) */
147321 Fts3Hash hPending; /* Pending terms table for this index */
147322 } *aIndex;
147323 int nMaxPendingData; /* Max pending data before flush to disk */
147324 int nPendingData; /* Current bytes of pending data */
147325 sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
147326 int iPrevLangid; /* Langid of recently inserted document */
147327 int bPrevDelete; /* True if last operation was a delete */
147329 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
147330 /* State variables used for validating that the transaction control
147331 ** methods of the virtual table are called at appropriate times. These
147332 ** values do not contribute to FTS functionality; they are used for
147333 ** verifying the operation of the SQLite core.
147335 int inTransaction; /* True after xBegin but before xCommit/xRollback */
147336 int mxSavepoint; /* Largest valid xSavepoint integer */
147337 #endif
147339 #ifdef SQLITE_TEST
147340 /* True to disable the incremental doclist optimization. This is controled
147341 ** by special insert command 'test-no-incr-doclist'. */
147342 int bNoIncrDoclist;
147343 #endif
147347 ** When the core wants to read from the virtual table, it creates a
147348 ** virtual table cursor (an instance of the following structure) using
147349 ** the xOpen method. Cursors are destroyed using the xClose method.
147351 struct Fts3Cursor {
147352 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
147353 i16 eSearch; /* Search strategy (see below) */
147354 u8 isEof; /* True if at End Of Results */
147355 u8 isRequireSeek; /* True if must seek pStmt to %_content row */
147356 u8 bSeekStmt; /* True if pStmt is a seek */
147357 sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
147358 Fts3Expr *pExpr; /* Parsed MATCH query string */
147359 int iLangid; /* Language being queried for */
147360 int nPhrase; /* Number of matchable phrases in query */
147361 Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
147362 sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
147363 char *pNextId; /* Pointer into the body of aDoclist */
147364 char *aDoclist; /* List of docids for full-text queries */
147365 int nDoclist; /* Size of buffer at aDoclist */
147366 u8 bDesc; /* True to sort in descending order */
147367 int eEvalmode; /* An FTS3_EVAL_XX constant */
147368 int nRowAvg; /* Average size of database rows, in pages */
147369 sqlite3_int64 nDoc; /* Documents in table */
147370 i64 iMinDocid; /* Minimum docid to return */
147371 i64 iMaxDocid; /* Maximum docid to return */
147372 int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
147373 MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
147376 #define FTS3_EVAL_FILTER 0
147377 #define FTS3_EVAL_NEXT 1
147378 #define FTS3_EVAL_MATCHINFO 2
147381 ** The Fts3Cursor.eSearch member is always set to one of the following.
147382 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
147383 ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
147384 ** of the column to be searched. For example, in
147386 ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
147387 ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
147389 ** Because the LHS of the MATCH operator is 2nd column "b",
147390 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
147391 ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
147392 ** indicating that all columns should be searched,
147393 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
147395 #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
147396 #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
147397 #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
147400 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
147401 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
147402 ** above. The upper 16-bits contain a combination of the following
147403 ** bits, used to describe extra constraints on full-text searches.
147405 #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
147406 #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
147407 #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
147409 struct Fts3Doclist {
147410 char *aAll; /* Array containing doclist (or NULL) */
147411 int nAll; /* Size of a[] in bytes */
147412 char *pNextDocid; /* Pointer to next docid */
147414 sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
147415 int bFreeList; /* True if pList should be sqlite3_free()d */
147416 char *pList; /* Pointer to position list following iDocid */
147417 int nList; /* Length of position list */
147421 ** A "phrase" is a sequence of one or more tokens that must match in
147422 ** sequence. A single token is the base case and the most common case.
147423 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
147424 ** nToken will be the number of tokens in the string.
147426 struct Fts3PhraseToken {
147427 char *z; /* Text of the token */
147428 int n; /* Number of bytes in buffer z */
147429 int isPrefix; /* True if token ends with a "*" character */
147430 int bFirst; /* True if token must appear at position 0 */
147432 /* Variables above this point are populated when the expression is
147433 ** parsed (by code in fts3_expr.c). Below this point the variables are
147434 ** used when evaluating the expression. */
147435 Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
147436 Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
147439 struct Fts3Phrase {
147440 /* Cache of doclist for this phrase. */
147441 Fts3Doclist doclist;
147442 int bIncr; /* True if doclist is loaded incrementally */
147443 int iDoclistToken;
147445 /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
147446 ** OR condition. */
147447 char *pOrPoslist;
147448 i64 iOrDocid;
147450 /* Variables below this point are populated by fts3_expr.c when parsing
147451 ** a MATCH expression. Everything above is part of the evaluation phase.
147453 int nToken; /* Number of tokens in the phrase */
147454 int iColumn; /* Index of column this phrase must match */
147455 Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
147459 ** A tree of these objects forms the RHS of a MATCH operator.
147461 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
147462 ** points to a malloced buffer, size nDoclist bytes, containing the results
147463 ** of this phrase query in FTS3 doclist format. As usual, the initial
147464 ** "Length" field found in doclists stored on disk is omitted from this
147465 ** buffer.
147467 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
147468 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
147469 ** where nCol is the number of columns in the queried FTS table. The array
147470 ** is populated as follows:
147472 ** aMI[iCol*3 + 0] = Undefined
147473 ** aMI[iCol*3 + 1] = Number of occurrences
147474 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
147476 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
147477 ** when the expression node is.
147479 struct Fts3Expr {
147480 int eType; /* One of the FTSQUERY_XXX values defined below */
147481 int nNear; /* Valid if eType==FTSQUERY_NEAR */
147482 Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
147483 Fts3Expr *pLeft; /* Left operand */
147484 Fts3Expr *pRight; /* Right operand */
147485 Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
147487 /* The following are used by the fts3_eval.c module. */
147488 sqlite3_int64 iDocid; /* Current docid */
147489 u8 bEof; /* True this expression is at EOF already */
147490 u8 bStart; /* True if iDocid is valid */
147491 u8 bDeferred; /* True if this expression is entirely deferred */
147493 /* The following are used by the fts3_snippet.c module. */
147494 int iPhrase; /* Index of this phrase in matchinfo() results */
147495 u32 *aMI; /* See above */
147499 ** Candidate values for Fts3Query.eType. Note that the order of the first
147500 ** four values is in order of precedence when parsing expressions. For
147501 ** example, the following:
147503 ** "a OR b AND c NOT d NEAR e"
147505 ** is equivalent to:
147507 ** "a OR (b AND (c NOT (d NEAR e)))"
147509 #define FTSQUERY_NEAR 1
147510 #define FTSQUERY_NOT 2
147511 #define FTSQUERY_AND 3
147512 #define FTSQUERY_OR 4
147513 #define FTSQUERY_PHRASE 5
147516 /* fts3_write.c */
147517 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
147518 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
147519 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
147520 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
147521 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
147522 sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
147523 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
147524 Fts3Table*,int,const char*,int,int,Fts3SegReader**);
147525 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
147526 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
147527 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
147529 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
147530 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
147532 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
147533 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
147534 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
147535 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
147536 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
147537 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
147538 #else
147539 # define sqlite3Fts3FreeDeferredTokens(x)
147540 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
147541 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
147542 # define sqlite3Fts3FreeDeferredDoclists(x)
147543 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
147544 #endif
147546 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
147547 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
147549 /* Special values interpreted by sqlite3SegReaderCursor() */
147550 #define FTS3_SEGCURSOR_PENDING -1
147551 #define FTS3_SEGCURSOR_ALL -2
147553 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
147554 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
147555 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
147557 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
147558 int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
147560 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
147561 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
147562 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
147563 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
147564 #define FTS3_SEGMENT_PREFIX 0x00000008
147565 #define FTS3_SEGMENT_SCAN 0x00000010
147566 #define FTS3_SEGMENT_FIRST 0x00000020
147568 /* Type passed as 4th argument to SegmentReaderIterate() */
147569 struct Fts3SegFilter {
147570 const char *zTerm;
147571 int nTerm;
147572 int iCol;
147573 int flags;
147576 struct Fts3MultiSegReader {
147577 /* Used internally by sqlite3Fts3SegReaderXXX() calls */
147578 Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
147579 int nSegment; /* Size of apSegment array */
147580 int nAdvance; /* How many seg-readers to advance */
147581 Fts3SegFilter *pFilter; /* Pointer to filter object */
147582 char *aBuffer; /* Buffer to merge doclists in */
147583 int nBuffer; /* Allocated size of aBuffer[] in bytes */
147585 int iColFilter; /* If >=0, filter for this column */
147586 int bRestart;
147588 /* Used by fts3.c only. */
147589 int nCost; /* Cost of running iterator */
147590 int bLookup; /* True if a lookup of a single entry. */
147592 /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
147593 char *zTerm; /* Pointer to term buffer */
147594 int nTerm; /* Size of zTerm in bytes */
147595 char *aDoclist; /* Pointer to doclist buffer */
147596 int nDoclist; /* Size of aDoclist[] in bytes */
147599 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
147601 #define fts3GetVarint32(p, piVal) ( \
147602 (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
147605 /* fts3.c */
147606 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
147607 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
147608 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
147609 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
147610 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
147611 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
147612 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
147613 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
147614 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
147615 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
147616 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
147618 /* fts3_tokenizer.c */
147619 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
147620 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
147621 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
147622 sqlite3_tokenizer **, char **
147624 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
147626 /* fts3_snippet.c */
147627 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
147628 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
147629 const char *, const char *, int, int
147631 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
147632 SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
147634 /* fts3_expr.c */
147635 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
147636 char **, int, int, int, const char *, int, Fts3Expr **, char **
147638 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
147639 #ifdef SQLITE_TEST
147640 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
147641 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
147642 #endif
147644 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
147645 sqlite3_tokenizer_cursor **
147648 /* fts3_aux.c */
147649 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
147651 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
147653 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
147654 Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
147655 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
147656 Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
147657 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
147658 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
147659 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
147661 /* fts3_tokenize_vtab.c */
147662 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
147664 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
147665 #ifndef SQLITE_DISABLE_FTS3_UNICODE
147666 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
147667 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
147668 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
147669 #endif
147671 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
147672 #endif /* _FTSINT_H */
147674 /************** End of fts3Int.h *********************************************/
147675 /************** Continuing where we left off in fts3.c ***********************/
147676 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
147678 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
147679 # define SQLITE_CORE 1
147680 #endif
147682 /* #include <assert.h> */
147683 /* #include <stdlib.h> */
147684 /* #include <stddef.h> */
147685 /* #include <stdio.h> */
147686 /* #include <string.h> */
147687 /* #include <stdarg.h> */
147689 /* #include "fts3.h" */
147690 #ifndef SQLITE_CORE
147691 /* # include "sqlite3ext.h" */
147692 SQLITE_EXTENSION_INIT1
147693 #endif
147695 static int fts3EvalNext(Fts3Cursor *pCsr);
147696 static int fts3EvalStart(Fts3Cursor *pCsr);
147697 static int fts3TermSegReaderCursor(
147698 Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
147700 #ifndef SQLITE_AMALGAMATION
147701 # if defined(SQLITE_DEBUG)
147702 SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
147703 SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
147704 # endif
147705 #endif
147708 ** Write a 64-bit variable-length integer to memory starting at p[0].
147709 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
147710 ** The number of bytes written is returned.
147712 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
147713 unsigned char *q = (unsigned char *) p;
147714 sqlite_uint64 vu = v;
147716 *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
147717 vu >>= 7;
147718 }while( vu!=0 );
147719 q[-1] &= 0x7f; /* turn off high bit in final byte */
147720 assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
147721 return (int) (q - (unsigned char *)p);
147724 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
147725 v = (v & mask1) | ( (*ptr++) << shift ); \
147726 if( (v & mask2)==0 ){ var = v; return ret; }
147727 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
147728 v = (*ptr++); \
147729 if( (v & mask2)==0 ){ var = v; return ret; }
147732 ** Read a 64-bit variable-length integer from memory starting at p[0].
147733 ** Return the number of bytes read, or 0 on error.
147734 ** The value is stored in *v.
147736 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
147737 const unsigned char *p = (const unsigned char*)pBuf;
147738 const unsigned char *pStart = p;
147739 u32 a;
147740 u64 b;
147741 int shift;
147743 GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
147744 GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
147745 GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
147746 GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
147747 b = (a & 0x0FFFFFFF );
147749 for(shift=28; shift<=63; shift+=7){
147750 u64 c = *p++;
147751 b += (c&0x7F) << shift;
147752 if( (c & 0x80)==0 ) break;
147754 *v = b;
147755 return (int)(p - pStart);
147759 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
147760 ** a non-negative 32-bit integer before it is returned.
147762 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
147763 u32 a;
147765 #ifndef fts3GetVarint32
147766 GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
147767 #else
147768 a = (*p++);
147769 assert( a & 0x80 );
147770 #endif
147772 GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
147773 GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
147774 GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
147775 a = (a & 0x0FFFFFFF );
147776 *pi = (int)(a | ((u32)(*p & 0x07) << 28));
147777 assert( 0==(a & 0x80000000) );
147778 assert( *pi>=0 );
147779 return 5;
147783 ** Return the number of bytes required to encode v as a varint
147785 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
147786 int i = 0;
147789 v >>= 7;
147790 }while( v!=0 );
147791 return i;
147795 ** Convert an SQL-style quoted string into a normal string by removing
147796 ** the quote characters. The conversion is done in-place. If the
147797 ** input does not begin with a quote character, then this routine
147798 ** is a no-op.
147800 ** Examples:
147802 ** "abc" becomes abc
147803 ** 'xyz' becomes xyz
147804 ** [pqr] becomes pqr
147805 ** `mno` becomes mno
147808 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
147809 char quote; /* Quote character (if any ) */
147811 quote = z[0];
147812 if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
147813 int iIn = 1; /* Index of next byte to read from input */
147814 int iOut = 0; /* Index of next byte to write to output */
147816 /* If the first byte was a '[', then the close-quote character is a ']' */
147817 if( quote=='[' ) quote = ']';
147819 while( z[iIn] ){
147820 if( z[iIn]==quote ){
147821 if( z[iIn+1]!=quote ) break;
147822 z[iOut++] = quote;
147823 iIn += 2;
147824 }else{
147825 z[iOut++] = z[iIn++];
147828 z[iOut] = '\0';
147833 ** Read a single varint from the doclist at *pp and advance *pp to point
147834 ** to the first byte past the end of the varint. Add the value of the varint
147835 ** to *pVal.
147837 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
147838 sqlite3_int64 iVal;
147839 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
147840 *pVal += iVal;
147844 ** When this function is called, *pp points to the first byte following a
147845 ** varint that is part of a doclist (or position-list, or any other list
147846 ** of varints). This function moves *pp to point to the start of that varint,
147847 ** and sets *pVal by the varint value.
147849 ** Argument pStart points to the first byte of the doclist that the
147850 ** varint is part of.
147852 static void fts3GetReverseVarint(
147853 char **pp,
147854 char *pStart,
147855 sqlite3_int64 *pVal
147857 sqlite3_int64 iVal;
147858 char *p;
147860 /* Pointer p now points at the first byte past the varint we are
147861 ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
147862 ** clear on character p[-1]. */
147863 for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
147865 *pp = p;
147867 sqlite3Fts3GetVarint(p, &iVal);
147868 *pVal = iVal;
147872 ** The xDisconnect() virtual table method.
147874 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
147875 Fts3Table *p = (Fts3Table *)pVtab;
147876 int i;
147878 assert( p->nPendingData==0 );
147879 assert( p->pSegments==0 );
147881 /* Free any prepared statements held */
147882 sqlite3_finalize(p->pSeekStmt);
147883 for(i=0; i<SizeofArray(p->aStmt); i++){
147884 sqlite3_finalize(p->aStmt[i]);
147886 sqlite3_free(p->zSegmentsTbl);
147887 sqlite3_free(p->zReadExprlist);
147888 sqlite3_free(p->zWriteExprlist);
147889 sqlite3_free(p->zContentTbl);
147890 sqlite3_free(p->zLanguageid);
147892 /* Invoke the tokenizer destructor to free the tokenizer. */
147893 p->pTokenizer->pModule->xDestroy(p->pTokenizer);
147895 sqlite3_free(p);
147896 return SQLITE_OK;
147900 ** Write an error message into *pzErr
147902 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
147903 va_list ap;
147904 sqlite3_free(*pzErr);
147905 va_start(ap, zFormat);
147906 *pzErr = sqlite3_vmprintf(zFormat, ap);
147907 va_end(ap);
147911 ** Construct one or more SQL statements from the format string given
147912 ** and then evaluate those statements. The success code is written
147913 ** into *pRc.
147915 ** If *pRc is initially non-zero then this routine is a no-op.
147917 static void fts3DbExec(
147918 int *pRc, /* Success code */
147919 sqlite3 *db, /* Database in which to run SQL */
147920 const char *zFormat, /* Format string for SQL */
147921 ... /* Arguments to the format string */
147923 va_list ap;
147924 char *zSql;
147925 if( *pRc ) return;
147926 va_start(ap, zFormat);
147927 zSql = sqlite3_vmprintf(zFormat, ap);
147928 va_end(ap);
147929 if( zSql==0 ){
147930 *pRc = SQLITE_NOMEM;
147931 }else{
147932 *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
147933 sqlite3_free(zSql);
147938 ** The xDestroy() virtual table method.
147940 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
147941 Fts3Table *p = (Fts3Table *)pVtab;
147942 int rc = SQLITE_OK; /* Return code */
147943 const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
147944 sqlite3 *db = p->db; /* Database handle */
147946 /* Drop the shadow tables */
147947 if( p->zContentTbl==0 ){
147948 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
147950 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
147951 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
147952 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
147953 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
147955 /* If everything has worked, invoke fts3DisconnectMethod() to free the
147956 ** memory associated with the Fts3Table structure and return SQLITE_OK.
147957 ** Otherwise, return an SQLite error code.
147959 return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
147964 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
147965 ** passed as the first argument. This is done as part of the xConnect()
147966 ** and xCreate() methods.
147968 ** If *pRc is non-zero when this function is called, it is a no-op.
147969 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
147970 ** before returning.
147972 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
147973 if( *pRc==SQLITE_OK ){
147974 int i; /* Iterator variable */
147975 int rc; /* Return code */
147976 char *zSql; /* SQL statement passed to declare_vtab() */
147977 char *zCols; /* List of user defined columns */
147978 const char *zLanguageid;
147980 zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
147981 sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
147983 /* Create a list of user columns for the virtual table */
147984 zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
147985 for(i=1; zCols && i<p->nColumn; i++){
147986 zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
147989 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
147990 zSql = sqlite3_mprintf(
147991 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
147992 zCols, p->zName, zLanguageid
147994 if( !zCols || !zSql ){
147995 rc = SQLITE_NOMEM;
147996 }else{
147997 rc = sqlite3_declare_vtab(p->db, zSql);
148000 sqlite3_free(zSql);
148001 sqlite3_free(zCols);
148002 *pRc = rc;
148007 ** Create the %_stat table if it does not already exist.
148009 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
148010 fts3DbExec(pRc, p->db,
148011 "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
148012 "(id INTEGER PRIMARY KEY, value BLOB);",
148013 p->zDb, p->zName
148015 if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
148019 ** Create the backing store tables (%_content, %_segments and %_segdir)
148020 ** required by the FTS3 table passed as the only argument. This is done
148021 ** as part of the vtab xCreate() method.
148023 ** If the p->bHasDocsize boolean is true (indicating that this is an
148024 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
148025 ** %_stat tables required by FTS4.
148027 static int fts3CreateTables(Fts3Table *p){
148028 int rc = SQLITE_OK; /* Return code */
148029 int i; /* Iterator variable */
148030 sqlite3 *db = p->db; /* The database connection */
148032 if( p->zContentTbl==0 ){
148033 const char *zLanguageid = p->zLanguageid;
148034 char *zContentCols; /* Columns of %_content table */
148036 /* Create a list of user columns for the content table */
148037 zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
148038 for(i=0; zContentCols && i<p->nColumn; i++){
148039 char *z = p->azColumn[i];
148040 zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
148042 if( zLanguageid && zContentCols ){
148043 zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
148045 if( zContentCols==0 ) rc = SQLITE_NOMEM;
148047 /* Create the content table */
148048 fts3DbExec(&rc, db,
148049 "CREATE TABLE %Q.'%q_content'(%s)",
148050 p->zDb, p->zName, zContentCols
148052 sqlite3_free(zContentCols);
148055 /* Create other tables */
148056 fts3DbExec(&rc, db,
148057 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
148058 p->zDb, p->zName
148060 fts3DbExec(&rc, db,
148061 "CREATE TABLE %Q.'%q_segdir'("
148062 "level INTEGER,"
148063 "idx INTEGER,"
148064 "start_block INTEGER,"
148065 "leaves_end_block INTEGER,"
148066 "end_block INTEGER,"
148067 "root BLOB,"
148068 "PRIMARY KEY(level, idx)"
148069 ");",
148070 p->zDb, p->zName
148072 if( p->bHasDocsize ){
148073 fts3DbExec(&rc, db,
148074 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
148075 p->zDb, p->zName
148078 assert( p->bHasStat==p->bFts4 );
148079 if( p->bHasStat ){
148080 sqlite3Fts3CreateStatTable(&rc, p);
148082 return rc;
148086 ** Store the current database page-size in bytes in p->nPgsz.
148088 ** If *pRc is non-zero when this function is called, it is a no-op.
148089 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
148090 ** before returning.
148092 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
148093 if( *pRc==SQLITE_OK ){
148094 int rc; /* Return code */
148095 char *zSql; /* SQL text "PRAGMA %Q.page_size" */
148096 sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
148098 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
148099 if( !zSql ){
148100 rc = SQLITE_NOMEM;
148101 }else{
148102 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
148103 if( rc==SQLITE_OK ){
148104 sqlite3_step(pStmt);
148105 p->nPgsz = sqlite3_column_int(pStmt, 0);
148106 rc = sqlite3_finalize(pStmt);
148107 }else if( rc==SQLITE_AUTH ){
148108 p->nPgsz = 1024;
148109 rc = SQLITE_OK;
148112 assert( p->nPgsz>0 || rc!=SQLITE_OK );
148113 sqlite3_free(zSql);
148114 *pRc = rc;
148119 ** "Special" FTS4 arguments are column specifications of the following form:
148121 ** <key> = <value>
148123 ** There may not be whitespace surrounding the "=" character. The <value>
148124 ** term may be quoted, but the <key> may not.
148126 static int fts3IsSpecialColumn(
148127 const char *z,
148128 int *pnKey,
148129 char **pzValue
148131 char *zValue;
148132 const char *zCsr = z;
148134 while( *zCsr!='=' ){
148135 if( *zCsr=='\0' ) return 0;
148136 zCsr++;
148139 *pnKey = (int)(zCsr-z);
148140 zValue = sqlite3_mprintf("%s", &zCsr[1]);
148141 if( zValue ){
148142 sqlite3Fts3Dequote(zValue);
148144 *pzValue = zValue;
148145 return 1;
148149 ** Append the output of a printf() style formatting to an existing string.
148151 static void fts3Appendf(
148152 int *pRc, /* IN/OUT: Error code */
148153 char **pz, /* IN/OUT: Pointer to string buffer */
148154 const char *zFormat, /* Printf format string to append */
148155 ... /* Arguments for printf format string */
148157 if( *pRc==SQLITE_OK ){
148158 va_list ap;
148159 char *z;
148160 va_start(ap, zFormat);
148161 z = sqlite3_vmprintf(zFormat, ap);
148162 va_end(ap);
148163 if( z && *pz ){
148164 char *z2 = sqlite3_mprintf("%s%s", *pz, z);
148165 sqlite3_free(z);
148166 z = z2;
148168 if( z==0 ) *pRc = SQLITE_NOMEM;
148169 sqlite3_free(*pz);
148170 *pz = z;
148175 ** Return a copy of input string zInput enclosed in double-quotes (") and
148176 ** with all double quote characters escaped. For example:
148178 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
148180 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
148181 ** is the callers responsibility to call sqlite3_free() to release this
148182 ** memory.
148184 static char *fts3QuoteId(char const *zInput){
148185 int nRet;
148186 char *zRet;
148187 nRet = 2 + (int)strlen(zInput)*2 + 1;
148188 zRet = sqlite3_malloc(nRet);
148189 if( zRet ){
148190 int i;
148191 char *z = zRet;
148192 *(z++) = '"';
148193 for(i=0; zInput[i]; i++){
148194 if( zInput[i]=='"' ) *(z++) = '"';
148195 *(z++) = zInput[i];
148197 *(z++) = '"';
148198 *(z++) = '\0';
148200 return zRet;
148204 ** Return a list of comma separated SQL expressions and a FROM clause that
148205 ** could be used in a SELECT statement such as the following:
148207 ** SELECT <list of expressions> FROM %_content AS x ...
148209 ** to return the docid, followed by each column of text data in order
148210 ** from left to write. If parameter zFunc is not NULL, then instead of
148211 ** being returned directly each column of text data is passed to an SQL
148212 ** function named zFunc first. For example, if zFunc is "unzip" and the
148213 ** table has the three user-defined columns "a", "b", and "c", the following
148214 ** string is returned:
148216 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
148218 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
148219 ** is the responsibility of the caller to eventually free it.
148221 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
148222 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
148223 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
148224 ** no error occurs, *pRc is left unmodified.
148226 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
148227 char *zRet = 0;
148228 char *zFree = 0;
148229 char *zFunction;
148230 int i;
148232 if( p->zContentTbl==0 ){
148233 if( !zFunc ){
148234 zFunction = "";
148235 }else{
148236 zFree = zFunction = fts3QuoteId(zFunc);
148238 fts3Appendf(pRc, &zRet, "docid");
148239 for(i=0; i<p->nColumn; i++){
148240 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
148242 if( p->zLanguageid ){
148243 fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
148245 sqlite3_free(zFree);
148246 }else{
148247 fts3Appendf(pRc, &zRet, "rowid");
148248 for(i=0; i<p->nColumn; i++){
148249 fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
148251 if( p->zLanguageid ){
148252 fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
148255 fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
148256 p->zDb,
148257 (p->zContentTbl ? p->zContentTbl : p->zName),
148258 (p->zContentTbl ? "" : "_content")
148260 return zRet;
148264 ** Return a list of N comma separated question marks, where N is the number
148265 ** of columns in the %_content table (one for the docid plus one for each
148266 ** user-defined text column).
148268 ** If argument zFunc is not NULL, then all but the first question mark
148269 ** is preceded by zFunc and an open bracket, and followed by a closed
148270 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
148271 ** user-defined text columns, the following string is returned:
148273 ** "?, zip(?), zip(?), zip(?)"
148275 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
148276 ** is the responsibility of the caller to eventually free it.
148278 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
148279 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
148280 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
148281 ** no error occurs, *pRc is left unmodified.
148283 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
148284 char *zRet = 0;
148285 char *zFree = 0;
148286 char *zFunction;
148287 int i;
148289 if( !zFunc ){
148290 zFunction = "";
148291 }else{
148292 zFree = zFunction = fts3QuoteId(zFunc);
148294 fts3Appendf(pRc, &zRet, "?");
148295 for(i=0; i<p->nColumn; i++){
148296 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
148298 if( p->zLanguageid ){
148299 fts3Appendf(pRc, &zRet, ", ?");
148301 sqlite3_free(zFree);
148302 return zRet;
148306 ** This function interprets the string at (*pp) as a non-negative integer
148307 ** value. It reads the integer and sets *pnOut to the value read, then
148308 ** sets *pp to point to the byte immediately following the last byte of
148309 ** the integer value.
148311 ** Only decimal digits ('0'..'9') may be part of an integer value.
148313 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
148314 ** the output value undefined. Otherwise SQLITE_OK is returned.
148316 ** This function is used when parsing the "prefix=" FTS4 parameter.
148318 static int fts3GobbleInt(const char **pp, int *pnOut){
148319 const int MAX_NPREFIX = 10000000;
148320 const char *p; /* Iterator pointer */
148321 int nInt = 0; /* Output value */
148323 for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
148324 nInt = nInt * 10 + (p[0] - '0');
148325 if( nInt>MAX_NPREFIX ){
148326 nInt = 0;
148327 break;
148330 if( p==*pp ) return SQLITE_ERROR;
148331 *pnOut = nInt;
148332 *pp = p;
148333 return SQLITE_OK;
148337 ** This function is called to allocate an array of Fts3Index structures
148338 ** representing the indexes maintained by the current FTS table. FTS tables
148339 ** always maintain the main "terms" index, but may also maintain one or
148340 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
148341 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
148343 ** Argument zParam is passed the value of the "prefix=" option if one was
148344 ** specified, or NULL otherwise.
148346 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
148347 ** the allocated array. *pnIndex is set to the number of elements in the
148348 ** array. If an error does occur, an SQLite error code is returned.
148350 ** Regardless of whether or not an error is returned, it is the responsibility
148351 ** of the caller to call sqlite3_free() on the output array to free it.
148353 static int fts3PrefixParameter(
148354 const char *zParam, /* ABC in prefix=ABC parameter to parse */
148355 int *pnIndex, /* OUT: size of *apIndex[] array */
148356 struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
148358 struct Fts3Index *aIndex; /* Allocated array */
148359 int nIndex = 1; /* Number of entries in array */
148361 if( zParam && zParam[0] ){
148362 const char *p;
148363 nIndex++;
148364 for(p=zParam; *p; p++){
148365 if( *p==',' ) nIndex++;
148369 aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
148370 *apIndex = aIndex;
148371 if( !aIndex ){
148372 return SQLITE_NOMEM;
148375 memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
148376 if( zParam ){
148377 const char *p = zParam;
148378 int i;
148379 for(i=1; i<nIndex; i++){
148380 int nPrefix = 0;
148381 if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
148382 assert( nPrefix>=0 );
148383 if( nPrefix==0 ){
148384 nIndex--;
148386 }else{
148387 aIndex[i].nPrefix = nPrefix;
148393 *pnIndex = nIndex;
148394 return SQLITE_OK;
148398 ** This function is called when initializing an FTS4 table that uses the
148399 ** content=xxx option. It determines the number of and names of the columns
148400 ** of the new FTS4 table.
148402 ** The third argument passed to this function is the value passed to the
148403 ** config=xxx option (i.e. "xxx"). This function queries the database for
148404 ** a table of that name. If found, the output variables are populated
148405 ** as follows:
148407 ** *pnCol: Set to the number of columns table xxx has,
148409 ** *pnStr: Set to the total amount of space required to store a copy
148410 ** of each columns name, including the nul-terminator.
148412 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
148413 ** the name of the corresponding column in table xxx. The array
148414 ** and its contents are allocated using a single allocation. It
148415 ** is the responsibility of the caller to free this allocation
148416 ** by eventually passing the *pazCol value to sqlite3_free().
148418 ** If the table cannot be found, an error code is returned and the output
148419 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
148420 ** returned (and the output variables are undefined).
148422 static int fts3ContentColumns(
148423 sqlite3 *db, /* Database handle */
148424 const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
148425 const char *zTbl, /* Name of content table */
148426 const char ***pazCol, /* OUT: Malloc'd array of column names */
148427 int *pnCol, /* OUT: Size of array *pazCol */
148428 int *pnStr, /* OUT: Bytes of string content */
148429 char **pzErr /* OUT: error message */
148431 int rc = SQLITE_OK; /* Return code */
148432 char *zSql; /* "SELECT *" statement on zTbl */
148433 sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
148435 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
148436 if( !zSql ){
148437 rc = SQLITE_NOMEM;
148438 }else{
148439 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
148440 if( rc!=SQLITE_OK ){
148441 sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
148444 sqlite3_free(zSql);
148446 if( rc==SQLITE_OK ){
148447 const char **azCol; /* Output array */
148448 int nStr = 0; /* Size of all column names (incl. 0x00) */
148449 int nCol; /* Number of table columns */
148450 int i; /* Used to iterate through columns */
148452 /* Loop through the returned columns. Set nStr to the number of bytes of
148453 ** space required to store a copy of each column name, including the
148454 ** nul-terminator byte. */
148455 nCol = sqlite3_column_count(pStmt);
148456 for(i=0; i<nCol; i++){
148457 const char *zCol = sqlite3_column_name(pStmt, i);
148458 nStr += (int)strlen(zCol) + 1;
148461 /* Allocate and populate the array to return. */
148462 azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
148463 if( azCol==0 ){
148464 rc = SQLITE_NOMEM;
148465 }else{
148466 char *p = (char *)&azCol[nCol];
148467 for(i=0; i<nCol; i++){
148468 const char *zCol = sqlite3_column_name(pStmt, i);
148469 int n = (int)strlen(zCol)+1;
148470 memcpy(p, zCol, n);
148471 azCol[i] = p;
148472 p += n;
148475 sqlite3_finalize(pStmt);
148477 /* Set the output variables. */
148478 *pnCol = nCol;
148479 *pnStr = nStr;
148480 *pazCol = azCol;
148483 return rc;
148487 ** This function is the implementation of both the xConnect and xCreate
148488 ** methods of the FTS3 virtual table.
148490 ** The argv[] array contains the following:
148492 ** argv[0] -> module name ("fts3" or "fts4")
148493 ** argv[1] -> database name
148494 ** argv[2] -> table name
148495 ** argv[...] -> "column name" and other module argument fields.
148497 static int fts3InitVtab(
148498 int isCreate, /* True for xCreate, false for xConnect */
148499 sqlite3 *db, /* The SQLite database connection */
148500 void *pAux, /* Hash table containing tokenizers */
148501 int argc, /* Number of elements in argv array */
148502 const char * const *argv, /* xCreate/xConnect argument array */
148503 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
148504 char **pzErr /* Write any error message here */
148506 Fts3Hash *pHash = (Fts3Hash *)pAux;
148507 Fts3Table *p = 0; /* Pointer to allocated vtab */
148508 int rc = SQLITE_OK; /* Return code */
148509 int i; /* Iterator variable */
148510 int nByte; /* Size of allocation used for *p */
148511 int iCol; /* Column index */
148512 int nString = 0; /* Bytes required to hold all column names */
148513 int nCol = 0; /* Number of columns in the FTS table */
148514 char *zCsr; /* Space for holding column names */
148515 int nDb; /* Bytes required to hold database name */
148516 int nName; /* Bytes required to hold table name */
148517 int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
148518 const char **aCol; /* Array of column names */
148519 sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
148521 int nIndex = 0; /* Size of aIndex[] array */
148522 struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
148524 /* The results of parsing supported FTS4 key=value options: */
148525 int bNoDocsize = 0; /* True to omit %_docsize table */
148526 int bDescIdx = 0; /* True to store descending indexes */
148527 char *zPrefix = 0; /* Prefix parameter value (or NULL) */
148528 char *zCompress = 0; /* compress=? parameter (or NULL) */
148529 char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
148530 char *zContent = 0; /* content=? parameter (or NULL) */
148531 char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
148532 char **azNotindexed = 0; /* The set of notindexed= columns */
148533 int nNotindexed = 0; /* Size of azNotindexed[] array */
148535 assert( strlen(argv[0])==4 );
148536 assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
148537 || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
148540 nDb = (int)strlen(argv[1]) + 1;
148541 nName = (int)strlen(argv[2]) + 1;
148543 nByte = sizeof(const char *) * (argc-2);
148544 aCol = (const char **)sqlite3_malloc(nByte);
148545 if( aCol ){
148546 memset((void*)aCol, 0, nByte);
148547 azNotindexed = (char **)sqlite3_malloc(nByte);
148549 if( azNotindexed ){
148550 memset(azNotindexed, 0, nByte);
148552 if( !aCol || !azNotindexed ){
148553 rc = SQLITE_NOMEM;
148554 goto fts3_init_out;
148557 /* Loop through all of the arguments passed by the user to the FTS3/4
148558 ** module (i.e. all the column names and special arguments). This loop
148559 ** does the following:
148561 ** + Figures out the number of columns the FTSX table will have, and
148562 ** the number of bytes of space that must be allocated to store copies
148563 ** of the column names.
148565 ** + If there is a tokenizer specification included in the arguments,
148566 ** initializes the tokenizer pTokenizer.
148568 for(i=3; rc==SQLITE_OK && i<argc; i++){
148569 char const *z = argv[i];
148570 int nKey;
148571 char *zVal;
148573 /* Check if this is a tokenizer specification */
148574 if( !pTokenizer
148575 && strlen(z)>8
148576 && 0==sqlite3_strnicmp(z, "tokenize", 8)
148577 && 0==sqlite3Fts3IsIdChar(z[8])
148579 rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
148582 /* Check if it is an FTS4 special argument. */
148583 else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
148584 struct Fts4Option {
148585 const char *zOpt;
148586 int nOpt;
148587 } aFts4Opt[] = {
148588 { "matchinfo", 9 }, /* 0 -> MATCHINFO */
148589 { "prefix", 6 }, /* 1 -> PREFIX */
148590 { "compress", 8 }, /* 2 -> COMPRESS */
148591 { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
148592 { "order", 5 }, /* 4 -> ORDER */
148593 { "content", 7 }, /* 5 -> CONTENT */
148594 { "languageid", 10 }, /* 6 -> LANGUAGEID */
148595 { "notindexed", 10 } /* 7 -> NOTINDEXED */
148598 int iOpt;
148599 if( !zVal ){
148600 rc = SQLITE_NOMEM;
148601 }else{
148602 for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
148603 struct Fts4Option *pOp = &aFts4Opt[iOpt];
148604 if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
148605 break;
148608 switch( iOpt ){
148609 case 0: /* MATCHINFO */
148610 if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
148611 sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
148612 rc = SQLITE_ERROR;
148614 bNoDocsize = 1;
148615 break;
148617 case 1: /* PREFIX */
148618 sqlite3_free(zPrefix);
148619 zPrefix = zVal;
148620 zVal = 0;
148621 break;
148623 case 2: /* COMPRESS */
148624 sqlite3_free(zCompress);
148625 zCompress = zVal;
148626 zVal = 0;
148627 break;
148629 case 3: /* UNCOMPRESS */
148630 sqlite3_free(zUncompress);
148631 zUncompress = zVal;
148632 zVal = 0;
148633 break;
148635 case 4: /* ORDER */
148636 if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
148637 && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
148639 sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
148640 rc = SQLITE_ERROR;
148642 bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
148643 break;
148645 case 5: /* CONTENT */
148646 sqlite3_free(zContent);
148647 zContent = zVal;
148648 zVal = 0;
148649 break;
148651 case 6: /* LANGUAGEID */
148652 assert( iOpt==6 );
148653 sqlite3_free(zLanguageid);
148654 zLanguageid = zVal;
148655 zVal = 0;
148656 break;
148658 case 7: /* NOTINDEXED */
148659 azNotindexed[nNotindexed++] = zVal;
148660 zVal = 0;
148661 break;
148663 default:
148664 assert( iOpt==SizeofArray(aFts4Opt) );
148665 sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
148666 rc = SQLITE_ERROR;
148667 break;
148669 sqlite3_free(zVal);
148673 /* Otherwise, the argument is a column name. */
148674 else {
148675 nString += (int)(strlen(z) + 1);
148676 aCol[nCol++] = z;
148680 /* If a content=xxx option was specified, the following:
148682 ** 1. Ignore any compress= and uncompress= options.
148684 ** 2. If no column names were specified as part of the CREATE VIRTUAL
148685 ** TABLE statement, use all columns from the content table.
148687 if( rc==SQLITE_OK && zContent ){
148688 sqlite3_free(zCompress);
148689 sqlite3_free(zUncompress);
148690 zCompress = 0;
148691 zUncompress = 0;
148692 if( nCol==0 ){
148693 sqlite3_free((void*)aCol);
148694 aCol = 0;
148695 rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
148697 /* If a languageid= option was specified, remove the language id
148698 ** column from the aCol[] array. */
148699 if( rc==SQLITE_OK && zLanguageid ){
148700 int j;
148701 for(j=0; j<nCol; j++){
148702 if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
148703 int k;
148704 for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
148705 nCol--;
148706 break;
148712 if( rc!=SQLITE_OK ) goto fts3_init_out;
148714 if( nCol==0 ){
148715 assert( nString==0 );
148716 aCol[0] = "content";
148717 nString = 8;
148718 nCol = 1;
148721 if( pTokenizer==0 ){
148722 rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
148723 if( rc!=SQLITE_OK ) goto fts3_init_out;
148725 assert( pTokenizer );
148727 rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
148728 if( rc==SQLITE_ERROR ){
148729 assert( zPrefix );
148730 sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
148732 if( rc!=SQLITE_OK ) goto fts3_init_out;
148734 /* Allocate and populate the Fts3Table structure. */
148735 nByte = sizeof(Fts3Table) + /* Fts3Table */
148736 nCol * sizeof(char *) + /* azColumn */
148737 nIndex * sizeof(struct Fts3Index) + /* aIndex */
148738 nCol * sizeof(u8) + /* abNotindexed */
148739 nName + /* zName */
148740 nDb + /* zDb */
148741 nString; /* Space for azColumn strings */
148742 p = (Fts3Table*)sqlite3_malloc(nByte);
148743 if( p==0 ){
148744 rc = SQLITE_NOMEM;
148745 goto fts3_init_out;
148747 memset(p, 0, nByte);
148748 p->db = db;
148749 p->nColumn = nCol;
148750 p->nPendingData = 0;
148751 p->azColumn = (char **)&p[1];
148752 p->pTokenizer = pTokenizer;
148753 p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
148754 p->bHasDocsize = (isFts4 && bNoDocsize==0);
148755 p->bHasStat = (u8)isFts4;
148756 p->bFts4 = (u8)isFts4;
148757 p->bDescIdx = (u8)bDescIdx;
148758 p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
148759 p->zContentTbl = zContent;
148760 p->zLanguageid = zLanguageid;
148761 zContent = 0;
148762 zLanguageid = 0;
148763 TESTONLY( p->inTransaction = -1 );
148764 TESTONLY( p->mxSavepoint = -1 );
148766 p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
148767 memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
148768 p->nIndex = nIndex;
148769 for(i=0; i<nIndex; i++){
148770 fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
148772 p->abNotindexed = (u8 *)&p->aIndex[nIndex];
148774 /* Fill in the zName and zDb fields of the vtab structure. */
148775 zCsr = (char *)&p->abNotindexed[nCol];
148776 p->zName = zCsr;
148777 memcpy(zCsr, argv[2], nName);
148778 zCsr += nName;
148779 p->zDb = zCsr;
148780 memcpy(zCsr, argv[1], nDb);
148781 zCsr += nDb;
148783 /* Fill in the azColumn array */
148784 for(iCol=0; iCol<nCol; iCol++){
148785 char *z;
148786 int n = 0;
148787 z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
148788 if( n>0 ){
148789 memcpy(zCsr, z, n);
148791 zCsr[n] = '\0';
148792 sqlite3Fts3Dequote(zCsr);
148793 p->azColumn[iCol] = zCsr;
148794 zCsr += n+1;
148795 assert( zCsr <= &((char *)p)[nByte] );
148798 /* Fill in the abNotindexed array */
148799 for(iCol=0; iCol<nCol; iCol++){
148800 int n = (int)strlen(p->azColumn[iCol]);
148801 for(i=0; i<nNotindexed; i++){
148802 char *zNot = azNotindexed[i];
148803 if( zNot && n==(int)strlen(zNot)
148804 && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
148806 p->abNotindexed[iCol] = 1;
148807 sqlite3_free(zNot);
148808 azNotindexed[i] = 0;
148812 for(i=0; i<nNotindexed; i++){
148813 if( azNotindexed[i] ){
148814 sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
148815 rc = SQLITE_ERROR;
148819 if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
148820 char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
148821 rc = SQLITE_ERROR;
148822 sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
148824 p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
148825 p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
148826 if( rc!=SQLITE_OK ) goto fts3_init_out;
148828 /* If this is an xCreate call, create the underlying tables in the
148829 ** database. TODO: For xConnect(), it could verify that said tables exist.
148831 if( isCreate ){
148832 rc = fts3CreateTables(p);
148835 /* Check to see if a legacy fts3 table has been "upgraded" by the
148836 ** addition of a %_stat table so that it can use incremental merge.
148838 if( !isFts4 && !isCreate ){
148839 p->bHasStat = 2;
148842 /* Figure out the page-size for the database. This is required in order to
148843 ** estimate the cost of loading large doclists from the database. */
148844 fts3DatabasePageSize(&rc, p);
148845 p->nNodeSize = p->nPgsz-35;
148847 /* Declare the table schema to SQLite. */
148848 fts3DeclareVtab(&rc, p);
148850 fts3_init_out:
148851 sqlite3_free(zPrefix);
148852 sqlite3_free(aIndex);
148853 sqlite3_free(zCompress);
148854 sqlite3_free(zUncompress);
148855 sqlite3_free(zContent);
148856 sqlite3_free(zLanguageid);
148857 for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
148858 sqlite3_free((void *)aCol);
148859 sqlite3_free((void *)azNotindexed);
148860 if( rc!=SQLITE_OK ){
148861 if( p ){
148862 fts3DisconnectMethod((sqlite3_vtab *)p);
148863 }else if( pTokenizer ){
148864 pTokenizer->pModule->xDestroy(pTokenizer);
148866 }else{
148867 assert( p->pSegments==0 );
148868 *ppVTab = &p->base;
148870 return rc;
148874 ** The xConnect() and xCreate() methods for the virtual table. All the
148875 ** work is done in function fts3InitVtab().
148877 static int fts3ConnectMethod(
148878 sqlite3 *db, /* Database connection */
148879 void *pAux, /* Pointer to tokenizer hash table */
148880 int argc, /* Number of elements in argv array */
148881 const char * const *argv, /* xCreate/xConnect argument array */
148882 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
148883 char **pzErr /* OUT: sqlite3_malloc'd error message */
148885 return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
148887 static int fts3CreateMethod(
148888 sqlite3 *db, /* Database connection */
148889 void *pAux, /* Pointer to tokenizer hash table */
148890 int argc, /* Number of elements in argv array */
148891 const char * const *argv, /* xCreate/xConnect argument array */
148892 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
148893 char **pzErr /* OUT: sqlite3_malloc'd error message */
148895 return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
148899 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
148900 ** extension is currently being used by a version of SQLite too old to
148901 ** support estimatedRows. In that case this function is a no-op.
148903 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
148904 #if SQLITE_VERSION_NUMBER>=3008002
148905 if( sqlite3_libversion_number()>=3008002 ){
148906 pIdxInfo->estimatedRows = nRow;
148908 #endif
148912 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
148913 ** extension is currently being used by a version of SQLite too old to
148914 ** support index-info flags. In that case this function is a no-op.
148916 static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
148917 #if SQLITE_VERSION_NUMBER>=3008012
148918 if( sqlite3_libversion_number()>=3008012 ){
148919 pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
148921 #endif
148925 ** Implementation of the xBestIndex method for FTS3 tables. There
148926 ** are three possible strategies, in order of preference:
148928 ** 1. Direct lookup by rowid or docid.
148929 ** 2. Full-text search using a MATCH operator on a non-docid column.
148930 ** 3. Linear scan of %_content table.
148932 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
148933 Fts3Table *p = (Fts3Table *)pVTab;
148934 int i; /* Iterator variable */
148935 int iCons = -1; /* Index of constraint to use */
148937 int iLangidCons = -1; /* Index of langid=x constraint, if present */
148938 int iDocidGe = -1; /* Index of docid>=x constraint, if present */
148939 int iDocidLe = -1; /* Index of docid<=x constraint, if present */
148940 int iIdx;
148942 /* By default use a full table scan. This is an expensive option,
148943 ** so search through the constraints to see if a more efficient
148944 ** strategy is possible.
148946 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
148947 pInfo->estimatedCost = 5000000;
148948 for(i=0; i<pInfo->nConstraint; i++){
148949 int bDocid; /* True if this constraint is on docid */
148950 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
148951 if( pCons->usable==0 ){
148952 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
148953 /* There exists an unusable MATCH constraint. This means that if
148954 ** the planner does elect to use the results of this call as part
148955 ** of the overall query plan the user will see an "unable to use
148956 ** function MATCH in the requested context" error. To discourage
148957 ** this, return a very high cost here. */
148958 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
148959 pInfo->estimatedCost = 1e50;
148960 fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
148961 return SQLITE_OK;
148963 continue;
148966 bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
148968 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
148969 if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
148970 pInfo->idxNum = FTS3_DOCID_SEARCH;
148971 pInfo->estimatedCost = 1.0;
148972 iCons = i;
148975 /* A MATCH constraint. Use a full-text search.
148977 ** If there is more than one MATCH constraint available, use the first
148978 ** one encountered. If there is both a MATCH constraint and a direct
148979 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
148980 ** though the rowid/docid lookup is faster than a MATCH query, selecting
148981 ** it would lead to an "unable to use function MATCH in the requested
148982 ** context" error.
148984 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
148985 && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
148987 pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
148988 pInfo->estimatedCost = 2.0;
148989 iCons = i;
148992 /* Equality constraint on the langid column */
148993 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
148994 && pCons->iColumn==p->nColumn + 2
148996 iLangidCons = i;
148999 if( bDocid ){
149000 switch( pCons->op ){
149001 case SQLITE_INDEX_CONSTRAINT_GE:
149002 case SQLITE_INDEX_CONSTRAINT_GT:
149003 iDocidGe = i;
149004 break;
149006 case SQLITE_INDEX_CONSTRAINT_LE:
149007 case SQLITE_INDEX_CONSTRAINT_LT:
149008 iDocidLe = i;
149009 break;
149014 /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
149015 if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
149017 iIdx = 1;
149018 if( iCons>=0 ){
149019 pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
149020 pInfo->aConstraintUsage[iCons].omit = 1;
149022 if( iLangidCons>=0 ){
149023 pInfo->idxNum |= FTS3_HAVE_LANGID;
149024 pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
149026 if( iDocidGe>=0 ){
149027 pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
149028 pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
149030 if( iDocidLe>=0 ){
149031 pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
149032 pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
149035 /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
149036 ** docid) order. Both ascending and descending are possible.
149038 if( pInfo->nOrderBy==1 ){
149039 struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
149040 if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
149041 if( pOrder->desc ){
149042 pInfo->idxStr = "DESC";
149043 }else{
149044 pInfo->idxStr = "ASC";
149046 pInfo->orderByConsumed = 1;
149050 assert( p->pSegments==0 );
149051 return SQLITE_OK;
149055 ** Implementation of xOpen method.
149057 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
149058 sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
149060 UNUSED_PARAMETER(pVTab);
149062 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
149063 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
149064 ** if the allocation fails, return SQLITE_NOMEM.
149066 *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
149067 if( !pCsr ){
149068 return SQLITE_NOMEM;
149070 memset(pCsr, 0, sizeof(Fts3Cursor));
149071 return SQLITE_OK;
149075 ** Finalize the statement handle at pCsr->pStmt.
149077 ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
149078 ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
149079 ** pointer there instead of finalizing it.
149081 static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
149082 if( pCsr->bSeekStmt ){
149083 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
149084 if( p->pSeekStmt==0 ){
149085 p->pSeekStmt = pCsr->pStmt;
149086 sqlite3_reset(pCsr->pStmt);
149087 pCsr->pStmt = 0;
149089 pCsr->bSeekStmt = 0;
149091 sqlite3_finalize(pCsr->pStmt);
149095 ** Free all resources currently held by the cursor passed as the only
149096 ** argument.
149098 static void fts3ClearCursor(Fts3Cursor *pCsr){
149099 fts3CursorFinalizeStmt(pCsr);
149100 sqlite3Fts3FreeDeferredTokens(pCsr);
149101 sqlite3_free(pCsr->aDoclist);
149102 sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
149103 sqlite3Fts3ExprFree(pCsr->pExpr);
149104 memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
149108 ** Close the cursor. For additional information see the documentation
149109 ** on the xClose method of the virtual table interface.
149111 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
149112 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
149113 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
149114 fts3ClearCursor(pCsr);
149115 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
149116 sqlite3_free(pCsr);
149117 return SQLITE_OK;
149121 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
149122 ** compose and prepare an SQL statement of the form:
149124 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
149126 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
149127 ** it. If an error occurs, return an SQLite error code.
149129 static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
149130 int rc = SQLITE_OK;
149131 if( pCsr->pStmt==0 ){
149132 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
149133 char *zSql;
149134 if( p->pSeekStmt ){
149135 pCsr->pStmt = p->pSeekStmt;
149136 p->pSeekStmt = 0;
149137 }else{
149138 zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
149139 if( !zSql ) return SQLITE_NOMEM;
149140 rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
149141 sqlite3_free(zSql);
149143 if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
149145 return rc;
149149 ** Position the pCsr->pStmt statement so that it is on the row
149150 ** of the %_content table that contains the last match. Return
149151 ** SQLITE_OK on success.
149153 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
149154 int rc = SQLITE_OK;
149155 if( pCsr->isRequireSeek ){
149156 rc = fts3CursorSeekStmt(pCsr);
149157 if( rc==SQLITE_OK ){
149158 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
149159 pCsr->isRequireSeek = 0;
149160 if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
149161 return SQLITE_OK;
149162 }else{
149163 rc = sqlite3_reset(pCsr->pStmt);
149164 if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
149165 /* If no row was found and no error has occurred, then the %_content
149166 ** table is missing a row that is present in the full-text index.
149167 ** The data structures are corrupt. */
149168 rc = FTS_CORRUPT_VTAB;
149169 pCsr->isEof = 1;
149175 if( rc!=SQLITE_OK && pContext ){
149176 sqlite3_result_error_code(pContext, rc);
149178 return rc;
149182 ** This function is used to process a single interior node when searching
149183 ** a b-tree for a term or term prefix. The node data is passed to this
149184 ** function via the zNode/nNode parameters. The term to search for is
149185 ** passed in zTerm/nTerm.
149187 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
149188 ** of the child node that heads the sub-tree that may contain the term.
149190 ** If piLast is not NULL, then *piLast is set to the right-most child node
149191 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
149192 ** a prefix.
149194 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
149196 static int fts3ScanInteriorNode(
149197 const char *zTerm, /* Term to select leaves for */
149198 int nTerm, /* Size of term zTerm in bytes */
149199 const char *zNode, /* Buffer containing segment interior node */
149200 int nNode, /* Size of buffer at zNode */
149201 sqlite3_int64 *piFirst, /* OUT: Selected child node */
149202 sqlite3_int64 *piLast /* OUT: Selected child node */
149204 int rc = SQLITE_OK; /* Return code */
149205 const char *zCsr = zNode; /* Cursor to iterate through node */
149206 const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
149207 char *zBuffer = 0; /* Buffer to load terms into */
149208 int nAlloc = 0; /* Size of allocated buffer */
149209 int isFirstTerm = 1; /* True when processing first term on page */
149210 sqlite3_int64 iChild; /* Block id of child node to descend to */
149212 /* Skip over the 'height' varint that occurs at the start of every
149213 ** interior node. Then load the blockid of the left-child of the b-tree
149214 ** node into variable iChild.
149216 ** Even if the data structure on disk is corrupted, this (reading two
149217 ** varints from the buffer) does not risk an overread. If zNode is a
149218 ** root node, then the buffer comes from a SELECT statement. SQLite does
149219 ** not make this guarantee explicitly, but in practice there are always
149220 ** either more than 20 bytes of allocated space following the nNode bytes of
149221 ** contents, or two zero bytes. Or, if the node is read from the %_segments
149222 ** table, then there are always 20 bytes of zeroed padding following the
149223 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
149225 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
149226 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
149227 if( zCsr>zEnd ){
149228 return FTS_CORRUPT_VTAB;
149231 while( zCsr<zEnd && (piFirst || piLast) ){
149232 int cmp; /* memcmp() result */
149233 int nSuffix; /* Size of term suffix */
149234 int nPrefix = 0; /* Size of term prefix */
149235 int nBuffer; /* Total term size */
149237 /* Load the next term on the node into zBuffer. Use realloc() to expand
149238 ** the size of zBuffer if required. */
149239 if( !isFirstTerm ){
149240 zCsr += fts3GetVarint32(zCsr, &nPrefix);
149242 isFirstTerm = 0;
149243 zCsr += fts3GetVarint32(zCsr, &nSuffix);
149245 assert( nPrefix>=0 && nSuffix>=0 );
149246 if( &zCsr[nSuffix]>zEnd ){
149247 rc = FTS_CORRUPT_VTAB;
149248 goto finish_scan;
149250 if( nPrefix+nSuffix>nAlloc ){
149251 char *zNew;
149252 nAlloc = (nPrefix+nSuffix) * 2;
149253 zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
149254 if( !zNew ){
149255 rc = SQLITE_NOMEM;
149256 goto finish_scan;
149258 zBuffer = zNew;
149260 assert( zBuffer );
149261 memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
149262 nBuffer = nPrefix + nSuffix;
149263 zCsr += nSuffix;
149265 /* Compare the term we are searching for with the term just loaded from
149266 ** the interior node. If the specified term is greater than or equal
149267 ** to the term from the interior node, then all terms on the sub-tree
149268 ** headed by node iChild are smaller than zTerm. No need to search
149269 ** iChild.
149271 ** If the interior node term is larger than the specified term, then
149272 ** the tree headed by iChild may contain the specified term.
149274 cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
149275 if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
149276 *piFirst = iChild;
149277 piFirst = 0;
149280 if( piLast && cmp<0 ){
149281 *piLast = iChild;
149282 piLast = 0;
149285 iChild++;
149288 if( piFirst ) *piFirst = iChild;
149289 if( piLast ) *piLast = iChild;
149291 finish_scan:
149292 sqlite3_free(zBuffer);
149293 return rc;
149298 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
149299 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
149300 ** contains a term. This function searches the sub-tree headed by the zNode
149301 ** node for the range of leaf nodes that may contain the specified term
149302 ** or terms for which the specified term is a prefix.
149304 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
149305 ** left-most leaf node in the tree that may contain the specified term.
149306 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
149307 ** right-most leaf node that may contain a term for which the specified
149308 ** term is a prefix.
149310 ** It is possible that the range of returned leaf nodes does not contain
149311 ** the specified term or any terms for which it is a prefix. However, if the
149312 ** segment does contain any such terms, they are stored within the identified
149313 ** range. Because this function only inspects interior segment nodes (and
149314 ** never loads leaf nodes into memory), it is not possible to be sure.
149316 ** If an error occurs, an error code other than SQLITE_OK is returned.
149318 static int fts3SelectLeaf(
149319 Fts3Table *p, /* Virtual table handle */
149320 const char *zTerm, /* Term to select leaves for */
149321 int nTerm, /* Size of term zTerm in bytes */
149322 const char *zNode, /* Buffer containing segment interior node */
149323 int nNode, /* Size of buffer at zNode */
149324 sqlite3_int64 *piLeaf, /* Selected leaf node */
149325 sqlite3_int64 *piLeaf2 /* Selected leaf node */
149327 int rc = SQLITE_OK; /* Return code */
149328 int iHeight; /* Height of this node in tree */
149330 assert( piLeaf || piLeaf2 );
149332 fts3GetVarint32(zNode, &iHeight);
149333 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
149334 assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
149336 if( rc==SQLITE_OK && iHeight>1 ){
149337 char *zBlob = 0; /* Blob read from %_segments table */
149338 int nBlob = 0; /* Size of zBlob in bytes */
149340 if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
149341 rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
149342 if( rc==SQLITE_OK ){
149343 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
149345 sqlite3_free(zBlob);
149346 piLeaf = 0;
149347 zBlob = 0;
149350 if( rc==SQLITE_OK ){
149351 rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
149353 if( rc==SQLITE_OK ){
149354 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
149356 sqlite3_free(zBlob);
149359 return rc;
149363 ** This function is used to create delta-encoded serialized lists of FTS3
149364 ** varints. Each call to this function appends a single varint to a list.
149366 static void fts3PutDeltaVarint(
149367 char **pp, /* IN/OUT: Output pointer */
149368 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
149369 sqlite3_int64 iVal /* Write this value to the list */
149371 assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
149372 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
149373 *piPrev = iVal;
149377 ** When this function is called, *ppPoslist is assumed to point to the
149378 ** start of a position-list. After it returns, *ppPoslist points to the
149379 ** first byte after the position-list.
149381 ** A position list is list of positions (delta encoded) and columns for
149382 ** a single document record of a doclist. So, in other words, this
149383 ** routine advances *ppPoslist so that it points to the next docid in
149384 ** the doclist, or to the first byte past the end of the doclist.
149386 ** If pp is not NULL, then the contents of the position list are copied
149387 ** to *pp. *pp is set to point to the first byte past the last byte copied
149388 ** before this function returns.
149390 static void fts3PoslistCopy(char **pp, char **ppPoslist){
149391 char *pEnd = *ppPoslist;
149392 char c = 0;
149394 /* The end of a position list is marked by a zero encoded as an FTS3
149395 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
149396 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
149397 ** of some other, multi-byte, value.
149399 ** The following while-loop moves pEnd to point to the first byte that is not
149400 ** immediately preceded by a byte with the 0x80 bit set. Then increments
149401 ** pEnd once more so that it points to the byte immediately following the
149402 ** last byte in the position-list.
149404 while( *pEnd | c ){
149405 c = *pEnd++ & 0x80;
149406 testcase( c!=0 && (*pEnd)==0 );
149408 pEnd++; /* Advance past the POS_END terminator byte */
149410 if( pp ){
149411 int n = (int)(pEnd - *ppPoslist);
149412 char *p = *pp;
149413 memcpy(p, *ppPoslist, n);
149414 p += n;
149415 *pp = p;
149417 *ppPoslist = pEnd;
149421 ** When this function is called, *ppPoslist is assumed to point to the
149422 ** start of a column-list. After it returns, *ppPoslist points to the
149423 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
149425 ** A column-list is list of delta-encoded positions for a single column
149426 ** within a single document within a doclist.
149428 ** The column-list is terminated either by a POS_COLUMN varint (1) or
149429 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
149430 ** the POS_COLUMN or POS_END that terminates the column-list.
149432 ** If pp is not NULL, then the contents of the column-list are copied
149433 ** to *pp. *pp is set to point to the first byte past the last byte copied
149434 ** before this function returns. The POS_COLUMN or POS_END terminator
149435 ** is not copied into *pp.
149437 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
149438 char *pEnd = *ppPoslist;
149439 char c = 0;
149441 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
149442 ** not part of a multi-byte varint.
149444 while( 0xFE & (*pEnd | c) ){
149445 c = *pEnd++ & 0x80;
149446 testcase( c!=0 && ((*pEnd)&0xfe)==0 );
149448 if( pp ){
149449 int n = (int)(pEnd - *ppPoslist);
149450 char *p = *pp;
149451 memcpy(p, *ppPoslist, n);
149452 p += n;
149453 *pp = p;
149455 *ppPoslist = pEnd;
149459 ** Value used to signify the end of an position-list. This is safe because
149460 ** it is not possible to have a document with 2^31 terms.
149462 #define POSITION_LIST_END 0x7fffffff
149465 ** This function is used to help parse position-lists. When this function is
149466 ** called, *pp may point to the start of the next varint in the position-list
149467 ** being parsed, or it may point to 1 byte past the end of the position-list
149468 ** (in which case **pp will be a terminator bytes POS_END (0) or
149469 ** (1)).
149471 ** If *pp points past the end of the current position-list, set *pi to
149472 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
149473 ** increment the current value of *pi by the value read, and set *pp to
149474 ** point to the next value before returning.
149476 ** Before calling this routine *pi must be initialized to the value of
149477 ** the previous position, or zero if we are reading the first position
149478 ** in the position-list. Because positions are delta-encoded, the value
149479 ** of the previous position is needed in order to compute the value of
149480 ** the next position.
149482 static void fts3ReadNextPos(
149483 char **pp, /* IN/OUT: Pointer into position-list buffer */
149484 sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
149486 if( (**pp)&0xFE ){
149487 fts3GetDeltaVarint(pp, pi);
149488 *pi -= 2;
149489 }else{
149490 *pi = POSITION_LIST_END;
149495 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
149496 ** the value of iCol encoded as a varint to *pp. This will start a new
149497 ** column list.
149499 ** Set *pp to point to the byte just after the last byte written before
149500 ** returning (do not modify it if iCol==0). Return the total number of bytes
149501 ** written (0 if iCol==0).
149503 static int fts3PutColNumber(char **pp, int iCol){
149504 int n = 0; /* Number of bytes written */
149505 if( iCol ){
149506 char *p = *pp; /* Output pointer */
149507 n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
149508 *p = 0x01;
149509 *pp = &p[n];
149511 return n;
149515 ** Compute the union of two position lists. The output written
149516 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
149517 ** order and with any duplicates removed. All pointers are
149518 ** updated appropriately. The caller is responsible for insuring
149519 ** that there is enough space in *pp to hold the complete output.
149521 static void fts3PoslistMerge(
149522 char **pp, /* Output buffer */
149523 char **pp1, /* Left input list */
149524 char **pp2 /* Right input list */
149526 char *p = *pp;
149527 char *p1 = *pp1;
149528 char *p2 = *pp2;
149530 while( *p1 || *p2 ){
149531 int iCol1; /* The current column index in pp1 */
149532 int iCol2; /* The current column index in pp2 */
149534 if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
149535 else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
149536 else iCol1 = 0;
149538 if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
149539 else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
149540 else iCol2 = 0;
149542 if( iCol1==iCol2 ){
149543 sqlite3_int64 i1 = 0; /* Last position from pp1 */
149544 sqlite3_int64 i2 = 0; /* Last position from pp2 */
149545 sqlite3_int64 iPrev = 0;
149546 int n = fts3PutColNumber(&p, iCol1);
149547 p1 += n;
149548 p2 += n;
149550 /* At this point, both p1 and p2 point to the start of column-lists
149551 ** for the same column (the column with index iCol1 and iCol2).
149552 ** A column-list is a list of non-negative delta-encoded varints, each
149553 ** incremented by 2 before being stored. Each list is terminated by a
149554 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
149555 ** and writes the results to buffer p. p is left pointing to the byte
149556 ** after the list written. No terminator (POS_END or POS_COLUMN) is
149557 ** written to the output.
149559 fts3GetDeltaVarint(&p1, &i1);
149560 fts3GetDeltaVarint(&p2, &i2);
149562 fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
149563 iPrev -= 2;
149564 if( i1==i2 ){
149565 fts3ReadNextPos(&p1, &i1);
149566 fts3ReadNextPos(&p2, &i2);
149567 }else if( i1<i2 ){
149568 fts3ReadNextPos(&p1, &i1);
149569 }else{
149570 fts3ReadNextPos(&p2, &i2);
149572 }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
149573 }else if( iCol1<iCol2 ){
149574 p1 += fts3PutColNumber(&p, iCol1);
149575 fts3ColumnlistCopy(&p, &p1);
149576 }else{
149577 p2 += fts3PutColNumber(&p, iCol2);
149578 fts3ColumnlistCopy(&p, &p2);
149582 *p++ = POS_END;
149583 *pp = p;
149584 *pp1 = p1 + 1;
149585 *pp2 = p2 + 1;
149589 ** This function is used to merge two position lists into one. When it is
149590 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
149591 ** the part of a doclist that follows each document id. For example, if a row
149592 ** contains:
149594 ** 'a b c'|'x y z'|'a b b a'
149596 ** Then the position list for this row for token 'b' would consist of:
149598 ** 0x02 0x01 0x02 0x03 0x03 0x00
149600 ** When this function returns, both *pp1 and *pp2 are left pointing to the
149601 ** byte following the 0x00 terminator of their respective position lists.
149603 ** If isSaveLeft is 0, an entry is added to the output position list for
149604 ** each position in *pp2 for which there exists one or more positions in
149605 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
149606 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
149607 ** slots before it.
149609 ** e.g. nToken==1 searches for adjacent positions.
149611 static int fts3PoslistPhraseMerge(
149612 char **pp, /* IN/OUT: Preallocated output buffer */
149613 int nToken, /* Maximum difference in token positions */
149614 int isSaveLeft, /* Save the left position */
149615 int isExact, /* If *pp1 is exactly nTokens before *pp2 */
149616 char **pp1, /* IN/OUT: Left input list */
149617 char **pp2 /* IN/OUT: Right input list */
149619 char *p = *pp;
149620 char *p1 = *pp1;
149621 char *p2 = *pp2;
149622 int iCol1 = 0;
149623 int iCol2 = 0;
149625 /* Never set both isSaveLeft and isExact for the same invocation. */
149626 assert( isSaveLeft==0 || isExact==0 );
149628 assert( p!=0 && *p1!=0 && *p2!=0 );
149629 if( *p1==POS_COLUMN ){
149630 p1++;
149631 p1 += fts3GetVarint32(p1, &iCol1);
149633 if( *p2==POS_COLUMN ){
149634 p2++;
149635 p2 += fts3GetVarint32(p2, &iCol2);
149638 while( 1 ){
149639 if( iCol1==iCol2 ){
149640 char *pSave = p;
149641 sqlite3_int64 iPrev = 0;
149642 sqlite3_int64 iPos1 = 0;
149643 sqlite3_int64 iPos2 = 0;
149645 if( iCol1 ){
149646 *p++ = POS_COLUMN;
149647 p += sqlite3Fts3PutVarint(p, iCol1);
149650 assert( *p1!=POS_END && *p1!=POS_COLUMN );
149651 assert( *p2!=POS_END && *p2!=POS_COLUMN );
149652 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
149653 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
149655 while( 1 ){
149656 if( iPos2==iPos1+nToken
149657 || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
149659 sqlite3_int64 iSave;
149660 iSave = isSaveLeft ? iPos1 : iPos2;
149661 fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
149662 pSave = 0;
149663 assert( p );
149665 if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
149666 if( (*p2&0xFE)==0 ) break;
149667 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
149668 }else{
149669 if( (*p1&0xFE)==0 ) break;
149670 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
149674 if( pSave ){
149675 assert( pp && p );
149676 p = pSave;
149679 fts3ColumnlistCopy(0, &p1);
149680 fts3ColumnlistCopy(0, &p2);
149681 assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
149682 if( 0==*p1 || 0==*p2 ) break;
149684 p1++;
149685 p1 += fts3GetVarint32(p1, &iCol1);
149686 p2++;
149687 p2 += fts3GetVarint32(p2, &iCol2);
149690 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
149691 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
149692 ** end of the position list, or the 0x01 that precedes the next
149693 ** column-number in the position list.
149695 else if( iCol1<iCol2 ){
149696 fts3ColumnlistCopy(0, &p1);
149697 if( 0==*p1 ) break;
149698 p1++;
149699 p1 += fts3GetVarint32(p1, &iCol1);
149700 }else{
149701 fts3ColumnlistCopy(0, &p2);
149702 if( 0==*p2 ) break;
149703 p2++;
149704 p2 += fts3GetVarint32(p2, &iCol2);
149708 fts3PoslistCopy(0, &p2);
149709 fts3PoslistCopy(0, &p1);
149710 *pp1 = p1;
149711 *pp2 = p2;
149712 if( *pp==p ){
149713 return 0;
149715 *p++ = 0x00;
149716 *pp = p;
149717 return 1;
149721 ** Merge two position-lists as required by the NEAR operator. The argument
149722 ** position lists correspond to the left and right phrases of an expression
149723 ** like:
149725 ** "phrase 1" NEAR "phrase number 2"
149727 ** Position list *pp1 corresponds to the left-hand side of the NEAR
149728 ** expression and *pp2 to the right. As usual, the indexes in the position
149729 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
149730 ** in the example above).
149732 ** The output position list - written to *pp - is a copy of *pp2 with those
149733 ** entries that are not sufficiently NEAR entries in *pp1 removed.
149735 static int fts3PoslistNearMerge(
149736 char **pp, /* Output buffer */
149737 char *aTmp, /* Temporary buffer space */
149738 int nRight, /* Maximum difference in token positions */
149739 int nLeft, /* Maximum difference in token positions */
149740 char **pp1, /* IN/OUT: Left input list */
149741 char **pp2 /* IN/OUT: Right input list */
149743 char *p1 = *pp1;
149744 char *p2 = *pp2;
149746 char *pTmp1 = aTmp;
149747 char *pTmp2;
149748 char *aTmp2;
149749 int res = 1;
149751 fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
149752 aTmp2 = pTmp2 = pTmp1;
149753 *pp1 = p1;
149754 *pp2 = p2;
149755 fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
149756 if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
149757 fts3PoslistMerge(pp, &aTmp, &aTmp2);
149758 }else if( pTmp1!=aTmp ){
149759 fts3PoslistCopy(pp, &aTmp);
149760 }else if( pTmp2!=aTmp2 ){
149761 fts3PoslistCopy(pp, &aTmp2);
149762 }else{
149763 res = 0;
149766 return res;
149770 ** An instance of this function is used to merge together the (potentially
149771 ** large number of) doclists for each term that matches a prefix query.
149772 ** See function fts3TermSelectMerge() for details.
149774 typedef struct TermSelect TermSelect;
149775 struct TermSelect {
149776 char *aaOutput[16]; /* Malloc'd output buffers */
149777 int anOutput[16]; /* Size each output buffer in bytes */
149781 ** This function is used to read a single varint from a buffer. Parameter
149782 ** pEnd points 1 byte past the end of the buffer. When this function is
149783 ** called, if *pp points to pEnd or greater, then the end of the buffer
149784 ** has been reached. In this case *pp is set to 0 and the function returns.
149786 ** If *pp does not point to or past pEnd, then a single varint is read
149787 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
149789 ** If bDescIdx is false, the value read is added to *pVal before returning.
149790 ** If it is true, the value read is subtracted from *pVal before this
149791 ** function returns.
149793 static void fts3GetDeltaVarint3(
149794 char **pp, /* IN/OUT: Point to read varint from */
149795 char *pEnd, /* End of buffer */
149796 int bDescIdx, /* True if docids are descending */
149797 sqlite3_int64 *pVal /* IN/OUT: Integer value */
149799 if( *pp>=pEnd ){
149800 *pp = 0;
149801 }else{
149802 sqlite3_int64 iVal;
149803 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
149804 if( bDescIdx ){
149805 *pVal -= iVal;
149806 }else{
149807 *pVal += iVal;
149813 ** This function is used to write a single varint to a buffer. The varint
149814 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
149815 ** end of the value written.
149817 ** If *pbFirst is zero when this function is called, the value written to
149818 ** the buffer is that of parameter iVal.
149820 ** If *pbFirst is non-zero when this function is called, then the value
149821 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
149822 ** (if bDescIdx is non-zero).
149824 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
149825 ** to the value of parameter iVal.
149827 static void fts3PutDeltaVarint3(
149828 char **pp, /* IN/OUT: Output pointer */
149829 int bDescIdx, /* True for descending docids */
149830 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
149831 int *pbFirst, /* IN/OUT: True after first int written */
149832 sqlite3_int64 iVal /* Write this value to the list */
149834 sqlite3_int64 iWrite;
149835 if( bDescIdx==0 || *pbFirst==0 ){
149836 iWrite = iVal - *piPrev;
149837 }else{
149838 iWrite = *piPrev - iVal;
149840 assert( *pbFirst || *piPrev==0 );
149841 assert( *pbFirst==0 || iWrite>0 );
149842 *pp += sqlite3Fts3PutVarint(*pp, iWrite);
149843 *piPrev = iVal;
149844 *pbFirst = 1;
149849 ** This macro is used by various functions that merge doclists. The two
149850 ** arguments are 64-bit docid values. If the value of the stack variable
149851 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
149852 ** Otherwise, (i2-i1).
149854 ** Using this makes it easier to write code that can merge doclists that are
149855 ** sorted in either ascending or descending order.
149857 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
149860 ** This function does an "OR" merge of two doclists (output contains all
149861 ** positions contained in either argument doclist). If the docids in the
149862 ** input doclists are sorted in ascending order, parameter bDescDoclist
149863 ** should be false. If they are sorted in ascending order, it should be
149864 ** passed a non-zero value.
149866 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
149867 ** containing the output doclist and SQLITE_OK is returned. In this case
149868 ** *pnOut is set to the number of bytes in the output doclist.
149870 ** If an error occurs, an SQLite error code is returned. The output values
149871 ** are undefined in this case.
149873 static int fts3DoclistOrMerge(
149874 int bDescDoclist, /* True if arguments are desc */
149875 char *a1, int n1, /* First doclist */
149876 char *a2, int n2, /* Second doclist */
149877 char **paOut, int *pnOut /* OUT: Malloc'd doclist */
149879 sqlite3_int64 i1 = 0;
149880 sqlite3_int64 i2 = 0;
149881 sqlite3_int64 iPrev = 0;
149882 char *pEnd1 = &a1[n1];
149883 char *pEnd2 = &a2[n2];
149884 char *p1 = a1;
149885 char *p2 = a2;
149886 char *p;
149887 char *aOut;
149888 int bFirstOut = 0;
149890 *paOut = 0;
149891 *pnOut = 0;
149893 /* Allocate space for the output. Both the input and output doclists
149894 ** are delta encoded. If they are in ascending order (bDescDoclist==0),
149895 ** then the first docid in each list is simply encoded as a varint. For
149896 ** each subsequent docid, the varint stored is the difference between the
149897 ** current and previous docid (a positive number - since the list is in
149898 ** ascending order).
149900 ** The first docid written to the output is therefore encoded using the
149901 ** same number of bytes as it is in whichever of the input lists it is
149902 ** read from. And each subsequent docid read from the same input list
149903 ** consumes either the same or less bytes as it did in the input (since
149904 ** the difference between it and the previous value in the output must
149905 ** be a positive value less than or equal to the delta value read from
149906 ** the input list). The same argument applies to all but the first docid
149907 ** read from the 'other' list. And to the contents of all position lists
149908 ** that will be copied and merged from the input to the output.
149910 ** However, if the first docid copied to the output is a negative number,
149911 ** then the encoding of the first docid from the 'other' input list may
149912 ** be larger in the output than it was in the input (since the delta value
149913 ** may be a larger positive integer than the actual docid).
149915 ** The space required to store the output is therefore the sum of the
149916 ** sizes of the two inputs, plus enough space for exactly one of the input
149917 ** docids to grow.
149919 ** A symetric argument may be made if the doclists are in descending
149920 ** order.
149922 aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
149923 if( !aOut ) return SQLITE_NOMEM;
149925 p = aOut;
149926 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
149927 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
149928 while( p1 || p2 ){
149929 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
149931 if( p2 && p1 && iDiff==0 ){
149932 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
149933 fts3PoslistMerge(&p, &p1, &p2);
149934 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
149935 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
149936 }else if( !p2 || (p1 && iDiff<0) ){
149937 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
149938 fts3PoslistCopy(&p, &p1);
149939 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
149940 }else{
149941 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
149942 fts3PoslistCopy(&p, &p2);
149943 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
149947 *paOut = aOut;
149948 *pnOut = (int)(p-aOut);
149949 assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
149950 return SQLITE_OK;
149954 ** This function does a "phrase" merge of two doclists. In a phrase merge,
149955 ** the output contains a copy of each position from the right-hand input
149956 ** doclist for which there is a position in the left-hand input doclist
149957 ** exactly nDist tokens before it.
149959 ** If the docids in the input doclists are sorted in ascending order,
149960 ** parameter bDescDoclist should be false. If they are sorted in ascending
149961 ** order, it should be passed a non-zero value.
149963 ** The right-hand input doclist is overwritten by this function.
149965 static int fts3DoclistPhraseMerge(
149966 int bDescDoclist, /* True if arguments are desc */
149967 int nDist, /* Distance from left to right (1=adjacent) */
149968 char *aLeft, int nLeft, /* Left doclist */
149969 char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
149971 sqlite3_int64 i1 = 0;
149972 sqlite3_int64 i2 = 0;
149973 sqlite3_int64 iPrev = 0;
149974 char *aRight = *paRight;
149975 char *pEnd1 = &aLeft[nLeft];
149976 char *pEnd2 = &aRight[*pnRight];
149977 char *p1 = aLeft;
149978 char *p2 = aRight;
149979 char *p;
149980 int bFirstOut = 0;
149981 char *aOut;
149983 assert( nDist>0 );
149984 if( bDescDoclist ){
149985 aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
149986 if( aOut==0 ) return SQLITE_NOMEM;
149987 }else{
149988 aOut = aRight;
149990 p = aOut;
149992 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
149993 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
149995 while( p1 && p2 ){
149996 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
149997 if( iDiff==0 ){
149998 char *pSave = p;
149999 sqlite3_int64 iPrevSave = iPrev;
150000 int bFirstOutSave = bFirstOut;
150002 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
150003 if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
150004 p = pSave;
150005 iPrev = iPrevSave;
150006 bFirstOut = bFirstOutSave;
150008 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
150009 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
150010 }else if( iDiff<0 ){
150011 fts3PoslistCopy(0, &p1);
150012 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
150013 }else{
150014 fts3PoslistCopy(0, &p2);
150015 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
150019 *pnRight = (int)(p - aOut);
150020 if( bDescDoclist ){
150021 sqlite3_free(aRight);
150022 *paRight = aOut;
150025 return SQLITE_OK;
150029 ** Argument pList points to a position list nList bytes in size. This
150030 ** function checks to see if the position list contains any entries for
150031 ** a token in position 0 (of any column). If so, it writes argument iDelta
150032 ** to the output buffer pOut, followed by a position list consisting only
150033 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
150034 ** The value returned is the number of bytes written to pOut (if any).
150036 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
150037 sqlite3_int64 iDelta, /* Varint that may be written to pOut */
150038 char *pList, /* Position list (no 0x00 term) */
150039 int nList, /* Size of pList in bytes */
150040 char *pOut /* Write output here */
150042 int nOut = 0;
150043 int bWritten = 0; /* True once iDelta has been written */
150044 char *p = pList;
150045 char *pEnd = &pList[nList];
150047 if( *p!=0x01 ){
150048 if( *p==0x02 ){
150049 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
150050 pOut[nOut++] = 0x02;
150051 bWritten = 1;
150053 fts3ColumnlistCopy(0, &p);
150056 while( p<pEnd ){
150057 sqlite3_int64 iCol;
150059 p += sqlite3Fts3GetVarint(p, &iCol);
150060 if( *p==0x02 ){
150061 if( bWritten==0 ){
150062 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
150063 bWritten = 1;
150065 pOut[nOut++] = 0x01;
150066 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
150067 pOut[nOut++] = 0x02;
150069 fts3ColumnlistCopy(0, &p);
150071 if( bWritten ){
150072 pOut[nOut++] = 0x00;
150075 return nOut;
150080 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
150081 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
150082 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
150084 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
150085 ** the responsibility of the caller to free any doclists left in the
150086 ** TermSelect.aaOutput[] array.
150088 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
150089 char *aOut = 0;
150090 int nOut = 0;
150091 int i;
150093 /* Loop through the doclists in the aaOutput[] array. Merge them all
150094 ** into a single doclist.
150096 for(i=0; i<SizeofArray(pTS->aaOutput); i++){
150097 if( pTS->aaOutput[i] ){
150098 if( !aOut ){
150099 aOut = pTS->aaOutput[i];
150100 nOut = pTS->anOutput[i];
150101 pTS->aaOutput[i] = 0;
150102 }else{
150103 int nNew;
150104 char *aNew;
150106 int rc = fts3DoclistOrMerge(p->bDescIdx,
150107 pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
150109 if( rc!=SQLITE_OK ){
150110 sqlite3_free(aOut);
150111 return rc;
150114 sqlite3_free(pTS->aaOutput[i]);
150115 sqlite3_free(aOut);
150116 pTS->aaOutput[i] = 0;
150117 aOut = aNew;
150118 nOut = nNew;
150123 pTS->aaOutput[0] = aOut;
150124 pTS->anOutput[0] = nOut;
150125 return SQLITE_OK;
150129 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
150130 ** as the first argument. The merge is an "OR" merge (see function
150131 ** fts3DoclistOrMerge() for details).
150133 ** This function is called with the doclist for each term that matches
150134 ** a queried prefix. It merges all these doclists into one, the doclist
150135 ** for the specified prefix. Since there can be a very large number of
150136 ** doclists to merge, the merging is done pair-wise using the TermSelect
150137 ** object.
150139 ** This function returns SQLITE_OK if the merge is successful, or an
150140 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
150142 static int fts3TermSelectMerge(
150143 Fts3Table *p, /* FTS table handle */
150144 TermSelect *pTS, /* TermSelect object to merge into */
150145 char *aDoclist, /* Pointer to doclist */
150146 int nDoclist /* Size of aDoclist in bytes */
150148 if( pTS->aaOutput[0]==0 ){
150149 /* If this is the first term selected, copy the doclist to the output
150150 ** buffer using memcpy().
150152 ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
150153 ** allocation. This is so as to ensure that the buffer is big enough
150154 ** to hold the current doclist AND'd with any other doclist. If the
150155 ** doclists are stored in order=ASC order, this padding would not be
150156 ** required (since the size of [doclistA AND doclistB] is always less
150157 ** than or equal to the size of [doclistA] in that case). But this is
150158 ** not true for order=DESC. For example, a doclist containing (1, -1)
150159 ** may be smaller than (-1), as in the first example the -1 may be stored
150160 ** as a single-byte delta, whereas in the second it must be stored as a
150161 ** FTS3_VARINT_MAX byte varint.
150163 ** Similar padding is added in the fts3DoclistOrMerge() function.
150165 pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
150166 pTS->anOutput[0] = nDoclist;
150167 if( pTS->aaOutput[0] ){
150168 memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
150169 }else{
150170 return SQLITE_NOMEM;
150172 }else{
150173 char *aMerge = aDoclist;
150174 int nMerge = nDoclist;
150175 int iOut;
150177 for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
150178 if( pTS->aaOutput[iOut]==0 ){
150179 assert( iOut>0 );
150180 pTS->aaOutput[iOut] = aMerge;
150181 pTS->anOutput[iOut] = nMerge;
150182 break;
150183 }else{
150184 char *aNew;
150185 int nNew;
150187 int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
150188 pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
150190 if( rc!=SQLITE_OK ){
150191 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
150192 return rc;
150195 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
150196 sqlite3_free(pTS->aaOutput[iOut]);
150197 pTS->aaOutput[iOut] = 0;
150199 aMerge = aNew;
150200 nMerge = nNew;
150201 if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
150202 pTS->aaOutput[iOut] = aMerge;
150203 pTS->anOutput[iOut] = nMerge;
150208 return SQLITE_OK;
150212 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
150214 static int fts3SegReaderCursorAppend(
150215 Fts3MultiSegReader *pCsr,
150216 Fts3SegReader *pNew
150218 if( (pCsr->nSegment%16)==0 ){
150219 Fts3SegReader **apNew;
150220 int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
150221 apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
150222 if( !apNew ){
150223 sqlite3Fts3SegReaderFree(pNew);
150224 return SQLITE_NOMEM;
150226 pCsr->apSegment = apNew;
150228 pCsr->apSegment[pCsr->nSegment++] = pNew;
150229 return SQLITE_OK;
150233 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
150234 ** 8th argument.
150236 ** This function returns SQLITE_OK if successful, or an SQLite error code
150237 ** otherwise.
150239 static int fts3SegReaderCursor(
150240 Fts3Table *p, /* FTS3 table handle */
150241 int iLangid, /* Language id */
150242 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
150243 int iLevel, /* Level of segments to scan */
150244 const char *zTerm, /* Term to query for */
150245 int nTerm, /* Size of zTerm in bytes */
150246 int isPrefix, /* True for a prefix search */
150247 int isScan, /* True to scan from zTerm to EOF */
150248 Fts3MultiSegReader *pCsr /* Cursor object to populate */
150250 int rc = SQLITE_OK; /* Error code */
150251 sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
150252 int rc2; /* Result of sqlite3_reset() */
150254 /* If iLevel is less than 0 and this is not a scan, include a seg-reader
150255 ** for the pending-terms. If this is a scan, then this call must be being
150256 ** made by an fts4aux module, not an FTS table. In this case calling
150257 ** Fts3SegReaderPending might segfault, as the data structures used by
150258 ** fts4aux are not completely populated. So it's easiest to filter these
150259 ** calls out here. */
150260 if( iLevel<0 && p->aIndex ){
150261 Fts3SegReader *pSeg = 0;
150262 rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
150263 if( rc==SQLITE_OK && pSeg ){
150264 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
150268 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
150269 if( rc==SQLITE_OK ){
150270 rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
150273 while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
150274 Fts3SegReader *pSeg = 0;
150276 /* Read the values returned by the SELECT into local variables. */
150277 sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
150278 sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
150279 sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
150280 int nRoot = sqlite3_column_bytes(pStmt, 4);
150281 char const *zRoot = sqlite3_column_blob(pStmt, 4);
150283 /* If zTerm is not NULL, and this segment is not stored entirely on its
150284 ** root node, the range of leaves scanned can be reduced. Do this. */
150285 if( iStartBlock && zTerm ){
150286 sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
150287 rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
150288 if( rc!=SQLITE_OK ) goto finished;
150289 if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
150292 rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
150293 (isPrefix==0 && isScan==0),
150294 iStartBlock, iLeavesEndBlock,
150295 iEndBlock, zRoot, nRoot, &pSeg
150297 if( rc!=SQLITE_OK ) goto finished;
150298 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
150302 finished:
150303 rc2 = sqlite3_reset(pStmt);
150304 if( rc==SQLITE_DONE ) rc = rc2;
150306 return rc;
150310 ** Set up a cursor object for iterating through a full-text index or a
150311 ** single level therein.
150313 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
150314 Fts3Table *p, /* FTS3 table handle */
150315 int iLangid, /* Language-id to search */
150316 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
150317 int iLevel, /* Level of segments to scan */
150318 const char *zTerm, /* Term to query for */
150319 int nTerm, /* Size of zTerm in bytes */
150320 int isPrefix, /* True for a prefix search */
150321 int isScan, /* True to scan from zTerm to EOF */
150322 Fts3MultiSegReader *pCsr /* Cursor object to populate */
150324 assert( iIndex>=0 && iIndex<p->nIndex );
150325 assert( iLevel==FTS3_SEGCURSOR_ALL
150326 || iLevel==FTS3_SEGCURSOR_PENDING
150327 || iLevel>=0
150329 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
150330 assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
150331 assert( isPrefix==0 || isScan==0 );
150333 memset(pCsr, 0, sizeof(Fts3MultiSegReader));
150334 return fts3SegReaderCursor(
150335 p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
150340 ** In addition to its current configuration, have the Fts3MultiSegReader
150341 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
150343 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
150345 static int fts3SegReaderCursorAddZero(
150346 Fts3Table *p, /* FTS virtual table handle */
150347 int iLangid,
150348 const char *zTerm, /* Term to scan doclist of */
150349 int nTerm, /* Number of bytes in zTerm */
150350 Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
150352 return fts3SegReaderCursor(p,
150353 iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
150358 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
150359 ** if isPrefix is true, to scan the doclist for all terms for which
150360 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
150361 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
150362 ** an SQLite error code.
150364 ** It is the responsibility of the caller to free this object by eventually
150365 ** passing it to fts3SegReaderCursorFree()
150367 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
150368 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
150370 static int fts3TermSegReaderCursor(
150371 Fts3Cursor *pCsr, /* Virtual table cursor handle */
150372 const char *zTerm, /* Term to query for */
150373 int nTerm, /* Size of zTerm in bytes */
150374 int isPrefix, /* True for a prefix search */
150375 Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
150377 Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
150378 int rc = SQLITE_NOMEM; /* Return code */
150380 pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
150381 if( pSegcsr ){
150382 int i;
150383 int bFound = 0; /* True once an index has been found */
150384 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
150386 if( isPrefix ){
150387 for(i=1; bFound==0 && i<p->nIndex; i++){
150388 if( p->aIndex[i].nPrefix==nTerm ){
150389 bFound = 1;
150390 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
150391 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
150393 pSegcsr->bLookup = 1;
150397 for(i=1; bFound==0 && i<p->nIndex; i++){
150398 if( p->aIndex[i].nPrefix==nTerm+1 ){
150399 bFound = 1;
150400 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
150401 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
150403 if( rc==SQLITE_OK ){
150404 rc = fts3SegReaderCursorAddZero(
150405 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
150412 if( bFound==0 ){
150413 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
150414 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
150416 pSegcsr->bLookup = !isPrefix;
150420 *ppSegcsr = pSegcsr;
150421 return rc;
150425 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
150427 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
150428 sqlite3Fts3SegReaderFinish(pSegcsr);
150429 sqlite3_free(pSegcsr);
150433 ** This function retrieves the doclist for the specified term (or term
150434 ** prefix) from the database.
150436 static int fts3TermSelect(
150437 Fts3Table *p, /* Virtual table handle */
150438 Fts3PhraseToken *pTok, /* Token to query for */
150439 int iColumn, /* Column to query (or -ve for all columns) */
150440 int *pnOut, /* OUT: Size of buffer at *ppOut */
150441 char **ppOut /* OUT: Malloced result buffer */
150443 int rc; /* Return code */
150444 Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
150445 TermSelect tsc; /* Object for pair-wise doclist merging */
150446 Fts3SegFilter filter; /* Segment term filter configuration */
150448 pSegcsr = pTok->pSegcsr;
150449 memset(&tsc, 0, sizeof(TermSelect));
150451 filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
150452 | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
150453 | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
150454 | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
150455 filter.iCol = iColumn;
150456 filter.zTerm = pTok->z;
150457 filter.nTerm = pTok->n;
150459 rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
150460 while( SQLITE_OK==rc
150461 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
150463 rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
150466 if( rc==SQLITE_OK ){
150467 rc = fts3TermSelectFinishMerge(p, &tsc);
150469 if( rc==SQLITE_OK ){
150470 *ppOut = tsc.aaOutput[0];
150471 *pnOut = tsc.anOutput[0];
150472 }else{
150473 int i;
150474 for(i=0; i<SizeofArray(tsc.aaOutput); i++){
150475 sqlite3_free(tsc.aaOutput[i]);
150479 fts3SegReaderCursorFree(pSegcsr);
150480 pTok->pSegcsr = 0;
150481 return rc;
150485 ** This function counts the total number of docids in the doclist stored
150486 ** in buffer aList[], size nList bytes.
150488 ** If the isPoslist argument is true, then it is assumed that the doclist
150489 ** contains a position-list following each docid. Otherwise, it is assumed
150490 ** that the doclist is simply a list of docids stored as delta encoded
150491 ** varints.
150493 static int fts3DoclistCountDocids(char *aList, int nList){
150494 int nDoc = 0; /* Return value */
150495 if( aList ){
150496 char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
150497 char *p = aList; /* Cursor */
150498 while( p<aEnd ){
150499 nDoc++;
150500 while( (*p++)&0x80 ); /* Skip docid varint */
150501 fts3PoslistCopy(0, &p); /* Skip over position list */
150505 return nDoc;
150509 ** Advance the cursor to the next row in the %_content table that
150510 ** matches the search criteria. For a MATCH search, this will be
150511 ** the next row that matches. For a full-table scan, this will be
150512 ** simply the next row in the %_content table. For a docid lookup,
150513 ** this routine simply sets the EOF flag.
150515 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
150516 ** even if we reach end-of-file. The fts3EofMethod() will be called
150517 ** subsequently to determine whether or not an EOF was hit.
150519 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
150520 int rc;
150521 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
150522 if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
150523 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
150524 pCsr->isEof = 1;
150525 rc = sqlite3_reset(pCsr->pStmt);
150526 }else{
150527 pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
150528 rc = SQLITE_OK;
150530 }else{
150531 rc = fts3EvalNext((Fts3Cursor *)pCursor);
150533 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
150534 return rc;
150538 ** The following are copied from sqliteInt.h.
150540 ** Constants for the largest and smallest possible 64-bit signed integers.
150541 ** These macros are designed to work correctly on both 32-bit and 64-bit
150542 ** compilers.
150544 #ifndef SQLITE_AMALGAMATION
150545 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
150546 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
150547 #endif
150550 ** If the numeric type of argument pVal is "integer", then return it
150551 ** converted to a 64-bit signed integer. Otherwise, return a copy of
150552 ** the second parameter, iDefault.
150554 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
150555 if( pVal ){
150556 int eType = sqlite3_value_numeric_type(pVal);
150557 if( eType==SQLITE_INTEGER ){
150558 return sqlite3_value_int64(pVal);
150561 return iDefault;
150565 ** This is the xFilter interface for the virtual table. See
150566 ** the virtual table xFilter method documentation for additional
150567 ** information.
150569 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
150570 ** the %_content table.
150572 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
150573 ** in the %_content table.
150575 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
150576 ** column on the left-hand side of the MATCH operator is column
150577 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
150578 ** side of the MATCH operator.
150580 static int fts3FilterMethod(
150581 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
150582 int idxNum, /* Strategy index */
150583 const char *idxStr, /* Unused */
150584 int nVal, /* Number of elements in apVal */
150585 sqlite3_value **apVal /* Arguments for the indexing scheme */
150587 int rc = SQLITE_OK;
150588 char *zSql; /* SQL statement used to access %_content */
150589 int eSearch;
150590 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
150591 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
150593 sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
150594 sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
150595 sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
150596 sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
150597 int iIdx;
150599 UNUSED_PARAMETER(idxStr);
150600 UNUSED_PARAMETER(nVal);
150602 eSearch = (idxNum & 0x0000FFFF);
150603 assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
150604 assert( p->pSegments==0 );
150606 /* Collect arguments into local variables */
150607 iIdx = 0;
150608 if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
150609 if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
150610 if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
150611 if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
150612 assert( iIdx==nVal );
150614 /* In case the cursor has been used before, clear it now. */
150615 fts3ClearCursor(pCsr);
150617 /* Set the lower and upper bounds on docids to return */
150618 pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
150619 pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
150621 if( idxStr ){
150622 pCsr->bDesc = (idxStr[0]=='D');
150623 }else{
150624 pCsr->bDesc = p->bDescIdx;
150626 pCsr->eSearch = (i16)eSearch;
150628 if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
150629 int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
150630 const char *zQuery = (const char *)sqlite3_value_text(pCons);
150632 if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
150633 return SQLITE_NOMEM;
150636 pCsr->iLangid = 0;
150637 if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
150639 assert( p->base.zErrMsg==0 );
150640 rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
150641 p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
150642 &p->base.zErrMsg
150644 if( rc!=SQLITE_OK ){
150645 return rc;
150648 rc = fts3EvalStart(pCsr);
150649 sqlite3Fts3SegmentsClose(p);
150650 if( rc!=SQLITE_OK ) return rc;
150651 pCsr->pNextId = pCsr->aDoclist;
150652 pCsr->iPrevId = 0;
150655 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
150656 ** statement loops through all rows of the %_content table. For a
150657 ** full-text query or docid lookup, the statement retrieves a single
150658 ** row by docid.
150660 if( eSearch==FTS3_FULLSCAN_SEARCH ){
150661 if( pDocidGe || pDocidLe ){
150662 zSql = sqlite3_mprintf(
150663 "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
150664 p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
150665 (pCsr->bDesc ? "DESC" : "ASC")
150667 }else{
150668 zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
150669 p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
150672 if( zSql ){
150673 rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
150674 sqlite3_free(zSql);
150675 }else{
150676 rc = SQLITE_NOMEM;
150678 }else if( eSearch==FTS3_DOCID_SEARCH ){
150679 rc = fts3CursorSeekStmt(pCsr);
150680 if( rc==SQLITE_OK ){
150681 rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
150684 if( rc!=SQLITE_OK ) return rc;
150686 return fts3NextMethod(pCursor);
150690 ** This is the xEof method of the virtual table. SQLite calls this
150691 ** routine to find out if it has reached the end of a result set.
150693 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
150694 Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
150695 if( pCsr->isEof ){
150696 fts3ClearCursor(pCsr);
150697 pCsr->isEof = 1;
150699 return pCsr->isEof;
150703 ** This is the xRowid method. The SQLite core calls this routine to
150704 ** retrieve the rowid for the current row of the result set. fts3
150705 ** exposes %_content.docid as the rowid for the virtual table. The
150706 ** rowid should be written to *pRowid.
150708 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
150709 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
150710 *pRowid = pCsr->iPrevId;
150711 return SQLITE_OK;
150715 ** This is the xColumn method, called by SQLite to request a value from
150716 ** the row that the supplied cursor currently points to.
150718 ** If:
150720 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
150721 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
150722 ** (iCol == p->nColumn+1) -> Docid column
150723 ** (iCol == p->nColumn+2) -> Langid column
150725 static int fts3ColumnMethod(
150726 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
150727 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
150728 int iCol /* Index of column to read value from */
150730 int rc = SQLITE_OK; /* Return Code */
150731 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
150732 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
150734 /* The column value supplied by SQLite must be in range. */
150735 assert( iCol>=0 && iCol<=p->nColumn+2 );
150737 switch( iCol-p->nColumn ){
150738 case 0:
150739 /* The special 'table-name' column */
150740 sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
150741 break;
150743 case 1:
150744 /* The docid column */
150745 sqlite3_result_int64(pCtx, pCsr->iPrevId);
150746 break;
150748 case 2:
150749 if( pCsr->pExpr ){
150750 sqlite3_result_int64(pCtx, pCsr->iLangid);
150751 break;
150752 }else if( p->zLanguageid==0 ){
150753 sqlite3_result_int(pCtx, 0);
150754 break;
150755 }else{
150756 iCol = p->nColumn;
150757 /* fall-through */
150760 default:
150761 /* A user column. Or, if this is a full-table scan, possibly the
150762 ** language-id column. Seek the cursor. */
150763 rc = fts3CursorSeek(0, pCsr);
150764 if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
150765 sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
150767 break;
150770 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
150771 return rc;
150775 ** This function is the implementation of the xUpdate callback used by
150776 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
150777 ** inserted, updated or deleted.
150779 static int fts3UpdateMethod(
150780 sqlite3_vtab *pVtab, /* Virtual table handle */
150781 int nArg, /* Size of argument array */
150782 sqlite3_value **apVal, /* Array of arguments */
150783 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
150785 return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
150789 ** Implementation of xSync() method. Flush the contents of the pending-terms
150790 ** hash-table to the database.
150792 static int fts3SyncMethod(sqlite3_vtab *pVtab){
150794 /* Following an incremental-merge operation, assuming that the input
150795 ** segments are not completely consumed (the usual case), they are updated
150796 ** in place to remove the entries that have already been merged. This
150797 ** involves updating the leaf block that contains the smallest unmerged
150798 ** entry and each block (if any) between the leaf and the root node. So
150799 ** if the height of the input segment b-trees is N, and input segments
150800 ** are merged eight at a time, updating the input segments at the end
150801 ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
150802 ** small - often between 0 and 2. So the overhead of the incremental
150803 ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
150804 ** dwarfing the actual productive work accomplished, the incremental merge
150805 ** is only attempted if it will write at least 64 leaf blocks. Hence
150806 ** nMinMerge.
150808 ** Of course, updating the input segments also involves deleting a bunch
150809 ** of blocks from the segments table. But this is not considered overhead
150810 ** as it would also be required by a crisis-merge that used the same input
150811 ** segments.
150813 const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
150815 Fts3Table *p = (Fts3Table*)pVtab;
150816 int rc;
150817 i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
150819 rc = sqlite3Fts3PendingTermsFlush(p);
150820 if( rc==SQLITE_OK
150821 && p->nLeafAdd>(nMinMerge/16)
150822 && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
150824 int mxLevel = 0; /* Maximum relative level value in db */
150825 int A; /* Incr-merge parameter A */
150827 rc = sqlite3Fts3MaxLevel(p, &mxLevel);
150828 assert( rc==SQLITE_OK || mxLevel==0 );
150829 A = p->nLeafAdd * mxLevel;
150830 A += (A/2);
150831 if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
150833 sqlite3Fts3SegmentsClose(p);
150834 sqlite3_set_last_insert_rowid(p->db, iLastRowid);
150835 return rc;
150839 ** If it is currently unknown whether or not the FTS table has an %_stat
150840 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
150841 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
150842 ** if an error occurs.
150844 static int fts3SetHasStat(Fts3Table *p){
150845 int rc = SQLITE_OK;
150846 if( p->bHasStat==2 ){
150847 char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
150848 if( zTbl ){
150849 int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
150850 sqlite3_free(zTbl);
150851 p->bHasStat = (res==SQLITE_OK);
150852 }else{
150853 rc = SQLITE_NOMEM;
150856 return rc;
150860 ** Implementation of xBegin() method.
150862 static int fts3BeginMethod(sqlite3_vtab *pVtab){
150863 Fts3Table *p = (Fts3Table*)pVtab;
150864 UNUSED_PARAMETER(pVtab);
150865 assert( p->pSegments==0 );
150866 assert( p->nPendingData==0 );
150867 assert( p->inTransaction!=1 );
150868 TESTONLY( p->inTransaction = 1 );
150869 TESTONLY( p->mxSavepoint = -1; );
150870 p->nLeafAdd = 0;
150871 return fts3SetHasStat(p);
150875 ** Implementation of xCommit() method. This is a no-op. The contents of
150876 ** the pending-terms hash-table have already been flushed into the database
150877 ** by fts3SyncMethod().
150879 static int fts3CommitMethod(sqlite3_vtab *pVtab){
150880 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
150881 UNUSED_PARAMETER(pVtab);
150882 assert( p->nPendingData==0 );
150883 assert( p->inTransaction!=0 );
150884 assert( p->pSegments==0 );
150885 TESTONLY( p->inTransaction = 0 );
150886 TESTONLY( p->mxSavepoint = -1; );
150887 return SQLITE_OK;
150891 ** Implementation of xRollback(). Discard the contents of the pending-terms
150892 ** hash-table. Any changes made to the database are reverted by SQLite.
150894 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
150895 Fts3Table *p = (Fts3Table*)pVtab;
150896 sqlite3Fts3PendingTermsClear(p);
150897 assert( p->inTransaction!=0 );
150898 TESTONLY( p->inTransaction = 0 );
150899 TESTONLY( p->mxSavepoint = -1; );
150900 return SQLITE_OK;
150904 ** When called, *ppPoslist must point to the byte immediately following the
150905 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
150906 ** moves *ppPoslist so that it instead points to the first byte of the
150907 ** same position list.
150909 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
150910 char *p = &(*ppPoslist)[-2];
150911 char c = 0;
150913 /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
150914 while( p>pStart && (c=*p--)==0 );
150916 /* Search backwards for a varint with value zero (the end of the previous
150917 ** poslist). This is an 0x00 byte preceded by some byte that does not
150918 ** have the 0x80 bit set. */
150919 while( p>pStart && (*p & 0x80) | c ){
150920 c = *p--;
150922 assert( p==pStart || c==0 );
150924 /* At this point p points to that preceding byte without the 0x80 bit
150925 ** set. So to find the start of the poslist, skip forward 2 bytes then
150926 ** over a varint.
150928 ** Normally. The other case is that p==pStart and the poslist to return
150929 ** is the first in the doclist. In this case do not skip forward 2 bytes.
150930 ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
150931 ** is required for cases where the first byte of a doclist and the
150932 ** doclist is empty. For example, if the first docid is 10, a doclist
150933 ** that begins with:
150935 ** 0x0A 0x00 <next docid delta varint>
150937 if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
150938 while( *p++&0x80 );
150939 *ppPoslist = p;
150943 ** Helper function used by the implementation of the overloaded snippet(),
150944 ** offsets() and optimize() SQL functions.
150946 ** If the value passed as the third argument is a blob of size
150947 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
150948 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
150949 ** message is written to context pContext and SQLITE_ERROR returned. The
150950 ** string passed via zFunc is used as part of the error message.
150952 static int fts3FunctionArg(
150953 sqlite3_context *pContext, /* SQL function call context */
150954 const char *zFunc, /* Function name */
150955 sqlite3_value *pVal, /* argv[0] passed to function */
150956 Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
150958 int rc;
150959 *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
150960 if( (*ppCsr)!=0 ){
150961 rc = SQLITE_OK;
150962 }else{
150963 char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
150964 sqlite3_result_error(pContext, zErr, -1);
150965 sqlite3_free(zErr);
150966 rc = SQLITE_ERROR;
150968 return rc;
150972 ** Implementation of the snippet() function for FTS3
150974 static void fts3SnippetFunc(
150975 sqlite3_context *pContext, /* SQLite function call context */
150976 int nVal, /* Size of apVal[] array */
150977 sqlite3_value **apVal /* Array of arguments */
150979 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
150980 const char *zStart = "<b>";
150981 const char *zEnd = "</b>";
150982 const char *zEllipsis = "<b>...</b>";
150983 int iCol = -1;
150984 int nToken = 15; /* Default number of tokens in snippet */
150986 /* There must be at least one argument passed to this function (otherwise
150987 ** the non-overloaded version would have been called instead of this one).
150989 assert( nVal>=1 );
150991 if( nVal>6 ){
150992 sqlite3_result_error(pContext,
150993 "wrong number of arguments to function snippet()", -1);
150994 return;
150996 if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
150998 switch( nVal ){
150999 case 6: nToken = sqlite3_value_int(apVal[5]);
151000 case 5: iCol = sqlite3_value_int(apVal[4]);
151001 case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
151002 case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
151003 case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
151005 if( !zEllipsis || !zEnd || !zStart ){
151006 sqlite3_result_error_nomem(pContext);
151007 }else if( nToken==0 ){
151008 sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
151009 }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
151010 sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
151015 ** Implementation of the offsets() function for FTS3
151017 static void fts3OffsetsFunc(
151018 sqlite3_context *pContext, /* SQLite function call context */
151019 int nVal, /* Size of argument array */
151020 sqlite3_value **apVal /* Array of arguments */
151022 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
151024 UNUSED_PARAMETER(nVal);
151026 assert( nVal==1 );
151027 if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
151028 assert( pCsr );
151029 if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
151030 sqlite3Fts3Offsets(pContext, pCsr);
151035 ** Implementation of the special optimize() function for FTS3. This
151036 ** function merges all segments in the database to a single segment.
151037 ** Example usage is:
151039 ** SELECT optimize(t) FROM t LIMIT 1;
151041 ** where 't' is the name of an FTS3 table.
151043 static void fts3OptimizeFunc(
151044 sqlite3_context *pContext, /* SQLite function call context */
151045 int nVal, /* Size of argument array */
151046 sqlite3_value **apVal /* Array of arguments */
151048 int rc; /* Return code */
151049 Fts3Table *p; /* Virtual table handle */
151050 Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
151052 UNUSED_PARAMETER(nVal);
151054 assert( nVal==1 );
151055 if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
151056 p = (Fts3Table *)pCursor->base.pVtab;
151057 assert( p );
151059 rc = sqlite3Fts3Optimize(p);
151061 switch( rc ){
151062 case SQLITE_OK:
151063 sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
151064 break;
151065 case SQLITE_DONE:
151066 sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
151067 break;
151068 default:
151069 sqlite3_result_error_code(pContext, rc);
151070 break;
151075 ** Implementation of the matchinfo() function for FTS3
151077 static void fts3MatchinfoFunc(
151078 sqlite3_context *pContext, /* SQLite function call context */
151079 int nVal, /* Size of argument array */
151080 sqlite3_value **apVal /* Array of arguments */
151082 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
151083 assert( nVal==1 || nVal==2 );
151084 if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
151085 const char *zArg = 0;
151086 if( nVal>1 ){
151087 zArg = (const char *)sqlite3_value_text(apVal[1]);
151089 sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
151094 ** This routine implements the xFindFunction method for the FTS3
151095 ** virtual table.
151097 static int fts3FindFunctionMethod(
151098 sqlite3_vtab *pVtab, /* Virtual table handle */
151099 int nArg, /* Number of SQL function arguments */
151100 const char *zName, /* Name of SQL function */
151101 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
151102 void **ppArg /* Unused */
151104 struct Overloaded {
151105 const char *zName;
151106 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
151107 } aOverload[] = {
151108 { "snippet", fts3SnippetFunc },
151109 { "offsets", fts3OffsetsFunc },
151110 { "optimize", fts3OptimizeFunc },
151111 { "matchinfo", fts3MatchinfoFunc },
151113 int i; /* Iterator variable */
151115 UNUSED_PARAMETER(pVtab);
151116 UNUSED_PARAMETER(nArg);
151117 UNUSED_PARAMETER(ppArg);
151119 for(i=0; i<SizeofArray(aOverload); i++){
151120 if( strcmp(zName, aOverload[i].zName)==0 ){
151121 *pxFunc = aOverload[i].xFunc;
151122 return 1;
151126 /* No function of the specified name was found. Return 0. */
151127 return 0;
151131 ** Implementation of FTS3 xRename method. Rename an fts3 table.
151133 static int fts3RenameMethod(
151134 sqlite3_vtab *pVtab, /* Virtual table handle */
151135 const char *zName /* New name of table */
151137 Fts3Table *p = (Fts3Table *)pVtab;
151138 sqlite3 *db = p->db; /* Database connection */
151139 int rc; /* Return Code */
151141 /* At this point it must be known if the %_stat table exists or not.
151142 ** So bHasStat may not be 2. */
151143 rc = fts3SetHasStat(p);
151145 /* As it happens, the pending terms table is always empty here. This is
151146 ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
151147 ** always opens a savepoint transaction. And the xSavepoint() method
151148 ** flushes the pending terms table. But leave the (no-op) call to
151149 ** PendingTermsFlush() in in case that changes.
151151 assert( p->nPendingData==0 );
151152 if( rc==SQLITE_OK ){
151153 rc = sqlite3Fts3PendingTermsFlush(p);
151156 if( p->zContentTbl==0 ){
151157 fts3DbExec(&rc, db,
151158 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
151159 p->zDb, p->zName, zName
151163 if( p->bHasDocsize ){
151164 fts3DbExec(&rc, db,
151165 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
151166 p->zDb, p->zName, zName
151169 if( p->bHasStat ){
151170 fts3DbExec(&rc, db,
151171 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
151172 p->zDb, p->zName, zName
151175 fts3DbExec(&rc, db,
151176 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
151177 p->zDb, p->zName, zName
151179 fts3DbExec(&rc, db,
151180 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
151181 p->zDb, p->zName, zName
151183 return rc;
151187 ** The xSavepoint() method.
151189 ** Flush the contents of the pending-terms table to disk.
151191 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
151192 int rc = SQLITE_OK;
151193 UNUSED_PARAMETER(iSavepoint);
151194 assert( ((Fts3Table *)pVtab)->inTransaction );
151195 assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
151196 TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
151197 if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
151198 rc = fts3SyncMethod(pVtab);
151200 return rc;
151204 ** The xRelease() method.
151206 ** This is a no-op.
151208 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
151209 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
151210 UNUSED_PARAMETER(iSavepoint);
151211 UNUSED_PARAMETER(pVtab);
151212 assert( p->inTransaction );
151213 assert( p->mxSavepoint >= iSavepoint );
151214 TESTONLY( p->mxSavepoint = iSavepoint-1 );
151215 return SQLITE_OK;
151219 ** The xRollbackTo() method.
151221 ** Discard the contents of the pending terms table.
151223 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
151224 Fts3Table *p = (Fts3Table*)pVtab;
151225 UNUSED_PARAMETER(iSavepoint);
151226 assert( p->inTransaction );
151227 assert( p->mxSavepoint >= iSavepoint );
151228 TESTONLY( p->mxSavepoint = iSavepoint );
151229 sqlite3Fts3PendingTermsClear(p);
151230 return SQLITE_OK;
151233 static const sqlite3_module fts3Module = {
151234 /* iVersion */ 2,
151235 /* xCreate */ fts3CreateMethod,
151236 /* xConnect */ fts3ConnectMethod,
151237 /* xBestIndex */ fts3BestIndexMethod,
151238 /* xDisconnect */ fts3DisconnectMethod,
151239 /* xDestroy */ fts3DestroyMethod,
151240 /* xOpen */ fts3OpenMethod,
151241 /* xClose */ fts3CloseMethod,
151242 /* xFilter */ fts3FilterMethod,
151243 /* xNext */ fts3NextMethod,
151244 /* xEof */ fts3EofMethod,
151245 /* xColumn */ fts3ColumnMethod,
151246 /* xRowid */ fts3RowidMethod,
151247 /* xUpdate */ fts3UpdateMethod,
151248 /* xBegin */ fts3BeginMethod,
151249 /* xSync */ fts3SyncMethod,
151250 /* xCommit */ fts3CommitMethod,
151251 /* xRollback */ fts3RollbackMethod,
151252 /* xFindFunction */ fts3FindFunctionMethod,
151253 /* xRename */ fts3RenameMethod,
151254 /* xSavepoint */ fts3SavepointMethod,
151255 /* xRelease */ fts3ReleaseMethod,
151256 /* xRollbackTo */ fts3RollbackToMethod,
151260 ** This function is registered as the module destructor (called when an
151261 ** FTS3 enabled database connection is closed). It frees the memory
151262 ** allocated for the tokenizer hash table.
151264 static void hashDestroy(void *p){
151265 Fts3Hash *pHash = (Fts3Hash *)p;
151266 sqlite3Fts3HashClear(pHash);
151267 sqlite3_free(pHash);
151271 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
151272 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
151273 ** respectively. The following three forward declarations are for functions
151274 ** declared in these files used to retrieve the respective implementations.
151276 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
151277 ** to by the argument to point to the "simple" tokenizer implementation.
151278 ** And so on.
151280 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
151281 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
151282 #ifndef SQLITE_DISABLE_FTS3_UNICODE
151283 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
151284 #endif
151285 #ifdef SQLITE_ENABLE_ICU
151286 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
151287 #endif
151290 ** Initialize the fts3 extension. If this extension is built as part
151291 ** of the sqlite library, then this function is called directly by
151292 ** SQLite. If fts3 is built as a dynamically loadable extension, this
151293 ** function is called by the sqlite3_extension_init() entry point.
151295 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
151296 int rc = SQLITE_OK;
151297 Fts3Hash *pHash = 0;
151298 const sqlite3_tokenizer_module *pSimple = 0;
151299 const sqlite3_tokenizer_module *pPorter = 0;
151300 #ifndef SQLITE_DISABLE_FTS3_UNICODE
151301 const sqlite3_tokenizer_module *pUnicode = 0;
151302 #endif
151304 #ifdef SQLITE_ENABLE_ICU
151305 const sqlite3_tokenizer_module *pIcu = 0;
151306 sqlite3Fts3IcuTokenizerModule(&pIcu);
151307 #endif
151309 #ifndef SQLITE_DISABLE_FTS3_UNICODE
151310 sqlite3Fts3UnicodeTokenizer(&pUnicode);
151311 #endif
151313 #ifdef SQLITE_TEST
151314 rc = sqlite3Fts3InitTerm(db);
151315 if( rc!=SQLITE_OK ) return rc;
151316 #endif
151318 rc = sqlite3Fts3InitAux(db);
151319 if( rc!=SQLITE_OK ) return rc;
151321 sqlite3Fts3SimpleTokenizerModule(&pSimple);
151322 sqlite3Fts3PorterTokenizerModule(&pPorter);
151324 /* Allocate and initialize the hash-table used to store tokenizers. */
151325 pHash = sqlite3_malloc(sizeof(Fts3Hash));
151326 if( !pHash ){
151327 rc = SQLITE_NOMEM;
151328 }else{
151329 sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
151332 /* Load the built-in tokenizers into the hash table */
151333 if( rc==SQLITE_OK ){
151334 if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
151335 || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
151337 #ifndef SQLITE_DISABLE_FTS3_UNICODE
151338 || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
151339 #endif
151340 #ifdef SQLITE_ENABLE_ICU
151341 || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
151342 #endif
151344 rc = SQLITE_NOMEM;
151348 #ifdef SQLITE_TEST
151349 if( rc==SQLITE_OK ){
151350 rc = sqlite3Fts3ExprInitTestInterface(db);
151352 #endif
151354 /* Create the virtual table wrapper around the hash-table and overload
151355 ** the four scalar functions. If this is successful, register the
151356 ** module with sqlite.
151358 if( SQLITE_OK==rc
151359 && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
151360 && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
151361 && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
151362 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
151363 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
151364 && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
151366 rc = sqlite3_create_module_v2(
151367 db, "fts3", &fts3Module, (void *)pHash, hashDestroy
151369 if( rc==SQLITE_OK ){
151370 rc = sqlite3_create_module_v2(
151371 db, "fts4", &fts3Module, (void *)pHash, 0
151374 if( rc==SQLITE_OK ){
151375 rc = sqlite3Fts3InitTok(db, (void *)pHash);
151377 return rc;
151381 /* An error has occurred. Delete the hash table and return the error code. */
151382 assert( rc!=SQLITE_OK );
151383 if( pHash ){
151384 sqlite3Fts3HashClear(pHash);
151385 sqlite3_free(pHash);
151387 return rc;
151391 ** Allocate an Fts3MultiSegReader for each token in the expression headed
151392 ** by pExpr.
151394 ** An Fts3SegReader object is a cursor that can seek or scan a range of
151395 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
151396 ** Fts3SegReader objects internally to provide an interface to seek or scan
151397 ** within the union of all segments of a b-tree. Hence the name.
151399 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
151400 ** segment b-tree (if the term is not a prefix or it is a prefix for which
151401 ** there exists prefix b-tree of the right length) then it may be traversed
151402 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
151403 ** doclist and then traversed.
151405 static void fts3EvalAllocateReaders(
151406 Fts3Cursor *pCsr, /* FTS cursor handle */
151407 Fts3Expr *pExpr, /* Allocate readers for this expression */
151408 int *pnToken, /* OUT: Total number of tokens in phrase. */
151409 int *pnOr, /* OUT: Total number of OR nodes in expr. */
151410 int *pRc /* IN/OUT: Error code */
151412 if( pExpr && SQLITE_OK==*pRc ){
151413 if( pExpr->eType==FTSQUERY_PHRASE ){
151414 int i;
151415 int nToken = pExpr->pPhrase->nToken;
151416 *pnToken += nToken;
151417 for(i=0; i<nToken; i++){
151418 Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
151419 int rc = fts3TermSegReaderCursor(pCsr,
151420 pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
151422 if( rc!=SQLITE_OK ){
151423 *pRc = rc;
151424 return;
151427 assert( pExpr->pPhrase->iDoclistToken==0 );
151428 pExpr->pPhrase->iDoclistToken = -1;
151429 }else{
151430 *pnOr += (pExpr->eType==FTSQUERY_OR);
151431 fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
151432 fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
151438 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
151439 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
151441 ** This function assumes that pList points to a buffer allocated using
151442 ** sqlite3_malloc(). This function takes responsibility for eventually
151443 ** freeing the buffer.
151445 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
151447 static int fts3EvalPhraseMergeToken(
151448 Fts3Table *pTab, /* FTS Table pointer */
151449 Fts3Phrase *p, /* Phrase to merge pList/nList into */
151450 int iToken, /* Token pList/nList corresponds to */
151451 char *pList, /* Pointer to doclist */
151452 int nList /* Number of bytes in pList */
151454 int rc = SQLITE_OK;
151455 assert( iToken!=p->iDoclistToken );
151457 if( pList==0 ){
151458 sqlite3_free(p->doclist.aAll);
151459 p->doclist.aAll = 0;
151460 p->doclist.nAll = 0;
151463 else if( p->iDoclistToken<0 ){
151464 p->doclist.aAll = pList;
151465 p->doclist.nAll = nList;
151468 else if( p->doclist.aAll==0 ){
151469 sqlite3_free(pList);
151472 else {
151473 char *pLeft;
151474 char *pRight;
151475 int nLeft;
151476 int nRight;
151477 int nDiff;
151479 if( p->iDoclistToken<iToken ){
151480 pLeft = p->doclist.aAll;
151481 nLeft = p->doclist.nAll;
151482 pRight = pList;
151483 nRight = nList;
151484 nDiff = iToken - p->iDoclistToken;
151485 }else{
151486 pRight = p->doclist.aAll;
151487 nRight = p->doclist.nAll;
151488 pLeft = pList;
151489 nLeft = nList;
151490 nDiff = p->iDoclistToken - iToken;
151493 rc = fts3DoclistPhraseMerge(
151494 pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
151496 sqlite3_free(pLeft);
151497 p->doclist.aAll = pRight;
151498 p->doclist.nAll = nRight;
151501 if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
151502 return rc;
151506 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
151507 ** does not take deferred tokens into account.
151509 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
151511 static int fts3EvalPhraseLoad(
151512 Fts3Cursor *pCsr, /* FTS Cursor handle */
151513 Fts3Phrase *p /* Phrase object */
151515 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151516 int iToken;
151517 int rc = SQLITE_OK;
151519 for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
151520 Fts3PhraseToken *pToken = &p->aToken[iToken];
151521 assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
151523 if( pToken->pSegcsr ){
151524 int nThis = 0;
151525 char *pThis = 0;
151526 rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
151527 if( rc==SQLITE_OK ){
151528 rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
151531 assert( pToken->pSegcsr==0 );
151534 return rc;
151538 ** This function is called on each phrase after the position lists for
151539 ** any deferred tokens have been loaded into memory. It updates the phrases
151540 ** current position list to include only those positions that are really
151541 ** instances of the phrase (after considering deferred tokens). If this
151542 ** means that the phrase does not appear in the current row, doclist.pList
151543 ** and doclist.nList are both zeroed.
151545 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
151547 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
151548 int iToken; /* Used to iterate through phrase tokens */
151549 char *aPoslist = 0; /* Position list for deferred tokens */
151550 int nPoslist = 0; /* Number of bytes in aPoslist */
151551 int iPrev = -1; /* Token number of previous deferred token */
151553 assert( pPhrase->doclist.bFreeList==0 );
151555 for(iToken=0; iToken<pPhrase->nToken; iToken++){
151556 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
151557 Fts3DeferredToken *pDeferred = pToken->pDeferred;
151559 if( pDeferred ){
151560 char *pList;
151561 int nList;
151562 int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
151563 if( rc!=SQLITE_OK ) return rc;
151565 if( pList==0 ){
151566 sqlite3_free(aPoslist);
151567 pPhrase->doclist.pList = 0;
151568 pPhrase->doclist.nList = 0;
151569 return SQLITE_OK;
151571 }else if( aPoslist==0 ){
151572 aPoslist = pList;
151573 nPoslist = nList;
151575 }else{
151576 char *aOut = pList;
151577 char *p1 = aPoslist;
151578 char *p2 = aOut;
151580 assert( iPrev>=0 );
151581 fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
151582 sqlite3_free(aPoslist);
151583 aPoslist = pList;
151584 nPoslist = (int)(aOut - aPoslist);
151585 if( nPoslist==0 ){
151586 sqlite3_free(aPoslist);
151587 pPhrase->doclist.pList = 0;
151588 pPhrase->doclist.nList = 0;
151589 return SQLITE_OK;
151592 iPrev = iToken;
151596 if( iPrev>=0 ){
151597 int nMaxUndeferred = pPhrase->iDoclistToken;
151598 if( nMaxUndeferred<0 ){
151599 pPhrase->doclist.pList = aPoslist;
151600 pPhrase->doclist.nList = nPoslist;
151601 pPhrase->doclist.iDocid = pCsr->iPrevId;
151602 pPhrase->doclist.bFreeList = 1;
151603 }else{
151604 int nDistance;
151605 char *p1;
151606 char *p2;
151607 char *aOut;
151609 if( nMaxUndeferred>iPrev ){
151610 p1 = aPoslist;
151611 p2 = pPhrase->doclist.pList;
151612 nDistance = nMaxUndeferred - iPrev;
151613 }else{
151614 p1 = pPhrase->doclist.pList;
151615 p2 = aPoslist;
151616 nDistance = iPrev - nMaxUndeferred;
151619 aOut = (char *)sqlite3_malloc(nPoslist+8);
151620 if( !aOut ){
151621 sqlite3_free(aPoslist);
151622 return SQLITE_NOMEM;
151625 pPhrase->doclist.pList = aOut;
151626 if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
151627 pPhrase->doclist.bFreeList = 1;
151628 pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
151629 }else{
151630 sqlite3_free(aOut);
151631 pPhrase->doclist.pList = 0;
151632 pPhrase->doclist.nList = 0;
151634 sqlite3_free(aPoslist);
151638 return SQLITE_OK;
151642 ** Maximum number of tokens a phrase may have to be considered for the
151643 ** incremental doclists strategy.
151645 #define MAX_INCR_PHRASE_TOKENS 4
151648 ** This function is called for each Fts3Phrase in a full-text query
151649 ** expression to initialize the mechanism for returning rows. Once this
151650 ** function has been called successfully on an Fts3Phrase, it may be
151651 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
151653 ** If parameter bOptOk is true, then the phrase may (or may not) use the
151654 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
151655 ** memory within this call.
151657 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
151659 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
151660 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151661 int rc = SQLITE_OK; /* Error code */
151662 int i;
151664 /* Determine if doclists may be loaded from disk incrementally. This is
151665 ** possible if the bOptOk argument is true, the FTS doclists will be
151666 ** scanned in forward order, and the phrase consists of
151667 ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
151668 ** tokens or prefix tokens that cannot use a prefix-index. */
151669 int bHaveIncr = 0;
151670 int bIncrOk = (bOptOk
151671 && pCsr->bDesc==pTab->bDescIdx
151672 && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
151673 #ifdef SQLITE_TEST
151674 && pTab->bNoIncrDoclist==0
151675 #endif
151677 for(i=0; bIncrOk==1 && i<p->nToken; i++){
151678 Fts3PhraseToken *pToken = &p->aToken[i];
151679 if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
151680 bIncrOk = 0;
151682 if( pToken->pSegcsr ) bHaveIncr = 1;
151685 if( bIncrOk && bHaveIncr ){
151686 /* Use the incremental approach. */
151687 int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
151688 for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
151689 Fts3PhraseToken *pToken = &p->aToken[i];
151690 Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
151691 if( pSegcsr ){
151692 rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
151695 p->bIncr = 1;
151696 }else{
151697 /* Load the full doclist for the phrase into memory. */
151698 rc = fts3EvalPhraseLoad(pCsr, p);
151699 p->bIncr = 0;
151702 assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
151703 return rc;
151707 ** This function is used to iterate backwards (from the end to start)
151708 ** through doclists. It is used by this module to iterate through phrase
151709 ** doclists in reverse and by the fts3_write.c module to iterate through
151710 ** pending-terms lists when writing to databases with "order=desc".
151712 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
151713 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
151714 ** function iterates from the end of the doclist to the beginning.
151716 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
151717 int bDescIdx, /* True if the doclist is desc */
151718 char *aDoclist, /* Pointer to entire doclist */
151719 int nDoclist, /* Length of aDoclist in bytes */
151720 char **ppIter, /* IN/OUT: Iterator pointer */
151721 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
151722 int *pnList, /* OUT: List length pointer */
151723 u8 *pbEof /* OUT: End-of-file flag */
151725 char *p = *ppIter;
151727 assert( nDoclist>0 );
151728 assert( *pbEof==0 );
151729 assert( p || *piDocid==0 );
151730 assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
151732 if( p==0 ){
151733 sqlite3_int64 iDocid = 0;
151734 char *pNext = 0;
151735 char *pDocid = aDoclist;
151736 char *pEnd = &aDoclist[nDoclist];
151737 int iMul = 1;
151739 while( pDocid<pEnd ){
151740 sqlite3_int64 iDelta;
151741 pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
151742 iDocid += (iMul * iDelta);
151743 pNext = pDocid;
151744 fts3PoslistCopy(0, &pDocid);
151745 while( pDocid<pEnd && *pDocid==0 ) pDocid++;
151746 iMul = (bDescIdx ? -1 : 1);
151749 *pnList = (int)(pEnd - pNext);
151750 *ppIter = pNext;
151751 *piDocid = iDocid;
151752 }else{
151753 int iMul = (bDescIdx ? -1 : 1);
151754 sqlite3_int64 iDelta;
151755 fts3GetReverseVarint(&p, aDoclist, &iDelta);
151756 *piDocid -= (iMul * iDelta);
151758 if( p==aDoclist ){
151759 *pbEof = 1;
151760 }else{
151761 char *pSave = p;
151762 fts3ReversePoslist(aDoclist, &p);
151763 *pnList = (int)(pSave - p);
151765 *ppIter = p;
151770 ** Iterate forwards through a doclist.
151772 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
151773 int bDescIdx, /* True if the doclist is desc */
151774 char *aDoclist, /* Pointer to entire doclist */
151775 int nDoclist, /* Length of aDoclist in bytes */
151776 char **ppIter, /* IN/OUT: Iterator pointer */
151777 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
151778 u8 *pbEof /* OUT: End-of-file flag */
151780 char *p = *ppIter;
151782 assert( nDoclist>0 );
151783 assert( *pbEof==0 );
151784 assert( p || *piDocid==0 );
151785 assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
151787 if( p==0 ){
151788 p = aDoclist;
151789 p += sqlite3Fts3GetVarint(p, piDocid);
151790 }else{
151791 fts3PoslistCopy(0, &p);
151792 while( p<&aDoclist[nDoclist] && *p==0 ) p++;
151793 if( p>=&aDoclist[nDoclist] ){
151794 *pbEof = 1;
151795 }else{
151796 sqlite3_int64 iVar;
151797 p += sqlite3Fts3GetVarint(p, &iVar);
151798 *piDocid += ((bDescIdx ? -1 : 1) * iVar);
151802 *ppIter = p;
151806 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
151807 ** to true if EOF is reached.
151809 static void fts3EvalDlPhraseNext(
151810 Fts3Table *pTab,
151811 Fts3Doclist *pDL,
151812 u8 *pbEof
151814 char *pIter; /* Used to iterate through aAll */
151815 char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
151817 if( pDL->pNextDocid ){
151818 pIter = pDL->pNextDocid;
151819 }else{
151820 pIter = pDL->aAll;
151823 if( pIter>=pEnd ){
151824 /* We have already reached the end of this doclist. EOF. */
151825 *pbEof = 1;
151826 }else{
151827 sqlite3_int64 iDelta;
151828 pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
151829 if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
151830 pDL->iDocid += iDelta;
151831 }else{
151832 pDL->iDocid -= iDelta;
151834 pDL->pList = pIter;
151835 fts3PoslistCopy(0, &pIter);
151836 pDL->nList = (int)(pIter - pDL->pList);
151838 /* pIter now points just past the 0x00 that terminates the position-
151839 ** list for document pDL->iDocid. However, if this position-list was
151840 ** edited in place by fts3EvalNearTrim(), then pIter may not actually
151841 ** point to the start of the next docid value. The following line deals
151842 ** with this case by advancing pIter past the zero-padding added by
151843 ** fts3EvalNearTrim(). */
151844 while( pIter<pEnd && *pIter==0 ) pIter++;
151846 pDL->pNextDocid = pIter;
151847 assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
151848 *pbEof = 0;
151853 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
151855 typedef struct TokenDoclist TokenDoclist;
151856 struct TokenDoclist {
151857 int bIgnore;
151858 sqlite3_int64 iDocid;
151859 char *pList;
151860 int nList;
151864 ** Token pToken is an incrementally loaded token that is part of a
151865 ** multi-token phrase. Advance it to the next matching document in the
151866 ** database and populate output variable *p with the details of the new
151867 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
151869 ** If an error occurs, return an SQLite error code. Otherwise, return
151870 ** SQLITE_OK.
151872 static int incrPhraseTokenNext(
151873 Fts3Table *pTab, /* Virtual table handle */
151874 Fts3Phrase *pPhrase, /* Phrase to advance token of */
151875 int iToken, /* Specific token to advance */
151876 TokenDoclist *p, /* OUT: Docid and doclist for new entry */
151877 u8 *pbEof /* OUT: True if iterator is at EOF */
151879 int rc = SQLITE_OK;
151881 if( pPhrase->iDoclistToken==iToken ){
151882 assert( p->bIgnore==0 );
151883 assert( pPhrase->aToken[iToken].pSegcsr==0 );
151884 fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
151885 p->pList = pPhrase->doclist.pList;
151886 p->nList = pPhrase->doclist.nList;
151887 p->iDocid = pPhrase->doclist.iDocid;
151888 }else{
151889 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
151890 assert( pToken->pDeferred==0 );
151891 assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
151892 if( pToken->pSegcsr ){
151893 assert( p->bIgnore==0 );
151894 rc = sqlite3Fts3MsrIncrNext(
151895 pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
151897 if( p->pList==0 ) *pbEof = 1;
151898 }else{
151899 p->bIgnore = 1;
151903 return rc;
151908 ** The phrase iterator passed as the second argument:
151910 ** * features at least one token that uses an incremental doclist, and
151912 ** * does not contain any deferred tokens.
151914 ** Advance it to the next matching documnent in the database and populate
151915 ** the Fts3Doclist.pList and nList fields.
151917 ** If there is no "next" entry and no error occurs, then *pbEof is set to
151918 ** 1 before returning. Otherwise, if no error occurs and the iterator is
151919 ** successfully advanced, *pbEof is set to 0.
151921 ** If an error occurs, return an SQLite error code. Otherwise, return
151922 ** SQLITE_OK.
151924 static int fts3EvalIncrPhraseNext(
151925 Fts3Cursor *pCsr, /* FTS Cursor handle */
151926 Fts3Phrase *p, /* Phrase object to advance to next docid */
151927 u8 *pbEof /* OUT: Set to 1 if EOF */
151929 int rc = SQLITE_OK;
151930 Fts3Doclist *pDL = &p->doclist;
151931 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151932 u8 bEof = 0;
151934 /* This is only called if it is guaranteed that the phrase has at least
151935 ** one incremental token. In which case the bIncr flag is set. */
151936 assert( p->bIncr==1 );
151938 if( p->nToken==1 ){
151939 rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
151940 &pDL->iDocid, &pDL->pList, &pDL->nList
151942 if( pDL->pList==0 ) bEof = 1;
151943 }else{
151944 int bDescDoclist = pCsr->bDesc;
151945 struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
151947 memset(a, 0, sizeof(a));
151948 assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
151949 assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
151951 while( bEof==0 ){
151952 int bMaxSet = 0;
151953 sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
151954 int i; /* Used to iterate through tokens */
151956 /* Advance the iterator for each token in the phrase once. */
151957 for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
151958 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
151959 if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
151960 iMax = a[i].iDocid;
151961 bMaxSet = 1;
151964 assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
151965 assert( rc!=SQLITE_OK || bMaxSet );
151967 /* Keep advancing iterators until they all point to the same document */
151968 for(i=0; i<p->nToken; i++){
151969 while( rc==SQLITE_OK && bEof==0
151970 && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
151972 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
151973 if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
151974 iMax = a[i].iDocid;
151975 i = 0;
151980 /* Check if the current entries really are a phrase match */
151981 if( bEof==0 ){
151982 int nList = 0;
151983 int nByte = a[p->nToken-1].nList;
151984 char *aDoclist = sqlite3_malloc(nByte+1);
151985 if( !aDoclist ) return SQLITE_NOMEM;
151986 memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
151988 for(i=0; i<(p->nToken-1); i++){
151989 if( a[i].bIgnore==0 ){
151990 char *pL = a[i].pList;
151991 char *pR = aDoclist;
151992 char *pOut = aDoclist;
151993 int nDist = p->nToken-1-i;
151994 int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
151995 if( res==0 ) break;
151996 nList = (int)(pOut - aDoclist);
151999 if( i==(p->nToken-1) ){
152000 pDL->iDocid = iMax;
152001 pDL->pList = aDoclist;
152002 pDL->nList = nList;
152003 pDL->bFreeList = 1;
152004 break;
152006 sqlite3_free(aDoclist);
152011 *pbEof = bEof;
152012 return rc;
152016 ** Attempt to move the phrase iterator to point to the next matching docid.
152017 ** If an error occurs, return an SQLite error code. Otherwise, return
152018 ** SQLITE_OK.
152020 ** If there is no "next" entry and no error occurs, then *pbEof is set to
152021 ** 1 before returning. Otherwise, if no error occurs and the iterator is
152022 ** successfully advanced, *pbEof is set to 0.
152024 static int fts3EvalPhraseNext(
152025 Fts3Cursor *pCsr, /* FTS Cursor handle */
152026 Fts3Phrase *p, /* Phrase object to advance to next docid */
152027 u8 *pbEof /* OUT: Set to 1 if EOF */
152029 int rc = SQLITE_OK;
152030 Fts3Doclist *pDL = &p->doclist;
152031 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152033 if( p->bIncr ){
152034 rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
152035 }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
152036 sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
152037 &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
152039 pDL->pList = pDL->pNextDocid;
152040 }else{
152041 fts3EvalDlPhraseNext(pTab, pDL, pbEof);
152044 return rc;
152049 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
152050 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
152051 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
152052 ** expressions for which all descendent tokens are deferred.
152054 ** If parameter bOptOk is zero, then it is guaranteed that the
152055 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
152056 ** each phrase in the expression (subject to deferred token processing).
152057 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
152058 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
152060 ** If an error occurs within this function, *pRc is set to an SQLite error
152061 ** code before returning.
152063 static void fts3EvalStartReaders(
152064 Fts3Cursor *pCsr, /* FTS Cursor handle */
152065 Fts3Expr *pExpr, /* Expression to initialize phrases in */
152066 int *pRc /* IN/OUT: Error code */
152068 if( pExpr && SQLITE_OK==*pRc ){
152069 if( pExpr->eType==FTSQUERY_PHRASE ){
152070 int nToken = pExpr->pPhrase->nToken;
152071 if( nToken ){
152072 int i;
152073 for(i=0; i<nToken; i++){
152074 if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
152076 pExpr->bDeferred = (i==nToken);
152078 *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
152079 }else{
152080 fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
152081 fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
152082 pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
152088 ** An array of the following structures is assembled as part of the process
152089 ** of selecting tokens to defer before the query starts executing (as part
152090 ** of the xFilter() method). There is one element in the array for each
152091 ** token in the FTS expression.
152093 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
152094 ** to phrases that are connected only by AND and NEAR operators (not OR or
152095 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
152096 ** separately. The root of a tokens AND/NEAR cluster is stored in
152097 ** Fts3TokenAndCost.pRoot.
152099 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
152100 struct Fts3TokenAndCost {
152101 Fts3Phrase *pPhrase; /* The phrase the token belongs to */
152102 int iToken; /* Position of token in phrase */
152103 Fts3PhraseToken *pToken; /* The token itself */
152104 Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
152105 int nOvfl; /* Number of overflow pages to load doclist */
152106 int iCol; /* The column the token must match */
152110 ** This function is used to populate an allocated Fts3TokenAndCost array.
152112 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
152113 ** Otherwise, if an error occurs during execution, *pRc is set to an
152114 ** SQLite error code.
152116 static void fts3EvalTokenCosts(
152117 Fts3Cursor *pCsr, /* FTS Cursor handle */
152118 Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
152119 Fts3Expr *pExpr, /* Expression to consider */
152120 Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
152121 Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
152122 int *pRc /* IN/OUT: Error code */
152124 if( *pRc==SQLITE_OK ){
152125 if( pExpr->eType==FTSQUERY_PHRASE ){
152126 Fts3Phrase *pPhrase = pExpr->pPhrase;
152127 int i;
152128 for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
152129 Fts3TokenAndCost *pTC = (*ppTC)++;
152130 pTC->pPhrase = pPhrase;
152131 pTC->iToken = i;
152132 pTC->pRoot = pRoot;
152133 pTC->pToken = &pPhrase->aToken[i];
152134 pTC->iCol = pPhrase->iColumn;
152135 *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
152137 }else if( pExpr->eType!=FTSQUERY_NOT ){
152138 assert( pExpr->eType==FTSQUERY_OR
152139 || pExpr->eType==FTSQUERY_AND
152140 || pExpr->eType==FTSQUERY_NEAR
152142 assert( pExpr->pLeft && pExpr->pRight );
152143 if( pExpr->eType==FTSQUERY_OR ){
152144 pRoot = pExpr->pLeft;
152145 **ppOr = pRoot;
152146 (*ppOr)++;
152148 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
152149 if( pExpr->eType==FTSQUERY_OR ){
152150 pRoot = pExpr->pRight;
152151 **ppOr = pRoot;
152152 (*ppOr)++;
152154 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
152160 ** Determine the average document (row) size in pages. If successful,
152161 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
152162 ** an SQLite error code.
152164 ** The average document size in pages is calculated by first calculating
152165 ** determining the average size in bytes, B. If B is less than the amount
152166 ** of data that will fit on a single leaf page of an intkey table in
152167 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
152168 ** the number of overflow pages consumed by a record B bytes in size.
152170 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
152171 int rc = SQLITE_OK;
152172 if( pCsr->nRowAvg==0 ){
152173 /* The average document size, which is required to calculate the cost
152174 ** of each doclist, has not yet been determined. Read the required
152175 ** data from the %_stat table to calculate it.
152177 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
152178 ** varints, where nCol is the number of columns in the FTS3 table.
152179 ** The first varint is the number of documents currently stored in
152180 ** the table. The following nCol varints contain the total amount of
152181 ** data stored in all rows of each column of the table, from left
152182 ** to right.
152184 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
152185 sqlite3_stmt *pStmt;
152186 sqlite3_int64 nDoc = 0;
152187 sqlite3_int64 nByte = 0;
152188 const char *pEnd;
152189 const char *a;
152191 rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
152192 if( rc!=SQLITE_OK ) return rc;
152193 a = sqlite3_column_blob(pStmt, 0);
152194 assert( a );
152196 pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
152197 a += sqlite3Fts3GetVarint(a, &nDoc);
152198 while( a<pEnd ){
152199 a += sqlite3Fts3GetVarint(a, &nByte);
152201 if( nDoc==0 || nByte==0 ){
152202 sqlite3_reset(pStmt);
152203 return FTS_CORRUPT_VTAB;
152206 pCsr->nDoc = nDoc;
152207 pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
152208 assert( pCsr->nRowAvg>0 );
152209 rc = sqlite3_reset(pStmt);
152212 *pnPage = pCsr->nRowAvg;
152213 return rc;
152217 ** This function is called to select the tokens (if any) that will be
152218 ** deferred. The array aTC[] has already been populated when this is
152219 ** called.
152221 ** This function is called once for each AND/NEAR cluster in the
152222 ** expression. Each invocation determines which tokens to defer within
152223 ** the cluster with root node pRoot. See comments above the definition
152224 ** of struct Fts3TokenAndCost for more details.
152226 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
152227 ** called on each token to defer. Otherwise, an SQLite error code is
152228 ** returned.
152230 static int fts3EvalSelectDeferred(
152231 Fts3Cursor *pCsr, /* FTS Cursor handle */
152232 Fts3Expr *pRoot, /* Consider tokens with this root node */
152233 Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
152234 int nTC /* Number of entries in aTC[] */
152236 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152237 int nDocSize = 0; /* Number of pages per doc loaded */
152238 int rc = SQLITE_OK; /* Return code */
152239 int ii; /* Iterator variable for various purposes */
152240 int nOvfl = 0; /* Total overflow pages used by doclists */
152241 int nToken = 0; /* Total number of tokens in cluster */
152243 int nMinEst = 0; /* The minimum count for any phrase so far. */
152244 int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
152246 /* Tokens are never deferred for FTS tables created using the content=xxx
152247 ** option. The reason being that it is not guaranteed that the content
152248 ** table actually contains the same data as the index. To prevent this from
152249 ** causing any problems, the deferred token optimization is completely
152250 ** disabled for content=xxx tables. */
152251 if( pTab->zContentTbl ){
152252 return SQLITE_OK;
152255 /* Count the tokens in this AND/NEAR cluster. If none of the doclists
152256 ** associated with the tokens spill onto overflow pages, or if there is
152257 ** only 1 token, exit early. No tokens to defer in this case. */
152258 for(ii=0; ii<nTC; ii++){
152259 if( aTC[ii].pRoot==pRoot ){
152260 nOvfl += aTC[ii].nOvfl;
152261 nToken++;
152264 if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
152266 /* Obtain the average docsize (in pages). */
152267 rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
152268 assert( rc!=SQLITE_OK || nDocSize>0 );
152271 /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
152272 ** of the number of overflow pages that will be loaded by the pager layer
152273 ** to retrieve the entire doclist for the token from the full-text index.
152274 ** Load the doclists for tokens that are either:
152276 ** a. The cheapest token in the entire query (i.e. the one visited by the
152277 ** first iteration of this loop), or
152279 ** b. Part of a multi-token phrase.
152281 ** After each token doclist is loaded, merge it with the others from the
152282 ** same phrase and count the number of documents that the merged doclist
152283 ** contains. Set variable "nMinEst" to the smallest number of documents in
152284 ** any phrase doclist for which 1 or more token doclists have been loaded.
152285 ** Let nOther be the number of other phrases for which it is certain that
152286 ** one or more tokens will not be deferred.
152288 ** Then, for each token, defer it if loading the doclist would result in
152289 ** loading N or more overflow pages into memory, where N is computed as:
152291 ** (nMinEst + 4^nOther - 1) / (4^nOther)
152293 for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
152294 int iTC; /* Used to iterate through aTC[] array. */
152295 Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
152297 /* Set pTC to point to the cheapest remaining token. */
152298 for(iTC=0; iTC<nTC; iTC++){
152299 if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
152300 && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
152302 pTC = &aTC[iTC];
152305 assert( pTC );
152307 if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
152308 /* The number of overflow pages to load for this (and therefore all
152309 ** subsequent) tokens is greater than the estimated number of pages
152310 ** that will be loaded if all subsequent tokens are deferred.
152312 Fts3PhraseToken *pToken = pTC->pToken;
152313 rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
152314 fts3SegReaderCursorFree(pToken->pSegcsr);
152315 pToken->pSegcsr = 0;
152316 }else{
152317 /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
152318 ** for-loop. Except, limit the value to 2^24 to prevent it from
152319 ** overflowing the 32-bit integer it is stored in. */
152320 if( ii<12 ) nLoad4 = nLoad4*4;
152322 if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
152323 /* Either this is the cheapest token in the entire query, or it is
152324 ** part of a multi-token phrase. Either way, the entire doclist will
152325 ** (eventually) be loaded into memory. It may as well be now. */
152326 Fts3PhraseToken *pToken = pTC->pToken;
152327 int nList = 0;
152328 char *pList = 0;
152329 rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
152330 assert( rc==SQLITE_OK || pList==0 );
152331 if( rc==SQLITE_OK ){
152332 rc = fts3EvalPhraseMergeToken(
152333 pTab, pTC->pPhrase, pTC->iToken,pList,nList
152336 if( rc==SQLITE_OK ){
152337 int nCount;
152338 nCount = fts3DoclistCountDocids(
152339 pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
152341 if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
152345 pTC->pToken = 0;
152348 return rc;
152352 ** This function is called from within the xFilter method. It initializes
152353 ** the full-text query currently stored in pCsr->pExpr. To iterate through
152354 ** the results of a query, the caller does:
152356 ** fts3EvalStart(pCsr);
152357 ** while( 1 ){
152358 ** fts3EvalNext(pCsr);
152359 ** if( pCsr->bEof ) break;
152360 ** ... return row pCsr->iPrevId to the caller ...
152363 static int fts3EvalStart(Fts3Cursor *pCsr){
152364 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152365 int rc = SQLITE_OK;
152366 int nToken = 0;
152367 int nOr = 0;
152369 /* Allocate a MultiSegReader for each token in the expression. */
152370 fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
152372 /* Determine which, if any, tokens in the expression should be deferred. */
152373 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
152374 if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
152375 Fts3TokenAndCost *aTC;
152376 Fts3Expr **apOr;
152377 aTC = (Fts3TokenAndCost *)sqlite3_malloc(
152378 sizeof(Fts3TokenAndCost) * nToken
152379 + sizeof(Fts3Expr *) * nOr * 2
152381 apOr = (Fts3Expr **)&aTC[nToken];
152383 if( !aTC ){
152384 rc = SQLITE_NOMEM;
152385 }else{
152386 int ii;
152387 Fts3TokenAndCost *pTC = aTC;
152388 Fts3Expr **ppOr = apOr;
152390 fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
152391 nToken = (int)(pTC-aTC);
152392 nOr = (int)(ppOr-apOr);
152394 if( rc==SQLITE_OK ){
152395 rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
152396 for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
152397 rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
152401 sqlite3_free(aTC);
152404 #endif
152406 fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
152407 return rc;
152411 ** Invalidate the current position list for phrase pPhrase.
152413 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
152414 if( pPhrase->doclist.bFreeList ){
152415 sqlite3_free(pPhrase->doclist.pList);
152417 pPhrase->doclist.pList = 0;
152418 pPhrase->doclist.nList = 0;
152419 pPhrase->doclist.bFreeList = 0;
152423 ** This function is called to edit the position list associated with
152424 ** the phrase object passed as the fifth argument according to a NEAR
152425 ** condition. For example:
152427 ** abc NEAR/5 "def ghi"
152429 ** Parameter nNear is passed the NEAR distance of the expression (5 in
152430 ** the example above). When this function is called, *paPoslist points to
152431 ** the position list, and *pnToken is the number of phrase tokens in, the
152432 ** phrase on the other side of the NEAR operator to pPhrase. For example,
152433 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
152434 ** the position list associated with phrase "abc".
152436 ** All positions in the pPhrase position list that are not sufficiently
152437 ** close to a position in the *paPoslist position list are removed. If this
152438 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
152440 ** Before returning, *paPoslist is set to point to the position lsit
152441 ** associated with pPhrase. And *pnToken is set to the number of tokens in
152442 ** pPhrase.
152444 static int fts3EvalNearTrim(
152445 int nNear, /* NEAR distance. As in "NEAR/nNear". */
152446 char *aTmp, /* Temporary space to use */
152447 char **paPoslist, /* IN/OUT: Position list */
152448 int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
152449 Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
152451 int nParam1 = nNear + pPhrase->nToken;
152452 int nParam2 = nNear + *pnToken;
152453 int nNew;
152454 char *p2;
152455 char *pOut;
152456 int res;
152458 assert( pPhrase->doclist.pList );
152460 p2 = pOut = pPhrase->doclist.pList;
152461 res = fts3PoslistNearMerge(
152462 &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
152464 if( res ){
152465 nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
152466 assert( pPhrase->doclist.pList[nNew]=='\0' );
152467 assert( nNew<=pPhrase->doclist.nList && nNew>0 );
152468 memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
152469 pPhrase->doclist.nList = nNew;
152470 *paPoslist = pPhrase->doclist.pList;
152471 *pnToken = pPhrase->nToken;
152474 return res;
152478 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
152479 ** Otherwise, it advances the expression passed as the second argument to
152480 ** point to the next matching row in the database. Expressions iterate through
152481 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
152482 ** or descending if it is non-zero.
152484 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
152485 ** successful, the following variables in pExpr are set:
152487 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
152488 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
152490 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
152491 ** at EOF, then the following variables are populated with the position list
152492 ** for the phrase for the visited row:
152494 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
152495 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
152497 ** It says above that this function advances the expression to the next
152498 ** matching row. This is usually true, but there are the following exceptions:
152500 ** 1. Deferred tokens are not taken into account. If a phrase consists
152501 ** entirely of deferred tokens, it is assumed to match every row in
152502 ** the db. In this case the position-list is not populated at all.
152504 ** Or, if a phrase contains one or more deferred tokens and one or
152505 ** more non-deferred tokens, then the expression is advanced to the
152506 ** next possible match, considering only non-deferred tokens. In other
152507 ** words, if the phrase is "A B C", and "B" is deferred, the expression
152508 ** is advanced to the next row that contains an instance of "A * C",
152509 ** where "*" may match any single token. The position list in this case
152510 ** is populated as for "A * C" before returning.
152512 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
152513 ** advanced to point to the next row that matches "x AND y".
152515 ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
152516 ** really a match, taking into account deferred tokens and NEAR operators.
152518 static void fts3EvalNextRow(
152519 Fts3Cursor *pCsr, /* FTS Cursor handle */
152520 Fts3Expr *pExpr, /* Expr. to advance to next matching row */
152521 int *pRc /* IN/OUT: Error code */
152523 if( *pRc==SQLITE_OK ){
152524 int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
152525 assert( pExpr->bEof==0 );
152526 pExpr->bStart = 1;
152528 switch( pExpr->eType ){
152529 case FTSQUERY_NEAR:
152530 case FTSQUERY_AND: {
152531 Fts3Expr *pLeft = pExpr->pLeft;
152532 Fts3Expr *pRight = pExpr->pRight;
152533 assert( !pLeft->bDeferred || !pRight->bDeferred );
152535 if( pLeft->bDeferred ){
152536 /* LHS is entirely deferred. So we assume it matches every row.
152537 ** Advance the RHS iterator to find the next row visited. */
152538 fts3EvalNextRow(pCsr, pRight, pRc);
152539 pExpr->iDocid = pRight->iDocid;
152540 pExpr->bEof = pRight->bEof;
152541 }else if( pRight->bDeferred ){
152542 /* RHS is entirely deferred. So we assume it matches every row.
152543 ** Advance the LHS iterator to find the next row visited. */
152544 fts3EvalNextRow(pCsr, pLeft, pRc);
152545 pExpr->iDocid = pLeft->iDocid;
152546 pExpr->bEof = pLeft->bEof;
152547 }else{
152548 /* Neither the RHS or LHS are deferred. */
152549 fts3EvalNextRow(pCsr, pLeft, pRc);
152550 fts3EvalNextRow(pCsr, pRight, pRc);
152551 while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
152552 sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
152553 if( iDiff==0 ) break;
152554 if( iDiff<0 ){
152555 fts3EvalNextRow(pCsr, pLeft, pRc);
152556 }else{
152557 fts3EvalNextRow(pCsr, pRight, pRc);
152560 pExpr->iDocid = pLeft->iDocid;
152561 pExpr->bEof = (pLeft->bEof || pRight->bEof);
152562 if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
152563 assert( pRight->eType==FTSQUERY_PHRASE );
152564 if( pRight->pPhrase->doclist.aAll ){
152565 Fts3Doclist *pDl = &pRight->pPhrase->doclist;
152566 while( *pRc==SQLITE_OK && pRight->bEof==0 ){
152567 memset(pDl->pList, 0, pDl->nList);
152568 fts3EvalNextRow(pCsr, pRight, pRc);
152571 if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
152572 Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
152573 while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
152574 memset(pDl->pList, 0, pDl->nList);
152575 fts3EvalNextRow(pCsr, pLeft, pRc);
152580 break;
152583 case FTSQUERY_OR: {
152584 Fts3Expr *pLeft = pExpr->pLeft;
152585 Fts3Expr *pRight = pExpr->pRight;
152586 sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
152588 assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
152589 assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
152591 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
152592 fts3EvalNextRow(pCsr, pLeft, pRc);
152593 }else if( pLeft->bEof || iCmp>0 ){
152594 fts3EvalNextRow(pCsr, pRight, pRc);
152595 }else{
152596 fts3EvalNextRow(pCsr, pLeft, pRc);
152597 fts3EvalNextRow(pCsr, pRight, pRc);
152600 pExpr->bEof = (pLeft->bEof && pRight->bEof);
152601 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
152602 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
152603 pExpr->iDocid = pLeft->iDocid;
152604 }else{
152605 pExpr->iDocid = pRight->iDocid;
152608 break;
152611 case FTSQUERY_NOT: {
152612 Fts3Expr *pLeft = pExpr->pLeft;
152613 Fts3Expr *pRight = pExpr->pRight;
152615 if( pRight->bStart==0 ){
152616 fts3EvalNextRow(pCsr, pRight, pRc);
152617 assert( *pRc!=SQLITE_OK || pRight->bStart );
152620 fts3EvalNextRow(pCsr, pLeft, pRc);
152621 if( pLeft->bEof==0 ){
152622 while( !*pRc
152623 && !pRight->bEof
152624 && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
152626 fts3EvalNextRow(pCsr, pRight, pRc);
152629 pExpr->iDocid = pLeft->iDocid;
152630 pExpr->bEof = pLeft->bEof;
152631 break;
152634 default: {
152635 Fts3Phrase *pPhrase = pExpr->pPhrase;
152636 fts3EvalInvalidatePoslist(pPhrase);
152637 *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
152638 pExpr->iDocid = pPhrase->doclist.iDocid;
152639 break;
152646 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
152647 ** cluster, then this function returns 1 immediately.
152649 ** Otherwise, it checks if the current row really does match the NEAR
152650 ** expression, using the data currently stored in the position lists
152651 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
152653 ** If the current row is a match, the position list associated with each
152654 ** phrase in the NEAR expression is edited in place to contain only those
152655 ** phrase instances sufficiently close to their peers to satisfy all NEAR
152656 ** constraints. In this case it returns 1. If the NEAR expression does not
152657 ** match the current row, 0 is returned. The position lists may or may not
152658 ** be edited if 0 is returned.
152660 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
152661 int res = 1;
152663 /* The following block runs if pExpr is the root of a NEAR query.
152664 ** For example, the query:
152666 ** "w" NEAR "x" NEAR "y" NEAR "z"
152668 ** which is represented in tree form as:
152671 ** +--NEAR--+ <-- root of NEAR query
152672 ** | |
152673 ** +--NEAR--+ "z"
152674 ** | |
152675 ** +--NEAR--+ "y"
152676 ** | |
152677 ** "w" "x"
152679 ** The right-hand child of a NEAR node is always a phrase. The
152680 ** left-hand child may be either a phrase or a NEAR node. There are
152681 ** no exceptions to this - it's the way the parser in fts3_expr.c works.
152683 if( *pRc==SQLITE_OK
152684 && pExpr->eType==FTSQUERY_NEAR
152685 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
152687 Fts3Expr *p;
152688 int nTmp = 0; /* Bytes of temp space */
152689 char *aTmp; /* Temp space for PoslistNearMerge() */
152691 /* Allocate temporary working space. */
152692 for(p=pExpr; p->pLeft; p=p->pLeft){
152693 assert( p->pRight->pPhrase->doclist.nList>0 );
152694 nTmp += p->pRight->pPhrase->doclist.nList;
152696 nTmp += p->pPhrase->doclist.nList;
152697 aTmp = sqlite3_malloc(nTmp*2);
152698 if( !aTmp ){
152699 *pRc = SQLITE_NOMEM;
152700 res = 0;
152701 }else{
152702 char *aPoslist = p->pPhrase->doclist.pList;
152703 int nToken = p->pPhrase->nToken;
152705 for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
152706 Fts3Phrase *pPhrase = p->pRight->pPhrase;
152707 int nNear = p->nNear;
152708 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
152711 aPoslist = pExpr->pRight->pPhrase->doclist.pList;
152712 nToken = pExpr->pRight->pPhrase->nToken;
152713 for(p=pExpr->pLeft; p && res; p=p->pLeft){
152714 int nNear;
152715 Fts3Phrase *pPhrase;
152716 assert( p->pParent && p->pParent->pLeft==p );
152717 nNear = p->pParent->nNear;
152718 pPhrase = (
152719 p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
152721 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
152725 sqlite3_free(aTmp);
152728 return res;
152732 ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
152733 ** Assuming no error occurs or has occurred, It returns non-zero if the
152734 ** expression passed as the second argument matches the row that pCsr
152735 ** currently points to, or zero if it does not.
152737 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
152738 ** If an error occurs during execution of this function, *pRc is set to
152739 ** the appropriate SQLite error code. In this case the returned value is
152740 ** undefined.
152742 static int fts3EvalTestExpr(
152743 Fts3Cursor *pCsr, /* FTS cursor handle */
152744 Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
152745 int *pRc /* IN/OUT: Error code */
152747 int bHit = 1; /* Return value */
152748 if( *pRc==SQLITE_OK ){
152749 switch( pExpr->eType ){
152750 case FTSQUERY_NEAR:
152751 case FTSQUERY_AND:
152752 bHit = (
152753 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
152754 && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
152755 && fts3EvalNearTest(pExpr, pRc)
152758 /* If the NEAR expression does not match any rows, zero the doclist for
152759 ** all phrases involved in the NEAR. This is because the snippet(),
152760 ** offsets() and matchinfo() functions are not supposed to recognize
152761 ** any instances of phrases that are part of unmatched NEAR queries.
152762 ** For example if this expression:
152764 ** ... MATCH 'a OR (b NEAR c)'
152766 ** is matched against a row containing:
152768 ** 'a b d e'
152770 ** then any snippet() should ony highlight the "a" term, not the "b"
152771 ** (as "b" is part of a non-matching NEAR clause).
152773 if( bHit==0
152774 && pExpr->eType==FTSQUERY_NEAR
152775 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
152777 Fts3Expr *p;
152778 for(p=pExpr; p->pPhrase==0; p=p->pLeft){
152779 if( p->pRight->iDocid==pCsr->iPrevId ){
152780 fts3EvalInvalidatePoslist(p->pRight->pPhrase);
152783 if( p->iDocid==pCsr->iPrevId ){
152784 fts3EvalInvalidatePoslist(p->pPhrase);
152788 break;
152790 case FTSQUERY_OR: {
152791 int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
152792 int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
152793 bHit = bHit1 || bHit2;
152794 break;
152797 case FTSQUERY_NOT:
152798 bHit = (
152799 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
152800 && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
152802 break;
152804 default: {
152805 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
152806 if( pCsr->pDeferred
152807 && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
152809 Fts3Phrase *pPhrase = pExpr->pPhrase;
152810 assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
152811 if( pExpr->bDeferred ){
152812 fts3EvalInvalidatePoslist(pPhrase);
152814 *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
152815 bHit = (pPhrase->doclist.pList!=0);
152816 pExpr->iDocid = pCsr->iPrevId;
152817 }else
152818 #endif
152820 bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
152822 break;
152826 return bHit;
152830 ** This function is called as the second part of each xNext operation when
152831 ** iterating through the results of a full-text query. At this point the
152832 ** cursor points to a row that matches the query expression, with the
152833 ** following caveats:
152835 ** * Up until this point, "NEAR" operators in the expression have been
152836 ** treated as "AND".
152838 ** * Deferred tokens have not yet been considered.
152840 ** If *pRc is not SQLITE_OK when this function is called, it immediately
152841 ** returns 0. Otherwise, it tests whether or not after considering NEAR
152842 ** operators and deferred tokens the current row is still a match for the
152843 ** expression. It returns 1 if both of the following are true:
152845 ** 1. *pRc is SQLITE_OK when this function returns, and
152847 ** 2. After scanning the current FTS table row for the deferred tokens,
152848 ** it is determined that the row does *not* match the query.
152850 ** Or, if no error occurs and it seems the current row does match the FTS
152851 ** query, return 0.
152853 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
152854 int rc = *pRc;
152855 int bMiss = 0;
152856 if( rc==SQLITE_OK ){
152858 /* If there are one or more deferred tokens, load the current row into
152859 ** memory and scan it to determine the position list for each deferred
152860 ** token. Then, see if this row is really a match, considering deferred
152861 ** tokens and NEAR operators (neither of which were taken into account
152862 ** earlier, by fts3EvalNextRow()).
152864 if( pCsr->pDeferred ){
152865 rc = fts3CursorSeek(0, pCsr);
152866 if( rc==SQLITE_OK ){
152867 rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
152870 bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
152872 /* Free the position-lists accumulated for each deferred token above. */
152873 sqlite3Fts3FreeDeferredDoclists(pCsr);
152874 *pRc = rc;
152876 return (rc==SQLITE_OK && bMiss);
152880 ** Advance to the next document that matches the FTS expression in
152881 ** Fts3Cursor.pExpr.
152883 static int fts3EvalNext(Fts3Cursor *pCsr){
152884 int rc = SQLITE_OK; /* Return Code */
152885 Fts3Expr *pExpr = pCsr->pExpr;
152886 assert( pCsr->isEof==0 );
152887 if( pExpr==0 ){
152888 pCsr->isEof = 1;
152889 }else{
152891 if( pCsr->isRequireSeek==0 ){
152892 sqlite3_reset(pCsr->pStmt);
152894 assert( sqlite3_data_count(pCsr->pStmt)==0 );
152895 fts3EvalNextRow(pCsr, pExpr, &rc);
152896 pCsr->isEof = pExpr->bEof;
152897 pCsr->isRequireSeek = 1;
152898 pCsr->isMatchinfoNeeded = 1;
152899 pCsr->iPrevId = pExpr->iDocid;
152900 }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
152903 /* Check if the cursor is past the end of the docid range specified
152904 ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
152905 if( rc==SQLITE_OK && (
152906 (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
152907 || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
152909 pCsr->isEof = 1;
152912 return rc;
152916 ** Restart interation for expression pExpr so that the next call to
152917 ** fts3EvalNext() visits the first row. Do not allow incremental
152918 ** loading or merging of phrase doclists for this iteration.
152920 ** If *pRc is other than SQLITE_OK when this function is called, it is
152921 ** a no-op. If an error occurs within this function, *pRc is set to an
152922 ** SQLite error code before returning.
152924 static void fts3EvalRestart(
152925 Fts3Cursor *pCsr,
152926 Fts3Expr *pExpr,
152927 int *pRc
152929 if( pExpr && *pRc==SQLITE_OK ){
152930 Fts3Phrase *pPhrase = pExpr->pPhrase;
152932 if( pPhrase ){
152933 fts3EvalInvalidatePoslist(pPhrase);
152934 if( pPhrase->bIncr ){
152935 int i;
152936 for(i=0; i<pPhrase->nToken; i++){
152937 Fts3PhraseToken *pToken = &pPhrase->aToken[i];
152938 assert( pToken->pDeferred==0 );
152939 if( pToken->pSegcsr ){
152940 sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
152943 *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
152945 pPhrase->doclist.pNextDocid = 0;
152946 pPhrase->doclist.iDocid = 0;
152947 pPhrase->pOrPoslist = 0;
152950 pExpr->iDocid = 0;
152951 pExpr->bEof = 0;
152952 pExpr->bStart = 0;
152954 fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
152955 fts3EvalRestart(pCsr, pExpr->pRight, pRc);
152960 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
152961 ** expression rooted at pExpr, the cursor iterates through all rows matched
152962 ** by pExpr, calling this function for each row. This function increments
152963 ** the values in Fts3Expr.aMI[] according to the position-list currently
152964 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
152965 ** expression nodes.
152967 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
152968 if( pExpr ){
152969 Fts3Phrase *pPhrase = pExpr->pPhrase;
152970 if( pPhrase && pPhrase->doclist.pList ){
152971 int iCol = 0;
152972 char *p = pPhrase->doclist.pList;
152974 assert( *p );
152975 while( 1 ){
152976 u8 c = 0;
152977 int iCnt = 0;
152978 while( 0xFE & (*p | c) ){
152979 if( (c&0x80)==0 ) iCnt++;
152980 c = *p++ & 0x80;
152983 /* aMI[iCol*3 + 1] = Number of occurrences
152984 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
152986 pExpr->aMI[iCol*3 + 1] += iCnt;
152987 pExpr->aMI[iCol*3 + 2] += (iCnt>0);
152988 if( *p==0x00 ) break;
152990 p += fts3GetVarint32(p, &iCol);
152994 fts3EvalUpdateCounts(pExpr->pLeft);
152995 fts3EvalUpdateCounts(pExpr->pRight);
153000 ** Expression pExpr must be of type FTSQUERY_PHRASE.
153002 ** If it is not already allocated and populated, this function allocates and
153003 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
153004 ** of a NEAR expression, then it also allocates and populates the same array
153005 ** for all other phrases that are part of the NEAR expression.
153007 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
153008 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
153010 static int fts3EvalGatherStats(
153011 Fts3Cursor *pCsr, /* Cursor object */
153012 Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
153014 int rc = SQLITE_OK; /* Return code */
153016 assert( pExpr->eType==FTSQUERY_PHRASE );
153017 if( pExpr->aMI==0 ){
153018 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
153019 Fts3Expr *pRoot; /* Root of NEAR expression */
153020 Fts3Expr *p; /* Iterator used for several purposes */
153022 sqlite3_int64 iPrevId = pCsr->iPrevId;
153023 sqlite3_int64 iDocid;
153024 u8 bEof;
153026 /* Find the root of the NEAR expression */
153027 pRoot = pExpr;
153028 while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
153029 pRoot = pRoot->pParent;
153031 iDocid = pRoot->iDocid;
153032 bEof = pRoot->bEof;
153033 assert( pRoot->bStart );
153035 /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
153036 for(p=pRoot; p; p=p->pLeft){
153037 Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
153038 assert( pE->aMI==0 );
153039 pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
153040 if( !pE->aMI ) return SQLITE_NOMEM;
153041 memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
153044 fts3EvalRestart(pCsr, pRoot, &rc);
153046 while( pCsr->isEof==0 && rc==SQLITE_OK ){
153049 /* Ensure the %_content statement is reset. */
153050 if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
153051 assert( sqlite3_data_count(pCsr->pStmt)==0 );
153053 /* Advance to the next document */
153054 fts3EvalNextRow(pCsr, pRoot, &rc);
153055 pCsr->isEof = pRoot->bEof;
153056 pCsr->isRequireSeek = 1;
153057 pCsr->isMatchinfoNeeded = 1;
153058 pCsr->iPrevId = pRoot->iDocid;
153059 }while( pCsr->isEof==0
153060 && pRoot->eType==FTSQUERY_NEAR
153061 && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
153064 if( rc==SQLITE_OK && pCsr->isEof==0 ){
153065 fts3EvalUpdateCounts(pRoot);
153069 pCsr->isEof = 0;
153070 pCsr->iPrevId = iPrevId;
153072 if( bEof ){
153073 pRoot->bEof = bEof;
153074 }else{
153075 /* Caution: pRoot may iterate through docids in ascending or descending
153076 ** order. For this reason, even though it seems more defensive, the
153077 ** do loop can not be written:
153079 ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
153081 fts3EvalRestart(pCsr, pRoot, &rc);
153083 fts3EvalNextRow(pCsr, pRoot, &rc);
153084 assert( pRoot->bEof==0 );
153085 }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
153088 return rc;
153092 ** This function is used by the matchinfo() module to query a phrase
153093 ** expression node for the following information:
153095 ** 1. The total number of occurrences of the phrase in each column of
153096 ** the FTS table (considering all rows), and
153098 ** 2. For each column, the number of rows in the table for which the
153099 ** column contains at least one instance of the phrase.
153101 ** If no error occurs, SQLITE_OK is returned and the values for each column
153102 ** written into the array aiOut as follows:
153104 ** aiOut[iCol*3 + 1] = Number of occurrences
153105 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
153107 ** Caveats:
153109 ** * If a phrase consists entirely of deferred tokens, then all output
153110 ** values are set to the number of documents in the table. In other
153111 ** words we assume that very common tokens occur exactly once in each
153112 ** column of each row of the table.
153114 ** * If a phrase contains some deferred tokens (and some non-deferred
153115 ** tokens), count the potential occurrence identified by considering
153116 ** the non-deferred tokens instead of actual phrase occurrences.
153118 ** * If the phrase is part of a NEAR expression, then only phrase instances
153119 ** that meet the NEAR constraint are included in the counts.
153121 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
153122 Fts3Cursor *pCsr, /* FTS cursor handle */
153123 Fts3Expr *pExpr, /* Phrase expression */
153124 u32 *aiOut /* Array to write results into (see above) */
153126 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
153127 int rc = SQLITE_OK;
153128 int iCol;
153130 if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
153131 assert( pCsr->nDoc>0 );
153132 for(iCol=0; iCol<pTab->nColumn; iCol++){
153133 aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
153134 aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
153136 }else{
153137 rc = fts3EvalGatherStats(pCsr, pExpr);
153138 if( rc==SQLITE_OK ){
153139 assert( pExpr->aMI );
153140 for(iCol=0; iCol<pTab->nColumn; iCol++){
153141 aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
153142 aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
153147 return rc;
153151 ** The expression pExpr passed as the second argument to this function
153152 ** must be of type FTSQUERY_PHRASE.
153154 ** The returned value is either NULL or a pointer to a buffer containing
153155 ** a position-list indicating the occurrences of the phrase in column iCol
153156 ** of the current row.
153158 ** More specifically, the returned buffer contains 1 varint for each
153159 ** occurrence of the phrase in the column, stored using the normal (delta+2)
153160 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
153161 ** if the requested column contains "a b X c d X X" and the position-list
153162 ** for 'X' is requested, the buffer returned may contain:
153164 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
153166 ** This function works regardless of whether or not the phrase is deferred,
153167 ** incremental, or neither.
153169 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
153170 Fts3Cursor *pCsr, /* FTS3 cursor object */
153171 Fts3Expr *pExpr, /* Phrase to return doclist for */
153172 int iCol, /* Column to return position list for */
153173 char **ppOut /* OUT: Pointer to position list */
153175 Fts3Phrase *pPhrase = pExpr->pPhrase;
153176 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
153177 char *pIter;
153178 int iThis;
153179 sqlite3_int64 iDocid;
153181 /* If this phrase is applies specifically to some column other than
153182 ** column iCol, return a NULL pointer. */
153183 *ppOut = 0;
153184 assert( iCol>=0 && iCol<pTab->nColumn );
153185 if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
153186 return SQLITE_OK;
153189 iDocid = pExpr->iDocid;
153190 pIter = pPhrase->doclist.pList;
153191 if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
153192 int rc = SQLITE_OK;
153193 int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
153194 int bOr = 0;
153195 u8 bTreeEof = 0;
153196 Fts3Expr *p; /* Used to iterate from pExpr to root */
153197 Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
153198 int bMatch;
153200 /* Check if this phrase descends from an OR expression node. If not,
153201 ** return NULL. Otherwise, the entry that corresponds to docid
153202 ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
153203 ** tree that the node is part of has been marked as EOF, but the node
153204 ** itself is not EOF, then it may point to an earlier entry. */
153205 pNear = pExpr;
153206 for(p=pExpr->pParent; p; p=p->pParent){
153207 if( p->eType==FTSQUERY_OR ) bOr = 1;
153208 if( p->eType==FTSQUERY_NEAR ) pNear = p;
153209 if( p->bEof ) bTreeEof = 1;
153211 if( bOr==0 ) return SQLITE_OK;
153213 /* This is the descendent of an OR node. In this case we cannot use
153214 ** an incremental phrase. Load the entire doclist for the phrase
153215 ** into memory in this case. */
153216 if( pPhrase->bIncr ){
153217 int bEofSave = pNear->bEof;
153218 fts3EvalRestart(pCsr, pNear, &rc);
153219 while( rc==SQLITE_OK && !pNear->bEof ){
153220 fts3EvalNextRow(pCsr, pNear, &rc);
153221 if( bEofSave==0 && pNear->iDocid==iDocid ) break;
153223 assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
153225 if( bTreeEof ){
153226 while( rc==SQLITE_OK && !pNear->bEof ){
153227 fts3EvalNextRow(pCsr, pNear, &rc);
153230 if( rc!=SQLITE_OK ) return rc;
153232 bMatch = 1;
153233 for(p=pNear; p; p=p->pLeft){
153234 u8 bEof = 0;
153235 Fts3Expr *pTest = p;
153236 Fts3Phrase *pPh;
153237 assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
153238 if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
153239 assert( pTest->eType==FTSQUERY_PHRASE );
153240 pPh = pTest->pPhrase;
153242 pIter = pPh->pOrPoslist;
153243 iDocid = pPh->iOrDocid;
153244 if( pCsr->bDesc==bDescDoclist ){
153245 bEof = !pPh->doclist.nAll ||
153246 (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
153247 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
153248 sqlite3Fts3DoclistNext(
153249 bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
153250 &pIter, &iDocid, &bEof
153253 }else{
153254 bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
153255 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
153256 int dummy;
153257 sqlite3Fts3DoclistPrev(
153258 bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
153259 &pIter, &iDocid, &dummy, &bEof
153263 pPh->pOrPoslist = pIter;
153264 pPh->iOrDocid = iDocid;
153265 if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
153268 if( bMatch ){
153269 pIter = pPhrase->pOrPoslist;
153270 }else{
153271 pIter = 0;
153274 if( pIter==0 ) return SQLITE_OK;
153276 if( *pIter==0x01 ){
153277 pIter++;
153278 pIter += fts3GetVarint32(pIter, &iThis);
153279 }else{
153280 iThis = 0;
153282 while( iThis<iCol ){
153283 fts3ColumnlistCopy(0, &pIter);
153284 if( *pIter==0x00 ) return SQLITE_OK;
153285 pIter++;
153286 pIter += fts3GetVarint32(pIter, &iThis);
153288 if( *pIter==0x00 ){
153289 pIter = 0;
153292 *ppOut = ((iCol==iThis)?pIter:0);
153293 return SQLITE_OK;
153297 ** Free all components of the Fts3Phrase structure that were allocated by
153298 ** the eval module. Specifically, this means to free:
153300 ** * the contents of pPhrase->doclist, and
153301 ** * any Fts3MultiSegReader objects held by phrase tokens.
153303 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
153304 if( pPhrase ){
153305 int i;
153306 sqlite3_free(pPhrase->doclist.aAll);
153307 fts3EvalInvalidatePoslist(pPhrase);
153308 memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
153309 for(i=0; i<pPhrase->nToken; i++){
153310 fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
153311 pPhrase->aToken[i].pSegcsr = 0;
153318 ** Return SQLITE_CORRUPT_VTAB.
153320 #ifdef SQLITE_DEBUG
153321 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
153322 return SQLITE_CORRUPT_VTAB;
153324 #endif
153326 #if !SQLITE_CORE
153328 ** Initialize API pointer table, if required.
153330 #ifdef _WIN32
153331 __declspec(dllexport)
153332 #endif
153333 SQLITE_API int sqlite3_fts3_init(
153334 sqlite3 *db,
153335 char **pzErrMsg,
153336 const sqlite3_api_routines *pApi
153338 SQLITE_EXTENSION_INIT2(pApi)
153339 return sqlite3Fts3Init(db);
153341 #endif
153343 #endif
153345 /************** End of fts3.c ************************************************/
153346 /************** Begin file fts3_aux.c ****************************************/
153348 ** 2011 Jan 27
153350 ** The author disclaims copyright to this source code. In place of
153351 ** a legal notice, here is a blessing:
153353 ** May you do good and not evil.
153354 ** May you find forgiveness for yourself and forgive others.
153355 ** May you share freely, never taking more than you give.
153357 ******************************************************************************
153360 /* #include "fts3Int.h" */
153361 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153363 /* #include <string.h> */
153364 /* #include <assert.h> */
153366 typedef struct Fts3auxTable Fts3auxTable;
153367 typedef struct Fts3auxCursor Fts3auxCursor;
153369 struct Fts3auxTable {
153370 sqlite3_vtab base; /* Base class used by SQLite core */
153371 Fts3Table *pFts3Tab;
153374 struct Fts3auxCursor {
153375 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
153376 Fts3MultiSegReader csr; /* Must be right after "base" */
153377 Fts3SegFilter filter;
153378 char *zStop;
153379 int nStop; /* Byte-length of string zStop */
153380 int iLangid; /* Language id to query */
153381 int isEof; /* True if cursor is at EOF */
153382 sqlite3_int64 iRowid; /* Current rowid */
153384 int iCol; /* Current value of 'col' column */
153385 int nStat; /* Size of aStat[] array */
153386 struct Fts3auxColstats {
153387 sqlite3_int64 nDoc; /* 'documents' values for current csr row */
153388 sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
153389 } *aStat;
153393 ** Schema of the terms table.
153395 #define FTS3_AUX_SCHEMA \
153396 "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
153399 ** This function does all the work for both the xConnect and xCreate methods.
153400 ** These tables have no persistent representation of their own, so xConnect
153401 ** and xCreate are identical operations.
153403 static int fts3auxConnectMethod(
153404 sqlite3 *db, /* Database connection */
153405 void *pUnused, /* Unused */
153406 int argc, /* Number of elements in argv array */
153407 const char * const *argv, /* xCreate/xConnect argument array */
153408 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
153409 char **pzErr /* OUT: sqlite3_malloc'd error message */
153411 char const *zDb; /* Name of database (e.g. "main") */
153412 char const *zFts3; /* Name of fts3 table */
153413 int nDb; /* Result of strlen(zDb) */
153414 int nFts3; /* Result of strlen(zFts3) */
153415 int nByte; /* Bytes of space to allocate here */
153416 int rc; /* value returned by declare_vtab() */
153417 Fts3auxTable *p; /* Virtual table object to return */
153419 UNUSED_PARAMETER(pUnused);
153421 /* The user should invoke this in one of two forms:
153423 ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
153424 ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
153426 if( argc!=4 && argc!=5 ) goto bad_args;
153428 zDb = argv[1];
153429 nDb = (int)strlen(zDb);
153430 if( argc==5 ){
153431 if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
153432 zDb = argv[3];
153433 nDb = (int)strlen(zDb);
153434 zFts3 = argv[4];
153435 }else{
153436 goto bad_args;
153438 }else{
153439 zFts3 = argv[3];
153441 nFts3 = (int)strlen(zFts3);
153443 rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
153444 if( rc!=SQLITE_OK ) return rc;
153446 nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
153447 p = (Fts3auxTable *)sqlite3_malloc(nByte);
153448 if( !p ) return SQLITE_NOMEM;
153449 memset(p, 0, nByte);
153451 p->pFts3Tab = (Fts3Table *)&p[1];
153452 p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
153453 p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
153454 p->pFts3Tab->db = db;
153455 p->pFts3Tab->nIndex = 1;
153457 memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
153458 memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
153459 sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
153461 *ppVtab = (sqlite3_vtab *)p;
153462 return SQLITE_OK;
153464 bad_args:
153465 sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
153466 return SQLITE_ERROR;
153470 ** This function does the work for both the xDisconnect and xDestroy methods.
153471 ** These tables have no persistent representation of their own, so xDisconnect
153472 ** and xDestroy are identical operations.
153474 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
153475 Fts3auxTable *p = (Fts3auxTable *)pVtab;
153476 Fts3Table *pFts3 = p->pFts3Tab;
153477 int i;
153479 /* Free any prepared statements held */
153480 for(i=0; i<SizeofArray(pFts3->aStmt); i++){
153481 sqlite3_finalize(pFts3->aStmt[i]);
153483 sqlite3_free(pFts3->zSegmentsTbl);
153484 sqlite3_free(p);
153485 return SQLITE_OK;
153488 #define FTS4AUX_EQ_CONSTRAINT 1
153489 #define FTS4AUX_GE_CONSTRAINT 2
153490 #define FTS4AUX_LE_CONSTRAINT 4
153493 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
153495 static int fts3auxBestIndexMethod(
153496 sqlite3_vtab *pVTab,
153497 sqlite3_index_info *pInfo
153499 int i;
153500 int iEq = -1;
153501 int iGe = -1;
153502 int iLe = -1;
153503 int iLangid = -1;
153504 int iNext = 1; /* Next free argvIndex value */
153506 UNUSED_PARAMETER(pVTab);
153508 /* This vtab delivers always results in "ORDER BY term ASC" order. */
153509 if( pInfo->nOrderBy==1
153510 && pInfo->aOrderBy[0].iColumn==0
153511 && pInfo->aOrderBy[0].desc==0
153513 pInfo->orderByConsumed = 1;
153516 /* Search for equality and range constraints on the "term" column.
153517 ** And equality constraints on the hidden "languageid" column. */
153518 for(i=0; i<pInfo->nConstraint; i++){
153519 if( pInfo->aConstraint[i].usable ){
153520 int op = pInfo->aConstraint[i].op;
153521 int iCol = pInfo->aConstraint[i].iColumn;
153523 if( iCol==0 ){
153524 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
153525 if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
153526 if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
153527 if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
153528 if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
153530 if( iCol==4 ){
153531 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
153536 if( iEq>=0 ){
153537 pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
153538 pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
153539 pInfo->estimatedCost = 5;
153540 }else{
153541 pInfo->idxNum = 0;
153542 pInfo->estimatedCost = 20000;
153543 if( iGe>=0 ){
153544 pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
153545 pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
153546 pInfo->estimatedCost /= 2;
153548 if( iLe>=0 ){
153549 pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
153550 pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
153551 pInfo->estimatedCost /= 2;
153554 if( iLangid>=0 ){
153555 pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
153556 pInfo->estimatedCost--;
153559 return SQLITE_OK;
153563 ** xOpen - Open a cursor.
153565 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
153566 Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
153568 UNUSED_PARAMETER(pVTab);
153570 pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
153571 if( !pCsr ) return SQLITE_NOMEM;
153572 memset(pCsr, 0, sizeof(Fts3auxCursor));
153574 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
153575 return SQLITE_OK;
153579 ** xClose - Close a cursor.
153581 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
153582 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
153583 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153585 sqlite3Fts3SegmentsClose(pFts3);
153586 sqlite3Fts3SegReaderFinish(&pCsr->csr);
153587 sqlite3_free((void *)pCsr->filter.zTerm);
153588 sqlite3_free(pCsr->zStop);
153589 sqlite3_free(pCsr->aStat);
153590 sqlite3_free(pCsr);
153591 return SQLITE_OK;
153594 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
153595 if( nSize>pCsr->nStat ){
153596 struct Fts3auxColstats *aNew;
153597 aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
153598 sizeof(struct Fts3auxColstats) * nSize
153600 if( aNew==0 ) return SQLITE_NOMEM;
153601 memset(&aNew[pCsr->nStat], 0,
153602 sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
153604 pCsr->aStat = aNew;
153605 pCsr->nStat = nSize;
153607 return SQLITE_OK;
153611 ** xNext - Advance the cursor to the next row, if any.
153613 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
153614 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153615 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
153616 int rc;
153618 /* Increment our pretend rowid value. */
153619 pCsr->iRowid++;
153621 for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
153622 if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
153625 rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
153626 if( rc==SQLITE_ROW ){
153627 int i = 0;
153628 int nDoclist = pCsr->csr.nDoclist;
153629 char *aDoclist = pCsr->csr.aDoclist;
153630 int iCol;
153632 int eState = 0;
153634 if( pCsr->zStop ){
153635 int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
153636 int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
153637 if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
153638 pCsr->isEof = 1;
153639 return SQLITE_OK;
153643 if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
153644 memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
153645 iCol = 0;
153647 while( i<nDoclist ){
153648 sqlite3_int64 v = 0;
153650 i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
153651 switch( eState ){
153652 /* State 0. In this state the integer just read was a docid. */
153653 case 0:
153654 pCsr->aStat[0].nDoc++;
153655 eState = 1;
153656 iCol = 0;
153657 break;
153659 /* State 1. In this state we are expecting either a 1, indicating
153660 ** that the following integer will be a column number, or the
153661 ** start of a position list for column 0.
153663 ** The only difference between state 1 and state 2 is that if the
153664 ** integer encountered in state 1 is not 0 or 1, then we need to
153665 ** increment the column 0 "nDoc" count for this term.
153667 case 1:
153668 assert( iCol==0 );
153669 if( v>1 ){
153670 pCsr->aStat[1].nDoc++;
153672 eState = 2;
153673 /* fall through */
153675 case 2:
153676 if( v==0 ){ /* 0x00. Next integer will be a docid. */
153677 eState = 0;
153678 }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
153679 eState = 3;
153680 }else{ /* 2 or greater. A position. */
153681 pCsr->aStat[iCol+1].nOcc++;
153682 pCsr->aStat[0].nOcc++;
153684 break;
153686 /* State 3. The integer just read is a column number. */
153687 default: assert( eState==3 );
153688 iCol = (int)v;
153689 if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
153690 pCsr->aStat[iCol+1].nDoc++;
153691 eState = 2;
153692 break;
153696 pCsr->iCol = 0;
153697 rc = SQLITE_OK;
153698 }else{
153699 pCsr->isEof = 1;
153701 return rc;
153705 ** xFilter - Initialize a cursor to point at the start of its data.
153707 static int fts3auxFilterMethod(
153708 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
153709 int idxNum, /* Strategy index */
153710 const char *idxStr, /* Unused */
153711 int nVal, /* Number of elements in apVal */
153712 sqlite3_value **apVal /* Arguments for the indexing scheme */
153714 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153715 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
153716 int rc;
153717 int isScan = 0;
153718 int iLangVal = 0; /* Language id to query */
153720 int iEq = -1; /* Index of term=? value in apVal */
153721 int iGe = -1; /* Index of term>=? value in apVal */
153722 int iLe = -1; /* Index of term<=? value in apVal */
153723 int iLangid = -1; /* Index of languageid=? value in apVal */
153724 int iNext = 0;
153726 UNUSED_PARAMETER(nVal);
153727 UNUSED_PARAMETER(idxStr);
153729 assert( idxStr==0 );
153730 assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
153731 || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
153732 || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
153735 if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
153736 iEq = iNext++;
153737 }else{
153738 isScan = 1;
153739 if( idxNum & FTS4AUX_GE_CONSTRAINT ){
153740 iGe = iNext++;
153742 if( idxNum & FTS4AUX_LE_CONSTRAINT ){
153743 iLe = iNext++;
153746 if( iNext<nVal ){
153747 iLangid = iNext++;
153750 /* In case this cursor is being reused, close and zero it. */
153751 testcase(pCsr->filter.zTerm);
153752 sqlite3Fts3SegReaderFinish(&pCsr->csr);
153753 sqlite3_free((void *)pCsr->filter.zTerm);
153754 sqlite3_free(pCsr->aStat);
153755 memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
153757 pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
153758 if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
153760 if( iEq>=0 || iGe>=0 ){
153761 const unsigned char *zStr = sqlite3_value_text(apVal[0]);
153762 assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
153763 if( zStr ){
153764 pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
153765 pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
153766 if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
153770 if( iLe>=0 ){
153771 pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
153772 pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
153773 if( pCsr->zStop==0 ) return SQLITE_NOMEM;
153776 if( iLangid>=0 ){
153777 iLangVal = sqlite3_value_int(apVal[iLangid]);
153779 /* If the user specified a negative value for the languageid, use zero
153780 ** instead. This works, as the "languageid=?" constraint will also
153781 ** be tested by the VDBE layer. The test will always be false (since
153782 ** this module will not return a row with a negative languageid), and
153783 ** so the overall query will return zero rows. */
153784 if( iLangVal<0 ) iLangVal = 0;
153786 pCsr->iLangid = iLangVal;
153788 rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
153789 pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
153791 if( rc==SQLITE_OK ){
153792 rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
153795 if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
153796 return rc;
153800 ** xEof - Return true if the cursor is at EOF, or false otherwise.
153802 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
153803 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153804 return pCsr->isEof;
153808 ** xColumn - Return a column value.
153810 static int fts3auxColumnMethod(
153811 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
153812 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
153813 int iCol /* Index of column to read value from */
153815 Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
153817 assert( p->isEof==0 );
153818 switch( iCol ){
153819 case 0: /* term */
153820 sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
153821 break;
153823 case 1: /* col */
153824 if( p->iCol ){
153825 sqlite3_result_int(pCtx, p->iCol-1);
153826 }else{
153827 sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
153829 break;
153831 case 2: /* documents */
153832 sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
153833 break;
153835 case 3: /* occurrences */
153836 sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
153837 break;
153839 default: /* languageid */
153840 assert( iCol==4 );
153841 sqlite3_result_int(pCtx, p->iLangid);
153842 break;
153845 return SQLITE_OK;
153849 ** xRowid - Return the current rowid for the cursor.
153851 static int fts3auxRowidMethod(
153852 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
153853 sqlite_int64 *pRowid /* OUT: Rowid value */
153855 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153856 *pRowid = pCsr->iRowid;
153857 return SQLITE_OK;
153861 ** Register the fts3aux module with database connection db. Return SQLITE_OK
153862 ** if successful or an error code if sqlite3_create_module() fails.
153864 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
153865 static const sqlite3_module fts3aux_module = {
153866 0, /* iVersion */
153867 fts3auxConnectMethod, /* xCreate */
153868 fts3auxConnectMethod, /* xConnect */
153869 fts3auxBestIndexMethod, /* xBestIndex */
153870 fts3auxDisconnectMethod, /* xDisconnect */
153871 fts3auxDisconnectMethod, /* xDestroy */
153872 fts3auxOpenMethod, /* xOpen */
153873 fts3auxCloseMethod, /* xClose */
153874 fts3auxFilterMethod, /* xFilter */
153875 fts3auxNextMethod, /* xNext */
153876 fts3auxEofMethod, /* xEof */
153877 fts3auxColumnMethod, /* xColumn */
153878 fts3auxRowidMethod, /* xRowid */
153879 0, /* xUpdate */
153880 0, /* xBegin */
153881 0, /* xSync */
153882 0, /* xCommit */
153883 0, /* xRollback */
153884 0, /* xFindFunction */
153885 0, /* xRename */
153886 0, /* xSavepoint */
153887 0, /* xRelease */
153888 0 /* xRollbackTo */
153890 int rc; /* Return code */
153892 rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
153893 return rc;
153896 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
153898 /************** End of fts3_aux.c ********************************************/
153899 /************** Begin file fts3_expr.c ***************************************/
153901 ** 2008 Nov 28
153903 ** The author disclaims copyright to this source code. In place of
153904 ** a legal notice, here is a blessing:
153906 ** May you do good and not evil.
153907 ** May you find forgiveness for yourself and forgive others.
153908 ** May you share freely, never taking more than you give.
153910 ******************************************************************************
153912 ** This module contains code that implements a parser for fts3 query strings
153913 ** (the right-hand argument to the MATCH operator). Because the supported
153914 ** syntax is relatively simple, the whole tokenizer/parser system is
153915 ** hand-coded.
153917 /* #include "fts3Int.h" */
153918 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153921 ** By default, this module parses the legacy syntax that has been
153922 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
153923 ** is defined, then it uses the new syntax. The differences between
153924 ** the new and the old syntaxes are:
153926 ** a) The new syntax supports parenthesis. The old does not.
153928 ** b) The new syntax supports the AND and NOT operators. The old does not.
153930 ** c) The old syntax supports the "-" token qualifier. This is not
153931 ** supported by the new syntax (it is replaced by the NOT operator).
153933 ** d) When using the old syntax, the OR operator has a greater precedence
153934 ** than an implicit AND. When using the new, both implicity and explicit
153935 ** AND operators have a higher precedence than OR.
153937 ** If compiled with SQLITE_TEST defined, then this module exports the
153938 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
153939 ** to zero causes the module to use the old syntax. If it is set to
153940 ** non-zero the new syntax is activated. This is so both syntaxes can
153941 ** be tested using a single build of testfixture.
153943 ** The following describes the syntax supported by the fts3 MATCH
153944 ** operator in a similar format to that used by the lemon parser
153945 ** generator. This module does not use actually lemon, it uses a
153946 ** custom parser.
153948 ** query ::= andexpr (OR andexpr)*.
153950 ** andexpr ::= notexpr (AND? notexpr)*.
153952 ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
153953 ** notexpr ::= LP query RP.
153955 ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
153957 ** distance_opt ::= .
153958 ** distance_opt ::= / INTEGER.
153960 ** phrase ::= TOKEN.
153961 ** phrase ::= COLUMN:TOKEN.
153962 ** phrase ::= "TOKEN TOKEN TOKEN...".
153965 #ifdef SQLITE_TEST
153966 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
153967 #else
153968 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
153969 # define sqlite3_fts3_enable_parentheses 1
153970 # else
153971 # define sqlite3_fts3_enable_parentheses 0
153972 # endif
153973 #endif
153976 ** Default span for NEAR operators.
153978 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
153980 /* #include <string.h> */
153981 /* #include <assert.h> */
153984 ** isNot:
153985 ** This variable is used by function getNextNode(). When getNextNode() is
153986 ** called, it sets ParseContext.isNot to true if the 'next node' is a
153987 ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
153988 ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
153989 ** zero.
153991 typedef struct ParseContext ParseContext;
153992 struct ParseContext {
153993 sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
153994 int iLangid; /* Language id used with tokenizer */
153995 const char **azCol; /* Array of column names for fts3 table */
153996 int bFts4; /* True to allow FTS4-only syntax */
153997 int nCol; /* Number of entries in azCol[] */
153998 int iDefaultCol; /* Default column to query */
153999 int isNot; /* True if getNextNode() sees a unary - */
154000 sqlite3_context *pCtx; /* Write error message here */
154001 int nNest; /* Number of nested brackets */
154005 ** This function is equivalent to the standard isspace() function.
154007 ** The standard isspace() can be awkward to use safely, because although it
154008 ** is defined to accept an argument of type int, its behavior when passed
154009 ** an integer that falls outside of the range of the unsigned char type
154010 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
154011 ** is defined to accept an argument of type char, and always returns 0 for
154012 ** any values that fall outside of the range of the unsigned char type (i.e.
154013 ** negative values).
154015 static int fts3isspace(char c){
154016 return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
154020 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
154021 ** zero the memory before returning a pointer to it. If unsuccessful,
154022 ** return NULL.
154024 static void *fts3MallocZero(int nByte){
154025 void *pRet = sqlite3_malloc(nByte);
154026 if( pRet ) memset(pRet, 0, nByte);
154027 return pRet;
154030 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
154031 sqlite3_tokenizer *pTokenizer,
154032 int iLangid,
154033 const char *z,
154034 int n,
154035 sqlite3_tokenizer_cursor **ppCsr
154037 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
154038 sqlite3_tokenizer_cursor *pCsr = 0;
154039 int rc;
154041 rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
154042 assert( rc==SQLITE_OK || pCsr==0 );
154043 if( rc==SQLITE_OK ){
154044 pCsr->pTokenizer = pTokenizer;
154045 if( pModule->iVersion>=1 ){
154046 rc = pModule->xLanguageid(pCsr, iLangid);
154047 if( rc!=SQLITE_OK ){
154048 pModule->xClose(pCsr);
154049 pCsr = 0;
154053 *ppCsr = pCsr;
154054 return rc;
154058 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
154059 ** call fts3ExprParse(). So this forward declaration is required.
154061 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
154064 ** Extract the next token from buffer z (length n) using the tokenizer
154065 ** and other information (column names etc.) in pParse. Create an Fts3Expr
154066 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
154067 ** single token and set *ppExpr to point to it. If the end of the buffer is
154068 ** reached before a token is found, set *ppExpr to zero. It is the
154069 ** responsibility of the caller to eventually deallocate the allocated
154070 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
154072 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
154073 ** fails.
154075 static int getNextToken(
154076 ParseContext *pParse, /* fts3 query parse context */
154077 int iCol, /* Value for Fts3Phrase.iColumn */
154078 const char *z, int n, /* Input string */
154079 Fts3Expr **ppExpr, /* OUT: expression */
154080 int *pnConsumed /* OUT: Number of bytes consumed */
154082 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
154083 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
154084 int rc;
154085 sqlite3_tokenizer_cursor *pCursor;
154086 Fts3Expr *pRet = 0;
154087 int i = 0;
154089 /* Set variable i to the maximum number of bytes of input to tokenize. */
154090 for(i=0; i<n; i++){
154091 if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
154092 if( z[i]=='"' ) break;
154095 *pnConsumed = i;
154096 rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
154097 if( rc==SQLITE_OK ){
154098 const char *zToken;
154099 int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
154100 int nByte; /* total space to allocate */
154102 rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
154103 if( rc==SQLITE_OK ){
154104 nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
154105 pRet = (Fts3Expr *)fts3MallocZero(nByte);
154106 if( !pRet ){
154107 rc = SQLITE_NOMEM;
154108 }else{
154109 pRet->eType = FTSQUERY_PHRASE;
154110 pRet->pPhrase = (Fts3Phrase *)&pRet[1];
154111 pRet->pPhrase->nToken = 1;
154112 pRet->pPhrase->iColumn = iCol;
154113 pRet->pPhrase->aToken[0].n = nToken;
154114 pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
154115 memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
154117 if( iEnd<n && z[iEnd]=='*' ){
154118 pRet->pPhrase->aToken[0].isPrefix = 1;
154119 iEnd++;
154122 while( 1 ){
154123 if( !sqlite3_fts3_enable_parentheses
154124 && iStart>0 && z[iStart-1]=='-'
154126 pParse->isNot = 1;
154127 iStart--;
154128 }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
154129 pRet->pPhrase->aToken[0].bFirst = 1;
154130 iStart--;
154131 }else{
154132 break;
154137 *pnConsumed = iEnd;
154138 }else if( i && rc==SQLITE_DONE ){
154139 rc = SQLITE_OK;
154142 pModule->xClose(pCursor);
154145 *ppExpr = pRet;
154146 return rc;
154151 ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
154152 ** then free the old allocation.
154154 static void *fts3ReallocOrFree(void *pOrig, int nNew){
154155 void *pRet = sqlite3_realloc(pOrig, nNew);
154156 if( !pRet ){
154157 sqlite3_free(pOrig);
154159 return pRet;
154163 ** Buffer zInput, length nInput, contains the contents of a quoted string
154164 ** that appeared as part of an fts3 query expression. Neither quote character
154165 ** is included in the buffer. This function attempts to tokenize the entire
154166 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
154167 ** containing the results.
154169 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
154170 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
154171 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
154172 ** to 0.
154174 static int getNextString(
154175 ParseContext *pParse, /* fts3 query parse context */
154176 const char *zInput, int nInput, /* Input string */
154177 Fts3Expr **ppExpr /* OUT: expression */
154179 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
154180 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
154181 int rc;
154182 Fts3Expr *p = 0;
154183 sqlite3_tokenizer_cursor *pCursor = 0;
154184 char *zTemp = 0;
154185 int nTemp = 0;
154187 const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
154188 int nToken = 0;
154190 /* The final Fts3Expr data structure, including the Fts3Phrase,
154191 ** Fts3PhraseToken structures token buffers are all stored as a single
154192 ** allocation so that the expression can be freed with a single call to
154193 ** sqlite3_free(). Setting this up requires a two pass approach.
154195 ** The first pass, in the block below, uses a tokenizer cursor to iterate
154196 ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
154197 ** to assemble data in two dynamic buffers:
154199 ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
154200 ** structure, followed by the array of Fts3PhraseToken
154201 ** structures. This pass only populates the Fts3PhraseToken array.
154203 ** Buffer zTemp: Contains copies of all tokens.
154205 ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
154206 ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
154207 ** structures.
154209 rc = sqlite3Fts3OpenTokenizer(
154210 pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
154211 if( rc==SQLITE_OK ){
154212 int ii;
154213 for(ii=0; rc==SQLITE_OK; ii++){
154214 const char *zByte;
154215 int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
154216 rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
154217 if( rc==SQLITE_OK ){
154218 Fts3PhraseToken *pToken;
154220 p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
154221 if( !p ) goto no_mem;
154223 zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
154224 if( !zTemp ) goto no_mem;
154226 assert( nToken==ii );
154227 pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
154228 memset(pToken, 0, sizeof(Fts3PhraseToken));
154230 memcpy(&zTemp[nTemp], zByte, nByte);
154231 nTemp += nByte;
154233 pToken->n = nByte;
154234 pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
154235 pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
154236 nToken = ii+1;
154240 pModule->xClose(pCursor);
154241 pCursor = 0;
154244 if( rc==SQLITE_DONE ){
154245 int jj;
154246 char *zBuf = 0;
154248 p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
154249 if( !p ) goto no_mem;
154250 memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
154251 p->eType = FTSQUERY_PHRASE;
154252 p->pPhrase = (Fts3Phrase *)&p[1];
154253 p->pPhrase->iColumn = pParse->iDefaultCol;
154254 p->pPhrase->nToken = nToken;
154256 zBuf = (char *)&p->pPhrase->aToken[nToken];
154257 if( zTemp ){
154258 memcpy(zBuf, zTemp, nTemp);
154259 sqlite3_free(zTemp);
154260 }else{
154261 assert( nTemp==0 );
154264 for(jj=0; jj<p->pPhrase->nToken; jj++){
154265 p->pPhrase->aToken[jj].z = zBuf;
154266 zBuf += p->pPhrase->aToken[jj].n;
154268 rc = SQLITE_OK;
154271 *ppExpr = p;
154272 return rc;
154273 no_mem:
154275 if( pCursor ){
154276 pModule->xClose(pCursor);
154278 sqlite3_free(zTemp);
154279 sqlite3_free(p);
154280 *ppExpr = 0;
154281 return SQLITE_NOMEM;
154285 ** The output variable *ppExpr is populated with an allocated Fts3Expr
154286 ** structure, or set to 0 if the end of the input buffer is reached.
154288 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
154289 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
154290 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
154292 static int getNextNode(
154293 ParseContext *pParse, /* fts3 query parse context */
154294 const char *z, int n, /* Input string */
154295 Fts3Expr **ppExpr, /* OUT: expression */
154296 int *pnConsumed /* OUT: Number of bytes consumed */
154298 static const struct Fts3Keyword {
154299 char *z; /* Keyword text */
154300 unsigned char n; /* Length of the keyword */
154301 unsigned char parenOnly; /* Only valid in paren mode */
154302 unsigned char eType; /* Keyword code */
154303 } aKeyword[] = {
154304 { "OR" , 2, 0, FTSQUERY_OR },
154305 { "AND", 3, 1, FTSQUERY_AND },
154306 { "NOT", 3, 1, FTSQUERY_NOT },
154307 { "NEAR", 4, 0, FTSQUERY_NEAR }
154309 int ii;
154310 int iCol;
154311 int iColLen;
154312 int rc;
154313 Fts3Expr *pRet = 0;
154315 const char *zInput = z;
154316 int nInput = n;
154318 pParse->isNot = 0;
154320 /* Skip over any whitespace before checking for a keyword, an open or
154321 ** close bracket, or a quoted string.
154323 while( nInput>0 && fts3isspace(*zInput) ){
154324 nInput--;
154325 zInput++;
154327 if( nInput==0 ){
154328 return SQLITE_DONE;
154331 /* See if we are dealing with a keyword. */
154332 for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
154333 const struct Fts3Keyword *pKey = &aKeyword[ii];
154335 if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
154336 continue;
154339 if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
154340 int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
154341 int nKey = pKey->n;
154342 char cNext;
154344 /* If this is a "NEAR" keyword, check for an explicit nearness. */
154345 if( pKey->eType==FTSQUERY_NEAR ){
154346 assert( nKey==4 );
154347 if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
154348 nNear = 0;
154349 for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
154350 nNear = nNear * 10 + (zInput[nKey] - '0');
154355 /* At this point this is probably a keyword. But for that to be true,
154356 ** the next byte must contain either whitespace, an open or close
154357 ** parenthesis, a quote character, or EOF.
154359 cNext = zInput[nKey];
154360 if( fts3isspace(cNext)
154361 || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
154363 pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
154364 if( !pRet ){
154365 return SQLITE_NOMEM;
154367 pRet->eType = pKey->eType;
154368 pRet->nNear = nNear;
154369 *ppExpr = pRet;
154370 *pnConsumed = (int)((zInput - z) + nKey);
154371 return SQLITE_OK;
154374 /* Turns out that wasn't a keyword after all. This happens if the
154375 ** user has supplied a token such as "ORacle". Continue.
154380 /* See if we are dealing with a quoted phrase. If this is the case, then
154381 ** search for the closing quote and pass the whole string to getNextString()
154382 ** for processing. This is easy to do, as fts3 has no syntax for escaping
154383 ** a quote character embedded in a string.
154385 if( *zInput=='"' ){
154386 for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
154387 *pnConsumed = (int)((zInput - z) + ii + 1);
154388 if( ii==nInput ){
154389 return SQLITE_ERROR;
154391 return getNextString(pParse, &zInput[1], ii-1, ppExpr);
154394 if( sqlite3_fts3_enable_parentheses ){
154395 if( *zInput=='(' ){
154396 int nConsumed = 0;
154397 pParse->nNest++;
154398 rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
154399 if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
154400 *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
154401 return rc;
154402 }else if( *zInput==')' ){
154403 pParse->nNest--;
154404 *pnConsumed = (int)((zInput - z) + 1);
154405 *ppExpr = 0;
154406 return SQLITE_DONE;
154410 /* If control flows to this point, this must be a regular token, or
154411 ** the end of the input. Read a regular token using the sqlite3_tokenizer
154412 ** interface. Before doing so, figure out if there is an explicit
154413 ** column specifier for the token.
154415 ** TODO: Strangely, it is not possible to associate a column specifier
154416 ** with a quoted phrase, only with a single token. Not sure if this was
154417 ** an implementation artifact or an intentional decision when fts3 was
154418 ** first implemented. Whichever it was, this module duplicates the
154419 ** limitation.
154421 iCol = pParse->iDefaultCol;
154422 iColLen = 0;
154423 for(ii=0; ii<pParse->nCol; ii++){
154424 const char *zStr = pParse->azCol[ii];
154425 int nStr = (int)strlen(zStr);
154426 if( nInput>nStr && zInput[nStr]==':'
154427 && sqlite3_strnicmp(zStr, zInput, nStr)==0
154429 iCol = ii;
154430 iColLen = (int)((zInput - z) + nStr + 1);
154431 break;
154434 rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
154435 *pnConsumed += iColLen;
154436 return rc;
154440 ** The argument is an Fts3Expr structure for a binary operator (any type
154441 ** except an FTSQUERY_PHRASE). Return an integer value representing the
154442 ** precedence of the operator. Lower values have a higher precedence (i.e.
154443 ** group more tightly). For example, in the C language, the == operator
154444 ** groups more tightly than ||, and would therefore have a higher precedence.
154446 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
154447 ** is defined), the order of the operators in precedence from highest to
154448 ** lowest is:
154450 ** NEAR
154451 ** NOT
154452 ** AND (including implicit ANDs)
154453 ** OR
154455 ** Note that when using the old query syntax, the OR operator has a higher
154456 ** precedence than the AND operator.
154458 static int opPrecedence(Fts3Expr *p){
154459 assert( p->eType!=FTSQUERY_PHRASE );
154460 if( sqlite3_fts3_enable_parentheses ){
154461 return p->eType;
154462 }else if( p->eType==FTSQUERY_NEAR ){
154463 return 1;
154464 }else if( p->eType==FTSQUERY_OR ){
154465 return 2;
154467 assert( p->eType==FTSQUERY_AND );
154468 return 3;
154472 ** Argument ppHead contains a pointer to the current head of a query
154473 ** expression tree being parsed. pPrev is the expression node most recently
154474 ** inserted into the tree. This function adds pNew, which is always a binary
154475 ** operator node, into the expression tree based on the relative precedence
154476 ** of pNew and the existing nodes of the tree. This may result in the head
154477 ** of the tree changing, in which case *ppHead is set to the new root node.
154479 static void insertBinaryOperator(
154480 Fts3Expr **ppHead, /* Pointer to the root node of a tree */
154481 Fts3Expr *pPrev, /* Node most recently inserted into the tree */
154482 Fts3Expr *pNew /* New binary node to insert into expression tree */
154484 Fts3Expr *pSplit = pPrev;
154485 while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
154486 pSplit = pSplit->pParent;
154489 if( pSplit->pParent ){
154490 assert( pSplit->pParent->pRight==pSplit );
154491 pSplit->pParent->pRight = pNew;
154492 pNew->pParent = pSplit->pParent;
154493 }else{
154494 *ppHead = pNew;
154496 pNew->pLeft = pSplit;
154497 pSplit->pParent = pNew;
154501 ** Parse the fts3 query expression found in buffer z, length n. This function
154502 ** returns either when the end of the buffer is reached or an unmatched
154503 ** closing bracket - ')' - is encountered.
154505 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
154506 ** parsed form of the expression and *pnConsumed is set to the number of
154507 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
154508 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
154510 static int fts3ExprParse(
154511 ParseContext *pParse, /* fts3 query parse context */
154512 const char *z, int n, /* Text of MATCH query */
154513 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
154514 int *pnConsumed /* OUT: Number of bytes consumed */
154516 Fts3Expr *pRet = 0;
154517 Fts3Expr *pPrev = 0;
154518 Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
154519 int nIn = n;
154520 const char *zIn = z;
154521 int rc = SQLITE_OK;
154522 int isRequirePhrase = 1;
154524 while( rc==SQLITE_OK ){
154525 Fts3Expr *p = 0;
154526 int nByte = 0;
154528 rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
154529 assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
154530 if( rc==SQLITE_OK ){
154531 if( p ){
154532 int isPhrase;
154534 if( !sqlite3_fts3_enable_parentheses
154535 && p->eType==FTSQUERY_PHRASE && pParse->isNot
154537 /* Create an implicit NOT operator. */
154538 Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
154539 if( !pNot ){
154540 sqlite3Fts3ExprFree(p);
154541 rc = SQLITE_NOMEM;
154542 goto exprparse_out;
154544 pNot->eType = FTSQUERY_NOT;
154545 pNot->pRight = p;
154546 p->pParent = pNot;
154547 if( pNotBranch ){
154548 pNot->pLeft = pNotBranch;
154549 pNotBranch->pParent = pNot;
154551 pNotBranch = pNot;
154552 p = pPrev;
154553 }else{
154554 int eType = p->eType;
154555 isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
154557 /* The isRequirePhrase variable is set to true if a phrase or
154558 ** an expression contained in parenthesis is required. If a
154559 ** binary operator (AND, OR, NOT or NEAR) is encounted when
154560 ** isRequirePhrase is set, this is a syntax error.
154562 if( !isPhrase && isRequirePhrase ){
154563 sqlite3Fts3ExprFree(p);
154564 rc = SQLITE_ERROR;
154565 goto exprparse_out;
154568 if( isPhrase && !isRequirePhrase ){
154569 /* Insert an implicit AND operator. */
154570 Fts3Expr *pAnd;
154571 assert( pRet && pPrev );
154572 pAnd = fts3MallocZero(sizeof(Fts3Expr));
154573 if( !pAnd ){
154574 sqlite3Fts3ExprFree(p);
154575 rc = SQLITE_NOMEM;
154576 goto exprparse_out;
154578 pAnd->eType = FTSQUERY_AND;
154579 insertBinaryOperator(&pRet, pPrev, pAnd);
154580 pPrev = pAnd;
154583 /* This test catches attempts to make either operand of a NEAR
154584 ** operator something other than a phrase. For example, either of
154585 ** the following:
154587 ** (bracketed expression) NEAR phrase
154588 ** phrase NEAR (bracketed expression)
154590 ** Return an error in either case.
154592 if( pPrev && (
154593 (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
154594 || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
154596 sqlite3Fts3ExprFree(p);
154597 rc = SQLITE_ERROR;
154598 goto exprparse_out;
154601 if( isPhrase ){
154602 if( pRet ){
154603 assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
154604 pPrev->pRight = p;
154605 p->pParent = pPrev;
154606 }else{
154607 pRet = p;
154609 }else{
154610 insertBinaryOperator(&pRet, pPrev, p);
154612 isRequirePhrase = !isPhrase;
154614 pPrev = p;
154616 assert( nByte>0 );
154618 assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
154619 nIn -= nByte;
154620 zIn += nByte;
154623 if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
154624 rc = SQLITE_ERROR;
154627 if( rc==SQLITE_DONE ){
154628 rc = SQLITE_OK;
154629 if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
154630 if( !pRet ){
154631 rc = SQLITE_ERROR;
154632 }else{
154633 Fts3Expr *pIter = pNotBranch;
154634 while( pIter->pLeft ){
154635 pIter = pIter->pLeft;
154637 pIter->pLeft = pRet;
154638 pRet->pParent = pIter;
154639 pRet = pNotBranch;
154643 *pnConsumed = n - nIn;
154645 exprparse_out:
154646 if( rc!=SQLITE_OK ){
154647 sqlite3Fts3ExprFree(pRet);
154648 sqlite3Fts3ExprFree(pNotBranch);
154649 pRet = 0;
154651 *ppExpr = pRet;
154652 return rc;
154656 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
154657 ** as the only argument is more than nMaxDepth.
154659 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
154660 int rc = SQLITE_OK;
154661 if( p ){
154662 if( nMaxDepth<0 ){
154663 rc = SQLITE_TOOBIG;
154664 }else{
154665 rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
154666 if( rc==SQLITE_OK ){
154667 rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
154671 return rc;
154675 ** This function attempts to transform the expression tree at (*pp) to
154676 ** an equivalent but more balanced form. The tree is modified in place.
154677 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
154678 ** new root expression node.
154680 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
154682 ** Otherwise, if an error occurs, an SQLite error code is returned and
154683 ** expression (*pp) freed.
154685 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
154686 int rc = SQLITE_OK; /* Return code */
154687 Fts3Expr *pRoot = *pp; /* Initial root node */
154688 Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
154689 int eType = pRoot->eType; /* Type of node in this tree */
154691 if( nMaxDepth==0 ){
154692 rc = SQLITE_ERROR;
154695 if( rc==SQLITE_OK ){
154696 if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
154697 Fts3Expr **apLeaf;
154698 apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
154699 if( 0==apLeaf ){
154700 rc = SQLITE_NOMEM;
154701 }else{
154702 memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
154705 if( rc==SQLITE_OK ){
154706 int i;
154707 Fts3Expr *p;
154709 /* Set $p to point to the left-most leaf in the tree of eType nodes. */
154710 for(p=pRoot; p->eType==eType; p=p->pLeft){
154711 assert( p->pParent==0 || p->pParent->pLeft==p );
154712 assert( p->pLeft && p->pRight );
154715 /* This loop runs once for each leaf in the tree of eType nodes. */
154716 while( 1 ){
154717 int iLvl;
154718 Fts3Expr *pParent = p->pParent; /* Current parent of p */
154720 assert( pParent==0 || pParent->pLeft==p );
154721 p->pParent = 0;
154722 if( pParent ){
154723 pParent->pLeft = 0;
154724 }else{
154725 pRoot = 0;
154727 rc = fts3ExprBalance(&p, nMaxDepth-1);
154728 if( rc!=SQLITE_OK ) break;
154730 for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
154731 if( apLeaf[iLvl]==0 ){
154732 apLeaf[iLvl] = p;
154733 p = 0;
154734 }else{
154735 assert( pFree );
154736 pFree->pLeft = apLeaf[iLvl];
154737 pFree->pRight = p;
154738 pFree->pLeft->pParent = pFree;
154739 pFree->pRight->pParent = pFree;
154741 p = pFree;
154742 pFree = pFree->pParent;
154743 p->pParent = 0;
154744 apLeaf[iLvl] = 0;
154747 if( p ){
154748 sqlite3Fts3ExprFree(p);
154749 rc = SQLITE_TOOBIG;
154750 break;
154753 /* If that was the last leaf node, break out of the loop */
154754 if( pParent==0 ) break;
154756 /* Set $p to point to the next leaf in the tree of eType nodes */
154757 for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
154759 /* Remove pParent from the original tree. */
154760 assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
154761 pParent->pRight->pParent = pParent->pParent;
154762 if( pParent->pParent ){
154763 pParent->pParent->pLeft = pParent->pRight;
154764 }else{
154765 assert( pParent==pRoot );
154766 pRoot = pParent->pRight;
154769 /* Link pParent into the free node list. It will be used as an
154770 ** internal node of the new tree. */
154771 pParent->pParent = pFree;
154772 pFree = pParent;
154775 if( rc==SQLITE_OK ){
154776 p = 0;
154777 for(i=0; i<nMaxDepth; i++){
154778 if( apLeaf[i] ){
154779 if( p==0 ){
154780 p = apLeaf[i];
154781 p->pParent = 0;
154782 }else{
154783 assert( pFree!=0 );
154784 pFree->pRight = p;
154785 pFree->pLeft = apLeaf[i];
154786 pFree->pLeft->pParent = pFree;
154787 pFree->pRight->pParent = pFree;
154789 p = pFree;
154790 pFree = pFree->pParent;
154791 p->pParent = 0;
154795 pRoot = p;
154796 }else{
154797 /* An error occurred. Delete the contents of the apLeaf[] array
154798 ** and pFree list. Everything else is cleaned up by the call to
154799 ** sqlite3Fts3ExprFree(pRoot) below. */
154800 Fts3Expr *pDel;
154801 for(i=0; i<nMaxDepth; i++){
154802 sqlite3Fts3ExprFree(apLeaf[i]);
154804 while( (pDel=pFree)!=0 ){
154805 pFree = pDel->pParent;
154806 sqlite3_free(pDel);
154810 assert( pFree==0 );
154811 sqlite3_free( apLeaf );
154813 }else if( eType==FTSQUERY_NOT ){
154814 Fts3Expr *pLeft = pRoot->pLeft;
154815 Fts3Expr *pRight = pRoot->pRight;
154817 pRoot->pLeft = 0;
154818 pRoot->pRight = 0;
154819 pLeft->pParent = 0;
154820 pRight->pParent = 0;
154822 rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
154823 if( rc==SQLITE_OK ){
154824 rc = fts3ExprBalance(&pRight, nMaxDepth-1);
154827 if( rc!=SQLITE_OK ){
154828 sqlite3Fts3ExprFree(pRight);
154829 sqlite3Fts3ExprFree(pLeft);
154830 }else{
154831 assert( pLeft && pRight );
154832 pRoot->pLeft = pLeft;
154833 pLeft->pParent = pRoot;
154834 pRoot->pRight = pRight;
154835 pRight->pParent = pRoot;
154840 if( rc!=SQLITE_OK ){
154841 sqlite3Fts3ExprFree(pRoot);
154842 pRoot = 0;
154844 *pp = pRoot;
154845 return rc;
154849 ** This function is similar to sqlite3Fts3ExprParse(), with the following
154850 ** differences:
154852 ** 1. It does not do expression rebalancing.
154853 ** 2. It does not check that the expression does not exceed the
154854 ** maximum allowable depth.
154855 ** 3. Even if it fails, *ppExpr may still be set to point to an
154856 ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
154857 ** in this case.
154859 static int fts3ExprParseUnbalanced(
154860 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
154861 int iLangid, /* Language id for tokenizer */
154862 char **azCol, /* Array of column names for fts3 table */
154863 int bFts4, /* True to allow FTS4-only syntax */
154864 int nCol, /* Number of entries in azCol[] */
154865 int iDefaultCol, /* Default column to query */
154866 const char *z, int n, /* Text of MATCH query */
154867 Fts3Expr **ppExpr /* OUT: Parsed query structure */
154869 int nParsed;
154870 int rc;
154871 ParseContext sParse;
154873 memset(&sParse, 0, sizeof(ParseContext));
154874 sParse.pTokenizer = pTokenizer;
154875 sParse.iLangid = iLangid;
154876 sParse.azCol = (const char **)azCol;
154877 sParse.nCol = nCol;
154878 sParse.iDefaultCol = iDefaultCol;
154879 sParse.bFts4 = bFts4;
154880 if( z==0 ){
154881 *ppExpr = 0;
154882 return SQLITE_OK;
154884 if( n<0 ){
154885 n = (int)strlen(z);
154887 rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
154888 assert( rc==SQLITE_OK || *ppExpr==0 );
154890 /* Check for mismatched parenthesis */
154891 if( rc==SQLITE_OK && sParse.nNest ){
154892 rc = SQLITE_ERROR;
154895 return rc;
154899 ** Parameters z and n contain a pointer to and length of a buffer containing
154900 ** an fts3 query expression, respectively. This function attempts to parse the
154901 ** query expression and create a tree of Fts3Expr structures representing the
154902 ** parsed expression. If successful, *ppExpr is set to point to the head
154903 ** of the parsed expression tree and SQLITE_OK is returned. If an error
154904 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
154905 ** error) is returned and *ppExpr is set to 0.
154907 ** If parameter n is a negative number, then z is assumed to point to a
154908 ** nul-terminated string and the length is determined using strlen().
154910 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
154911 ** use to normalize query tokens while parsing the expression. The azCol[]
154912 ** array, which is assumed to contain nCol entries, should contain the names
154913 ** of each column in the target fts3 table, in order from left to right.
154914 ** Column names must be nul-terminated strings.
154916 ** The iDefaultCol parameter should be passed the index of the table column
154917 ** that appears on the left-hand-side of the MATCH operator (the default
154918 ** column to match against for tokens for which a column name is not explicitly
154919 ** specified as part of the query string), or -1 if tokens may by default
154920 ** match any table column.
154922 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
154923 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
154924 int iLangid, /* Language id for tokenizer */
154925 char **azCol, /* Array of column names for fts3 table */
154926 int bFts4, /* True to allow FTS4-only syntax */
154927 int nCol, /* Number of entries in azCol[] */
154928 int iDefaultCol, /* Default column to query */
154929 const char *z, int n, /* Text of MATCH query */
154930 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
154931 char **pzErr /* OUT: Error message (sqlite3_malloc) */
154933 int rc = fts3ExprParseUnbalanced(
154934 pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
154937 /* Rebalance the expression. And check that its depth does not exceed
154938 ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
154939 if( rc==SQLITE_OK && *ppExpr ){
154940 rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
154941 if( rc==SQLITE_OK ){
154942 rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
154946 if( rc!=SQLITE_OK ){
154947 sqlite3Fts3ExprFree(*ppExpr);
154948 *ppExpr = 0;
154949 if( rc==SQLITE_TOOBIG ){
154950 sqlite3Fts3ErrMsg(pzErr,
154951 "FTS expression tree is too large (maximum depth %d)",
154952 SQLITE_FTS3_MAX_EXPR_DEPTH
154954 rc = SQLITE_ERROR;
154955 }else if( rc==SQLITE_ERROR ){
154956 sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
154960 return rc;
154964 ** Free a single node of an expression tree.
154966 static void fts3FreeExprNode(Fts3Expr *p){
154967 assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
154968 sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
154969 sqlite3_free(p->aMI);
154970 sqlite3_free(p);
154974 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
154976 ** This function would be simpler if it recursively called itself. But
154977 ** that would mean passing a sufficiently large expression to ExprParse()
154978 ** could cause a stack overflow.
154980 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
154981 Fts3Expr *p;
154982 assert( pDel==0 || pDel->pParent==0 );
154983 for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
154984 assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
154986 while( p ){
154987 Fts3Expr *pParent = p->pParent;
154988 fts3FreeExprNode(p);
154989 if( pParent && p==pParent->pLeft && pParent->pRight ){
154990 p = pParent->pRight;
154991 while( p && (p->pLeft || p->pRight) ){
154992 assert( p==p->pParent->pRight || p==p->pParent->pLeft );
154993 p = (p->pLeft ? p->pLeft : p->pRight);
154995 }else{
154996 p = pParent;
155001 /****************************************************************************
155002 *****************************************************************************
155003 ** Everything after this point is just test code.
155006 #ifdef SQLITE_TEST
155008 /* #include <stdio.h> */
155011 ** Function to query the hash-table of tokenizers (see README.tokenizers).
155013 static int queryTestTokenizer(
155014 sqlite3 *db,
155015 const char *zName,
155016 const sqlite3_tokenizer_module **pp
155018 int rc;
155019 sqlite3_stmt *pStmt;
155020 const char zSql[] = "SELECT fts3_tokenizer(?)";
155022 *pp = 0;
155023 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
155024 if( rc!=SQLITE_OK ){
155025 return rc;
155028 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
155029 if( SQLITE_ROW==sqlite3_step(pStmt) ){
155030 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
155031 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
155035 return sqlite3_finalize(pStmt);
155039 ** Return a pointer to a buffer containing a text representation of the
155040 ** expression passed as the first argument. The buffer is obtained from
155041 ** sqlite3_malloc(). It is the responsibility of the caller to use
155042 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
155043 ** NULL is returned.
155045 ** If the second argument is not NULL, then its contents are prepended to
155046 ** the returned expression text and then freed using sqlite3_free().
155048 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
155049 if( pExpr==0 ){
155050 return sqlite3_mprintf("");
155052 switch( pExpr->eType ){
155053 case FTSQUERY_PHRASE: {
155054 Fts3Phrase *pPhrase = pExpr->pPhrase;
155055 int i;
155056 zBuf = sqlite3_mprintf(
155057 "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
155058 for(i=0; zBuf && i<pPhrase->nToken; i++){
155059 zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
155060 pPhrase->aToken[i].n, pPhrase->aToken[i].z,
155061 (pPhrase->aToken[i].isPrefix?"+":"")
155064 return zBuf;
155067 case FTSQUERY_NEAR:
155068 zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
155069 break;
155070 case FTSQUERY_NOT:
155071 zBuf = sqlite3_mprintf("%zNOT ", zBuf);
155072 break;
155073 case FTSQUERY_AND:
155074 zBuf = sqlite3_mprintf("%zAND ", zBuf);
155075 break;
155076 case FTSQUERY_OR:
155077 zBuf = sqlite3_mprintf("%zOR ", zBuf);
155078 break;
155081 if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
155082 if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
155083 if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
155085 if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
155086 if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
155088 return zBuf;
155092 ** This is the implementation of a scalar SQL function used to test the
155093 ** expression parser. It should be called as follows:
155095 ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
155097 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
155098 ** to parse the query expression (see README.tokenizers). The second argument
155099 ** is the query expression to parse. Each subsequent argument is the name
155100 ** of a column of the fts3 table that the query expression may refer to.
155101 ** For example:
155103 ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
155105 static void fts3ExprTest(
155106 sqlite3_context *context,
155107 int argc,
155108 sqlite3_value **argv
155110 sqlite3_tokenizer_module const *pModule = 0;
155111 sqlite3_tokenizer *pTokenizer = 0;
155112 int rc;
155113 char **azCol = 0;
155114 const char *zExpr;
155115 int nExpr;
155116 int nCol;
155117 int ii;
155118 Fts3Expr *pExpr;
155119 char *zBuf = 0;
155120 sqlite3 *db = sqlite3_context_db_handle(context);
155122 if( argc<3 ){
155123 sqlite3_result_error(context,
155124 "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
155126 return;
155129 rc = queryTestTokenizer(db,
155130 (const char *)sqlite3_value_text(argv[0]), &pModule);
155131 if( rc==SQLITE_NOMEM ){
155132 sqlite3_result_error_nomem(context);
155133 goto exprtest_out;
155134 }else if( !pModule ){
155135 sqlite3_result_error(context, "No such tokenizer module", -1);
155136 goto exprtest_out;
155139 rc = pModule->xCreate(0, 0, &pTokenizer);
155140 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
155141 if( rc==SQLITE_NOMEM ){
155142 sqlite3_result_error_nomem(context);
155143 goto exprtest_out;
155145 pTokenizer->pModule = pModule;
155147 zExpr = (const char *)sqlite3_value_text(argv[1]);
155148 nExpr = sqlite3_value_bytes(argv[1]);
155149 nCol = argc-2;
155150 azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
155151 if( !azCol ){
155152 sqlite3_result_error_nomem(context);
155153 goto exprtest_out;
155155 for(ii=0; ii<nCol; ii++){
155156 azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
155159 if( sqlite3_user_data(context) ){
155160 char *zDummy = 0;
155161 rc = sqlite3Fts3ExprParse(
155162 pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
155164 assert( rc==SQLITE_OK || pExpr==0 );
155165 sqlite3_free(zDummy);
155166 }else{
155167 rc = fts3ExprParseUnbalanced(
155168 pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
155172 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
155173 sqlite3Fts3ExprFree(pExpr);
155174 sqlite3_result_error(context, "Error parsing expression", -1);
155175 }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
155176 sqlite3_result_error_nomem(context);
155177 }else{
155178 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
155179 sqlite3_free(zBuf);
155182 sqlite3Fts3ExprFree(pExpr);
155184 exprtest_out:
155185 if( pModule && pTokenizer ){
155186 rc = pModule->xDestroy(pTokenizer);
155188 sqlite3_free(azCol);
155192 ** Register the query expression parser test function fts3_exprtest()
155193 ** with database connection db.
155195 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
155196 int rc = sqlite3_create_function(
155197 db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
155199 if( rc==SQLITE_OK ){
155200 rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
155201 -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
155204 return rc;
155207 #endif
155208 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
155210 /************** End of fts3_expr.c *******************************************/
155211 /************** Begin file fts3_hash.c ***************************************/
155213 ** 2001 September 22
155215 ** The author disclaims copyright to this source code. In place of
155216 ** a legal notice, here is a blessing:
155218 ** May you do good and not evil.
155219 ** May you find forgiveness for yourself and forgive others.
155220 ** May you share freely, never taking more than you give.
155222 *************************************************************************
155223 ** This is the implementation of generic hash-tables used in SQLite.
155224 ** We've modified it slightly to serve as a standalone hash table
155225 ** implementation for the full-text indexing module.
155229 ** The code in this file is only compiled if:
155231 ** * The FTS3 module is being built as an extension
155232 ** (in which case SQLITE_CORE is not defined), or
155234 ** * The FTS3 module is being built into the core of
155235 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
155237 /* #include "fts3Int.h" */
155238 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
155240 /* #include <assert.h> */
155241 /* #include <stdlib.h> */
155242 /* #include <string.h> */
155244 /* #include "fts3_hash.h" */
155247 ** Malloc and Free functions
155249 static void *fts3HashMalloc(int n){
155250 void *p = sqlite3_malloc(n);
155251 if( p ){
155252 memset(p, 0, n);
155254 return p;
155256 static void fts3HashFree(void *p){
155257 sqlite3_free(p);
155260 /* Turn bulk memory into a hash table object by initializing the
155261 ** fields of the Hash structure.
155263 ** "pNew" is a pointer to the hash table that is to be initialized.
155264 ** keyClass is one of the constants
155265 ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
155266 ** determines what kind of key the hash table will use. "copyKey" is
155267 ** true if the hash table should make its own private copy of keys and
155268 ** false if it should just use the supplied pointer.
155270 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
155271 assert( pNew!=0 );
155272 assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
155273 pNew->keyClass = keyClass;
155274 pNew->copyKey = copyKey;
155275 pNew->first = 0;
155276 pNew->count = 0;
155277 pNew->htsize = 0;
155278 pNew->ht = 0;
155281 /* Remove all entries from a hash table. Reclaim all memory.
155282 ** Call this routine to delete a hash table or to reset a hash table
155283 ** to the empty state.
155285 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
155286 Fts3HashElem *elem; /* For looping over all elements of the table */
155288 assert( pH!=0 );
155289 elem = pH->first;
155290 pH->first = 0;
155291 fts3HashFree(pH->ht);
155292 pH->ht = 0;
155293 pH->htsize = 0;
155294 while( elem ){
155295 Fts3HashElem *next_elem = elem->next;
155296 if( pH->copyKey && elem->pKey ){
155297 fts3HashFree(elem->pKey);
155299 fts3HashFree(elem);
155300 elem = next_elem;
155302 pH->count = 0;
155306 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
155308 static int fts3StrHash(const void *pKey, int nKey){
155309 const char *z = (const char *)pKey;
155310 unsigned h = 0;
155311 if( nKey<=0 ) nKey = (int) strlen(z);
155312 while( nKey > 0 ){
155313 h = (h<<3) ^ h ^ *z++;
155314 nKey--;
155316 return (int)(h & 0x7fffffff);
155318 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
155319 if( n1!=n2 ) return 1;
155320 return strncmp((const char*)pKey1,(const char*)pKey2,n1);
155324 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
155326 static int fts3BinHash(const void *pKey, int nKey){
155327 int h = 0;
155328 const char *z = (const char *)pKey;
155329 while( nKey-- > 0 ){
155330 h = (h<<3) ^ h ^ *(z++);
155332 return h & 0x7fffffff;
155334 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
155335 if( n1!=n2 ) return 1;
155336 return memcmp(pKey1,pKey2,n1);
155340 ** Return a pointer to the appropriate hash function given the key class.
155342 ** The C syntax in this function definition may be unfamilar to some
155343 ** programmers, so we provide the following additional explanation:
155345 ** The name of the function is "ftsHashFunction". The function takes a
155346 ** single parameter "keyClass". The return value of ftsHashFunction()
155347 ** is a pointer to another function. Specifically, the return value
155348 ** of ftsHashFunction() is a pointer to a function that takes two parameters
155349 ** with types "const void*" and "int" and returns an "int".
155351 static int (*ftsHashFunction(int keyClass))(const void*,int){
155352 if( keyClass==FTS3_HASH_STRING ){
155353 return &fts3StrHash;
155354 }else{
155355 assert( keyClass==FTS3_HASH_BINARY );
155356 return &fts3BinHash;
155361 ** Return a pointer to the appropriate hash function given the key class.
155363 ** For help in interpreted the obscure C code in the function definition,
155364 ** see the header comment on the previous function.
155366 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
155367 if( keyClass==FTS3_HASH_STRING ){
155368 return &fts3StrCompare;
155369 }else{
155370 assert( keyClass==FTS3_HASH_BINARY );
155371 return &fts3BinCompare;
155375 /* Link an element into the hash table
155377 static void fts3HashInsertElement(
155378 Fts3Hash *pH, /* The complete hash table */
155379 struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
155380 Fts3HashElem *pNew /* The element to be inserted */
155382 Fts3HashElem *pHead; /* First element already in pEntry */
155383 pHead = pEntry->chain;
155384 if( pHead ){
155385 pNew->next = pHead;
155386 pNew->prev = pHead->prev;
155387 if( pHead->prev ){ pHead->prev->next = pNew; }
155388 else { pH->first = pNew; }
155389 pHead->prev = pNew;
155390 }else{
155391 pNew->next = pH->first;
155392 if( pH->first ){ pH->first->prev = pNew; }
155393 pNew->prev = 0;
155394 pH->first = pNew;
155396 pEntry->count++;
155397 pEntry->chain = pNew;
155401 /* Resize the hash table so that it cantains "new_size" buckets.
155402 ** "new_size" must be a power of 2. The hash table might fail
155403 ** to resize if sqliteMalloc() fails.
155405 ** Return non-zero if a memory allocation error occurs.
155407 static int fts3Rehash(Fts3Hash *pH, int new_size){
155408 struct _fts3ht *new_ht; /* The new hash table */
155409 Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
155410 int (*xHash)(const void*,int); /* The hash function */
155412 assert( (new_size & (new_size-1))==0 );
155413 new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
155414 if( new_ht==0 ) return 1;
155415 fts3HashFree(pH->ht);
155416 pH->ht = new_ht;
155417 pH->htsize = new_size;
155418 xHash = ftsHashFunction(pH->keyClass);
155419 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
155420 int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
155421 next_elem = elem->next;
155422 fts3HashInsertElement(pH, &new_ht[h], elem);
155424 return 0;
155427 /* This function (for internal use only) locates an element in an
155428 ** hash table that matches the given key. The hash for this key has
155429 ** already been computed and is passed as the 4th parameter.
155431 static Fts3HashElem *fts3FindElementByHash(
155432 const Fts3Hash *pH, /* The pH to be searched */
155433 const void *pKey, /* The key we are searching for */
155434 int nKey,
155435 int h /* The hash for this key. */
155437 Fts3HashElem *elem; /* Used to loop thru the element list */
155438 int count; /* Number of elements left to test */
155439 int (*xCompare)(const void*,int,const void*,int); /* comparison function */
155441 if( pH->ht ){
155442 struct _fts3ht *pEntry = &pH->ht[h];
155443 elem = pEntry->chain;
155444 count = pEntry->count;
155445 xCompare = ftsCompareFunction(pH->keyClass);
155446 while( count-- && elem ){
155447 if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
155448 return elem;
155450 elem = elem->next;
155453 return 0;
155456 /* Remove a single entry from the hash table given a pointer to that
155457 ** element and a hash on the element's key.
155459 static void fts3RemoveElementByHash(
155460 Fts3Hash *pH, /* The pH containing "elem" */
155461 Fts3HashElem* elem, /* The element to be removed from the pH */
155462 int h /* Hash value for the element */
155464 struct _fts3ht *pEntry;
155465 if( elem->prev ){
155466 elem->prev->next = elem->next;
155467 }else{
155468 pH->first = elem->next;
155470 if( elem->next ){
155471 elem->next->prev = elem->prev;
155473 pEntry = &pH->ht[h];
155474 if( pEntry->chain==elem ){
155475 pEntry->chain = elem->next;
155477 pEntry->count--;
155478 if( pEntry->count<=0 ){
155479 pEntry->chain = 0;
155481 if( pH->copyKey && elem->pKey ){
155482 fts3HashFree(elem->pKey);
155484 fts3HashFree( elem );
155485 pH->count--;
155486 if( pH->count<=0 ){
155487 assert( pH->first==0 );
155488 assert( pH->count==0 );
155489 fts3HashClear(pH);
155493 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
155494 const Fts3Hash *pH,
155495 const void *pKey,
155496 int nKey
155498 int h; /* A hash on key */
155499 int (*xHash)(const void*,int); /* The hash function */
155501 if( pH==0 || pH->ht==0 ) return 0;
155502 xHash = ftsHashFunction(pH->keyClass);
155503 assert( xHash!=0 );
155504 h = (*xHash)(pKey,nKey);
155505 assert( (pH->htsize & (pH->htsize-1))==0 );
155506 return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
155510 ** Attempt to locate an element of the hash table pH with a key
155511 ** that matches pKey,nKey. Return the data for this element if it is
155512 ** found, or NULL if there is no match.
155514 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
155515 Fts3HashElem *pElem; /* The element that matches key (if any) */
155517 pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
155518 return pElem ? pElem->data : 0;
155521 /* Insert an element into the hash table pH. The key is pKey,nKey
155522 ** and the data is "data".
155524 ** If no element exists with a matching key, then a new
155525 ** element is created. A copy of the key is made if the copyKey
155526 ** flag is set. NULL is returned.
155528 ** If another element already exists with the same key, then the
155529 ** new data replaces the old data and the old data is returned.
155530 ** The key is not copied in this instance. If a malloc fails, then
155531 ** the new data is returned and the hash table is unchanged.
155533 ** If the "data" parameter to this function is NULL, then the
155534 ** element corresponding to "key" is removed from the hash table.
155536 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
155537 Fts3Hash *pH, /* The hash table to insert into */
155538 const void *pKey, /* The key */
155539 int nKey, /* Number of bytes in the key */
155540 void *data /* The data */
155542 int hraw; /* Raw hash value of the key */
155543 int h; /* the hash of the key modulo hash table size */
155544 Fts3HashElem *elem; /* Used to loop thru the element list */
155545 Fts3HashElem *new_elem; /* New element added to the pH */
155546 int (*xHash)(const void*,int); /* The hash function */
155548 assert( pH!=0 );
155549 xHash = ftsHashFunction(pH->keyClass);
155550 assert( xHash!=0 );
155551 hraw = (*xHash)(pKey, nKey);
155552 assert( (pH->htsize & (pH->htsize-1))==0 );
155553 h = hraw & (pH->htsize-1);
155554 elem = fts3FindElementByHash(pH,pKey,nKey,h);
155555 if( elem ){
155556 void *old_data = elem->data;
155557 if( data==0 ){
155558 fts3RemoveElementByHash(pH,elem,h);
155559 }else{
155560 elem->data = data;
155562 return old_data;
155564 if( data==0 ) return 0;
155565 if( (pH->htsize==0 && fts3Rehash(pH,8))
155566 || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
155568 pH->count = 0;
155569 return data;
155571 assert( pH->htsize>0 );
155572 new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
155573 if( new_elem==0 ) return data;
155574 if( pH->copyKey && pKey!=0 ){
155575 new_elem->pKey = fts3HashMalloc( nKey );
155576 if( new_elem->pKey==0 ){
155577 fts3HashFree(new_elem);
155578 return data;
155580 memcpy((void*)new_elem->pKey, pKey, nKey);
155581 }else{
155582 new_elem->pKey = (void*)pKey;
155584 new_elem->nKey = nKey;
155585 pH->count++;
155586 assert( pH->htsize>0 );
155587 assert( (pH->htsize & (pH->htsize-1))==0 );
155588 h = hraw & (pH->htsize-1);
155589 fts3HashInsertElement(pH, &pH->ht[h], new_elem);
155590 new_elem->data = data;
155591 return 0;
155594 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
155596 /************** End of fts3_hash.c *******************************************/
155597 /************** Begin file fts3_porter.c *************************************/
155599 ** 2006 September 30
155601 ** The author disclaims copyright to this source code. In place of
155602 ** a legal notice, here is a blessing:
155604 ** May you do good and not evil.
155605 ** May you find forgiveness for yourself and forgive others.
155606 ** May you share freely, never taking more than you give.
155608 *************************************************************************
155609 ** Implementation of the full-text-search tokenizer that implements
155610 ** a Porter stemmer.
155614 ** The code in this file is only compiled if:
155616 ** * The FTS3 module is being built as an extension
155617 ** (in which case SQLITE_CORE is not defined), or
155619 ** * The FTS3 module is being built into the core of
155620 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
155622 /* #include "fts3Int.h" */
155623 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
155625 /* #include <assert.h> */
155626 /* #include <stdlib.h> */
155627 /* #include <stdio.h> */
155628 /* #include <string.h> */
155630 /* #include "fts3_tokenizer.h" */
155633 ** Class derived from sqlite3_tokenizer
155635 typedef struct porter_tokenizer {
155636 sqlite3_tokenizer base; /* Base class */
155637 } porter_tokenizer;
155640 ** Class derived from sqlite3_tokenizer_cursor
155642 typedef struct porter_tokenizer_cursor {
155643 sqlite3_tokenizer_cursor base;
155644 const char *zInput; /* input we are tokenizing */
155645 int nInput; /* size of the input */
155646 int iOffset; /* current position in zInput */
155647 int iToken; /* index of next token to be returned */
155648 char *zToken; /* storage for current token */
155649 int nAllocated; /* space allocated to zToken buffer */
155650 } porter_tokenizer_cursor;
155654 ** Create a new tokenizer instance.
155656 static int porterCreate(
155657 int argc, const char * const *argv,
155658 sqlite3_tokenizer **ppTokenizer
155660 porter_tokenizer *t;
155662 UNUSED_PARAMETER(argc);
155663 UNUSED_PARAMETER(argv);
155665 t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
155666 if( t==NULL ) return SQLITE_NOMEM;
155667 memset(t, 0, sizeof(*t));
155668 *ppTokenizer = &t->base;
155669 return SQLITE_OK;
155673 ** Destroy a tokenizer
155675 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
155676 sqlite3_free(pTokenizer);
155677 return SQLITE_OK;
155681 ** Prepare to begin tokenizing a particular string. The input
155682 ** string to be tokenized is zInput[0..nInput-1]. A cursor
155683 ** used to incrementally tokenize this string is returned in
155684 ** *ppCursor.
155686 static int porterOpen(
155687 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
155688 const char *zInput, int nInput, /* String to be tokenized */
155689 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
155691 porter_tokenizer_cursor *c;
155693 UNUSED_PARAMETER(pTokenizer);
155695 c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
155696 if( c==NULL ) return SQLITE_NOMEM;
155698 c->zInput = zInput;
155699 if( zInput==0 ){
155700 c->nInput = 0;
155701 }else if( nInput<0 ){
155702 c->nInput = (int)strlen(zInput);
155703 }else{
155704 c->nInput = nInput;
155706 c->iOffset = 0; /* start tokenizing at the beginning */
155707 c->iToken = 0;
155708 c->zToken = NULL; /* no space allocated, yet. */
155709 c->nAllocated = 0;
155711 *ppCursor = &c->base;
155712 return SQLITE_OK;
155716 ** Close a tokenization cursor previously opened by a call to
155717 ** porterOpen() above.
155719 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
155720 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
155721 sqlite3_free(c->zToken);
155722 sqlite3_free(c);
155723 return SQLITE_OK;
155726 ** Vowel or consonant
155728 static const char cType[] = {
155729 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
155730 1, 1, 1, 2, 1
155734 ** isConsonant() and isVowel() determine if their first character in
155735 ** the string they point to is a consonant or a vowel, according
155736 ** to Porter ruls.
155738 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
155739 ** 'Y' is a consonant unless it follows another consonant,
155740 ** in which case it is a vowel.
155742 ** In these routine, the letters are in reverse order. So the 'y' rule
155743 ** is that 'y' is a consonant unless it is followed by another
155744 ** consonent.
155746 static int isVowel(const char*);
155747 static int isConsonant(const char *z){
155748 int j;
155749 char x = *z;
155750 if( x==0 ) return 0;
155751 assert( x>='a' && x<='z' );
155752 j = cType[x-'a'];
155753 if( j<2 ) return j;
155754 return z[1]==0 || isVowel(z + 1);
155756 static int isVowel(const char *z){
155757 int j;
155758 char x = *z;
155759 if( x==0 ) return 0;
155760 assert( x>='a' && x<='z' );
155761 j = cType[x-'a'];
155762 if( j<2 ) return 1-j;
155763 return isConsonant(z + 1);
155767 ** Let any sequence of one or more vowels be represented by V and let
155768 ** C be sequence of one or more consonants. Then every word can be
155769 ** represented as:
155771 ** [C] (VC){m} [V]
155773 ** In prose: A word is an optional consonant followed by zero or
155774 ** vowel-consonant pairs followed by an optional vowel. "m" is the
155775 ** number of vowel consonant pairs. This routine computes the value
155776 ** of m for the first i bytes of a word.
155778 ** Return true if the m-value for z is 1 or more. In other words,
155779 ** return true if z contains at least one vowel that is followed
155780 ** by a consonant.
155782 ** In this routine z[] is in reverse order. So we are really looking
155783 ** for an instance of a consonant followed by a vowel.
155785 static int m_gt_0(const char *z){
155786 while( isVowel(z) ){ z++; }
155787 if( *z==0 ) return 0;
155788 while( isConsonant(z) ){ z++; }
155789 return *z!=0;
155792 /* Like mgt0 above except we are looking for a value of m which is
155793 ** exactly 1
155795 static int m_eq_1(const char *z){
155796 while( isVowel(z) ){ z++; }
155797 if( *z==0 ) return 0;
155798 while( isConsonant(z) ){ z++; }
155799 if( *z==0 ) return 0;
155800 while( isVowel(z) ){ z++; }
155801 if( *z==0 ) return 1;
155802 while( isConsonant(z) ){ z++; }
155803 return *z==0;
155806 /* Like mgt0 above except we are looking for a value of m>1 instead
155807 ** or m>0
155809 static int m_gt_1(const char *z){
155810 while( isVowel(z) ){ z++; }
155811 if( *z==0 ) return 0;
155812 while( isConsonant(z) ){ z++; }
155813 if( *z==0 ) return 0;
155814 while( isVowel(z) ){ z++; }
155815 if( *z==0 ) return 0;
155816 while( isConsonant(z) ){ z++; }
155817 return *z!=0;
155821 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
155823 static int hasVowel(const char *z){
155824 while( isConsonant(z) ){ z++; }
155825 return *z!=0;
155829 ** Return TRUE if the word ends in a double consonant.
155831 ** The text is reversed here. So we are really looking at
155832 ** the first two characters of z[].
155834 static int doubleConsonant(const char *z){
155835 return isConsonant(z) && z[0]==z[1];
155839 ** Return TRUE if the word ends with three letters which
155840 ** are consonant-vowel-consonent and where the final consonant
155841 ** is not 'w', 'x', or 'y'.
155843 ** The word is reversed here. So we are really checking the
155844 ** first three letters and the first one cannot be in [wxy].
155846 static int star_oh(const char *z){
155847 return
155848 isConsonant(z) &&
155849 z[0]!='w' && z[0]!='x' && z[0]!='y' &&
155850 isVowel(z+1) &&
155851 isConsonant(z+2);
155855 ** If the word ends with zFrom and xCond() is true for the stem
155856 ** of the word that preceeds the zFrom ending, then change the
155857 ** ending to zTo.
155859 ** The input word *pz and zFrom are both in reverse order. zTo
155860 ** is in normal order.
155862 ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
155863 ** match. Not that TRUE is returned even if xCond() fails and
155864 ** no substitution occurs.
155866 static int stem(
155867 char **pz, /* The word being stemmed (Reversed) */
155868 const char *zFrom, /* If the ending matches this... (Reversed) */
155869 const char *zTo, /* ... change the ending to this (not reversed) */
155870 int (*xCond)(const char*) /* Condition that must be true */
155872 char *z = *pz;
155873 while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
155874 if( *zFrom!=0 ) return 0;
155875 if( xCond && !xCond(z) ) return 1;
155876 while( *zTo ){
155877 *(--z) = *(zTo++);
155879 *pz = z;
155880 return 1;
155884 ** This is the fallback stemmer used when the porter stemmer is
155885 ** inappropriate. The input word is copied into the output with
155886 ** US-ASCII case folding. If the input word is too long (more
155887 ** than 20 bytes if it contains no digits or more than 6 bytes if
155888 ** it contains digits) then word is truncated to 20 or 6 bytes
155889 ** by taking 10 or 3 bytes from the beginning and end.
155891 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
155892 int i, mx, j;
155893 int hasDigit = 0;
155894 for(i=0; i<nIn; i++){
155895 char c = zIn[i];
155896 if( c>='A' && c<='Z' ){
155897 zOut[i] = c - 'A' + 'a';
155898 }else{
155899 if( c>='0' && c<='9' ) hasDigit = 1;
155900 zOut[i] = c;
155903 mx = hasDigit ? 3 : 10;
155904 if( nIn>mx*2 ){
155905 for(j=mx, i=nIn-mx; i<nIn; i++, j++){
155906 zOut[j] = zOut[i];
155908 i = j;
155910 zOut[i] = 0;
155911 *pnOut = i;
155916 ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
155917 ** zOut is at least big enough to hold nIn bytes. Write the actual
155918 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
155920 ** Any upper-case characters in the US-ASCII character set ([A-Z])
155921 ** are converted to lower case. Upper-case UTF characters are
155922 ** unchanged.
155924 ** Words that are longer than about 20 bytes are stemmed by retaining
155925 ** a few bytes from the beginning and the end of the word. If the
155926 ** word contains digits, 3 bytes are taken from the beginning and
155927 ** 3 bytes from the end. For long words without digits, 10 bytes
155928 ** are taken from each end. US-ASCII case folding still applies.
155930 ** If the input word contains not digits but does characters not
155931 ** in [a-zA-Z] then no stemming is attempted and this routine just
155932 ** copies the input into the input into the output with US-ASCII
155933 ** case folding.
155935 ** Stemming never increases the length of the word. So there is
155936 ** no chance of overflowing the zOut buffer.
155938 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
155939 int i, j;
155940 char zReverse[28];
155941 char *z, *z2;
155942 if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
155943 /* The word is too big or too small for the porter stemmer.
155944 ** Fallback to the copy stemmer */
155945 copy_stemmer(zIn, nIn, zOut, pnOut);
155946 return;
155948 for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
155949 char c = zIn[i];
155950 if( c>='A' && c<='Z' ){
155951 zReverse[j] = c + 'a' - 'A';
155952 }else if( c>='a' && c<='z' ){
155953 zReverse[j] = c;
155954 }else{
155955 /* The use of a character not in [a-zA-Z] means that we fallback
155956 ** to the copy stemmer */
155957 copy_stemmer(zIn, nIn, zOut, pnOut);
155958 return;
155961 memset(&zReverse[sizeof(zReverse)-5], 0, 5);
155962 z = &zReverse[j+1];
155965 /* Step 1a */
155966 if( z[0]=='s' ){
155968 !stem(&z, "sess", "ss", 0) &&
155969 !stem(&z, "sei", "i", 0) &&
155970 !stem(&z, "ss", "ss", 0)
155976 /* Step 1b */
155977 z2 = z;
155978 if( stem(&z, "dee", "ee", m_gt_0) ){
155979 /* Do nothing. The work was all in the test */
155980 }else if(
155981 (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
155982 && z!=z2
155984 if( stem(&z, "ta", "ate", 0) ||
155985 stem(&z, "lb", "ble", 0) ||
155986 stem(&z, "zi", "ize", 0) ){
155987 /* Do nothing. The work was all in the test */
155988 }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
155990 }else if( m_eq_1(z) && star_oh(z) ){
155991 *(--z) = 'e';
155995 /* Step 1c */
155996 if( z[0]=='y' && hasVowel(z+1) ){
155997 z[0] = 'i';
156000 /* Step 2 */
156001 switch( z[1] ){
156002 case 'a':
156003 if( !stem(&z, "lanoita", "ate", m_gt_0) ){
156004 stem(&z, "lanoit", "tion", m_gt_0);
156006 break;
156007 case 'c':
156008 if( !stem(&z, "icne", "ence", m_gt_0) ){
156009 stem(&z, "icna", "ance", m_gt_0);
156011 break;
156012 case 'e':
156013 stem(&z, "rezi", "ize", m_gt_0);
156014 break;
156015 case 'g':
156016 stem(&z, "igol", "log", m_gt_0);
156017 break;
156018 case 'l':
156019 if( !stem(&z, "ilb", "ble", m_gt_0)
156020 && !stem(&z, "illa", "al", m_gt_0)
156021 && !stem(&z, "iltne", "ent", m_gt_0)
156022 && !stem(&z, "ile", "e", m_gt_0)
156024 stem(&z, "ilsuo", "ous", m_gt_0);
156026 break;
156027 case 'o':
156028 if( !stem(&z, "noitazi", "ize", m_gt_0)
156029 && !stem(&z, "noita", "ate", m_gt_0)
156031 stem(&z, "rota", "ate", m_gt_0);
156033 break;
156034 case 's':
156035 if( !stem(&z, "msila", "al", m_gt_0)
156036 && !stem(&z, "ssenevi", "ive", m_gt_0)
156037 && !stem(&z, "ssenluf", "ful", m_gt_0)
156039 stem(&z, "ssensuo", "ous", m_gt_0);
156041 break;
156042 case 't':
156043 if( !stem(&z, "itila", "al", m_gt_0)
156044 && !stem(&z, "itivi", "ive", m_gt_0)
156046 stem(&z, "itilib", "ble", m_gt_0);
156048 break;
156051 /* Step 3 */
156052 switch( z[0] ){
156053 case 'e':
156054 if( !stem(&z, "etaci", "ic", m_gt_0)
156055 && !stem(&z, "evita", "", m_gt_0)
156057 stem(&z, "ezila", "al", m_gt_0);
156059 break;
156060 case 'i':
156061 stem(&z, "itici", "ic", m_gt_0);
156062 break;
156063 case 'l':
156064 if( !stem(&z, "laci", "ic", m_gt_0) ){
156065 stem(&z, "luf", "", m_gt_0);
156067 break;
156068 case 's':
156069 stem(&z, "ssen", "", m_gt_0);
156070 break;
156073 /* Step 4 */
156074 switch( z[1] ){
156075 case 'a':
156076 if( z[0]=='l' && m_gt_1(z+2) ){
156077 z += 2;
156079 break;
156080 case 'c':
156081 if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
156082 z += 4;
156084 break;
156085 case 'e':
156086 if( z[0]=='r' && m_gt_1(z+2) ){
156087 z += 2;
156089 break;
156090 case 'i':
156091 if( z[0]=='c' && m_gt_1(z+2) ){
156092 z += 2;
156094 break;
156095 case 'l':
156096 if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
156097 z += 4;
156099 break;
156100 case 'n':
156101 if( z[0]=='t' ){
156102 if( z[2]=='a' ){
156103 if( m_gt_1(z+3) ){
156104 z += 3;
156106 }else if( z[2]=='e' ){
156107 if( !stem(&z, "tneme", "", m_gt_1)
156108 && !stem(&z, "tnem", "", m_gt_1)
156110 stem(&z, "tne", "", m_gt_1);
156114 break;
156115 case 'o':
156116 if( z[0]=='u' ){
156117 if( m_gt_1(z+2) ){
156118 z += 2;
156120 }else if( z[3]=='s' || z[3]=='t' ){
156121 stem(&z, "noi", "", m_gt_1);
156123 break;
156124 case 's':
156125 if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
156126 z += 3;
156128 break;
156129 case 't':
156130 if( !stem(&z, "eta", "", m_gt_1) ){
156131 stem(&z, "iti", "", m_gt_1);
156133 break;
156134 case 'u':
156135 if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
156136 z += 3;
156138 break;
156139 case 'v':
156140 case 'z':
156141 if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
156142 z += 3;
156144 break;
156147 /* Step 5a */
156148 if( z[0]=='e' ){
156149 if( m_gt_1(z+1) ){
156151 }else if( m_eq_1(z+1) && !star_oh(z+1) ){
156156 /* Step 5b */
156157 if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
156161 /* z[] is now the stemmed word in reverse order. Flip it back
156162 ** around into forward order and return.
156164 *pnOut = i = (int)strlen(z);
156165 zOut[i] = 0;
156166 while( *z ){
156167 zOut[--i] = *(z++);
156172 ** Characters that can be part of a token. We assume any character
156173 ** whose value is greater than 0x80 (any UTF character) can be
156174 ** part of a token. In other words, delimiters all must have
156175 ** values of 0x7f or lower.
156177 static const char porterIdChar[] = {
156178 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
156179 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
156180 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
156181 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
156182 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
156183 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
156185 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
156188 ** Extract the next token from a tokenization cursor. The cursor must
156189 ** have been opened by a prior call to porterOpen().
156191 static int porterNext(
156192 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
156193 const char **pzToken, /* OUT: *pzToken is the token text */
156194 int *pnBytes, /* OUT: Number of bytes in token */
156195 int *piStartOffset, /* OUT: Starting offset of token */
156196 int *piEndOffset, /* OUT: Ending offset of token */
156197 int *piPosition /* OUT: Position integer of token */
156199 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
156200 const char *z = c->zInput;
156202 while( c->iOffset<c->nInput ){
156203 int iStartOffset, ch;
156205 /* Scan past delimiter characters */
156206 while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
156207 c->iOffset++;
156210 /* Count non-delimiter characters. */
156211 iStartOffset = c->iOffset;
156212 while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
156213 c->iOffset++;
156216 if( c->iOffset>iStartOffset ){
156217 int n = c->iOffset-iStartOffset;
156218 if( n>c->nAllocated ){
156219 char *pNew;
156220 c->nAllocated = n+20;
156221 pNew = sqlite3_realloc(c->zToken, c->nAllocated);
156222 if( !pNew ) return SQLITE_NOMEM;
156223 c->zToken = pNew;
156225 porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
156226 *pzToken = c->zToken;
156227 *piStartOffset = iStartOffset;
156228 *piEndOffset = c->iOffset;
156229 *piPosition = c->iToken++;
156230 return SQLITE_OK;
156233 return SQLITE_DONE;
156237 ** The set of routines that implement the porter-stemmer tokenizer
156239 static const sqlite3_tokenizer_module porterTokenizerModule = {
156241 porterCreate,
156242 porterDestroy,
156243 porterOpen,
156244 porterClose,
156245 porterNext,
156250 ** Allocate a new porter tokenizer. Return a pointer to the new
156251 ** tokenizer in *ppModule
156253 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
156254 sqlite3_tokenizer_module const**ppModule
156256 *ppModule = &porterTokenizerModule;
156259 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
156261 /************** End of fts3_porter.c *****************************************/
156262 /************** Begin file fts3_tokenizer.c **********************************/
156264 ** 2007 June 22
156266 ** The author disclaims copyright to this source code. In place of
156267 ** a legal notice, here is a blessing:
156269 ** May you do good and not evil.
156270 ** May you find forgiveness for yourself and forgive others.
156271 ** May you share freely, never taking more than you give.
156273 ******************************************************************************
156275 ** This is part of an SQLite module implementing full-text search.
156276 ** This particular file implements the generic tokenizer interface.
156280 ** The code in this file is only compiled if:
156282 ** * The FTS3 module is being built as an extension
156283 ** (in which case SQLITE_CORE is not defined), or
156285 ** * The FTS3 module is being built into the core of
156286 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
156288 /* #include "fts3Int.h" */
156289 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
156291 /* #include <assert.h> */
156292 /* #include <string.h> */
156295 ** Return true if the two-argument version of fts3_tokenizer()
156296 ** has been activated via a prior call to sqlite3_db_config(db,
156297 ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
156299 static int fts3TokenizerEnabled(sqlite3_context *context){
156300 sqlite3 *db = sqlite3_context_db_handle(context);
156301 int isEnabled = 0;
156302 sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
156303 return isEnabled;
156307 ** Implementation of the SQL scalar function for accessing the underlying
156308 ** hash table. This function may be called as follows:
156310 ** SELECT <function-name>(<key-name>);
156311 ** SELECT <function-name>(<key-name>, <pointer>);
156313 ** where <function-name> is the name passed as the second argument
156314 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
156316 ** If the <pointer> argument is specified, it must be a blob value
156317 ** containing a pointer to be stored as the hash data corresponding
156318 ** to the string <key-name>. If <pointer> is not specified, then
156319 ** the string <key-name> must already exist in the has table. Otherwise,
156320 ** an error is returned.
156322 ** Whether or not the <pointer> argument is specified, the value returned
156323 ** is a blob containing the pointer stored as the hash data corresponding
156324 ** to string <key-name> (after the hash-table is updated, if applicable).
156326 static void fts3TokenizerFunc(
156327 sqlite3_context *context,
156328 int argc,
156329 sqlite3_value **argv
156331 Fts3Hash *pHash;
156332 void *pPtr = 0;
156333 const unsigned char *zName;
156334 int nName;
156336 assert( argc==1 || argc==2 );
156338 pHash = (Fts3Hash *)sqlite3_user_data(context);
156340 zName = sqlite3_value_text(argv[0]);
156341 nName = sqlite3_value_bytes(argv[0])+1;
156343 if( argc==2 ){
156344 if( fts3TokenizerEnabled(context) ){
156345 void *pOld;
156346 int n = sqlite3_value_bytes(argv[1]);
156347 if( zName==0 || n!=sizeof(pPtr) ){
156348 sqlite3_result_error(context, "argument type mismatch", -1);
156349 return;
156351 pPtr = *(void **)sqlite3_value_blob(argv[1]);
156352 pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
156353 if( pOld==pPtr ){
156354 sqlite3_result_error(context, "out of memory", -1);
156356 }else{
156357 sqlite3_result_error(context, "fts3tokenize disabled", -1);
156358 return;
156360 }else{
156361 if( zName ){
156362 pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
156364 if( !pPtr ){
156365 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
156366 sqlite3_result_error(context, zErr, -1);
156367 sqlite3_free(zErr);
156368 return;
156371 sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
156374 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
156375 static const char isFtsIdChar[] = {
156376 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
156377 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
156378 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
156379 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
156380 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
156381 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
156382 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
156383 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
156385 return (c&0x80 || isFtsIdChar[(int)(c)]);
156388 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
156389 const char *z1;
156390 const char *z2 = 0;
156392 /* Find the start of the next token. */
156393 z1 = zStr;
156394 while( z2==0 ){
156395 char c = *z1;
156396 switch( c ){
156397 case '\0': return 0; /* No more tokens here */
156398 case '\'':
156399 case '"':
156400 case '`': {
156401 z2 = z1;
156402 while( *++z2 && (*z2!=c || *++z2==c) );
156403 break;
156405 case '[':
156406 z2 = &z1[1];
156407 while( *z2 && z2[0]!=']' ) z2++;
156408 if( *z2 ) z2++;
156409 break;
156411 default:
156412 if( sqlite3Fts3IsIdChar(*z1) ){
156413 z2 = &z1[1];
156414 while( sqlite3Fts3IsIdChar(*z2) ) z2++;
156415 }else{
156416 z1++;
156421 *pn = (int)(z2-z1);
156422 return z1;
156425 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
156426 Fts3Hash *pHash, /* Tokenizer hash table */
156427 const char *zArg, /* Tokenizer name */
156428 sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
156429 char **pzErr /* OUT: Set to malloced error message */
156431 int rc;
156432 char *z = (char *)zArg;
156433 int n = 0;
156434 char *zCopy;
156435 char *zEnd; /* Pointer to nul-term of zCopy */
156436 sqlite3_tokenizer_module *m;
156438 zCopy = sqlite3_mprintf("%s", zArg);
156439 if( !zCopy ) return SQLITE_NOMEM;
156440 zEnd = &zCopy[strlen(zCopy)];
156442 z = (char *)sqlite3Fts3NextToken(zCopy, &n);
156443 if( z==0 ){
156444 assert( n==0 );
156445 z = zCopy;
156447 z[n] = '\0';
156448 sqlite3Fts3Dequote(z);
156450 m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
156451 if( !m ){
156452 sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
156453 rc = SQLITE_ERROR;
156454 }else{
156455 char const **aArg = 0;
156456 int iArg = 0;
156457 z = &z[n+1];
156458 while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
156459 int nNew = sizeof(char *)*(iArg+1);
156460 char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
156461 if( !aNew ){
156462 sqlite3_free(zCopy);
156463 sqlite3_free((void *)aArg);
156464 return SQLITE_NOMEM;
156466 aArg = aNew;
156467 aArg[iArg++] = z;
156468 z[n] = '\0';
156469 sqlite3Fts3Dequote(z);
156470 z = &z[n+1];
156472 rc = m->xCreate(iArg, aArg, ppTok);
156473 assert( rc!=SQLITE_OK || *ppTok );
156474 if( rc!=SQLITE_OK ){
156475 sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
156476 }else{
156477 (*ppTok)->pModule = m;
156479 sqlite3_free((void *)aArg);
156482 sqlite3_free(zCopy);
156483 return rc;
156487 #ifdef SQLITE_TEST
156489 #if defined(INCLUDE_SQLITE_TCL_H)
156490 # include "sqlite_tcl.h"
156491 #else
156492 # include "tcl.h"
156493 #endif
156494 /* #include <string.h> */
156497 ** Implementation of a special SQL scalar function for testing tokenizers
156498 ** designed to be used in concert with the Tcl testing framework. This
156499 ** function must be called with two or more arguments:
156501 ** SELECT <function-name>(<key-name>, ..., <input-string>);
156503 ** where <function-name> is the name passed as the second argument
156504 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
156505 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
156507 ** The return value is a string that may be interpreted as a Tcl
156508 ** list. For each token in the <input-string>, three elements are
156509 ** added to the returned list. The first is the token position, the
156510 ** second is the token text (folded, stemmed, etc.) and the third is the
156511 ** substring of <input-string> associated with the token. For example,
156512 ** using the built-in "simple" tokenizer:
156514 ** SELECT fts_tokenizer_test('simple', 'I don't see how');
156516 ** will return the string:
156518 ** "{0 i I 1 dont don't 2 see see 3 how how}"
156521 static void testFunc(
156522 sqlite3_context *context,
156523 int argc,
156524 sqlite3_value **argv
156526 Fts3Hash *pHash;
156527 sqlite3_tokenizer_module *p;
156528 sqlite3_tokenizer *pTokenizer = 0;
156529 sqlite3_tokenizer_cursor *pCsr = 0;
156531 const char *zErr = 0;
156533 const char *zName;
156534 int nName;
156535 const char *zInput;
156536 int nInput;
156538 const char *azArg[64];
156540 const char *zToken;
156541 int nToken = 0;
156542 int iStart = 0;
156543 int iEnd = 0;
156544 int iPos = 0;
156545 int i;
156547 Tcl_Obj *pRet;
156549 if( argc<2 ){
156550 sqlite3_result_error(context, "insufficient arguments", -1);
156551 return;
156554 nName = sqlite3_value_bytes(argv[0]);
156555 zName = (const char *)sqlite3_value_text(argv[0]);
156556 nInput = sqlite3_value_bytes(argv[argc-1]);
156557 zInput = (const char *)sqlite3_value_text(argv[argc-1]);
156559 pHash = (Fts3Hash *)sqlite3_user_data(context);
156560 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
156562 if( !p ){
156563 char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
156564 sqlite3_result_error(context, zErr2, -1);
156565 sqlite3_free(zErr2);
156566 return;
156569 pRet = Tcl_NewObj();
156570 Tcl_IncrRefCount(pRet);
156572 for(i=1; i<argc-1; i++){
156573 azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
156576 if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
156577 zErr = "error in xCreate()";
156578 goto finish;
156580 pTokenizer->pModule = p;
156581 if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
156582 zErr = "error in xOpen()";
156583 goto finish;
156586 while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
156587 Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
156588 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
156589 zToken = &zInput[iStart];
156590 nToken = iEnd-iStart;
156591 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
156594 if( SQLITE_OK!=p->xClose(pCsr) ){
156595 zErr = "error in xClose()";
156596 goto finish;
156598 if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
156599 zErr = "error in xDestroy()";
156600 goto finish;
156603 finish:
156604 if( zErr ){
156605 sqlite3_result_error(context, zErr, -1);
156606 }else{
156607 sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
156609 Tcl_DecrRefCount(pRet);
156612 static
156613 int registerTokenizer(
156614 sqlite3 *db,
156615 char *zName,
156616 const sqlite3_tokenizer_module *p
156618 int rc;
156619 sqlite3_stmt *pStmt;
156620 const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
156622 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
156623 if( rc!=SQLITE_OK ){
156624 return rc;
156627 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
156628 sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
156629 sqlite3_step(pStmt);
156631 return sqlite3_finalize(pStmt);
156635 static
156636 int queryTokenizer(
156637 sqlite3 *db,
156638 char *zName,
156639 const sqlite3_tokenizer_module **pp
156641 int rc;
156642 sqlite3_stmt *pStmt;
156643 const char zSql[] = "SELECT fts3_tokenizer(?)";
156645 *pp = 0;
156646 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
156647 if( rc!=SQLITE_OK ){
156648 return rc;
156651 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
156652 if( SQLITE_ROW==sqlite3_step(pStmt) ){
156653 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
156654 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
156658 return sqlite3_finalize(pStmt);
156661 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
156664 ** Implementation of the scalar function fts3_tokenizer_internal_test().
156665 ** This function is used for testing only, it is not included in the
156666 ** build unless SQLITE_TEST is defined.
156668 ** The purpose of this is to test that the fts3_tokenizer() function
156669 ** can be used as designed by the C-code in the queryTokenizer and
156670 ** registerTokenizer() functions above. These two functions are repeated
156671 ** in the README.tokenizer file as an example, so it is important to
156672 ** test them.
156674 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
156675 ** function with no arguments. An assert() will fail if a problem is
156676 ** detected. i.e.:
156678 ** SELECT fts3_tokenizer_internal_test();
156681 static void intTestFunc(
156682 sqlite3_context *context,
156683 int argc,
156684 sqlite3_value **argv
156686 int rc;
156687 const sqlite3_tokenizer_module *p1;
156688 const sqlite3_tokenizer_module *p2;
156689 sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
156691 UNUSED_PARAMETER(argc);
156692 UNUSED_PARAMETER(argv);
156694 /* Test the query function */
156695 sqlite3Fts3SimpleTokenizerModule(&p1);
156696 rc = queryTokenizer(db, "simple", &p2);
156697 assert( rc==SQLITE_OK );
156698 assert( p1==p2 );
156699 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
156700 assert( rc==SQLITE_ERROR );
156701 assert( p2==0 );
156702 assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
156704 /* Test the storage function */
156705 if( fts3TokenizerEnabled(context) ){
156706 rc = registerTokenizer(db, "nosuchtokenizer", p1);
156707 assert( rc==SQLITE_OK );
156708 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
156709 assert( rc==SQLITE_OK );
156710 assert( p2==p1 );
156713 sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
156716 #endif
156719 ** Set up SQL objects in database db used to access the contents of
156720 ** the hash table pointed to by argument pHash. The hash table must
156721 ** been initialized to use string keys, and to take a private copy
156722 ** of the key when a value is inserted. i.e. by a call similar to:
156724 ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
156726 ** This function adds a scalar function (see header comment above
156727 ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
156728 ** defined at compilation time, a temporary virtual table (see header
156729 ** comment above struct HashTableVtab) to the database schema. Both
156730 ** provide read/write access to the contents of *pHash.
156732 ** The third argument to this function, zName, is used as the name
156733 ** of both the scalar and, if created, the virtual table.
156735 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
156736 sqlite3 *db,
156737 Fts3Hash *pHash,
156738 const char *zName
156740 int rc = SQLITE_OK;
156741 void *p = (void *)pHash;
156742 const int any = SQLITE_ANY;
156744 #ifdef SQLITE_TEST
156745 char *zTest = 0;
156746 char *zTest2 = 0;
156747 void *pdb = (void *)db;
156748 zTest = sqlite3_mprintf("%s_test", zName);
156749 zTest2 = sqlite3_mprintf("%s_internal_test", zName);
156750 if( !zTest || !zTest2 ){
156751 rc = SQLITE_NOMEM;
156753 #endif
156755 if( SQLITE_OK==rc ){
156756 rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
156758 if( SQLITE_OK==rc ){
156759 rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
156761 #ifdef SQLITE_TEST
156762 if( SQLITE_OK==rc ){
156763 rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
156765 if( SQLITE_OK==rc ){
156766 rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
156768 #endif
156770 #ifdef SQLITE_TEST
156771 sqlite3_free(zTest);
156772 sqlite3_free(zTest2);
156773 #endif
156775 return rc;
156778 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
156780 /************** End of fts3_tokenizer.c **************************************/
156781 /************** Begin file fts3_tokenizer1.c *********************************/
156783 ** 2006 Oct 10
156785 ** The author disclaims copyright to this source code. In place of
156786 ** a legal notice, here is a blessing:
156788 ** May you do good and not evil.
156789 ** May you find forgiveness for yourself and forgive others.
156790 ** May you share freely, never taking more than you give.
156792 ******************************************************************************
156794 ** Implementation of the "simple" full-text-search tokenizer.
156798 ** The code in this file is only compiled if:
156800 ** * The FTS3 module is being built as an extension
156801 ** (in which case SQLITE_CORE is not defined), or
156803 ** * The FTS3 module is being built into the core of
156804 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
156806 /* #include "fts3Int.h" */
156807 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
156809 /* #include <assert.h> */
156810 /* #include <stdlib.h> */
156811 /* #include <stdio.h> */
156812 /* #include <string.h> */
156814 /* #include "fts3_tokenizer.h" */
156816 typedef struct simple_tokenizer {
156817 sqlite3_tokenizer base;
156818 char delim[128]; /* flag ASCII delimiters */
156819 } simple_tokenizer;
156821 typedef struct simple_tokenizer_cursor {
156822 sqlite3_tokenizer_cursor base;
156823 const char *pInput; /* input we are tokenizing */
156824 int nBytes; /* size of the input */
156825 int iOffset; /* current position in pInput */
156826 int iToken; /* index of next token to be returned */
156827 char *pToken; /* storage for current token */
156828 int nTokenAllocated; /* space allocated to zToken buffer */
156829 } simple_tokenizer_cursor;
156832 static int simpleDelim(simple_tokenizer *t, unsigned char c){
156833 return c<0x80 && t->delim[c];
156835 static int fts3_isalnum(int x){
156836 return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
156840 ** Create a new tokenizer instance.
156842 static int simpleCreate(
156843 int argc, const char * const *argv,
156844 sqlite3_tokenizer **ppTokenizer
156846 simple_tokenizer *t;
156848 t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
156849 if( t==NULL ) return SQLITE_NOMEM;
156850 memset(t, 0, sizeof(*t));
156852 /* TODO(shess) Delimiters need to remain the same from run to run,
156853 ** else we need to reindex. One solution would be a meta-table to
156854 ** track such information in the database, then we'd only want this
156855 ** information on the initial create.
156857 if( argc>1 ){
156858 int i, n = (int)strlen(argv[1]);
156859 for(i=0; i<n; i++){
156860 unsigned char ch = argv[1][i];
156861 /* We explicitly don't support UTF-8 delimiters for now. */
156862 if( ch>=0x80 ){
156863 sqlite3_free(t);
156864 return SQLITE_ERROR;
156866 t->delim[ch] = 1;
156868 } else {
156869 /* Mark non-alphanumeric ASCII characters as delimiters */
156870 int i;
156871 for(i=1; i<0x80; i++){
156872 t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
156876 *ppTokenizer = &t->base;
156877 return SQLITE_OK;
156881 ** Destroy a tokenizer
156883 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
156884 sqlite3_free(pTokenizer);
156885 return SQLITE_OK;
156889 ** Prepare to begin tokenizing a particular string. The input
156890 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
156891 ** used to incrementally tokenize this string is returned in
156892 ** *ppCursor.
156894 static int simpleOpen(
156895 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
156896 const char *pInput, int nBytes, /* String to be tokenized */
156897 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
156899 simple_tokenizer_cursor *c;
156901 UNUSED_PARAMETER(pTokenizer);
156903 c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
156904 if( c==NULL ) return SQLITE_NOMEM;
156906 c->pInput = pInput;
156907 if( pInput==0 ){
156908 c->nBytes = 0;
156909 }else if( nBytes<0 ){
156910 c->nBytes = (int)strlen(pInput);
156911 }else{
156912 c->nBytes = nBytes;
156914 c->iOffset = 0; /* start tokenizing at the beginning */
156915 c->iToken = 0;
156916 c->pToken = NULL; /* no space allocated, yet. */
156917 c->nTokenAllocated = 0;
156919 *ppCursor = &c->base;
156920 return SQLITE_OK;
156924 ** Close a tokenization cursor previously opened by a call to
156925 ** simpleOpen() above.
156927 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
156928 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
156929 sqlite3_free(c->pToken);
156930 sqlite3_free(c);
156931 return SQLITE_OK;
156935 ** Extract the next token from a tokenization cursor. The cursor must
156936 ** have been opened by a prior call to simpleOpen().
156938 static int simpleNext(
156939 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
156940 const char **ppToken, /* OUT: *ppToken is the token text */
156941 int *pnBytes, /* OUT: Number of bytes in token */
156942 int *piStartOffset, /* OUT: Starting offset of token */
156943 int *piEndOffset, /* OUT: Ending offset of token */
156944 int *piPosition /* OUT: Position integer of token */
156946 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
156947 simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
156948 unsigned char *p = (unsigned char *)c->pInput;
156950 while( c->iOffset<c->nBytes ){
156951 int iStartOffset;
156953 /* Scan past delimiter characters */
156954 while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
156955 c->iOffset++;
156958 /* Count non-delimiter characters. */
156959 iStartOffset = c->iOffset;
156960 while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
156961 c->iOffset++;
156964 if( c->iOffset>iStartOffset ){
156965 int i, n = c->iOffset-iStartOffset;
156966 if( n>c->nTokenAllocated ){
156967 char *pNew;
156968 c->nTokenAllocated = n+20;
156969 pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
156970 if( !pNew ) return SQLITE_NOMEM;
156971 c->pToken = pNew;
156973 for(i=0; i<n; i++){
156974 /* TODO(shess) This needs expansion to handle UTF-8
156975 ** case-insensitivity.
156977 unsigned char ch = p[iStartOffset+i];
156978 c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
156980 *ppToken = c->pToken;
156981 *pnBytes = n;
156982 *piStartOffset = iStartOffset;
156983 *piEndOffset = c->iOffset;
156984 *piPosition = c->iToken++;
156986 return SQLITE_OK;
156989 return SQLITE_DONE;
156993 ** The set of routines that implement the simple tokenizer
156995 static const sqlite3_tokenizer_module simpleTokenizerModule = {
156997 simpleCreate,
156998 simpleDestroy,
156999 simpleOpen,
157000 simpleClose,
157001 simpleNext,
157006 ** Allocate a new simple tokenizer. Return a pointer to the new
157007 ** tokenizer in *ppModule
157009 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
157010 sqlite3_tokenizer_module const**ppModule
157012 *ppModule = &simpleTokenizerModule;
157015 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
157017 /************** End of fts3_tokenizer1.c *************************************/
157018 /************** Begin file fts3_tokenize_vtab.c ******************************/
157020 ** 2013 Apr 22
157022 ** The author disclaims copyright to this source code. In place of
157023 ** a legal notice, here is a blessing:
157025 ** May you do good and not evil.
157026 ** May you find forgiveness for yourself and forgive others.
157027 ** May you share freely, never taking more than you give.
157029 ******************************************************************************
157031 ** This file contains code for the "fts3tokenize" virtual table module.
157032 ** An fts3tokenize virtual table is created as follows:
157034 ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
157035 ** <tokenizer-name>, <arg-1>, ...
157036 ** );
157038 ** The table created has the following schema:
157040 ** CREATE TABLE <tbl>(input, token, start, end, position)
157042 ** When queried, the query must include a WHERE clause of type:
157044 ** input = <string>
157046 ** The virtual table module tokenizes this <string>, using the FTS3
157047 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
157048 ** statement and returns one row for each token in the result. With
157049 ** fields set as follows:
157051 ** input: Always set to a copy of <string>
157052 ** token: A token from the input.
157053 ** start: Byte offset of the token within the input <string>.
157054 ** end: Byte offset of the byte immediately following the end of the
157055 ** token within the input string.
157056 ** pos: Token offset of token within input.
157059 /* #include "fts3Int.h" */
157060 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
157062 /* #include <string.h> */
157063 /* #include <assert.h> */
157065 typedef struct Fts3tokTable Fts3tokTable;
157066 typedef struct Fts3tokCursor Fts3tokCursor;
157069 ** Virtual table structure.
157071 struct Fts3tokTable {
157072 sqlite3_vtab base; /* Base class used by SQLite core */
157073 const sqlite3_tokenizer_module *pMod;
157074 sqlite3_tokenizer *pTok;
157078 ** Virtual table cursor structure.
157080 struct Fts3tokCursor {
157081 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
157082 char *zInput; /* Input string */
157083 sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
157084 int iRowid; /* Current 'rowid' value */
157085 const char *zToken; /* Current 'token' value */
157086 int nToken; /* Size of zToken in bytes */
157087 int iStart; /* Current 'start' value */
157088 int iEnd; /* Current 'end' value */
157089 int iPos; /* Current 'pos' value */
157093 ** Query FTS for the tokenizer implementation named zName.
157095 static int fts3tokQueryTokenizer(
157096 Fts3Hash *pHash,
157097 const char *zName,
157098 const sqlite3_tokenizer_module **pp,
157099 char **pzErr
157101 sqlite3_tokenizer_module *p;
157102 int nName = (int)strlen(zName);
157104 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
157105 if( !p ){
157106 sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
157107 return SQLITE_ERROR;
157110 *pp = p;
157111 return SQLITE_OK;
157115 ** The second argument, argv[], is an array of pointers to nul-terminated
157116 ** strings. This function makes a copy of the array and strings into a
157117 ** single block of memory. It then dequotes any of the strings that appear
157118 ** to be quoted.
157120 ** If successful, output parameter *pazDequote is set to point at the
157121 ** array of dequoted strings and SQLITE_OK is returned. The caller is
157122 ** responsible for eventually calling sqlite3_free() to free the array
157123 ** in this case. Or, if an error occurs, an SQLite error code is returned.
157124 ** The final value of *pazDequote is undefined in this case.
157126 static int fts3tokDequoteArray(
157127 int argc, /* Number of elements in argv[] */
157128 const char * const *argv, /* Input array */
157129 char ***pazDequote /* Output array */
157131 int rc = SQLITE_OK; /* Return code */
157132 if( argc==0 ){
157133 *pazDequote = 0;
157134 }else{
157135 int i;
157136 int nByte = 0;
157137 char **azDequote;
157139 for(i=0; i<argc; i++){
157140 nByte += (int)(strlen(argv[i]) + 1);
157143 *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
157144 if( azDequote==0 ){
157145 rc = SQLITE_NOMEM;
157146 }else{
157147 char *pSpace = (char *)&azDequote[argc];
157148 for(i=0; i<argc; i++){
157149 int n = (int)strlen(argv[i]);
157150 azDequote[i] = pSpace;
157151 memcpy(pSpace, argv[i], n+1);
157152 sqlite3Fts3Dequote(pSpace);
157153 pSpace += (n+1);
157158 return rc;
157162 ** Schema of the tokenizer table.
157164 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
157167 ** This function does all the work for both the xConnect and xCreate methods.
157168 ** These tables have no persistent representation of their own, so xConnect
157169 ** and xCreate are identical operations.
157171 ** argv[0]: module name
157172 ** argv[1]: database name
157173 ** argv[2]: table name
157174 ** argv[3]: first argument (tokenizer name)
157176 static int fts3tokConnectMethod(
157177 sqlite3 *db, /* Database connection */
157178 void *pHash, /* Hash table of tokenizers */
157179 int argc, /* Number of elements in argv array */
157180 const char * const *argv, /* xCreate/xConnect argument array */
157181 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
157182 char **pzErr /* OUT: sqlite3_malloc'd error message */
157184 Fts3tokTable *pTab = 0;
157185 const sqlite3_tokenizer_module *pMod = 0;
157186 sqlite3_tokenizer *pTok = 0;
157187 int rc;
157188 char **azDequote = 0;
157189 int nDequote;
157191 rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
157192 if( rc!=SQLITE_OK ) return rc;
157194 nDequote = argc-3;
157195 rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
157197 if( rc==SQLITE_OK ){
157198 const char *zModule;
157199 if( nDequote<1 ){
157200 zModule = "simple";
157201 }else{
157202 zModule = azDequote[0];
157204 rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
157207 assert( (rc==SQLITE_OK)==(pMod!=0) );
157208 if( rc==SQLITE_OK ){
157209 const char * const *azArg = (const char * const *)&azDequote[1];
157210 rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
157213 if( rc==SQLITE_OK ){
157214 pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
157215 if( pTab==0 ){
157216 rc = SQLITE_NOMEM;
157220 if( rc==SQLITE_OK ){
157221 memset(pTab, 0, sizeof(Fts3tokTable));
157222 pTab->pMod = pMod;
157223 pTab->pTok = pTok;
157224 *ppVtab = &pTab->base;
157225 }else{
157226 if( pTok ){
157227 pMod->xDestroy(pTok);
157231 sqlite3_free(azDequote);
157232 return rc;
157236 ** This function does the work for both the xDisconnect and xDestroy methods.
157237 ** These tables have no persistent representation of their own, so xDisconnect
157238 ** and xDestroy are identical operations.
157240 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
157241 Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
157243 pTab->pMod->xDestroy(pTab->pTok);
157244 sqlite3_free(pTab);
157245 return SQLITE_OK;
157249 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
157251 static int fts3tokBestIndexMethod(
157252 sqlite3_vtab *pVTab,
157253 sqlite3_index_info *pInfo
157255 int i;
157256 UNUSED_PARAMETER(pVTab);
157258 for(i=0; i<pInfo->nConstraint; i++){
157259 if( pInfo->aConstraint[i].usable
157260 && pInfo->aConstraint[i].iColumn==0
157261 && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
157263 pInfo->idxNum = 1;
157264 pInfo->aConstraintUsage[i].argvIndex = 1;
157265 pInfo->aConstraintUsage[i].omit = 1;
157266 pInfo->estimatedCost = 1;
157267 return SQLITE_OK;
157271 pInfo->idxNum = 0;
157272 assert( pInfo->estimatedCost>1000000.0 );
157274 return SQLITE_OK;
157278 ** xOpen - Open a cursor.
157280 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
157281 Fts3tokCursor *pCsr;
157282 UNUSED_PARAMETER(pVTab);
157284 pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
157285 if( pCsr==0 ){
157286 return SQLITE_NOMEM;
157288 memset(pCsr, 0, sizeof(Fts3tokCursor));
157290 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
157291 return SQLITE_OK;
157295 ** Reset the tokenizer cursor passed as the only argument. As if it had
157296 ** just been returned by fts3tokOpenMethod().
157298 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
157299 if( pCsr->pCsr ){
157300 Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
157301 pTab->pMod->xClose(pCsr->pCsr);
157302 pCsr->pCsr = 0;
157304 sqlite3_free(pCsr->zInput);
157305 pCsr->zInput = 0;
157306 pCsr->zToken = 0;
157307 pCsr->nToken = 0;
157308 pCsr->iStart = 0;
157309 pCsr->iEnd = 0;
157310 pCsr->iPos = 0;
157311 pCsr->iRowid = 0;
157315 ** xClose - Close a cursor.
157317 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
157318 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157320 fts3tokResetCursor(pCsr);
157321 sqlite3_free(pCsr);
157322 return SQLITE_OK;
157326 ** xNext - Advance the cursor to the next row, if any.
157328 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
157329 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157330 Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
157331 int rc; /* Return code */
157333 pCsr->iRowid++;
157334 rc = pTab->pMod->xNext(pCsr->pCsr,
157335 &pCsr->zToken, &pCsr->nToken,
157336 &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
157339 if( rc!=SQLITE_OK ){
157340 fts3tokResetCursor(pCsr);
157341 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
157344 return rc;
157348 ** xFilter - Initialize a cursor to point at the start of its data.
157350 static int fts3tokFilterMethod(
157351 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
157352 int idxNum, /* Strategy index */
157353 const char *idxStr, /* Unused */
157354 int nVal, /* Number of elements in apVal */
157355 sqlite3_value **apVal /* Arguments for the indexing scheme */
157357 int rc = SQLITE_ERROR;
157358 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157359 Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
157360 UNUSED_PARAMETER(idxStr);
157361 UNUSED_PARAMETER(nVal);
157363 fts3tokResetCursor(pCsr);
157364 if( idxNum==1 ){
157365 const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
157366 int nByte = sqlite3_value_bytes(apVal[0]);
157367 pCsr->zInput = sqlite3_malloc(nByte+1);
157368 if( pCsr->zInput==0 ){
157369 rc = SQLITE_NOMEM;
157370 }else{
157371 memcpy(pCsr->zInput, zByte, nByte);
157372 pCsr->zInput[nByte] = 0;
157373 rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
157374 if( rc==SQLITE_OK ){
157375 pCsr->pCsr->pTokenizer = pTab->pTok;
157380 if( rc!=SQLITE_OK ) return rc;
157381 return fts3tokNextMethod(pCursor);
157385 ** xEof - Return true if the cursor is at EOF, or false otherwise.
157387 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
157388 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157389 return (pCsr->zToken==0);
157393 ** xColumn - Return a column value.
157395 static int fts3tokColumnMethod(
157396 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
157397 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
157398 int iCol /* Index of column to read value from */
157400 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157402 /* CREATE TABLE x(input, token, start, end, position) */
157403 switch( iCol ){
157404 case 0:
157405 sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
157406 break;
157407 case 1:
157408 sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
157409 break;
157410 case 2:
157411 sqlite3_result_int(pCtx, pCsr->iStart);
157412 break;
157413 case 3:
157414 sqlite3_result_int(pCtx, pCsr->iEnd);
157415 break;
157416 default:
157417 assert( iCol==4 );
157418 sqlite3_result_int(pCtx, pCsr->iPos);
157419 break;
157421 return SQLITE_OK;
157425 ** xRowid - Return the current rowid for the cursor.
157427 static int fts3tokRowidMethod(
157428 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
157429 sqlite_int64 *pRowid /* OUT: Rowid value */
157431 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157432 *pRowid = (sqlite3_int64)pCsr->iRowid;
157433 return SQLITE_OK;
157437 ** Register the fts3tok module with database connection db. Return SQLITE_OK
157438 ** if successful or an error code if sqlite3_create_module() fails.
157440 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
157441 static const sqlite3_module fts3tok_module = {
157442 0, /* iVersion */
157443 fts3tokConnectMethod, /* xCreate */
157444 fts3tokConnectMethod, /* xConnect */
157445 fts3tokBestIndexMethod, /* xBestIndex */
157446 fts3tokDisconnectMethod, /* xDisconnect */
157447 fts3tokDisconnectMethod, /* xDestroy */
157448 fts3tokOpenMethod, /* xOpen */
157449 fts3tokCloseMethod, /* xClose */
157450 fts3tokFilterMethod, /* xFilter */
157451 fts3tokNextMethod, /* xNext */
157452 fts3tokEofMethod, /* xEof */
157453 fts3tokColumnMethod, /* xColumn */
157454 fts3tokRowidMethod, /* xRowid */
157455 0, /* xUpdate */
157456 0, /* xBegin */
157457 0, /* xSync */
157458 0, /* xCommit */
157459 0, /* xRollback */
157460 0, /* xFindFunction */
157461 0, /* xRename */
157462 0, /* xSavepoint */
157463 0, /* xRelease */
157464 0 /* xRollbackTo */
157466 int rc; /* Return code */
157468 rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
157469 return rc;
157472 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
157474 /************** End of fts3_tokenize_vtab.c **********************************/
157475 /************** Begin file fts3_write.c **************************************/
157477 ** 2009 Oct 23
157479 ** The author disclaims copyright to this source code. In place of
157480 ** a legal notice, here is a blessing:
157482 ** May you do good and not evil.
157483 ** May you find forgiveness for yourself and forgive others.
157484 ** May you share freely, never taking more than you give.
157486 ******************************************************************************
157488 ** This file is part of the SQLite FTS3 extension module. Specifically,
157489 ** this file contains code to insert, update and delete rows from FTS3
157490 ** tables. It also contains code to merge FTS3 b-tree segments. Some
157491 ** of the sub-routines used to merge segments are also used by the query
157492 ** code in fts3.c.
157495 /* #include "fts3Int.h" */
157496 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
157498 /* #include <string.h> */
157499 /* #include <assert.h> */
157500 /* #include <stdlib.h> */
157503 #define FTS_MAX_APPENDABLE_HEIGHT 16
157506 ** When full-text index nodes are loaded from disk, the buffer that they
157507 ** are loaded into has the following number of bytes of padding at the end
157508 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
157509 ** of 920 bytes is allocated for it.
157511 ** This means that if we have a pointer into a buffer containing node data,
157512 ** it is always safe to read up to two varints from it without risking an
157513 ** overread, even if the node data is corrupted.
157515 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
157518 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
157519 ** memory incrementally instead of all at once. This can be a big performance
157520 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
157521 ** method before retrieving all query results (as may happen, for example,
157522 ** if a query has a LIMIT clause).
157524 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
157525 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
157526 ** The code is written so that the hard lower-limit for each of these values
157527 ** is 1. Clearly such small values would be inefficient, but can be useful
157528 ** for testing purposes.
157530 ** If this module is built with SQLITE_TEST defined, these constants may
157531 ** be overridden at runtime for testing purposes. File fts3_test.c contains
157532 ** a Tcl interface to read and write the values.
157534 #ifdef SQLITE_TEST
157535 int test_fts3_node_chunksize = (4*1024);
157536 int test_fts3_node_chunk_threshold = (4*1024)*4;
157537 # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
157538 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
157539 #else
157540 # define FTS3_NODE_CHUNKSIZE (4*1024)
157541 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
157542 #endif
157545 ** The two values that may be meaningfully bound to the :1 parameter in
157546 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
157548 #define FTS_STAT_DOCTOTAL 0
157549 #define FTS_STAT_INCRMERGEHINT 1
157550 #define FTS_STAT_AUTOINCRMERGE 2
157553 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
157554 ** and incremental merge operation that takes place. This is used for
157555 ** debugging FTS only, it should not usually be turned on in production
157556 ** systems.
157558 #ifdef FTS3_LOG_MERGES
157559 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
157560 sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
157562 #else
157563 #define fts3LogMerge(x, y)
157564 #endif
157567 typedef struct PendingList PendingList;
157568 typedef struct SegmentNode SegmentNode;
157569 typedef struct SegmentWriter SegmentWriter;
157572 ** An instance of the following data structure is used to build doclists
157573 ** incrementally. See function fts3PendingListAppend() for details.
157575 struct PendingList {
157576 int nData;
157577 char *aData;
157578 int nSpace;
157579 sqlite3_int64 iLastDocid;
157580 sqlite3_int64 iLastCol;
157581 sqlite3_int64 iLastPos;
157586 ** Each cursor has a (possibly empty) linked list of the following objects.
157588 struct Fts3DeferredToken {
157589 Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
157590 int iCol; /* Column token must occur in */
157591 Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
157592 PendingList *pList; /* Doclist is assembled here */
157596 ** An instance of this structure is used to iterate through the terms on
157597 ** a contiguous set of segment b-tree leaf nodes. Although the details of
157598 ** this structure are only manipulated by code in this file, opaque handles
157599 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
157600 ** terms when querying the full-text index. See functions:
157602 ** sqlite3Fts3SegReaderNew()
157603 ** sqlite3Fts3SegReaderFree()
157604 ** sqlite3Fts3SegReaderIterate()
157606 ** Methods used to manipulate Fts3SegReader structures:
157608 ** fts3SegReaderNext()
157609 ** fts3SegReaderFirstDocid()
157610 ** fts3SegReaderNextDocid()
157612 struct Fts3SegReader {
157613 int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
157614 u8 bLookup; /* True for a lookup only */
157615 u8 rootOnly; /* True for a root-only reader */
157617 sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
157618 sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
157619 sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
157620 sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
157622 char *aNode; /* Pointer to node data (or NULL) */
157623 int nNode; /* Size of buffer at aNode (or 0) */
157624 int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
157625 sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
157627 Fts3HashElem **ppNextElem;
157629 /* Variables set by fts3SegReaderNext(). These may be read directly
157630 ** by the caller. They are valid from the time SegmentReaderNew() returns
157631 ** until SegmentReaderNext() returns something other than SQLITE_OK
157632 ** (i.e. SQLITE_DONE).
157634 int nTerm; /* Number of bytes in current term */
157635 char *zTerm; /* Pointer to current term */
157636 int nTermAlloc; /* Allocated size of zTerm buffer */
157637 char *aDoclist; /* Pointer to doclist of current entry */
157638 int nDoclist; /* Size of doclist in current entry */
157640 /* The following variables are used by fts3SegReaderNextDocid() to iterate
157641 ** through the current doclist (aDoclist/nDoclist).
157643 char *pOffsetList;
157644 int nOffsetList; /* For descending pending seg-readers only */
157645 sqlite3_int64 iDocid;
157648 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
157649 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
157652 ** An instance of this structure is used to create a segment b-tree in the
157653 ** database. The internal details of this type are only accessed by the
157654 ** following functions:
157656 ** fts3SegWriterAdd()
157657 ** fts3SegWriterFlush()
157658 ** fts3SegWriterFree()
157660 struct SegmentWriter {
157661 SegmentNode *pTree; /* Pointer to interior tree structure */
157662 sqlite3_int64 iFirst; /* First slot in %_segments written */
157663 sqlite3_int64 iFree; /* Next free slot in %_segments */
157664 char *zTerm; /* Pointer to previous term buffer */
157665 int nTerm; /* Number of bytes in zTerm */
157666 int nMalloc; /* Size of malloc'd buffer at zMalloc */
157667 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
157668 int nSize; /* Size of allocation at aData */
157669 int nData; /* Bytes of data in aData */
157670 char *aData; /* Pointer to block from malloc() */
157671 i64 nLeafData; /* Number of bytes of leaf data written */
157675 ** Type SegmentNode is used by the following three functions to create
157676 ** the interior part of the segment b+-tree structures (everything except
157677 ** the leaf nodes). These functions and type are only ever used by code
157678 ** within the fts3SegWriterXXX() family of functions described above.
157680 ** fts3NodeAddTerm()
157681 ** fts3NodeWrite()
157682 ** fts3NodeFree()
157684 ** When a b+tree is written to the database (either as a result of a merge
157685 ** or the pending-terms table being flushed), leaves are written into the
157686 ** database file as soon as they are completely populated. The interior of
157687 ** the tree is assembled in memory and written out only once all leaves have
157688 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
157689 ** very large, meaning that the interior of the tree consumes relatively
157690 ** little memory.
157692 struct SegmentNode {
157693 SegmentNode *pParent; /* Parent node (or NULL for root node) */
157694 SegmentNode *pRight; /* Pointer to right-sibling */
157695 SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
157696 int nEntry; /* Number of terms written to node so far */
157697 char *zTerm; /* Pointer to previous term buffer */
157698 int nTerm; /* Number of bytes in zTerm */
157699 int nMalloc; /* Size of malloc'd buffer at zMalloc */
157700 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
157701 int nData; /* Bytes of valid data so far */
157702 char *aData; /* Node data */
157706 ** Valid values for the second argument to fts3SqlStmt().
157708 #define SQL_DELETE_CONTENT 0
157709 #define SQL_IS_EMPTY 1
157710 #define SQL_DELETE_ALL_CONTENT 2
157711 #define SQL_DELETE_ALL_SEGMENTS 3
157712 #define SQL_DELETE_ALL_SEGDIR 4
157713 #define SQL_DELETE_ALL_DOCSIZE 5
157714 #define SQL_DELETE_ALL_STAT 6
157715 #define SQL_SELECT_CONTENT_BY_ROWID 7
157716 #define SQL_NEXT_SEGMENT_INDEX 8
157717 #define SQL_INSERT_SEGMENTS 9
157718 #define SQL_NEXT_SEGMENTS_ID 10
157719 #define SQL_INSERT_SEGDIR 11
157720 #define SQL_SELECT_LEVEL 12
157721 #define SQL_SELECT_LEVEL_RANGE 13
157722 #define SQL_SELECT_LEVEL_COUNT 14
157723 #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
157724 #define SQL_DELETE_SEGDIR_LEVEL 16
157725 #define SQL_DELETE_SEGMENTS_RANGE 17
157726 #define SQL_CONTENT_INSERT 18
157727 #define SQL_DELETE_DOCSIZE 19
157728 #define SQL_REPLACE_DOCSIZE 20
157729 #define SQL_SELECT_DOCSIZE 21
157730 #define SQL_SELECT_STAT 22
157731 #define SQL_REPLACE_STAT 23
157733 #define SQL_SELECT_ALL_PREFIX_LEVEL 24
157734 #define SQL_DELETE_ALL_TERMS_SEGDIR 25
157735 #define SQL_DELETE_SEGDIR_RANGE 26
157736 #define SQL_SELECT_ALL_LANGID 27
157737 #define SQL_FIND_MERGE_LEVEL 28
157738 #define SQL_MAX_LEAF_NODE_ESTIMATE 29
157739 #define SQL_DELETE_SEGDIR_ENTRY 30
157740 #define SQL_SHIFT_SEGDIR_ENTRY 31
157741 #define SQL_SELECT_SEGDIR 32
157742 #define SQL_CHOMP_SEGDIR 33
157743 #define SQL_SEGMENT_IS_APPENDABLE 34
157744 #define SQL_SELECT_INDEXES 35
157745 #define SQL_SELECT_MXLEVEL 36
157747 #define SQL_SELECT_LEVEL_RANGE2 37
157748 #define SQL_UPDATE_LEVEL_IDX 38
157749 #define SQL_UPDATE_LEVEL 39
157752 ** This function is used to obtain an SQLite prepared statement handle
157753 ** for the statement identified by the second argument. If successful,
157754 ** *pp is set to the requested statement handle and SQLITE_OK returned.
157755 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
157757 ** If argument apVal is not NULL, then it must point to an array with
157758 ** at least as many entries as the requested statement has bound
157759 ** parameters. The values are bound to the statements parameters before
157760 ** returning.
157762 static int fts3SqlStmt(
157763 Fts3Table *p, /* Virtual table handle */
157764 int eStmt, /* One of the SQL_XXX constants above */
157765 sqlite3_stmt **pp, /* OUT: Statement handle */
157766 sqlite3_value **apVal /* Values to bind to statement */
157768 const char *azSql[] = {
157769 /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
157770 /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
157771 /* 2 */ "DELETE FROM %Q.'%q_content'",
157772 /* 3 */ "DELETE FROM %Q.'%q_segments'",
157773 /* 4 */ "DELETE FROM %Q.'%q_segdir'",
157774 /* 5 */ "DELETE FROM %Q.'%q_docsize'",
157775 /* 6 */ "DELETE FROM %Q.'%q_stat'",
157776 /* 7 */ "SELECT %s WHERE rowid=?",
157777 /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
157778 /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
157779 /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
157780 /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
157782 /* Return segments in order from oldest to newest.*/
157783 /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
157784 "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
157785 /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
157786 "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
157787 "ORDER BY level DESC, idx ASC",
157789 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
157790 /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
157792 /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
157793 /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
157794 /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
157795 /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
157796 /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
157797 /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
157798 /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
157799 /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
157800 /* 24 */ "",
157801 /* 25 */ "",
157803 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
157804 /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
157806 /* This statement is used to determine which level to read the input from
157807 ** when performing an incremental merge. It returns the absolute level number
157808 ** of the oldest level in the db that contains at least ? segments. Or,
157809 ** if no level in the FTS index contains more than ? segments, the statement
157810 ** returns zero rows. */
157811 /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
157812 " GROUP BY level HAVING cnt>=?"
157813 " ORDER BY (level %% 1024) ASC LIMIT 1",
157815 /* Estimate the upper limit on the number of leaf nodes in a new segment
157816 ** created by merging the oldest :2 segments from absolute level :1. See
157817 ** function sqlite3Fts3Incrmerge() for details. */
157818 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
157819 " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
157821 /* SQL_DELETE_SEGDIR_ENTRY
157822 ** Delete the %_segdir entry on absolute level :1 with index :2. */
157823 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
157825 /* SQL_SHIFT_SEGDIR_ENTRY
157826 ** Modify the idx value for the segment with idx=:3 on absolute level :2
157827 ** to :1. */
157828 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
157830 /* SQL_SELECT_SEGDIR
157831 ** Read a single entry from the %_segdir table. The entry from absolute
157832 ** level :1 with index value :2. */
157833 /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
157834 "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
157836 /* SQL_CHOMP_SEGDIR
157837 ** Update the start_block (:1) and root (:2) fields of the %_segdir
157838 ** entry located on absolute level :3 with index :4. */
157839 /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
157840 "WHERE level = ? AND idx = ?",
157842 /* SQL_SEGMENT_IS_APPENDABLE
157843 ** Return a single row if the segment with end_block=? is appendable. Or
157844 ** no rows otherwise. */
157845 /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
157847 /* SQL_SELECT_INDEXES
157848 ** Return the list of valid segment indexes for absolute level ? */
157849 /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
157851 /* SQL_SELECT_MXLEVEL
157852 ** Return the largest relative level in the FTS index or indexes. */
157853 /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
157855 /* Return segments in order from oldest to newest.*/
157856 /* 37 */ "SELECT level, idx, end_block "
157857 "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
157858 "ORDER BY level DESC, idx ASC",
157860 /* Update statements used while promoting segments */
157861 /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
157862 "WHERE level=? AND idx=?",
157863 /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
157866 int rc = SQLITE_OK;
157867 sqlite3_stmt *pStmt;
157869 assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
157870 assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
157872 pStmt = p->aStmt[eStmt];
157873 if( !pStmt ){
157874 char *zSql;
157875 if( eStmt==SQL_CONTENT_INSERT ){
157876 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
157877 }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
157878 zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
157879 }else{
157880 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
157882 if( !zSql ){
157883 rc = SQLITE_NOMEM;
157884 }else{
157885 rc = sqlite3_prepare_v3(p->db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
157886 &pStmt, NULL);
157887 sqlite3_free(zSql);
157888 assert( rc==SQLITE_OK || pStmt==0 );
157889 p->aStmt[eStmt] = pStmt;
157892 if( apVal ){
157893 int i;
157894 int nParam = sqlite3_bind_parameter_count(pStmt);
157895 for(i=0; rc==SQLITE_OK && i<nParam; i++){
157896 rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
157899 *pp = pStmt;
157900 return rc;
157904 static int fts3SelectDocsize(
157905 Fts3Table *pTab, /* FTS3 table handle */
157906 sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
157907 sqlite3_stmt **ppStmt /* OUT: Statement handle */
157909 sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
157910 int rc; /* Return code */
157912 rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
157913 if( rc==SQLITE_OK ){
157914 sqlite3_bind_int64(pStmt, 1, iDocid);
157915 rc = sqlite3_step(pStmt);
157916 if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
157917 rc = sqlite3_reset(pStmt);
157918 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
157919 pStmt = 0;
157920 }else{
157921 rc = SQLITE_OK;
157925 *ppStmt = pStmt;
157926 return rc;
157929 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
157930 Fts3Table *pTab, /* Fts3 table handle */
157931 sqlite3_stmt **ppStmt /* OUT: Statement handle */
157933 sqlite3_stmt *pStmt = 0;
157934 int rc;
157935 rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
157936 if( rc==SQLITE_OK ){
157937 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
157938 if( sqlite3_step(pStmt)!=SQLITE_ROW
157939 || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
157941 rc = sqlite3_reset(pStmt);
157942 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
157943 pStmt = 0;
157946 *ppStmt = pStmt;
157947 return rc;
157950 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
157951 Fts3Table *pTab, /* Fts3 table handle */
157952 sqlite3_int64 iDocid, /* Docid to read size data for */
157953 sqlite3_stmt **ppStmt /* OUT: Statement handle */
157955 return fts3SelectDocsize(pTab, iDocid, ppStmt);
157959 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
157960 ** array apVal[] to the SQL statement identified by eStmt, the statement
157961 ** is executed.
157963 ** Returns SQLITE_OK if the statement is successfully executed, or an
157964 ** SQLite error code otherwise.
157966 static void fts3SqlExec(
157967 int *pRC, /* Result code */
157968 Fts3Table *p, /* The FTS3 table */
157969 int eStmt, /* Index of statement to evaluate */
157970 sqlite3_value **apVal /* Parameters to bind */
157972 sqlite3_stmt *pStmt;
157973 int rc;
157974 if( *pRC ) return;
157975 rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
157976 if( rc==SQLITE_OK ){
157977 sqlite3_step(pStmt);
157978 rc = sqlite3_reset(pStmt);
157980 *pRC = rc;
157985 ** This function ensures that the caller has obtained an exclusive
157986 ** shared-cache table-lock on the %_segdir table. This is required before
157987 ** writing data to the fts3 table. If this lock is not acquired first, then
157988 ** the caller may end up attempting to take this lock as part of committing
157989 ** a transaction, causing SQLite to return SQLITE_LOCKED or
157990 ** LOCKED_SHAREDCACHEto a COMMIT command.
157992 ** It is best to avoid this because if FTS3 returns any error when
157993 ** committing a transaction, the whole transaction will be rolled back.
157994 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
157995 ** It can still happen if the user locks the underlying tables directly
157996 ** instead of accessing them via FTS.
157998 static int fts3Writelock(Fts3Table *p){
157999 int rc = SQLITE_OK;
158001 if( p->nPendingData==0 ){
158002 sqlite3_stmt *pStmt;
158003 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
158004 if( rc==SQLITE_OK ){
158005 sqlite3_bind_null(pStmt, 1);
158006 sqlite3_step(pStmt);
158007 rc = sqlite3_reset(pStmt);
158011 return rc;
158015 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
158016 ** Within each language id, a separate index is maintained to store the
158017 ** document terms, and each configured prefix size (configured the FTS
158018 ** "prefix=" option). And each index consists of multiple levels ("relative
158019 ** levels").
158021 ** All three of these values (the language id, the specific index and the
158022 ** level within the index) are encoded in 64-bit integer values stored
158023 ** in the %_segdir table on disk. This function is used to convert three
158024 ** separate component values into the single 64-bit integer value that
158025 ** can be used to query the %_segdir table.
158027 ** Specifically, each language-id/index combination is allocated 1024
158028 ** 64-bit integer level values ("absolute levels"). The main terms index
158029 ** for language-id 0 is allocate values 0-1023. The first prefix index
158030 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
158031 ** Language 1 indexes are allocated immediately following language 0.
158033 ** So, for a system with nPrefix prefix indexes configured, the block of
158034 ** absolute levels that corresponds to language-id iLangid and index
158035 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
158037 static sqlite3_int64 getAbsoluteLevel(
158038 Fts3Table *p, /* FTS3 table handle */
158039 int iLangid, /* Language id */
158040 int iIndex, /* Index in p->aIndex[] */
158041 int iLevel /* Level of segments */
158043 sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
158044 assert( iLangid>=0 );
158045 assert( p->nIndex>0 );
158046 assert( iIndex>=0 && iIndex<p->nIndex );
158048 iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
158049 return iBase + iLevel;
158053 ** Set *ppStmt to a statement handle that may be used to iterate through
158054 ** all rows in the %_segdir table, from oldest to newest. If successful,
158055 ** return SQLITE_OK. If an error occurs while preparing the statement,
158056 ** return an SQLite error code.
158058 ** There is only ever one instance of this SQL statement compiled for
158059 ** each FTS3 table.
158061 ** The statement returns the following columns from the %_segdir table:
158063 ** 0: idx
158064 ** 1: start_block
158065 ** 2: leaves_end_block
158066 ** 3: end_block
158067 ** 4: root
158069 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
158070 Fts3Table *p, /* FTS3 table */
158071 int iLangid, /* Language being queried */
158072 int iIndex, /* Index for p->aIndex[] */
158073 int iLevel, /* Level to select (relative level) */
158074 sqlite3_stmt **ppStmt /* OUT: Compiled statement */
158076 int rc;
158077 sqlite3_stmt *pStmt = 0;
158079 assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
158080 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
158081 assert( iIndex>=0 && iIndex<p->nIndex );
158083 if( iLevel<0 ){
158084 /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
158085 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
158086 if( rc==SQLITE_OK ){
158087 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
158088 sqlite3_bind_int64(pStmt, 2,
158089 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
158092 }else{
158093 /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
158094 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
158095 if( rc==SQLITE_OK ){
158096 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
158099 *ppStmt = pStmt;
158100 return rc;
158105 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
158106 ** if successful, or an SQLite error code otherwise.
158108 ** This function also serves to allocate the PendingList structure itself.
158109 ** For example, to create a new PendingList structure containing two
158110 ** varints:
158112 ** PendingList *p = 0;
158113 ** fts3PendingListAppendVarint(&p, 1);
158114 ** fts3PendingListAppendVarint(&p, 2);
158116 static int fts3PendingListAppendVarint(
158117 PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
158118 sqlite3_int64 i /* Value to append to data */
158120 PendingList *p = *pp;
158122 /* Allocate or grow the PendingList as required. */
158123 if( !p ){
158124 p = sqlite3_malloc(sizeof(*p) + 100);
158125 if( !p ){
158126 return SQLITE_NOMEM;
158128 p->nSpace = 100;
158129 p->aData = (char *)&p[1];
158130 p->nData = 0;
158132 else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
158133 int nNew = p->nSpace * 2;
158134 p = sqlite3_realloc(p, sizeof(*p) + nNew);
158135 if( !p ){
158136 sqlite3_free(*pp);
158137 *pp = 0;
158138 return SQLITE_NOMEM;
158140 p->nSpace = nNew;
158141 p->aData = (char *)&p[1];
158144 /* Append the new serialized varint to the end of the list. */
158145 p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
158146 p->aData[p->nData] = '\0';
158147 *pp = p;
158148 return SQLITE_OK;
158152 ** Add a docid/column/position entry to a PendingList structure. Non-zero
158153 ** is returned if the structure is sqlite3_realloced as part of adding
158154 ** the entry. Otherwise, zero.
158156 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
158157 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
158158 ** it is set to SQLITE_OK.
158160 static int fts3PendingListAppend(
158161 PendingList **pp, /* IN/OUT: PendingList structure */
158162 sqlite3_int64 iDocid, /* Docid for entry to add */
158163 sqlite3_int64 iCol, /* Column for entry to add */
158164 sqlite3_int64 iPos, /* Position of term for entry to add */
158165 int *pRc /* OUT: Return code */
158167 PendingList *p = *pp;
158168 int rc = SQLITE_OK;
158170 assert( !p || p->iLastDocid<=iDocid );
158172 if( !p || p->iLastDocid!=iDocid ){
158173 sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
158174 if( p ){
158175 assert( p->nData<p->nSpace );
158176 assert( p->aData[p->nData]==0 );
158177 p->nData++;
158179 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
158180 goto pendinglistappend_out;
158182 p->iLastCol = -1;
158183 p->iLastPos = 0;
158184 p->iLastDocid = iDocid;
158186 if( iCol>0 && p->iLastCol!=iCol ){
158187 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
158188 || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
158190 goto pendinglistappend_out;
158192 p->iLastCol = iCol;
158193 p->iLastPos = 0;
158195 if( iCol>=0 ){
158196 assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
158197 rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
158198 if( rc==SQLITE_OK ){
158199 p->iLastPos = iPos;
158203 pendinglistappend_out:
158204 *pRc = rc;
158205 if( p!=*pp ){
158206 *pp = p;
158207 return 1;
158209 return 0;
158213 ** Free a PendingList object allocated by fts3PendingListAppend().
158215 static void fts3PendingListDelete(PendingList *pList){
158216 sqlite3_free(pList);
158220 ** Add an entry to one of the pending-terms hash tables.
158222 static int fts3PendingTermsAddOne(
158223 Fts3Table *p,
158224 int iCol,
158225 int iPos,
158226 Fts3Hash *pHash, /* Pending terms hash table to add entry to */
158227 const char *zToken,
158228 int nToken
158230 PendingList *pList;
158231 int rc = SQLITE_OK;
158233 pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
158234 if( pList ){
158235 p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
158237 if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
158238 if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
158239 /* Malloc failed while inserting the new entry. This can only
158240 ** happen if there was no previous entry for this token.
158242 assert( 0==fts3HashFind(pHash, zToken, nToken) );
158243 sqlite3_free(pList);
158244 rc = SQLITE_NOMEM;
158247 if( rc==SQLITE_OK ){
158248 p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
158250 return rc;
158254 ** Tokenize the nul-terminated string zText and add all tokens to the
158255 ** pending-terms hash-table. The docid used is that currently stored in
158256 ** p->iPrevDocid, and the column is specified by argument iCol.
158258 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
158260 static int fts3PendingTermsAdd(
158261 Fts3Table *p, /* Table into which text will be inserted */
158262 int iLangid, /* Language id to use */
158263 const char *zText, /* Text of document to be inserted */
158264 int iCol, /* Column into which text is being inserted */
158265 u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
158267 int rc;
158268 int iStart = 0;
158269 int iEnd = 0;
158270 int iPos = 0;
158271 int nWord = 0;
158273 char const *zToken;
158274 int nToken = 0;
158276 sqlite3_tokenizer *pTokenizer = p->pTokenizer;
158277 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
158278 sqlite3_tokenizer_cursor *pCsr;
158279 int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
158280 const char**,int*,int*,int*,int*);
158282 assert( pTokenizer && pModule );
158284 /* If the user has inserted a NULL value, this function may be called with
158285 ** zText==0. In this case, add zero token entries to the hash table and
158286 ** return early. */
158287 if( zText==0 ){
158288 *pnWord = 0;
158289 return SQLITE_OK;
158292 rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
158293 if( rc!=SQLITE_OK ){
158294 return rc;
158297 xNext = pModule->xNext;
158298 while( SQLITE_OK==rc
158299 && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
158301 int i;
158302 if( iPos>=nWord ) nWord = iPos+1;
158304 /* Positions cannot be negative; we use -1 as a terminator internally.
158305 ** Tokens must have a non-zero length.
158307 if( iPos<0 || !zToken || nToken<=0 ){
158308 rc = SQLITE_ERROR;
158309 break;
158312 /* Add the term to the terms index */
158313 rc = fts3PendingTermsAddOne(
158314 p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
158317 /* Add the term to each of the prefix indexes that it is not too
158318 ** short for. */
158319 for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
158320 struct Fts3Index *pIndex = &p->aIndex[i];
158321 if( nToken<pIndex->nPrefix ) continue;
158322 rc = fts3PendingTermsAddOne(
158323 p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
158328 pModule->xClose(pCsr);
158329 *pnWord += nWord;
158330 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
158334 ** Calling this function indicates that subsequent calls to
158335 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
158336 ** contents of the document with docid iDocid.
158338 static int fts3PendingTermsDocid(
158339 Fts3Table *p, /* Full-text table handle */
158340 int bDelete, /* True if this op is a delete */
158341 int iLangid, /* Language id of row being written */
158342 sqlite_int64 iDocid /* Docid of row being written */
158344 assert( iLangid>=0 );
158345 assert( bDelete==1 || bDelete==0 );
158347 /* TODO(shess) Explore whether partially flushing the buffer on
158348 ** forced-flush would provide better performance. I suspect that if
158349 ** we ordered the doclists by size and flushed the largest until the
158350 ** buffer was half empty, that would let the less frequent terms
158351 ** generate longer doclists.
158353 if( iDocid<p->iPrevDocid
158354 || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
158355 || p->iPrevLangid!=iLangid
158356 || p->nPendingData>p->nMaxPendingData
158358 int rc = sqlite3Fts3PendingTermsFlush(p);
158359 if( rc!=SQLITE_OK ) return rc;
158361 p->iPrevDocid = iDocid;
158362 p->iPrevLangid = iLangid;
158363 p->bPrevDelete = bDelete;
158364 return SQLITE_OK;
158368 ** Discard the contents of the pending-terms hash tables.
158370 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
158371 int i;
158372 for(i=0; i<p->nIndex; i++){
158373 Fts3HashElem *pElem;
158374 Fts3Hash *pHash = &p->aIndex[i].hPending;
158375 for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
158376 PendingList *pList = (PendingList *)fts3HashData(pElem);
158377 fts3PendingListDelete(pList);
158379 fts3HashClear(pHash);
158381 p->nPendingData = 0;
158385 ** This function is called by the xUpdate() method as part of an INSERT
158386 ** operation. It adds entries for each term in the new record to the
158387 ** pendingTerms hash table.
158389 ** Argument apVal is the same as the similarly named argument passed to
158390 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
158392 static int fts3InsertTerms(
158393 Fts3Table *p,
158394 int iLangid,
158395 sqlite3_value **apVal,
158396 u32 *aSz
158398 int i; /* Iterator variable */
158399 for(i=2; i<p->nColumn+2; i++){
158400 int iCol = i-2;
158401 if( p->abNotindexed[iCol]==0 ){
158402 const char *zText = (const char *)sqlite3_value_text(apVal[i]);
158403 int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
158404 if( rc!=SQLITE_OK ){
158405 return rc;
158407 aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
158410 return SQLITE_OK;
158414 ** This function is called by the xUpdate() method for an INSERT operation.
158415 ** The apVal parameter is passed a copy of the apVal argument passed by
158416 ** SQLite to the xUpdate() method. i.e:
158418 ** apVal[0] Not used for INSERT.
158419 ** apVal[1] rowid
158420 ** apVal[2] Left-most user-defined column
158421 ** ...
158422 ** apVal[p->nColumn+1] Right-most user-defined column
158423 ** apVal[p->nColumn+2] Hidden column with same name as table
158424 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
158425 ** apVal[p->nColumn+4] Hidden languageid column
158427 static int fts3InsertData(
158428 Fts3Table *p, /* Full-text table */
158429 sqlite3_value **apVal, /* Array of values to insert */
158430 sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
158432 int rc; /* Return code */
158433 sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
158435 if( p->zContentTbl ){
158436 sqlite3_value *pRowid = apVal[p->nColumn+3];
158437 if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
158438 pRowid = apVal[1];
158440 if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
158441 return SQLITE_CONSTRAINT;
158443 *piDocid = sqlite3_value_int64(pRowid);
158444 return SQLITE_OK;
158447 /* Locate the statement handle used to insert data into the %_content
158448 ** table. The SQL for this statement is:
158450 ** INSERT INTO %_content VALUES(?, ?, ?, ...)
158452 ** The statement features N '?' variables, where N is the number of user
158453 ** defined columns in the FTS3 table, plus one for the docid field.
158455 rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
158456 if( rc==SQLITE_OK && p->zLanguageid ){
158457 rc = sqlite3_bind_int(
158458 pContentInsert, p->nColumn+2,
158459 sqlite3_value_int(apVal[p->nColumn+4])
158462 if( rc!=SQLITE_OK ) return rc;
158464 /* There is a quirk here. The users INSERT statement may have specified
158465 ** a value for the "rowid" field, for the "docid" field, or for both.
158466 ** Which is a problem, since "rowid" and "docid" are aliases for the
158467 ** same value. For example:
158469 ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
158471 ** In FTS3, this is an error. It is an error to specify non-NULL values
158472 ** for both docid and some other rowid alias.
158474 if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
158475 if( SQLITE_NULL==sqlite3_value_type(apVal[0])
158476 && SQLITE_NULL!=sqlite3_value_type(apVal[1])
158478 /* A rowid/docid conflict. */
158479 return SQLITE_ERROR;
158481 rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
158482 if( rc!=SQLITE_OK ) return rc;
158485 /* Execute the statement to insert the record. Set *piDocid to the
158486 ** new docid value.
158488 sqlite3_step(pContentInsert);
158489 rc = sqlite3_reset(pContentInsert);
158491 *piDocid = sqlite3_last_insert_rowid(p->db);
158492 return rc;
158498 ** Remove all data from the FTS3 table. Clear the hash table containing
158499 ** pending terms.
158501 static int fts3DeleteAll(Fts3Table *p, int bContent){
158502 int rc = SQLITE_OK; /* Return code */
158504 /* Discard the contents of the pending-terms hash table. */
158505 sqlite3Fts3PendingTermsClear(p);
158507 /* Delete everything from the shadow tables. Except, leave %_content as
158508 ** is if bContent is false. */
158509 assert( p->zContentTbl==0 || bContent==0 );
158510 if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
158511 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
158512 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
158513 if( p->bHasDocsize ){
158514 fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
158516 if( p->bHasStat ){
158517 fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
158519 return rc;
158525 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
158526 int iLangid = 0;
158527 if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
158528 return iLangid;
158532 ** The first element in the apVal[] array is assumed to contain the docid
158533 ** (an integer) of a row about to be deleted. Remove all terms from the
158534 ** full-text index.
158536 static void fts3DeleteTerms(
158537 int *pRC, /* Result code */
158538 Fts3Table *p, /* The FTS table to delete from */
158539 sqlite3_value *pRowid, /* The docid to be deleted */
158540 u32 *aSz, /* Sizes of deleted document written here */
158541 int *pbFound /* OUT: Set to true if row really does exist */
158543 int rc;
158544 sqlite3_stmt *pSelect;
158546 assert( *pbFound==0 );
158547 if( *pRC ) return;
158548 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
158549 if( rc==SQLITE_OK ){
158550 if( SQLITE_ROW==sqlite3_step(pSelect) ){
158551 int i;
158552 int iLangid = langidFromSelect(p, pSelect);
158553 i64 iDocid = sqlite3_column_int64(pSelect, 0);
158554 rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
158555 for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
158556 int iCol = i-1;
158557 if( p->abNotindexed[iCol]==0 ){
158558 const char *zText = (const char *)sqlite3_column_text(pSelect, i);
158559 rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
158560 aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
158563 if( rc!=SQLITE_OK ){
158564 sqlite3_reset(pSelect);
158565 *pRC = rc;
158566 return;
158568 *pbFound = 1;
158570 rc = sqlite3_reset(pSelect);
158571 }else{
158572 sqlite3_reset(pSelect);
158574 *pRC = rc;
158578 ** Forward declaration to account for the circular dependency between
158579 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
158581 static int fts3SegmentMerge(Fts3Table *, int, int, int);
158584 ** This function allocates a new level iLevel index in the segdir table.
158585 ** Usually, indexes are allocated within a level sequentially starting
158586 ** with 0, so the allocated index is one greater than the value returned
158587 ** by:
158589 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
158591 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
158592 ** level, they are merged into a single level (iLevel+1) segment and the
158593 ** allocated index is 0.
158595 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
158596 ** returned. Otherwise, an SQLite error code is returned.
158598 static int fts3AllocateSegdirIdx(
158599 Fts3Table *p,
158600 int iLangid, /* Language id */
158601 int iIndex, /* Index for p->aIndex */
158602 int iLevel,
158603 int *piIdx
158605 int rc; /* Return Code */
158606 sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
158607 int iNext = 0; /* Result of query pNextIdx */
158609 assert( iLangid>=0 );
158610 assert( p->nIndex>=1 );
158612 /* Set variable iNext to the next available segdir index at level iLevel. */
158613 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
158614 if( rc==SQLITE_OK ){
158615 sqlite3_bind_int64(
158616 pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
158618 if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
158619 iNext = sqlite3_column_int(pNextIdx, 0);
158621 rc = sqlite3_reset(pNextIdx);
158624 if( rc==SQLITE_OK ){
158625 /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
158626 ** full, merge all segments in level iLevel into a single iLevel+1
158627 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
158628 ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
158630 if( iNext>=FTS3_MERGE_COUNT ){
158631 fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
158632 rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
158633 *piIdx = 0;
158634 }else{
158635 *piIdx = iNext;
158639 return rc;
158643 ** The %_segments table is declared as follows:
158645 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
158647 ** This function reads data from a single row of the %_segments table. The
158648 ** specific row is identified by the iBlockid parameter. If paBlob is not
158649 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
158650 ** with the contents of the blob stored in the "block" column of the
158651 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
158652 ** to the size of the blob in bytes before returning.
158654 ** If an error occurs, or the table does not contain the specified row,
158655 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
158656 ** paBlob is non-NULL, then it is the responsibility of the caller to
158657 ** eventually free the returned buffer.
158659 ** This function may leave an open sqlite3_blob* handle in the
158660 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
158661 ** to this function. The handle may be closed by calling the
158662 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
158663 ** performance improvement, but the blob handle should always be closed
158664 ** before control is returned to the user (to prevent a lock being held
158665 ** on the database file for longer than necessary). Thus, any virtual table
158666 ** method (xFilter etc.) that may directly or indirectly call this function
158667 ** must call sqlite3Fts3SegmentsClose() before returning.
158669 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
158670 Fts3Table *p, /* FTS3 table handle */
158671 sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
158672 char **paBlob, /* OUT: Blob data in malloc'd buffer */
158673 int *pnBlob, /* OUT: Size of blob data */
158674 int *pnLoad /* OUT: Bytes actually loaded */
158676 int rc; /* Return code */
158678 /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
158679 assert( pnBlob );
158681 if( p->pSegments ){
158682 rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
158683 }else{
158684 if( 0==p->zSegmentsTbl ){
158685 p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
158686 if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
158688 rc = sqlite3_blob_open(
158689 p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
158693 if( rc==SQLITE_OK ){
158694 int nByte = sqlite3_blob_bytes(p->pSegments);
158695 *pnBlob = nByte;
158696 if( paBlob ){
158697 char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
158698 if( !aByte ){
158699 rc = SQLITE_NOMEM;
158700 }else{
158701 if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
158702 nByte = FTS3_NODE_CHUNKSIZE;
158703 *pnLoad = nByte;
158705 rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
158706 memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
158707 if( rc!=SQLITE_OK ){
158708 sqlite3_free(aByte);
158709 aByte = 0;
158712 *paBlob = aByte;
158716 return rc;
158720 ** Close the blob handle at p->pSegments, if it is open. See comments above
158721 ** the sqlite3Fts3ReadBlock() function for details.
158723 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
158724 sqlite3_blob_close(p->pSegments);
158725 p->pSegments = 0;
158728 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
158729 int nRead; /* Number of bytes to read */
158730 int rc; /* Return code */
158732 nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
158733 rc = sqlite3_blob_read(
158734 pReader->pBlob,
158735 &pReader->aNode[pReader->nPopulate],
158736 nRead,
158737 pReader->nPopulate
158740 if( rc==SQLITE_OK ){
158741 pReader->nPopulate += nRead;
158742 memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
158743 if( pReader->nPopulate==pReader->nNode ){
158744 sqlite3_blob_close(pReader->pBlob);
158745 pReader->pBlob = 0;
158746 pReader->nPopulate = 0;
158749 return rc;
158752 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
158753 int rc = SQLITE_OK;
158754 assert( !pReader->pBlob
158755 || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
158757 while( pReader->pBlob && rc==SQLITE_OK
158758 && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
158760 rc = fts3SegReaderIncrRead(pReader);
158762 return rc;
158766 ** Set an Fts3SegReader cursor to point at EOF.
158768 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
158769 if( !fts3SegReaderIsRootOnly(pSeg) ){
158770 sqlite3_free(pSeg->aNode);
158771 sqlite3_blob_close(pSeg->pBlob);
158772 pSeg->pBlob = 0;
158774 pSeg->aNode = 0;
158778 ** Move the iterator passed as the first argument to the next term in the
158779 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
158780 ** SQLITE_DONE. Otherwise, an SQLite error code.
158782 static int fts3SegReaderNext(
158783 Fts3Table *p,
158784 Fts3SegReader *pReader,
158785 int bIncr
158787 int rc; /* Return code of various sub-routines */
158788 char *pNext; /* Cursor variable */
158789 int nPrefix; /* Number of bytes in term prefix */
158790 int nSuffix; /* Number of bytes in term suffix */
158792 if( !pReader->aDoclist ){
158793 pNext = pReader->aNode;
158794 }else{
158795 pNext = &pReader->aDoclist[pReader->nDoclist];
158798 if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
158800 if( fts3SegReaderIsPending(pReader) ){
158801 Fts3HashElem *pElem = *(pReader->ppNextElem);
158802 sqlite3_free(pReader->aNode);
158803 pReader->aNode = 0;
158804 if( pElem ){
158805 char *aCopy;
158806 PendingList *pList = (PendingList *)fts3HashData(pElem);
158807 int nCopy = pList->nData+1;
158808 pReader->zTerm = (char *)fts3HashKey(pElem);
158809 pReader->nTerm = fts3HashKeysize(pElem);
158810 aCopy = (char*)sqlite3_malloc(nCopy);
158811 if( !aCopy ) return SQLITE_NOMEM;
158812 memcpy(aCopy, pList->aData, nCopy);
158813 pReader->nNode = pReader->nDoclist = nCopy;
158814 pReader->aNode = pReader->aDoclist = aCopy;
158815 pReader->ppNextElem++;
158816 assert( pReader->aNode );
158818 return SQLITE_OK;
158821 fts3SegReaderSetEof(pReader);
158823 /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
158824 ** blocks have already been traversed. */
158825 assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
158826 if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
158827 return SQLITE_OK;
158830 rc = sqlite3Fts3ReadBlock(
158831 p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
158832 (bIncr ? &pReader->nPopulate : 0)
158834 if( rc!=SQLITE_OK ) return rc;
158835 assert( pReader->pBlob==0 );
158836 if( bIncr && pReader->nPopulate<pReader->nNode ){
158837 pReader->pBlob = p->pSegments;
158838 p->pSegments = 0;
158840 pNext = pReader->aNode;
158843 assert( !fts3SegReaderIsPending(pReader) );
158845 rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
158846 if( rc!=SQLITE_OK ) return rc;
158848 /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
158849 ** safe (no risk of overread) even if the node data is corrupted. */
158850 pNext += fts3GetVarint32(pNext, &nPrefix);
158851 pNext += fts3GetVarint32(pNext, &nSuffix);
158852 if( nPrefix<0 || nSuffix<=0
158853 || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
158855 return FTS_CORRUPT_VTAB;
158858 if( nPrefix+nSuffix>pReader->nTermAlloc ){
158859 int nNew = (nPrefix+nSuffix)*2;
158860 char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
158861 if( !zNew ){
158862 return SQLITE_NOMEM;
158864 pReader->zTerm = zNew;
158865 pReader->nTermAlloc = nNew;
158868 rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
158869 if( rc!=SQLITE_OK ) return rc;
158871 memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
158872 pReader->nTerm = nPrefix+nSuffix;
158873 pNext += nSuffix;
158874 pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
158875 pReader->aDoclist = pNext;
158876 pReader->pOffsetList = 0;
158878 /* Check that the doclist does not appear to extend past the end of the
158879 ** b-tree node. And that the final byte of the doclist is 0x00. If either
158880 ** of these statements is untrue, then the data structure is corrupt.
158882 if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
158883 || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
158885 return FTS_CORRUPT_VTAB;
158887 return SQLITE_OK;
158891 ** Set the SegReader to point to the first docid in the doclist associated
158892 ** with the current term.
158894 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
158895 int rc = SQLITE_OK;
158896 assert( pReader->aDoclist );
158897 assert( !pReader->pOffsetList );
158898 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
158899 u8 bEof = 0;
158900 pReader->iDocid = 0;
158901 pReader->nOffsetList = 0;
158902 sqlite3Fts3DoclistPrev(0,
158903 pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
158904 &pReader->iDocid, &pReader->nOffsetList, &bEof
158906 }else{
158907 rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
158908 if( rc==SQLITE_OK ){
158909 int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
158910 pReader->pOffsetList = &pReader->aDoclist[n];
158913 return rc;
158917 ** Advance the SegReader to point to the next docid in the doclist
158918 ** associated with the current term.
158920 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
158921 ** *ppOffsetList is set to point to the first column-offset list
158922 ** in the doclist entry (i.e. immediately past the docid varint).
158923 ** *pnOffsetList is set to the length of the set of column-offset
158924 ** lists, not including the nul-terminator byte. For example:
158926 static int fts3SegReaderNextDocid(
158927 Fts3Table *pTab,
158928 Fts3SegReader *pReader, /* Reader to advance to next docid */
158929 char **ppOffsetList, /* OUT: Pointer to current position-list */
158930 int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
158932 int rc = SQLITE_OK;
158933 char *p = pReader->pOffsetList;
158934 char c = 0;
158936 assert( p );
158938 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
158939 /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
158940 ** Pending-terms doclists are always built up in ascending order, so
158941 ** we have to iterate through them backwards here. */
158942 u8 bEof = 0;
158943 if( ppOffsetList ){
158944 *ppOffsetList = pReader->pOffsetList;
158945 *pnOffsetList = pReader->nOffsetList - 1;
158947 sqlite3Fts3DoclistPrev(0,
158948 pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
158949 &pReader->nOffsetList, &bEof
158951 if( bEof ){
158952 pReader->pOffsetList = 0;
158953 }else{
158954 pReader->pOffsetList = p;
158956 }else{
158957 char *pEnd = &pReader->aDoclist[pReader->nDoclist];
158959 /* Pointer p currently points at the first byte of an offset list. The
158960 ** following block advances it to point one byte past the end of
158961 ** the same offset list. */
158962 while( 1 ){
158964 /* The following line of code (and the "p++" below the while() loop) is
158965 ** normally all that is required to move pointer p to the desired
158966 ** position. The exception is if this node is being loaded from disk
158967 ** incrementally and pointer "p" now points to the first byte past
158968 ** the populated part of pReader->aNode[].
158970 while( *p | c ) c = *p++ & 0x80;
158971 assert( *p==0 );
158973 if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
158974 rc = fts3SegReaderIncrRead(pReader);
158975 if( rc!=SQLITE_OK ) return rc;
158979 /* If required, populate the output variables with a pointer to and the
158980 ** size of the previous offset-list.
158982 if( ppOffsetList ){
158983 *ppOffsetList = pReader->pOffsetList;
158984 *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
158987 /* List may have been edited in place by fts3EvalNearTrim() */
158988 while( p<pEnd && *p==0 ) p++;
158990 /* If there are no more entries in the doclist, set pOffsetList to
158991 ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
158992 ** Fts3SegReader.pOffsetList to point to the next offset list before
158993 ** returning.
158995 if( p>=pEnd ){
158996 pReader->pOffsetList = 0;
158997 }else{
158998 rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
158999 if( rc==SQLITE_OK ){
159000 sqlite3_int64 iDelta;
159001 pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
159002 if( pTab->bDescIdx ){
159003 pReader->iDocid -= iDelta;
159004 }else{
159005 pReader->iDocid += iDelta;
159011 return SQLITE_OK;
159015 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
159016 Fts3Cursor *pCsr,
159017 Fts3MultiSegReader *pMsr,
159018 int *pnOvfl
159020 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
159021 int nOvfl = 0;
159022 int ii;
159023 int rc = SQLITE_OK;
159024 int pgsz = p->nPgsz;
159026 assert( p->bFts4 );
159027 assert( pgsz>0 );
159029 for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
159030 Fts3SegReader *pReader = pMsr->apSegment[ii];
159031 if( !fts3SegReaderIsPending(pReader)
159032 && !fts3SegReaderIsRootOnly(pReader)
159034 sqlite3_int64 jj;
159035 for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
159036 int nBlob;
159037 rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
159038 if( rc!=SQLITE_OK ) break;
159039 if( (nBlob+35)>pgsz ){
159040 nOvfl += (nBlob + 34)/pgsz;
159045 *pnOvfl = nOvfl;
159046 return rc;
159050 ** Free all allocations associated with the iterator passed as the
159051 ** second argument.
159053 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
159054 if( pReader ){
159055 if( !fts3SegReaderIsPending(pReader) ){
159056 sqlite3_free(pReader->zTerm);
159058 if( !fts3SegReaderIsRootOnly(pReader) ){
159059 sqlite3_free(pReader->aNode);
159061 sqlite3_blob_close(pReader->pBlob);
159063 sqlite3_free(pReader);
159067 ** Allocate a new SegReader object.
159069 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
159070 int iAge, /* Segment "age". */
159071 int bLookup, /* True for a lookup only */
159072 sqlite3_int64 iStartLeaf, /* First leaf to traverse */
159073 sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
159074 sqlite3_int64 iEndBlock, /* Final block of segment */
159075 const char *zRoot, /* Buffer containing root node */
159076 int nRoot, /* Size of buffer containing root node */
159077 Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
159079 Fts3SegReader *pReader; /* Newly allocated SegReader object */
159080 int nExtra = 0; /* Bytes to allocate segment root node */
159082 assert( iStartLeaf<=iEndLeaf );
159083 if( iStartLeaf==0 ){
159084 nExtra = nRoot + FTS3_NODE_PADDING;
159087 pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
159088 if( !pReader ){
159089 return SQLITE_NOMEM;
159091 memset(pReader, 0, sizeof(Fts3SegReader));
159092 pReader->iIdx = iAge;
159093 pReader->bLookup = bLookup!=0;
159094 pReader->iStartBlock = iStartLeaf;
159095 pReader->iLeafEndBlock = iEndLeaf;
159096 pReader->iEndBlock = iEndBlock;
159098 if( nExtra ){
159099 /* The entire segment is stored in the root node. */
159100 pReader->aNode = (char *)&pReader[1];
159101 pReader->rootOnly = 1;
159102 pReader->nNode = nRoot;
159103 memcpy(pReader->aNode, zRoot, nRoot);
159104 memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
159105 }else{
159106 pReader->iCurrentBlock = iStartLeaf-1;
159108 *ppReader = pReader;
159109 return SQLITE_OK;
159113 ** This is a comparison function used as a qsort() callback when sorting
159114 ** an array of pending terms by term. This occurs as part of flushing
159115 ** the contents of the pending-terms hash table to the database.
159117 static int SQLITE_CDECL fts3CompareElemByTerm(
159118 const void *lhs,
159119 const void *rhs
159121 char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
159122 char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
159123 int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
159124 int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
159126 int n = (n1<n2 ? n1 : n2);
159127 int c = memcmp(z1, z2, n);
159128 if( c==0 ){
159129 c = n1 - n2;
159131 return c;
159135 ** This function is used to allocate an Fts3SegReader that iterates through
159136 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
159138 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
159139 ** through each term in the pending-terms table. Or, if isPrefixIter is
159140 ** non-zero, it iterates through each term and its prefixes. For example, if
159141 ** the pending terms hash table contains the terms "sqlite", "mysql" and
159142 ** "firebird", then the iterator visits the following 'terms' (in the order
159143 ** shown):
159145 ** f fi fir fire fireb firebi firebir firebird
159146 ** m my mys mysq mysql
159147 ** s sq sql sqli sqlit sqlite
159149 ** Whereas if isPrefixIter is zero, the terms visited are:
159151 ** firebird mysql sqlite
159153 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
159154 Fts3Table *p, /* Virtual table handle */
159155 int iIndex, /* Index for p->aIndex */
159156 const char *zTerm, /* Term to search for */
159157 int nTerm, /* Size of buffer zTerm */
159158 int bPrefix, /* True for a prefix iterator */
159159 Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
159161 Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
159162 Fts3HashElem *pE; /* Iterator variable */
159163 Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
159164 int nElem = 0; /* Size of array at aElem */
159165 int rc = SQLITE_OK; /* Return Code */
159166 Fts3Hash *pHash;
159168 pHash = &p->aIndex[iIndex].hPending;
159169 if( bPrefix ){
159170 int nAlloc = 0; /* Size of allocated array at aElem */
159172 for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
159173 char *zKey = (char *)fts3HashKey(pE);
159174 int nKey = fts3HashKeysize(pE);
159175 if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
159176 if( nElem==nAlloc ){
159177 Fts3HashElem **aElem2;
159178 nAlloc += 16;
159179 aElem2 = (Fts3HashElem **)sqlite3_realloc(
159180 aElem, nAlloc*sizeof(Fts3HashElem *)
159182 if( !aElem2 ){
159183 rc = SQLITE_NOMEM;
159184 nElem = 0;
159185 break;
159187 aElem = aElem2;
159190 aElem[nElem++] = pE;
159194 /* If more than one term matches the prefix, sort the Fts3HashElem
159195 ** objects in term order using qsort(). This uses the same comparison
159196 ** callback as is used when flushing terms to disk.
159198 if( nElem>1 ){
159199 qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
159202 }else{
159203 /* The query is a simple term lookup that matches at most one term in
159204 ** the index. All that is required is a straight hash-lookup.
159206 ** Because the stack address of pE may be accessed via the aElem pointer
159207 ** below, the "Fts3HashElem *pE" must be declared so that it is valid
159208 ** within this entire function, not just this "else{...}" block.
159210 pE = fts3HashFindElem(pHash, zTerm, nTerm);
159211 if( pE ){
159212 aElem = &pE;
159213 nElem = 1;
159217 if( nElem>0 ){
159218 int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
159219 pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
159220 if( !pReader ){
159221 rc = SQLITE_NOMEM;
159222 }else{
159223 memset(pReader, 0, nByte);
159224 pReader->iIdx = 0x7FFFFFFF;
159225 pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
159226 memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
159230 if( bPrefix ){
159231 sqlite3_free(aElem);
159233 *ppReader = pReader;
159234 return rc;
159238 ** Compare the entries pointed to by two Fts3SegReader structures.
159239 ** Comparison is as follows:
159241 ** 1) EOF is greater than not EOF.
159243 ** 2) The current terms (if any) are compared using memcmp(). If one
159244 ** term is a prefix of another, the longer term is considered the
159245 ** larger.
159247 ** 3) By segment age. An older segment is considered larger.
159249 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
159250 int rc;
159251 if( pLhs->aNode && pRhs->aNode ){
159252 int rc2 = pLhs->nTerm - pRhs->nTerm;
159253 if( rc2<0 ){
159254 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
159255 }else{
159256 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
159258 if( rc==0 ){
159259 rc = rc2;
159261 }else{
159262 rc = (pLhs->aNode==0) - (pRhs->aNode==0);
159264 if( rc==0 ){
159265 rc = pRhs->iIdx - pLhs->iIdx;
159267 assert( rc!=0 );
159268 return rc;
159272 ** A different comparison function for SegReader structures. In this
159273 ** version, it is assumed that each SegReader points to an entry in
159274 ** a doclist for identical terms. Comparison is made as follows:
159276 ** 1) EOF (end of doclist in this case) is greater than not EOF.
159278 ** 2) By current docid.
159280 ** 3) By segment age. An older segment is considered larger.
159282 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
159283 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
159284 if( rc==0 ){
159285 if( pLhs->iDocid==pRhs->iDocid ){
159286 rc = pRhs->iIdx - pLhs->iIdx;
159287 }else{
159288 rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
159291 assert( pLhs->aNode && pRhs->aNode );
159292 return rc;
159294 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
159295 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
159296 if( rc==0 ){
159297 if( pLhs->iDocid==pRhs->iDocid ){
159298 rc = pRhs->iIdx - pLhs->iIdx;
159299 }else{
159300 rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
159303 assert( pLhs->aNode && pRhs->aNode );
159304 return rc;
159308 ** Compare the term that the Fts3SegReader object passed as the first argument
159309 ** points to with the term specified by arguments zTerm and nTerm.
159311 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
159312 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
159313 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
159315 static int fts3SegReaderTermCmp(
159316 Fts3SegReader *pSeg, /* Segment reader object */
159317 const char *zTerm, /* Term to compare to */
159318 int nTerm /* Size of term zTerm in bytes */
159320 int res = 0;
159321 if( pSeg->aNode ){
159322 if( pSeg->nTerm>nTerm ){
159323 res = memcmp(pSeg->zTerm, zTerm, nTerm);
159324 }else{
159325 res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
159327 if( res==0 ){
159328 res = pSeg->nTerm-nTerm;
159331 return res;
159335 ** Argument apSegment is an array of nSegment elements. It is known that
159336 ** the final (nSegment-nSuspect) members are already in sorted order
159337 ** (according to the comparison function provided). This function shuffles
159338 ** the array around until all entries are in sorted order.
159340 static void fts3SegReaderSort(
159341 Fts3SegReader **apSegment, /* Array to sort entries of */
159342 int nSegment, /* Size of apSegment array */
159343 int nSuspect, /* Unsorted entry count */
159344 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
159346 int i; /* Iterator variable */
159348 assert( nSuspect<=nSegment );
159350 if( nSuspect==nSegment ) nSuspect--;
159351 for(i=nSuspect-1; i>=0; i--){
159352 int j;
159353 for(j=i; j<(nSegment-1); j++){
159354 Fts3SegReader *pTmp;
159355 if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
159356 pTmp = apSegment[j+1];
159357 apSegment[j+1] = apSegment[j];
159358 apSegment[j] = pTmp;
159362 #ifndef NDEBUG
159363 /* Check that the list really is sorted now. */
159364 for(i=0; i<(nSuspect-1); i++){
159365 assert( xCmp(apSegment[i], apSegment[i+1])<0 );
159367 #endif
159371 ** Insert a record into the %_segments table.
159373 static int fts3WriteSegment(
159374 Fts3Table *p, /* Virtual table handle */
159375 sqlite3_int64 iBlock, /* Block id for new block */
159376 char *z, /* Pointer to buffer containing block data */
159377 int n /* Size of buffer z in bytes */
159379 sqlite3_stmt *pStmt;
159380 int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
159381 if( rc==SQLITE_OK ){
159382 sqlite3_bind_int64(pStmt, 1, iBlock);
159383 sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
159384 sqlite3_step(pStmt);
159385 rc = sqlite3_reset(pStmt);
159387 return rc;
159391 ** Find the largest relative level number in the table. If successful, set
159392 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
159393 ** set *pnMax to zero and return an SQLite error code.
159395 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
159396 int rc;
159397 int mxLevel = 0;
159398 sqlite3_stmt *pStmt = 0;
159400 rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
159401 if( rc==SQLITE_OK ){
159402 if( SQLITE_ROW==sqlite3_step(pStmt) ){
159403 mxLevel = sqlite3_column_int(pStmt, 0);
159405 rc = sqlite3_reset(pStmt);
159407 *pnMax = mxLevel;
159408 return rc;
159412 ** Insert a record into the %_segdir table.
159414 static int fts3WriteSegdir(
159415 Fts3Table *p, /* Virtual table handle */
159416 sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
159417 int iIdx, /* Value for "idx" field */
159418 sqlite3_int64 iStartBlock, /* Value for "start_block" field */
159419 sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
159420 sqlite3_int64 iEndBlock, /* Value for "end_block" field */
159421 sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
159422 char *zRoot, /* Blob value for "root" field */
159423 int nRoot /* Number of bytes in buffer zRoot */
159425 sqlite3_stmt *pStmt;
159426 int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
159427 if( rc==SQLITE_OK ){
159428 sqlite3_bind_int64(pStmt, 1, iLevel);
159429 sqlite3_bind_int(pStmt, 2, iIdx);
159430 sqlite3_bind_int64(pStmt, 3, iStartBlock);
159431 sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
159432 if( nLeafData==0 ){
159433 sqlite3_bind_int64(pStmt, 5, iEndBlock);
159434 }else{
159435 char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
159436 if( !zEnd ) return SQLITE_NOMEM;
159437 sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
159439 sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
159440 sqlite3_step(pStmt);
159441 rc = sqlite3_reset(pStmt);
159443 return rc;
159447 ** Return the size of the common prefix (if any) shared by zPrev and
159448 ** zNext, in bytes. For example,
159450 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
159451 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
159452 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
159454 static int fts3PrefixCompress(
159455 const char *zPrev, /* Buffer containing previous term */
159456 int nPrev, /* Size of buffer zPrev in bytes */
159457 const char *zNext, /* Buffer containing next term */
159458 int nNext /* Size of buffer zNext in bytes */
159460 int n;
159461 UNUSED_PARAMETER(nNext);
159462 for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
159463 return n;
159467 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
159468 ** (according to memcmp) than the previous term.
159470 static int fts3NodeAddTerm(
159471 Fts3Table *p, /* Virtual table handle */
159472 SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
159473 int isCopyTerm, /* True if zTerm/nTerm is transient */
159474 const char *zTerm, /* Pointer to buffer containing term */
159475 int nTerm /* Size of term in bytes */
159477 SegmentNode *pTree = *ppTree;
159478 int rc;
159479 SegmentNode *pNew;
159481 /* First try to append the term to the current node. Return early if
159482 ** this is possible.
159484 if( pTree ){
159485 int nData = pTree->nData; /* Current size of node in bytes */
159486 int nReq = nData; /* Required space after adding zTerm */
159487 int nPrefix; /* Number of bytes of prefix compression */
159488 int nSuffix; /* Suffix length */
159490 nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
159491 nSuffix = nTerm-nPrefix;
159493 nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
159494 if( nReq<=p->nNodeSize || !pTree->zTerm ){
159496 if( nReq>p->nNodeSize ){
159497 /* An unusual case: this is the first term to be added to the node
159498 ** and the static node buffer (p->nNodeSize bytes) is not large
159499 ** enough. Use a separately malloced buffer instead This wastes
159500 ** p->nNodeSize bytes, but since this scenario only comes about when
159501 ** the database contain two terms that share a prefix of almost 2KB,
159502 ** this is not expected to be a serious problem.
159504 assert( pTree->aData==(char *)&pTree[1] );
159505 pTree->aData = (char *)sqlite3_malloc(nReq);
159506 if( !pTree->aData ){
159507 return SQLITE_NOMEM;
159511 if( pTree->zTerm ){
159512 /* There is no prefix-length field for first term in a node */
159513 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
159516 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
159517 memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
159518 pTree->nData = nData + nSuffix;
159519 pTree->nEntry++;
159521 if( isCopyTerm ){
159522 if( pTree->nMalloc<nTerm ){
159523 char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
159524 if( !zNew ){
159525 return SQLITE_NOMEM;
159527 pTree->nMalloc = nTerm*2;
159528 pTree->zMalloc = zNew;
159530 pTree->zTerm = pTree->zMalloc;
159531 memcpy(pTree->zTerm, zTerm, nTerm);
159532 pTree->nTerm = nTerm;
159533 }else{
159534 pTree->zTerm = (char *)zTerm;
159535 pTree->nTerm = nTerm;
159537 return SQLITE_OK;
159541 /* If control flows to here, it was not possible to append zTerm to the
159542 ** current node. Create a new node (a right-sibling of the current node).
159543 ** If this is the first node in the tree, the term is added to it.
159545 ** Otherwise, the term is not added to the new node, it is left empty for
159546 ** now. Instead, the term is inserted into the parent of pTree. If pTree
159547 ** has no parent, one is created here.
159549 pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
159550 if( !pNew ){
159551 return SQLITE_NOMEM;
159553 memset(pNew, 0, sizeof(SegmentNode));
159554 pNew->nData = 1 + FTS3_VARINT_MAX;
159555 pNew->aData = (char *)&pNew[1];
159557 if( pTree ){
159558 SegmentNode *pParent = pTree->pParent;
159559 rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
159560 if( pTree->pParent==0 ){
159561 pTree->pParent = pParent;
159563 pTree->pRight = pNew;
159564 pNew->pLeftmost = pTree->pLeftmost;
159565 pNew->pParent = pParent;
159566 pNew->zMalloc = pTree->zMalloc;
159567 pNew->nMalloc = pTree->nMalloc;
159568 pTree->zMalloc = 0;
159569 }else{
159570 pNew->pLeftmost = pNew;
159571 rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
159574 *ppTree = pNew;
159575 return rc;
159579 ** Helper function for fts3NodeWrite().
159581 static int fts3TreeFinishNode(
159582 SegmentNode *pTree,
159583 int iHeight,
159584 sqlite3_int64 iLeftChild
159586 int nStart;
159587 assert( iHeight>=1 && iHeight<128 );
159588 nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
159589 pTree->aData[nStart] = (char)iHeight;
159590 sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
159591 return nStart;
159595 ** Write the buffer for the segment node pTree and all of its peers to the
159596 ** database. Then call this function recursively to write the parent of
159597 ** pTree and its peers to the database.
159599 ** Except, if pTree is a root node, do not write it to the database. Instead,
159600 ** set output variables *paRoot and *pnRoot to contain the root node.
159602 ** If successful, SQLITE_OK is returned and output variable *piLast is
159603 ** set to the largest blockid written to the database (or zero if no
159604 ** blocks were written to the db). Otherwise, an SQLite error code is
159605 ** returned.
159607 static int fts3NodeWrite(
159608 Fts3Table *p, /* Virtual table handle */
159609 SegmentNode *pTree, /* SegmentNode handle */
159610 int iHeight, /* Height of this node in tree */
159611 sqlite3_int64 iLeaf, /* Block id of first leaf node */
159612 sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
159613 sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
159614 char **paRoot, /* OUT: Data for root node */
159615 int *pnRoot /* OUT: Size of root node in bytes */
159617 int rc = SQLITE_OK;
159619 if( !pTree->pParent ){
159620 /* Root node of the tree. */
159621 int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
159622 *piLast = iFree-1;
159623 *pnRoot = pTree->nData - nStart;
159624 *paRoot = &pTree->aData[nStart];
159625 }else{
159626 SegmentNode *pIter;
159627 sqlite3_int64 iNextFree = iFree;
159628 sqlite3_int64 iNextLeaf = iLeaf;
159629 for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
159630 int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
159631 int nWrite = pIter->nData - nStart;
159633 rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
159634 iNextFree++;
159635 iNextLeaf += (pIter->nEntry+1);
159637 if( rc==SQLITE_OK ){
159638 assert( iNextLeaf==iFree );
159639 rc = fts3NodeWrite(
159640 p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
159645 return rc;
159649 ** Free all memory allocations associated with the tree pTree.
159651 static void fts3NodeFree(SegmentNode *pTree){
159652 if( pTree ){
159653 SegmentNode *p = pTree->pLeftmost;
159654 fts3NodeFree(p->pParent);
159655 while( p ){
159656 SegmentNode *pRight = p->pRight;
159657 if( p->aData!=(char *)&p[1] ){
159658 sqlite3_free(p->aData);
159660 assert( pRight==0 || p->zMalloc==0 );
159661 sqlite3_free(p->zMalloc);
159662 sqlite3_free(p);
159663 p = pRight;
159669 ** Add a term to the segment being constructed by the SegmentWriter object
159670 ** *ppWriter. When adding the first term to a segment, *ppWriter should
159671 ** be passed NULL. This function will allocate a new SegmentWriter object
159672 ** and return it via the input/output variable *ppWriter in this case.
159674 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
159676 static int fts3SegWriterAdd(
159677 Fts3Table *p, /* Virtual table handle */
159678 SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
159679 int isCopyTerm, /* True if buffer zTerm must be copied */
159680 const char *zTerm, /* Pointer to buffer containing term */
159681 int nTerm, /* Size of term in bytes */
159682 const char *aDoclist, /* Pointer to buffer containing doclist */
159683 int nDoclist /* Size of doclist in bytes */
159685 int nPrefix; /* Size of term prefix in bytes */
159686 int nSuffix; /* Size of term suffix in bytes */
159687 int nReq; /* Number of bytes required on leaf page */
159688 int nData;
159689 SegmentWriter *pWriter = *ppWriter;
159691 if( !pWriter ){
159692 int rc;
159693 sqlite3_stmt *pStmt;
159695 /* Allocate the SegmentWriter structure */
159696 pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
159697 if( !pWriter ) return SQLITE_NOMEM;
159698 memset(pWriter, 0, sizeof(SegmentWriter));
159699 *ppWriter = pWriter;
159701 /* Allocate a buffer in which to accumulate data */
159702 pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
159703 if( !pWriter->aData ) return SQLITE_NOMEM;
159704 pWriter->nSize = p->nNodeSize;
159706 /* Find the next free blockid in the %_segments table */
159707 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
159708 if( rc!=SQLITE_OK ) return rc;
159709 if( SQLITE_ROW==sqlite3_step(pStmt) ){
159710 pWriter->iFree = sqlite3_column_int64(pStmt, 0);
159711 pWriter->iFirst = pWriter->iFree;
159713 rc = sqlite3_reset(pStmt);
159714 if( rc!=SQLITE_OK ) return rc;
159716 nData = pWriter->nData;
159718 nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
159719 nSuffix = nTerm-nPrefix;
159721 /* Figure out how many bytes are required by this new entry */
159722 nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
159723 sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
159724 nSuffix + /* Term suffix */
159725 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
159726 nDoclist; /* Doclist data */
159728 if( nData>0 && nData+nReq>p->nNodeSize ){
159729 int rc;
159731 /* The current leaf node is full. Write it out to the database. */
159732 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
159733 if( rc!=SQLITE_OK ) return rc;
159734 p->nLeafAdd++;
159736 /* Add the current term to the interior node tree. The term added to
159737 ** the interior tree must:
159739 ** a) be greater than the largest term on the leaf node just written
159740 ** to the database (still available in pWriter->zTerm), and
159742 ** b) be less than or equal to the term about to be added to the new
159743 ** leaf node (zTerm/nTerm).
159745 ** In other words, it must be the prefix of zTerm 1 byte longer than
159746 ** the common prefix (if any) of zTerm and pWriter->zTerm.
159748 assert( nPrefix<nTerm );
159749 rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
159750 if( rc!=SQLITE_OK ) return rc;
159752 nData = 0;
159753 pWriter->nTerm = 0;
159755 nPrefix = 0;
159756 nSuffix = nTerm;
159757 nReq = 1 + /* varint containing prefix size */
159758 sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
159759 nTerm + /* Term suffix */
159760 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
159761 nDoclist; /* Doclist data */
159764 /* Increase the total number of bytes written to account for the new entry. */
159765 pWriter->nLeafData += nReq;
159767 /* If the buffer currently allocated is too small for this entry, realloc
159768 ** the buffer to make it large enough.
159770 if( nReq>pWriter->nSize ){
159771 char *aNew = sqlite3_realloc(pWriter->aData, nReq);
159772 if( !aNew ) return SQLITE_NOMEM;
159773 pWriter->aData = aNew;
159774 pWriter->nSize = nReq;
159776 assert( nData+nReq<=pWriter->nSize );
159778 /* Append the prefix-compressed term and doclist to the buffer. */
159779 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
159780 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
159781 memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
159782 nData += nSuffix;
159783 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
159784 memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
159785 pWriter->nData = nData + nDoclist;
159787 /* Save the current term so that it can be used to prefix-compress the next.
159788 ** If the isCopyTerm parameter is true, then the buffer pointed to by
159789 ** zTerm is transient, so take a copy of the term data. Otherwise, just
159790 ** store a copy of the pointer.
159792 if( isCopyTerm ){
159793 if( nTerm>pWriter->nMalloc ){
159794 char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
159795 if( !zNew ){
159796 return SQLITE_NOMEM;
159798 pWriter->nMalloc = nTerm*2;
159799 pWriter->zMalloc = zNew;
159800 pWriter->zTerm = zNew;
159802 assert( pWriter->zTerm==pWriter->zMalloc );
159803 memcpy(pWriter->zTerm, zTerm, nTerm);
159804 }else{
159805 pWriter->zTerm = (char *)zTerm;
159807 pWriter->nTerm = nTerm;
159809 return SQLITE_OK;
159813 ** Flush all data associated with the SegmentWriter object pWriter to the
159814 ** database. This function must be called after all terms have been added
159815 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
159816 ** returned. Otherwise, an SQLite error code.
159818 static int fts3SegWriterFlush(
159819 Fts3Table *p, /* Virtual table handle */
159820 SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
159821 sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
159822 int iIdx /* Value for 'idx' column of %_segdir */
159824 int rc; /* Return code */
159825 if( pWriter->pTree ){
159826 sqlite3_int64 iLast = 0; /* Largest block id written to database */
159827 sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
159828 char *zRoot = NULL; /* Pointer to buffer containing root node */
159829 int nRoot = 0; /* Size of buffer zRoot */
159831 iLastLeaf = pWriter->iFree;
159832 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
159833 if( rc==SQLITE_OK ){
159834 rc = fts3NodeWrite(p, pWriter->pTree, 1,
159835 pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
159837 if( rc==SQLITE_OK ){
159838 rc = fts3WriteSegdir(p, iLevel, iIdx,
159839 pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
159841 }else{
159842 /* The entire tree fits on the root node. Write it to the segdir table. */
159843 rc = fts3WriteSegdir(p, iLevel, iIdx,
159844 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
159846 p->nLeafAdd++;
159847 return rc;
159851 ** Release all memory held by the SegmentWriter object passed as the
159852 ** first argument.
159854 static void fts3SegWriterFree(SegmentWriter *pWriter){
159855 if( pWriter ){
159856 sqlite3_free(pWriter->aData);
159857 sqlite3_free(pWriter->zMalloc);
159858 fts3NodeFree(pWriter->pTree);
159859 sqlite3_free(pWriter);
159864 ** The first value in the apVal[] array is assumed to contain an integer.
159865 ** This function tests if there exist any documents with docid values that
159866 ** are different from that integer. i.e. if deleting the document with docid
159867 ** pRowid would mean the FTS3 table were empty.
159869 ** If successful, *pisEmpty is set to true if the table is empty except for
159870 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
159871 ** error occurs, an SQLite error code is returned.
159873 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
159874 sqlite3_stmt *pStmt;
159875 int rc;
159876 if( p->zContentTbl ){
159877 /* If using the content=xxx option, assume the table is never empty */
159878 *pisEmpty = 0;
159879 rc = SQLITE_OK;
159880 }else{
159881 rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
159882 if( rc==SQLITE_OK ){
159883 if( SQLITE_ROW==sqlite3_step(pStmt) ){
159884 *pisEmpty = sqlite3_column_int(pStmt, 0);
159886 rc = sqlite3_reset(pStmt);
159889 return rc;
159893 ** Set *pnMax to the largest segment level in the database for the index
159894 ** iIndex.
159896 ** Segment levels are stored in the 'level' column of the %_segdir table.
159898 ** Return SQLITE_OK if successful, or an SQLite error code if not.
159900 static int fts3SegmentMaxLevel(
159901 Fts3Table *p,
159902 int iLangid,
159903 int iIndex,
159904 sqlite3_int64 *pnMax
159906 sqlite3_stmt *pStmt;
159907 int rc;
159908 assert( iIndex>=0 && iIndex<p->nIndex );
159910 /* Set pStmt to the compiled version of:
159912 ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
159914 ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
159916 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
159917 if( rc!=SQLITE_OK ) return rc;
159918 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
159919 sqlite3_bind_int64(pStmt, 2,
159920 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
159922 if( SQLITE_ROW==sqlite3_step(pStmt) ){
159923 *pnMax = sqlite3_column_int64(pStmt, 0);
159925 return sqlite3_reset(pStmt);
159929 ** iAbsLevel is an absolute level that may be assumed to exist within
159930 ** the database. This function checks if it is the largest level number
159931 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
159932 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
159933 ** is returned. If an error occurs, an error code is returned and the
159934 ** final value of *pbMax is undefined.
159936 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
159938 /* Set pStmt to the compiled version of:
159940 ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
159942 ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
159944 sqlite3_stmt *pStmt;
159945 int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
159946 if( rc!=SQLITE_OK ) return rc;
159947 sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
159948 sqlite3_bind_int64(pStmt, 2,
159949 ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
159952 *pbMax = 0;
159953 if( SQLITE_ROW==sqlite3_step(pStmt) ){
159954 *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
159956 return sqlite3_reset(pStmt);
159960 ** Delete all entries in the %_segments table associated with the segment
159961 ** opened with seg-reader pSeg. This function does not affect the contents
159962 ** of the %_segdir table.
159964 static int fts3DeleteSegment(
159965 Fts3Table *p, /* FTS table handle */
159966 Fts3SegReader *pSeg /* Segment to delete */
159968 int rc = SQLITE_OK; /* Return code */
159969 if( pSeg->iStartBlock ){
159970 sqlite3_stmt *pDelete; /* SQL statement to delete rows */
159971 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
159972 if( rc==SQLITE_OK ){
159973 sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
159974 sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
159975 sqlite3_step(pDelete);
159976 rc = sqlite3_reset(pDelete);
159979 return rc;
159983 ** This function is used after merging multiple segments into a single large
159984 ** segment to delete the old, now redundant, segment b-trees. Specifically,
159985 ** it:
159987 ** 1) Deletes all %_segments entries for the segments associated with
159988 ** each of the SegReader objects in the array passed as the third
159989 ** argument, and
159991 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
159992 ** entries regardless of level if (iLevel<0).
159994 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
159996 static int fts3DeleteSegdir(
159997 Fts3Table *p, /* Virtual table handle */
159998 int iLangid, /* Language id */
159999 int iIndex, /* Index for p->aIndex */
160000 int iLevel, /* Level of %_segdir entries to delete */
160001 Fts3SegReader **apSegment, /* Array of SegReader objects */
160002 int nReader /* Size of array apSegment */
160004 int rc = SQLITE_OK; /* Return Code */
160005 int i; /* Iterator variable */
160006 sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
160008 for(i=0; rc==SQLITE_OK && i<nReader; i++){
160009 rc = fts3DeleteSegment(p, apSegment[i]);
160011 if( rc!=SQLITE_OK ){
160012 return rc;
160015 assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
160016 if( iLevel==FTS3_SEGCURSOR_ALL ){
160017 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
160018 if( rc==SQLITE_OK ){
160019 sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
160020 sqlite3_bind_int64(pDelete, 2,
160021 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
160024 }else{
160025 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
160026 if( rc==SQLITE_OK ){
160027 sqlite3_bind_int64(
160028 pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
160033 if( rc==SQLITE_OK ){
160034 sqlite3_step(pDelete);
160035 rc = sqlite3_reset(pDelete);
160038 return rc;
160042 ** When this function is called, buffer *ppList (size *pnList bytes) contains
160043 ** a position list that may (or may not) feature multiple columns. This
160044 ** function adjusts the pointer *ppList and the length *pnList so that they
160045 ** identify the subset of the position list that corresponds to column iCol.
160047 ** If there are no entries in the input position list for column iCol, then
160048 ** *pnList is set to zero before returning.
160050 ** If parameter bZero is non-zero, then any part of the input list following
160051 ** the end of the output list is zeroed before returning.
160053 static void fts3ColumnFilter(
160054 int iCol, /* Column to filter on */
160055 int bZero, /* Zero out anything following *ppList */
160056 char **ppList, /* IN/OUT: Pointer to position list */
160057 int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
160059 char *pList = *ppList;
160060 int nList = *pnList;
160061 char *pEnd = &pList[nList];
160062 int iCurrent = 0;
160063 char *p = pList;
160065 assert( iCol>=0 );
160066 while( 1 ){
160067 char c = 0;
160068 while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
160070 if( iCol==iCurrent ){
160071 nList = (int)(p - pList);
160072 break;
160075 nList -= (int)(p - pList);
160076 pList = p;
160077 if( nList==0 ){
160078 break;
160080 p = &pList[1];
160081 p += fts3GetVarint32(p, &iCurrent);
160084 if( bZero && &pList[nList]!=pEnd ){
160085 memset(&pList[nList], 0, pEnd - &pList[nList]);
160087 *ppList = pList;
160088 *pnList = nList;
160092 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
160093 ** existing data). Grow the buffer if required.
160095 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
160096 ** trying to resize the buffer, return SQLITE_NOMEM.
160098 static int fts3MsrBufferData(
160099 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
160100 char *pList,
160101 int nList
160103 if( nList>pMsr->nBuffer ){
160104 char *pNew;
160105 pMsr->nBuffer = nList*2;
160106 pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
160107 if( !pNew ) return SQLITE_NOMEM;
160108 pMsr->aBuffer = pNew;
160111 memcpy(pMsr->aBuffer, pList, nList);
160112 return SQLITE_OK;
160115 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
160116 Fts3Table *p, /* Virtual table handle */
160117 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
160118 sqlite3_int64 *piDocid, /* OUT: Docid value */
160119 char **paPoslist, /* OUT: Pointer to position list */
160120 int *pnPoslist /* OUT: Size of position list in bytes */
160122 int nMerge = pMsr->nAdvance;
160123 Fts3SegReader **apSegment = pMsr->apSegment;
160124 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
160125 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
160128 if( nMerge==0 ){
160129 *paPoslist = 0;
160130 return SQLITE_OK;
160133 while( 1 ){
160134 Fts3SegReader *pSeg;
160135 pSeg = pMsr->apSegment[0];
160137 if( pSeg->pOffsetList==0 ){
160138 *paPoslist = 0;
160139 break;
160140 }else{
160141 int rc;
160142 char *pList;
160143 int nList;
160144 int j;
160145 sqlite3_int64 iDocid = apSegment[0]->iDocid;
160147 rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
160148 j = 1;
160149 while( rc==SQLITE_OK
160150 && j<nMerge
160151 && apSegment[j]->pOffsetList
160152 && apSegment[j]->iDocid==iDocid
160154 rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
160157 if( rc!=SQLITE_OK ) return rc;
160158 fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
160160 if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
160161 rc = fts3MsrBufferData(pMsr, pList, nList+1);
160162 if( rc!=SQLITE_OK ) return rc;
160163 assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
160164 pList = pMsr->aBuffer;
160167 if( pMsr->iColFilter>=0 ){
160168 fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
160171 if( nList>0 ){
160172 *paPoslist = pList;
160173 *piDocid = iDocid;
160174 *pnPoslist = nList;
160175 break;
160180 return SQLITE_OK;
160183 static int fts3SegReaderStart(
160184 Fts3Table *p, /* Virtual table handle */
160185 Fts3MultiSegReader *pCsr, /* Cursor object */
160186 const char *zTerm, /* Term searched for (or NULL) */
160187 int nTerm /* Length of zTerm in bytes */
160189 int i;
160190 int nSeg = pCsr->nSegment;
160192 /* If the Fts3SegFilter defines a specific term (or term prefix) to search
160193 ** for, then advance each segment iterator until it points to a term of
160194 ** equal or greater value than the specified term. This prevents many
160195 ** unnecessary merge/sort operations for the case where single segment
160196 ** b-tree leaf nodes contain more than one term.
160198 for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
160199 int res = 0;
160200 Fts3SegReader *pSeg = pCsr->apSegment[i];
160202 int rc = fts3SegReaderNext(p, pSeg, 0);
160203 if( rc!=SQLITE_OK ) return rc;
160204 }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
160206 if( pSeg->bLookup && res!=0 ){
160207 fts3SegReaderSetEof(pSeg);
160210 fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
160212 return SQLITE_OK;
160215 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
160216 Fts3Table *p, /* Virtual table handle */
160217 Fts3MultiSegReader *pCsr, /* Cursor object */
160218 Fts3SegFilter *pFilter /* Restrictions on range of iteration */
160220 pCsr->pFilter = pFilter;
160221 return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
160224 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
160225 Fts3Table *p, /* Virtual table handle */
160226 Fts3MultiSegReader *pCsr, /* Cursor object */
160227 int iCol, /* Column to match on. */
160228 const char *zTerm, /* Term to iterate through a doclist for */
160229 int nTerm /* Number of bytes in zTerm */
160231 int i;
160232 int rc;
160233 int nSegment = pCsr->nSegment;
160234 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
160235 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
160238 assert( pCsr->pFilter==0 );
160239 assert( zTerm && nTerm>0 );
160241 /* Advance each segment iterator until it points to the term zTerm/nTerm. */
160242 rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
160243 if( rc!=SQLITE_OK ) return rc;
160245 /* Determine how many of the segments actually point to zTerm/nTerm. */
160246 for(i=0; i<nSegment; i++){
160247 Fts3SegReader *pSeg = pCsr->apSegment[i];
160248 if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
160249 break;
160252 pCsr->nAdvance = i;
160254 /* Advance each of the segments to point to the first docid. */
160255 for(i=0; i<pCsr->nAdvance; i++){
160256 rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
160257 if( rc!=SQLITE_OK ) return rc;
160259 fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
160261 assert( iCol<0 || iCol<p->nColumn );
160262 pCsr->iColFilter = iCol;
160264 return SQLITE_OK;
160268 ** This function is called on a MultiSegReader that has been started using
160269 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
160270 ** have been made. Calling this function puts the MultiSegReader in such
160271 ** a state that if the next two calls are:
160273 ** sqlite3Fts3SegReaderStart()
160274 ** sqlite3Fts3SegReaderStep()
160276 ** then the entire doclist for the term is available in
160277 ** MultiSegReader.aDoclist/nDoclist.
160279 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
160280 int i; /* Used to iterate through segment-readers */
160282 assert( pCsr->zTerm==0 );
160283 assert( pCsr->nTerm==0 );
160284 assert( pCsr->aDoclist==0 );
160285 assert( pCsr->nDoclist==0 );
160287 pCsr->nAdvance = 0;
160288 pCsr->bRestart = 1;
160289 for(i=0; i<pCsr->nSegment; i++){
160290 pCsr->apSegment[i]->pOffsetList = 0;
160291 pCsr->apSegment[i]->nOffsetList = 0;
160292 pCsr->apSegment[i]->iDocid = 0;
160295 return SQLITE_OK;
160299 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
160300 Fts3Table *p, /* Virtual table handle */
160301 Fts3MultiSegReader *pCsr /* Cursor object */
160303 int rc = SQLITE_OK;
160305 int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
160306 int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
160307 int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
160308 int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
160309 int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
160310 int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
160312 Fts3SegReader **apSegment = pCsr->apSegment;
160313 int nSegment = pCsr->nSegment;
160314 Fts3SegFilter *pFilter = pCsr->pFilter;
160315 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
160316 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
160319 if( pCsr->nSegment==0 ) return SQLITE_OK;
160322 int nMerge;
160323 int i;
160325 /* Advance the first pCsr->nAdvance entries in the apSegment[] array
160326 ** forward. Then sort the list in order of current term again.
160328 for(i=0; i<pCsr->nAdvance; i++){
160329 Fts3SegReader *pSeg = apSegment[i];
160330 if( pSeg->bLookup ){
160331 fts3SegReaderSetEof(pSeg);
160332 }else{
160333 rc = fts3SegReaderNext(p, pSeg, 0);
160335 if( rc!=SQLITE_OK ) return rc;
160337 fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
160338 pCsr->nAdvance = 0;
160340 /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
160341 assert( rc==SQLITE_OK );
160342 if( apSegment[0]->aNode==0 ) break;
160344 pCsr->nTerm = apSegment[0]->nTerm;
160345 pCsr->zTerm = apSegment[0]->zTerm;
160347 /* If this is a prefix-search, and if the term that apSegment[0] points
160348 ** to does not share a suffix with pFilter->zTerm/nTerm, then all
160349 ** required callbacks have been made. In this case exit early.
160351 ** Similarly, if this is a search for an exact match, and the first term
160352 ** of segment apSegment[0] is not a match, exit early.
160354 if( pFilter->zTerm && !isScan ){
160355 if( pCsr->nTerm<pFilter->nTerm
160356 || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
160357 || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
160359 break;
160363 nMerge = 1;
160364 while( nMerge<nSegment
160365 && apSegment[nMerge]->aNode
160366 && apSegment[nMerge]->nTerm==pCsr->nTerm
160367 && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
160369 nMerge++;
160372 assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
160373 if( nMerge==1
160374 && !isIgnoreEmpty
160375 && !isFirst
160376 && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
160378 pCsr->nDoclist = apSegment[0]->nDoclist;
160379 if( fts3SegReaderIsPending(apSegment[0]) ){
160380 rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
160381 pCsr->aDoclist = pCsr->aBuffer;
160382 }else{
160383 pCsr->aDoclist = apSegment[0]->aDoclist;
160385 if( rc==SQLITE_OK ) rc = SQLITE_ROW;
160386 }else{
160387 int nDoclist = 0; /* Size of doclist */
160388 sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
160390 /* The current term of the first nMerge entries in the array
160391 ** of Fts3SegReader objects is the same. The doclists must be merged
160392 ** and a single term returned with the merged doclist.
160394 for(i=0; i<nMerge; i++){
160395 fts3SegReaderFirstDocid(p, apSegment[i]);
160397 fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
160398 while( apSegment[0]->pOffsetList ){
160399 int j; /* Number of segments that share a docid */
160400 char *pList = 0;
160401 int nList = 0;
160402 int nByte;
160403 sqlite3_int64 iDocid = apSegment[0]->iDocid;
160404 fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
160405 j = 1;
160406 while( j<nMerge
160407 && apSegment[j]->pOffsetList
160408 && apSegment[j]->iDocid==iDocid
160410 fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
160414 if( isColFilter ){
160415 fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
160418 if( !isIgnoreEmpty || nList>0 ){
160420 /* Calculate the 'docid' delta value to write into the merged
160421 ** doclist. */
160422 sqlite3_int64 iDelta;
160423 if( p->bDescIdx && nDoclist>0 ){
160424 iDelta = iPrev - iDocid;
160425 }else{
160426 iDelta = iDocid - iPrev;
160428 assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
160429 assert( nDoclist>0 || iDelta==iDocid );
160431 nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
160432 if( nDoclist+nByte>pCsr->nBuffer ){
160433 char *aNew;
160434 pCsr->nBuffer = (nDoclist+nByte)*2;
160435 aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
160436 if( !aNew ){
160437 return SQLITE_NOMEM;
160439 pCsr->aBuffer = aNew;
160442 if( isFirst ){
160443 char *a = &pCsr->aBuffer[nDoclist];
160444 int nWrite;
160446 nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
160447 if( nWrite ){
160448 iPrev = iDocid;
160449 nDoclist += nWrite;
160451 }else{
160452 nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
160453 iPrev = iDocid;
160454 if( isRequirePos ){
160455 memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
160456 nDoclist += nList;
160457 pCsr->aBuffer[nDoclist++] = '\0';
160462 fts3SegReaderSort(apSegment, nMerge, j, xCmp);
160464 if( nDoclist>0 ){
160465 pCsr->aDoclist = pCsr->aBuffer;
160466 pCsr->nDoclist = nDoclist;
160467 rc = SQLITE_ROW;
160470 pCsr->nAdvance = nMerge;
160471 }while( rc==SQLITE_OK );
160473 return rc;
160477 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
160478 Fts3MultiSegReader *pCsr /* Cursor object */
160480 if( pCsr ){
160481 int i;
160482 for(i=0; i<pCsr->nSegment; i++){
160483 sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
160485 sqlite3_free(pCsr->apSegment);
160486 sqlite3_free(pCsr->aBuffer);
160488 pCsr->nSegment = 0;
160489 pCsr->apSegment = 0;
160490 pCsr->aBuffer = 0;
160495 ** Decode the "end_block" field, selected by column iCol of the SELECT
160496 ** statement passed as the first argument.
160498 ** The "end_block" field may contain either an integer, or a text field
160499 ** containing the text representation of two non-negative integers separated
160500 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
160501 ** to the integer value and *pnByte to zero before returning. In the second,
160502 ** set *piEndBlock to the first value and *pnByte to the second.
160504 static void fts3ReadEndBlockField(
160505 sqlite3_stmt *pStmt,
160506 int iCol,
160507 i64 *piEndBlock,
160508 i64 *pnByte
160510 const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
160511 if( zText ){
160512 int i;
160513 int iMul = 1;
160514 i64 iVal = 0;
160515 for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
160516 iVal = iVal*10 + (zText[i] - '0');
160518 *piEndBlock = iVal;
160519 while( zText[i]==' ' ) i++;
160520 iVal = 0;
160521 if( zText[i]=='-' ){
160523 iMul = -1;
160525 for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
160526 iVal = iVal*10 + (zText[i] - '0');
160528 *pnByte = (iVal * (i64)iMul);
160534 ** A segment of size nByte bytes has just been written to absolute level
160535 ** iAbsLevel. Promote any segments that should be promoted as a result.
160537 static int fts3PromoteSegments(
160538 Fts3Table *p, /* FTS table handle */
160539 sqlite3_int64 iAbsLevel, /* Absolute level just updated */
160540 sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
160542 int rc = SQLITE_OK;
160543 sqlite3_stmt *pRange;
160545 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
160547 if( rc==SQLITE_OK ){
160548 int bOk = 0;
160549 i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
160550 i64 nLimit = (nByte*3)/2;
160552 /* Loop through all entries in the %_segdir table corresponding to
160553 ** segments in this index on levels greater than iAbsLevel. If there is
160554 ** at least one such segment, and it is possible to determine that all
160555 ** such segments are smaller than nLimit bytes in size, they will be
160556 ** promoted to level iAbsLevel. */
160557 sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
160558 sqlite3_bind_int64(pRange, 2, iLast);
160559 while( SQLITE_ROW==sqlite3_step(pRange) ){
160560 i64 nSize = 0, dummy;
160561 fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
160562 if( nSize<=0 || nSize>nLimit ){
160563 /* If nSize==0, then the %_segdir.end_block field does not not
160564 ** contain a size value. This happens if it was written by an
160565 ** old version of FTS. In this case it is not possible to determine
160566 ** the size of the segment, and so segment promotion does not
160567 ** take place. */
160568 bOk = 0;
160569 break;
160571 bOk = 1;
160573 rc = sqlite3_reset(pRange);
160575 if( bOk ){
160576 int iIdx = 0;
160577 sqlite3_stmt *pUpdate1 = 0;
160578 sqlite3_stmt *pUpdate2 = 0;
160580 if( rc==SQLITE_OK ){
160581 rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
160583 if( rc==SQLITE_OK ){
160584 rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
160587 if( rc==SQLITE_OK ){
160589 /* Loop through all %_segdir entries for segments in this index with
160590 ** levels equal to or greater than iAbsLevel. As each entry is visited,
160591 ** updated it to set (level = -1) and (idx = N), where N is 0 for the
160592 ** oldest segment in the range, 1 for the next oldest, and so on.
160594 ** In other words, move all segments being promoted to level -1,
160595 ** setting the "idx" fields as appropriate to keep them in the same
160596 ** order. The contents of level -1 (which is never used, except
160597 ** transiently here), will be moved back to level iAbsLevel below. */
160598 sqlite3_bind_int64(pRange, 1, iAbsLevel);
160599 while( SQLITE_ROW==sqlite3_step(pRange) ){
160600 sqlite3_bind_int(pUpdate1, 1, iIdx++);
160601 sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
160602 sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
160603 sqlite3_step(pUpdate1);
160604 rc = sqlite3_reset(pUpdate1);
160605 if( rc!=SQLITE_OK ){
160606 sqlite3_reset(pRange);
160607 break;
160611 if( rc==SQLITE_OK ){
160612 rc = sqlite3_reset(pRange);
160615 /* Move level -1 to level iAbsLevel */
160616 if( rc==SQLITE_OK ){
160617 sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
160618 sqlite3_step(pUpdate2);
160619 rc = sqlite3_reset(pUpdate2);
160625 return rc;
160629 ** Merge all level iLevel segments in the database into a single
160630 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
160631 ** single segment with a level equal to the numerically largest level
160632 ** currently present in the database.
160634 ** If this function is called with iLevel<0, but there is only one
160635 ** segment in the database, SQLITE_DONE is returned immediately.
160636 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
160637 ** an SQLite error code is returned.
160639 static int fts3SegmentMerge(
160640 Fts3Table *p,
160641 int iLangid, /* Language id to merge */
160642 int iIndex, /* Index in p->aIndex[] to merge */
160643 int iLevel /* Level to merge */
160645 int rc; /* Return code */
160646 int iIdx = 0; /* Index of new segment */
160647 sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
160648 SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
160649 Fts3SegFilter filter; /* Segment term filter condition */
160650 Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
160651 int bIgnoreEmpty = 0; /* True to ignore empty segments */
160652 i64 iMaxLevel = 0; /* Max level number for this index/langid */
160654 assert( iLevel==FTS3_SEGCURSOR_ALL
160655 || iLevel==FTS3_SEGCURSOR_PENDING
160656 || iLevel>=0
160658 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
160659 assert( iIndex>=0 && iIndex<p->nIndex );
160661 rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
160662 if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
160664 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
160665 rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
160666 if( rc!=SQLITE_OK ) goto finished;
160669 if( iLevel==FTS3_SEGCURSOR_ALL ){
160670 /* This call is to merge all segments in the database to a single
160671 ** segment. The level of the new segment is equal to the numerically
160672 ** greatest segment level currently present in the database for this
160673 ** index. The idx of the new segment is always 0. */
160674 if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
160675 rc = SQLITE_DONE;
160676 goto finished;
160678 iNewLevel = iMaxLevel;
160679 bIgnoreEmpty = 1;
160681 }else{
160682 /* This call is to merge all segments at level iLevel. find the next
160683 ** available segment index at level iLevel+1. The call to
160684 ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
160685 ** a single iLevel+2 segment if necessary. */
160686 assert( FTS3_SEGCURSOR_PENDING==-1 );
160687 iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
160688 rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
160689 bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
160691 if( rc!=SQLITE_OK ) goto finished;
160693 assert( csr.nSegment>0 );
160694 assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
160695 assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
160697 memset(&filter, 0, sizeof(Fts3SegFilter));
160698 filter.flags = FTS3_SEGMENT_REQUIRE_POS;
160699 filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
160701 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
160702 while( SQLITE_OK==rc ){
160703 rc = sqlite3Fts3SegReaderStep(p, &csr);
160704 if( rc!=SQLITE_ROW ) break;
160705 rc = fts3SegWriterAdd(p, &pWriter, 1,
160706 csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
160708 if( rc!=SQLITE_OK ) goto finished;
160709 assert( pWriter || bIgnoreEmpty );
160711 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
160712 rc = fts3DeleteSegdir(
160713 p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
160715 if( rc!=SQLITE_OK ) goto finished;
160717 if( pWriter ){
160718 rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
160719 if( rc==SQLITE_OK ){
160720 if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
160721 rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
160726 finished:
160727 fts3SegWriterFree(pWriter);
160728 sqlite3Fts3SegReaderFinish(&csr);
160729 return rc;
160734 ** Flush the contents of pendingTerms to level 0 segments.
160736 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
160737 int rc = SQLITE_OK;
160738 int i;
160740 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
160741 rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
160742 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
160744 sqlite3Fts3PendingTermsClear(p);
160746 /* Determine the auto-incr-merge setting if unknown. If enabled,
160747 ** estimate the number of leaf blocks of content to be written
160749 if( rc==SQLITE_OK && p->bHasStat
160750 && p->nAutoincrmerge==0xff && p->nLeafAdd>0
160752 sqlite3_stmt *pStmt = 0;
160753 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
160754 if( rc==SQLITE_OK ){
160755 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
160756 rc = sqlite3_step(pStmt);
160757 if( rc==SQLITE_ROW ){
160758 p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
160759 if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
160760 }else if( rc==SQLITE_DONE ){
160761 p->nAutoincrmerge = 0;
160763 rc = sqlite3_reset(pStmt);
160766 return rc;
160770 ** Encode N integers as varints into a blob.
160772 static void fts3EncodeIntArray(
160773 int N, /* The number of integers to encode */
160774 u32 *a, /* The integer values */
160775 char *zBuf, /* Write the BLOB here */
160776 int *pNBuf /* Write number of bytes if zBuf[] used here */
160778 int i, j;
160779 for(i=j=0; i<N; i++){
160780 j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
160782 *pNBuf = j;
160786 ** Decode a blob of varints into N integers
160788 static void fts3DecodeIntArray(
160789 int N, /* The number of integers to decode */
160790 u32 *a, /* Write the integer values */
160791 const char *zBuf, /* The BLOB containing the varints */
160792 int nBuf /* size of the BLOB */
160794 int i, j;
160795 UNUSED_PARAMETER(nBuf);
160796 for(i=j=0; i<N; i++){
160797 sqlite3_int64 x;
160798 j += sqlite3Fts3GetVarint(&zBuf[j], &x);
160799 assert(j<=nBuf);
160800 a[i] = (u32)(x & 0xffffffff);
160805 ** Insert the sizes (in tokens) for each column of the document
160806 ** with docid equal to p->iPrevDocid. The sizes are encoded as
160807 ** a blob of varints.
160809 static void fts3InsertDocsize(
160810 int *pRC, /* Result code */
160811 Fts3Table *p, /* Table into which to insert */
160812 u32 *aSz /* Sizes of each column, in tokens */
160814 char *pBlob; /* The BLOB encoding of the document size */
160815 int nBlob; /* Number of bytes in the BLOB */
160816 sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
160817 int rc; /* Result code from subfunctions */
160819 if( *pRC ) return;
160820 pBlob = sqlite3_malloc( 10*p->nColumn );
160821 if( pBlob==0 ){
160822 *pRC = SQLITE_NOMEM;
160823 return;
160825 fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
160826 rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
160827 if( rc ){
160828 sqlite3_free(pBlob);
160829 *pRC = rc;
160830 return;
160832 sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
160833 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
160834 sqlite3_step(pStmt);
160835 *pRC = sqlite3_reset(pStmt);
160839 ** Record 0 of the %_stat table contains a blob consisting of N varints,
160840 ** where N is the number of user defined columns in the fts3 table plus
160841 ** two. If nCol is the number of user defined columns, then values of the
160842 ** varints are set as follows:
160844 ** Varint 0: Total number of rows in the table.
160846 ** Varint 1..nCol: For each column, the total number of tokens stored in
160847 ** the column for all rows of the table.
160849 ** Varint 1+nCol: The total size, in bytes, of all text values in all
160850 ** columns of all rows of the table.
160853 static void fts3UpdateDocTotals(
160854 int *pRC, /* The result code */
160855 Fts3Table *p, /* Table being updated */
160856 u32 *aSzIns, /* Size increases */
160857 u32 *aSzDel, /* Size decreases */
160858 int nChng /* Change in the number of documents */
160860 char *pBlob; /* Storage for BLOB written into %_stat */
160861 int nBlob; /* Size of BLOB written into %_stat */
160862 u32 *a; /* Array of integers that becomes the BLOB */
160863 sqlite3_stmt *pStmt; /* Statement for reading and writing */
160864 int i; /* Loop counter */
160865 int rc; /* Result code from subfunctions */
160867 const int nStat = p->nColumn+2;
160869 if( *pRC ) return;
160870 a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
160871 if( a==0 ){
160872 *pRC = SQLITE_NOMEM;
160873 return;
160875 pBlob = (char*)&a[nStat];
160876 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
160877 if( rc ){
160878 sqlite3_free(a);
160879 *pRC = rc;
160880 return;
160882 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
160883 if( sqlite3_step(pStmt)==SQLITE_ROW ){
160884 fts3DecodeIntArray(nStat, a,
160885 sqlite3_column_blob(pStmt, 0),
160886 sqlite3_column_bytes(pStmt, 0));
160887 }else{
160888 memset(a, 0, sizeof(u32)*(nStat) );
160890 rc = sqlite3_reset(pStmt);
160891 if( rc!=SQLITE_OK ){
160892 sqlite3_free(a);
160893 *pRC = rc;
160894 return;
160896 if( nChng<0 && a[0]<(u32)(-nChng) ){
160897 a[0] = 0;
160898 }else{
160899 a[0] += nChng;
160901 for(i=0; i<p->nColumn+1; i++){
160902 u32 x = a[i+1];
160903 if( x+aSzIns[i] < aSzDel[i] ){
160904 x = 0;
160905 }else{
160906 x = x + aSzIns[i] - aSzDel[i];
160908 a[i+1] = x;
160910 fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
160911 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
160912 if( rc ){
160913 sqlite3_free(a);
160914 *pRC = rc;
160915 return;
160917 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
160918 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
160919 sqlite3_step(pStmt);
160920 *pRC = sqlite3_reset(pStmt);
160921 sqlite3_free(a);
160925 ** Merge the entire database so that there is one segment for each
160926 ** iIndex/iLangid combination.
160928 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
160929 int bSeenDone = 0;
160930 int rc;
160931 sqlite3_stmt *pAllLangid = 0;
160933 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
160934 if( rc==SQLITE_OK ){
160935 int rc2;
160936 sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
160937 sqlite3_bind_int(pAllLangid, 2, p->nIndex);
160938 while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
160939 int i;
160940 int iLangid = sqlite3_column_int(pAllLangid, 0);
160941 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
160942 rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
160943 if( rc==SQLITE_DONE ){
160944 bSeenDone = 1;
160945 rc = SQLITE_OK;
160949 rc2 = sqlite3_reset(pAllLangid);
160950 if( rc==SQLITE_OK ) rc = rc2;
160953 sqlite3Fts3SegmentsClose(p);
160954 sqlite3Fts3PendingTermsClear(p);
160956 return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
160960 ** This function is called when the user executes the following statement:
160962 ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
160964 ** The entire FTS index is discarded and rebuilt. If the table is one
160965 ** created using the content=xxx option, then the new index is based on
160966 ** the current contents of the xxx table. Otherwise, it is rebuilt based
160967 ** on the contents of the %_content table.
160969 static int fts3DoRebuild(Fts3Table *p){
160970 int rc; /* Return Code */
160972 rc = fts3DeleteAll(p, 0);
160973 if( rc==SQLITE_OK ){
160974 u32 *aSz = 0;
160975 u32 *aSzIns = 0;
160976 u32 *aSzDel = 0;
160977 sqlite3_stmt *pStmt = 0;
160978 int nEntry = 0;
160980 /* Compose and prepare an SQL statement to loop through the content table */
160981 char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
160982 if( !zSql ){
160983 rc = SQLITE_NOMEM;
160984 }else{
160985 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
160986 sqlite3_free(zSql);
160989 if( rc==SQLITE_OK ){
160990 int nByte = sizeof(u32) * (p->nColumn+1)*3;
160991 aSz = (u32 *)sqlite3_malloc(nByte);
160992 if( aSz==0 ){
160993 rc = SQLITE_NOMEM;
160994 }else{
160995 memset(aSz, 0, nByte);
160996 aSzIns = &aSz[p->nColumn+1];
160997 aSzDel = &aSzIns[p->nColumn+1];
161001 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
161002 int iCol;
161003 int iLangid = langidFromSelect(p, pStmt);
161004 rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
161005 memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
161006 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
161007 if( p->abNotindexed[iCol]==0 ){
161008 const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
161009 rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
161010 aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
161013 if( p->bHasDocsize ){
161014 fts3InsertDocsize(&rc, p, aSz);
161016 if( rc!=SQLITE_OK ){
161017 sqlite3_finalize(pStmt);
161018 pStmt = 0;
161019 }else{
161020 nEntry++;
161021 for(iCol=0; iCol<=p->nColumn; iCol++){
161022 aSzIns[iCol] += aSz[iCol];
161026 if( p->bFts4 ){
161027 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
161029 sqlite3_free(aSz);
161031 if( pStmt ){
161032 int rc2 = sqlite3_finalize(pStmt);
161033 if( rc==SQLITE_OK ){
161034 rc = rc2;
161039 return rc;
161044 ** This function opens a cursor used to read the input data for an
161045 ** incremental merge operation. Specifically, it opens a cursor to scan
161046 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
161047 ** level iAbsLevel.
161049 static int fts3IncrmergeCsr(
161050 Fts3Table *p, /* FTS3 table handle */
161051 sqlite3_int64 iAbsLevel, /* Absolute level to open */
161052 int nSeg, /* Number of segments to merge */
161053 Fts3MultiSegReader *pCsr /* Cursor object to populate */
161055 int rc; /* Return Code */
161056 sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
161057 int nByte; /* Bytes allocated at pCsr->apSegment[] */
161059 /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
161060 memset(pCsr, 0, sizeof(*pCsr));
161061 nByte = sizeof(Fts3SegReader *) * nSeg;
161062 pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
161064 if( pCsr->apSegment==0 ){
161065 rc = SQLITE_NOMEM;
161066 }else{
161067 memset(pCsr->apSegment, 0, nByte);
161068 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
161070 if( rc==SQLITE_OK ){
161071 int i;
161072 int rc2;
161073 sqlite3_bind_int64(pStmt, 1, iAbsLevel);
161074 assert( pCsr->nSegment==0 );
161075 for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
161076 rc = sqlite3Fts3SegReaderNew(i, 0,
161077 sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
161078 sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
161079 sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
161080 sqlite3_column_blob(pStmt, 4), /* segdir.root */
161081 sqlite3_column_bytes(pStmt, 4), /* segdir.root */
161082 &pCsr->apSegment[i]
161084 pCsr->nSegment++;
161086 rc2 = sqlite3_reset(pStmt);
161087 if( rc==SQLITE_OK ) rc = rc2;
161090 return rc;
161093 typedef struct IncrmergeWriter IncrmergeWriter;
161094 typedef struct NodeWriter NodeWriter;
161095 typedef struct Blob Blob;
161096 typedef struct NodeReader NodeReader;
161099 ** An instance of the following structure is used as a dynamic buffer
161100 ** to build up nodes or other blobs of data in.
161102 ** The function blobGrowBuffer() is used to extend the allocation.
161104 struct Blob {
161105 char *a; /* Pointer to allocation */
161106 int n; /* Number of valid bytes of data in a[] */
161107 int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
161111 ** This structure is used to build up buffers containing segment b-tree
161112 ** nodes (blocks).
161114 struct NodeWriter {
161115 sqlite3_int64 iBlock; /* Current block id */
161116 Blob key; /* Last key written to the current block */
161117 Blob block; /* Current block image */
161121 ** An object of this type contains the state required to create or append
161122 ** to an appendable b-tree segment.
161124 struct IncrmergeWriter {
161125 int nLeafEst; /* Space allocated for leaf blocks */
161126 int nWork; /* Number of leaf pages flushed */
161127 sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
161128 int iIdx; /* Index of *output* segment in iAbsLevel+1 */
161129 sqlite3_int64 iStart; /* Block number of first allocated block */
161130 sqlite3_int64 iEnd; /* Block number of last allocated block */
161131 sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
161132 u8 bNoLeafData; /* If true, store 0 for segment size */
161133 NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
161137 ** An object of the following type is used to read data from a single
161138 ** FTS segment node. See the following functions:
161140 ** nodeReaderInit()
161141 ** nodeReaderNext()
161142 ** nodeReaderRelease()
161144 struct NodeReader {
161145 const char *aNode;
161146 int nNode;
161147 int iOff; /* Current offset within aNode[] */
161149 /* Output variables. Containing the current node entry. */
161150 sqlite3_int64 iChild; /* Pointer to child node */
161151 Blob term; /* Current term */
161152 const char *aDoclist; /* Pointer to doclist */
161153 int nDoclist; /* Size of doclist in bytes */
161157 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
161158 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
161159 ** bytes in size, extend (realloc) it to be so.
161161 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
161162 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
161163 ** to reflect the new size of the pBlob->a[] buffer.
161165 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
161166 if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
161167 int nAlloc = nMin;
161168 char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
161169 if( a ){
161170 pBlob->nAlloc = nAlloc;
161171 pBlob->a = a;
161172 }else{
161173 *pRc = SQLITE_NOMEM;
161179 ** Attempt to advance the node-reader object passed as the first argument to
161180 ** the next entry on the node.
161182 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
161183 ** Otherwise return SQLITE_OK. If there is no next entry on the node
161184 ** (e.g. because the current entry is the last) set NodeReader->aNode to
161185 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
161186 ** variables for the new entry.
161188 static int nodeReaderNext(NodeReader *p){
161189 int bFirst = (p->term.n==0); /* True for first term on the node */
161190 int nPrefix = 0; /* Bytes to copy from previous term */
161191 int nSuffix = 0; /* Bytes to append to the prefix */
161192 int rc = SQLITE_OK; /* Return code */
161194 assert( p->aNode );
161195 if( p->iChild && bFirst==0 ) p->iChild++;
161196 if( p->iOff>=p->nNode ){
161197 /* EOF */
161198 p->aNode = 0;
161199 }else{
161200 if( bFirst==0 ){
161201 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
161203 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
161205 blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
161206 if( rc==SQLITE_OK ){
161207 memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
161208 p->term.n = nPrefix+nSuffix;
161209 p->iOff += nSuffix;
161210 if( p->iChild==0 ){
161211 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
161212 p->aDoclist = &p->aNode[p->iOff];
161213 p->iOff += p->nDoclist;
161218 assert( p->iOff<=p->nNode );
161220 return rc;
161224 ** Release all dynamic resources held by node-reader object *p.
161226 static void nodeReaderRelease(NodeReader *p){
161227 sqlite3_free(p->term.a);
161231 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
161233 ** If successful, SQLITE_OK is returned and the NodeReader object set to
161234 ** point to the first entry on the node (if any). Otherwise, an SQLite
161235 ** error code is returned.
161237 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
161238 memset(p, 0, sizeof(NodeReader));
161239 p->aNode = aNode;
161240 p->nNode = nNode;
161242 /* Figure out if this is a leaf or an internal node. */
161243 if( p->aNode[0] ){
161244 /* An internal node. */
161245 p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
161246 }else{
161247 p->iOff = 1;
161250 return nodeReaderNext(p);
161254 ** This function is called while writing an FTS segment each time a leaf o
161255 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
161256 ** to be greater than the largest key on the node just written, but smaller
161257 ** than or equal to the first key that will be written to the next leaf
161258 ** node.
161260 ** The block id of the leaf node just written to disk may be found in
161261 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
161263 static int fts3IncrmergePush(
161264 Fts3Table *p, /* Fts3 table handle */
161265 IncrmergeWriter *pWriter, /* Writer object */
161266 const char *zTerm, /* Term to write to internal node */
161267 int nTerm /* Bytes at zTerm */
161269 sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
161270 int iLayer;
161272 assert( nTerm>0 );
161273 for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
161274 sqlite3_int64 iNextPtr = 0;
161275 NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
161276 int rc = SQLITE_OK;
161277 int nPrefix;
161278 int nSuffix;
161279 int nSpace;
161281 /* Figure out how much space the key will consume if it is written to
161282 ** the current node of layer iLayer. Due to the prefix compression,
161283 ** the space required changes depending on which node the key is to
161284 ** be added to. */
161285 nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
161286 nSuffix = nTerm - nPrefix;
161287 nSpace = sqlite3Fts3VarintLen(nPrefix);
161288 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
161290 if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
161291 /* If the current node of layer iLayer contains zero keys, or if adding
161292 ** the key to it will not cause it to grow to larger than nNodeSize
161293 ** bytes in size, write the key here. */
161295 Blob *pBlk = &pNode->block;
161296 if( pBlk->n==0 ){
161297 blobGrowBuffer(pBlk, p->nNodeSize, &rc);
161298 if( rc==SQLITE_OK ){
161299 pBlk->a[0] = (char)iLayer;
161300 pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
161303 blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
161304 blobGrowBuffer(&pNode->key, nTerm, &rc);
161306 if( rc==SQLITE_OK ){
161307 if( pNode->key.n ){
161308 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
161310 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
161311 memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
161312 pBlk->n += nSuffix;
161314 memcpy(pNode->key.a, zTerm, nTerm);
161315 pNode->key.n = nTerm;
161317 }else{
161318 /* Otherwise, flush the current node of layer iLayer to disk.
161319 ** Then allocate a new, empty sibling node. The key will be written
161320 ** into the parent of this node. */
161321 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
161323 assert( pNode->block.nAlloc>=p->nNodeSize );
161324 pNode->block.a[0] = (char)iLayer;
161325 pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
161327 iNextPtr = pNode->iBlock;
161328 pNode->iBlock++;
161329 pNode->key.n = 0;
161332 if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
161333 iPtr = iNextPtr;
161336 assert( 0 );
161337 return 0;
161341 ** Append a term and (optionally) doclist to the FTS segment node currently
161342 ** stored in blob *pNode. The node need not contain any terms, but the
161343 ** header must be written before this function is called.
161345 ** A node header is a single 0x00 byte for a leaf node, or a height varint
161346 ** followed by the left-hand-child varint for an internal node.
161348 ** The term to be appended is passed via arguments zTerm/nTerm. For a
161349 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
161350 ** node, both aDoclist and nDoclist must be passed 0.
161352 ** If the size of the value in blob pPrev is zero, then this is the first
161353 ** term written to the node. Otherwise, pPrev contains a copy of the
161354 ** previous term. Before this function returns, it is updated to contain a
161355 ** copy of zTerm/nTerm.
161357 ** It is assumed that the buffer associated with pNode is already large
161358 ** enough to accommodate the new entry. The buffer associated with pPrev
161359 ** is extended by this function if requrired.
161361 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
161362 ** returned. Otherwise, SQLITE_OK.
161364 static int fts3AppendToNode(
161365 Blob *pNode, /* Current node image to append to */
161366 Blob *pPrev, /* Buffer containing previous term written */
161367 const char *zTerm, /* New term to write */
161368 int nTerm, /* Size of zTerm in bytes */
161369 const char *aDoclist, /* Doclist (or NULL) to write */
161370 int nDoclist /* Size of aDoclist in bytes */
161372 int rc = SQLITE_OK; /* Return code */
161373 int bFirst = (pPrev->n==0); /* True if this is the first term written */
161374 int nPrefix; /* Size of term prefix in bytes */
161375 int nSuffix; /* Size of term suffix in bytes */
161377 /* Node must have already been started. There must be a doclist for a
161378 ** leaf node, and there must not be a doclist for an internal node. */
161379 assert( pNode->n>0 );
161380 assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
161382 blobGrowBuffer(pPrev, nTerm, &rc);
161383 if( rc!=SQLITE_OK ) return rc;
161385 nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
161386 nSuffix = nTerm - nPrefix;
161387 memcpy(pPrev->a, zTerm, nTerm);
161388 pPrev->n = nTerm;
161390 if( bFirst==0 ){
161391 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
161393 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
161394 memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
161395 pNode->n += nSuffix;
161397 if( aDoclist ){
161398 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
161399 memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
161400 pNode->n += nDoclist;
161403 assert( pNode->n<=pNode->nAlloc );
161405 return SQLITE_OK;
161409 ** Append the current term and doclist pointed to by cursor pCsr to the
161410 ** appendable b-tree segment opened for writing by pWriter.
161412 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
161414 static int fts3IncrmergeAppend(
161415 Fts3Table *p, /* Fts3 table handle */
161416 IncrmergeWriter *pWriter, /* Writer object */
161417 Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
161419 const char *zTerm = pCsr->zTerm;
161420 int nTerm = pCsr->nTerm;
161421 const char *aDoclist = pCsr->aDoclist;
161422 int nDoclist = pCsr->nDoclist;
161423 int rc = SQLITE_OK; /* Return code */
161424 int nSpace; /* Total space in bytes required on leaf */
161425 int nPrefix; /* Size of prefix shared with previous term */
161426 int nSuffix; /* Size of suffix (nTerm - nPrefix) */
161427 NodeWriter *pLeaf; /* Object used to write leaf nodes */
161429 pLeaf = &pWriter->aNodeWriter[0];
161430 nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
161431 nSuffix = nTerm - nPrefix;
161433 nSpace = sqlite3Fts3VarintLen(nPrefix);
161434 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
161435 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
161437 /* If the current block is not empty, and if adding this term/doclist
161438 ** to the current block would make it larger than Fts3Table.nNodeSize
161439 ** bytes, write this block out to the database. */
161440 if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
161441 rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
161442 pWriter->nWork++;
161444 /* Add the current term to the parent node. The term added to the
161445 ** parent must:
161447 ** a) be greater than the largest term on the leaf node just written
161448 ** to the database (still available in pLeaf->key), and
161450 ** b) be less than or equal to the term about to be added to the new
161451 ** leaf node (zTerm/nTerm).
161453 ** In other words, it must be the prefix of zTerm 1 byte longer than
161454 ** the common prefix (if any) of zTerm and pWriter->zTerm.
161456 if( rc==SQLITE_OK ){
161457 rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
161460 /* Advance to the next output block */
161461 pLeaf->iBlock++;
161462 pLeaf->key.n = 0;
161463 pLeaf->block.n = 0;
161465 nSuffix = nTerm;
161466 nSpace = 1;
161467 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
161468 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
161471 pWriter->nLeafData += nSpace;
161472 blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
161473 if( rc==SQLITE_OK ){
161474 if( pLeaf->block.n==0 ){
161475 pLeaf->block.n = 1;
161476 pLeaf->block.a[0] = '\0';
161478 rc = fts3AppendToNode(
161479 &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
161483 return rc;
161487 ** This function is called to release all dynamic resources held by the
161488 ** merge-writer object pWriter, and if no error has occurred, to flush
161489 ** all outstanding node buffers held by pWriter to disk.
161491 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
161492 ** is made to write any data to disk. Instead, this function serves only
161493 ** to release outstanding resources.
161495 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
161496 ** flushing buffers to disk, *pRc is set to an SQLite error code before
161497 ** returning.
161499 static void fts3IncrmergeRelease(
161500 Fts3Table *p, /* FTS3 table handle */
161501 IncrmergeWriter *pWriter, /* Merge-writer object */
161502 int *pRc /* IN/OUT: Error code */
161504 int i; /* Used to iterate through non-root layers */
161505 int iRoot; /* Index of root in pWriter->aNodeWriter */
161506 NodeWriter *pRoot; /* NodeWriter for root node */
161507 int rc = *pRc; /* Error code */
161509 /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
161510 ** root node. If the segment fits entirely on a single leaf node, iRoot
161511 ** will be set to 0. If the root node is the parent of the leaves, iRoot
161512 ** will be 1. And so on. */
161513 for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
161514 NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
161515 if( pNode->block.n>0 ) break;
161516 assert( *pRc || pNode->block.nAlloc==0 );
161517 assert( *pRc || pNode->key.nAlloc==0 );
161518 sqlite3_free(pNode->block.a);
161519 sqlite3_free(pNode->key.a);
161522 /* Empty output segment. This is a no-op. */
161523 if( iRoot<0 ) return;
161525 /* The entire output segment fits on a single node. Normally, this means
161526 ** the node would be stored as a blob in the "root" column of the %_segdir
161527 ** table. However, this is not permitted in this case. The problem is that
161528 ** space has already been reserved in the %_segments table, and so the
161529 ** start_block and end_block fields of the %_segdir table must be populated.
161530 ** And, by design or by accident, released versions of FTS cannot handle
161531 ** segments that fit entirely on the root node with start_block!=0.
161533 ** Instead, create a synthetic root node that contains nothing but a
161534 ** pointer to the single content node. So that the segment consists of a
161535 ** single leaf and a single interior (root) node.
161537 ** Todo: Better might be to defer allocating space in the %_segments
161538 ** table until we are sure it is needed.
161540 if( iRoot==0 ){
161541 Blob *pBlock = &pWriter->aNodeWriter[1].block;
161542 blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
161543 if( rc==SQLITE_OK ){
161544 pBlock->a[0] = 0x01;
161545 pBlock->n = 1 + sqlite3Fts3PutVarint(
161546 &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
161549 iRoot = 1;
161551 pRoot = &pWriter->aNodeWriter[iRoot];
161553 /* Flush all currently outstanding nodes to disk. */
161554 for(i=0; i<iRoot; i++){
161555 NodeWriter *pNode = &pWriter->aNodeWriter[i];
161556 if( pNode->block.n>0 && rc==SQLITE_OK ){
161557 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
161559 sqlite3_free(pNode->block.a);
161560 sqlite3_free(pNode->key.a);
161563 /* Write the %_segdir record. */
161564 if( rc==SQLITE_OK ){
161565 rc = fts3WriteSegdir(p,
161566 pWriter->iAbsLevel+1, /* level */
161567 pWriter->iIdx, /* idx */
161568 pWriter->iStart, /* start_block */
161569 pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
161570 pWriter->iEnd, /* end_block */
161571 (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
161572 pRoot->block.a, pRoot->block.n /* root */
161575 sqlite3_free(pRoot->block.a);
161576 sqlite3_free(pRoot->key.a);
161578 *pRc = rc;
161582 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
161583 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
161584 ** the other, it is considered to be smaller than the other.
161586 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
161587 ** if it is greater.
161589 static int fts3TermCmp(
161590 const char *zLhs, int nLhs, /* LHS of comparison */
161591 const char *zRhs, int nRhs /* RHS of comparison */
161593 int nCmp = MIN(nLhs, nRhs);
161594 int res;
161596 res = memcmp(zLhs, zRhs, nCmp);
161597 if( res==0 ) res = nLhs - nRhs;
161599 return res;
161604 ** Query to see if the entry in the %_segments table with blockid iEnd is
161605 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
161606 ** returning. Otherwise, set *pbRes to 0.
161608 ** Or, if an error occurs while querying the database, return an SQLite
161609 ** error code. The final value of *pbRes is undefined in this case.
161611 ** This is used to test if a segment is an "appendable" segment. If it
161612 ** is, then a NULL entry has been inserted into the %_segments table
161613 ** with blockid %_segdir.end_block.
161615 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
161616 int bRes = 0; /* Result to set *pbRes to */
161617 sqlite3_stmt *pCheck = 0; /* Statement to query database with */
161618 int rc; /* Return code */
161620 rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
161621 if( rc==SQLITE_OK ){
161622 sqlite3_bind_int64(pCheck, 1, iEnd);
161623 if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
161624 rc = sqlite3_reset(pCheck);
161627 *pbRes = bRes;
161628 return rc;
161632 ** This function is called when initializing an incremental-merge operation.
161633 ** It checks if the existing segment with index value iIdx at absolute level
161634 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
161635 ** merge-writer object *pWriter is initialized to write to it.
161637 ** An existing segment can be appended to by an incremental merge if:
161639 ** * It was initially created as an appendable segment (with all required
161640 ** space pre-allocated), and
161642 ** * The first key read from the input (arguments zKey and nKey) is
161643 ** greater than the largest key currently stored in the potential
161644 ** output segment.
161646 static int fts3IncrmergeLoad(
161647 Fts3Table *p, /* Fts3 table handle */
161648 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
161649 int iIdx, /* Index of candidate output segment */
161650 const char *zKey, /* First key to write */
161651 int nKey, /* Number of bytes in nKey */
161652 IncrmergeWriter *pWriter /* Populate this object */
161654 int rc; /* Return code */
161655 sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
161657 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
161658 if( rc==SQLITE_OK ){
161659 sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
161660 sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
161661 sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
161662 const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
161663 int nRoot = 0; /* Size of aRoot[] in bytes */
161664 int rc2; /* Return code from sqlite3_reset() */
161665 int bAppendable = 0; /* Set to true if segment is appendable */
161667 /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
161668 sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
161669 sqlite3_bind_int(pSelect, 2, iIdx);
161670 if( sqlite3_step(pSelect)==SQLITE_ROW ){
161671 iStart = sqlite3_column_int64(pSelect, 1);
161672 iLeafEnd = sqlite3_column_int64(pSelect, 2);
161673 fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
161674 if( pWriter->nLeafData<0 ){
161675 pWriter->nLeafData = pWriter->nLeafData * -1;
161677 pWriter->bNoLeafData = (pWriter->nLeafData==0);
161678 nRoot = sqlite3_column_bytes(pSelect, 4);
161679 aRoot = sqlite3_column_blob(pSelect, 4);
161680 }else{
161681 return sqlite3_reset(pSelect);
161684 /* Check for the zero-length marker in the %_segments table */
161685 rc = fts3IsAppendable(p, iEnd, &bAppendable);
161687 /* Check that zKey/nKey is larger than the largest key the candidate */
161688 if( rc==SQLITE_OK && bAppendable ){
161689 char *aLeaf = 0;
161690 int nLeaf = 0;
161692 rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
161693 if( rc==SQLITE_OK ){
161694 NodeReader reader;
161695 for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
161696 rc==SQLITE_OK && reader.aNode;
161697 rc = nodeReaderNext(&reader)
161699 assert( reader.aNode );
161701 if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
161702 bAppendable = 0;
161704 nodeReaderRelease(&reader);
161706 sqlite3_free(aLeaf);
161709 if( rc==SQLITE_OK && bAppendable ){
161710 /* It is possible to append to this segment. Set up the IncrmergeWriter
161711 ** object to do so. */
161712 int i;
161713 int nHeight = (int)aRoot[0];
161714 NodeWriter *pNode;
161716 pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
161717 pWriter->iStart = iStart;
161718 pWriter->iEnd = iEnd;
161719 pWriter->iAbsLevel = iAbsLevel;
161720 pWriter->iIdx = iIdx;
161722 for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
161723 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
161726 pNode = &pWriter->aNodeWriter[nHeight];
161727 pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
161728 blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
161729 if( rc==SQLITE_OK ){
161730 memcpy(pNode->block.a, aRoot, nRoot);
161731 pNode->block.n = nRoot;
161734 for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
161735 NodeReader reader;
161736 pNode = &pWriter->aNodeWriter[i];
161738 rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
161739 while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
161740 blobGrowBuffer(&pNode->key, reader.term.n, &rc);
161741 if( rc==SQLITE_OK ){
161742 memcpy(pNode->key.a, reader.term.a, reader.term.n);
161743 pNode->key.n = reader.term.n;
161744 if( i>0 ){
161745 char *aBlock = 0;
161746 int nBlock = 0;
161747 pNode = &pWriter->aNodeWriter[i-1];
161748 pNode->iBlock = reader.iChild;
161749 rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
161750 blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
161751 if( rc==SQLITE_OK ){
161752 memcpy(pNode->block.a, aBlock, nBlock);
161753 pNode->block.n = nBlock;
161755 sqlite3_free(aBlock);
161758 nodeReaderRelease(&reader);
161762 rc2 = sqlite3_reset(pSelect);
161763 if( rc==SQLITE_OK ) rc = rc2;
161766 return rc;
161770 ** Determine the largest segment index value that exists within absolute
161771 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
161772 ** one before returning SQLITE_OK. Or, if there are no segments at all
161773 ** within level iAbsLevel, set *piIdx to zero.
161775 ** If an error occurs, return an SQLite error code. The final value of
161776 ** *piIdx is undefined in this case.
161778 static int fts3IncrmergeOutputIdx(
161779 Fts3Table *p, /* FTS Table handle */
161780 sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
161781 int *piIdx /* OUT: Next free index at iAbsLevel+1 */
161783 int rc;
161784 sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
161786 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
161787 if( rc==SQLITE_OK ){
161788 sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
161789 sqlite3_step(pOutputIdx);
161790 *piIdx = sqlite3_column_int(pOutputIdx, 0);
161791 rc = sqlite3_reset(pOutputIdx);
161794 return rc;
161798 ** Allocate an appendable output segment on absolute level iAbsLevel+1
161799 ** with idx value iIdx.
161801 ** In the %_segdir table, a segment is defined by the values in three
161802 ** columns:
161804 ** start_block
161805 ** leaves_end_block
161806 ** end_block
161808 ** When an appendable segment is allocated, it is estimated that the
161809 ** maximum number of leaf blocks that may be required is the sum of the
161810 ** number of leaf blocks consumed by the input segments, plus the number
161811 ** of input segments, multiplied by two. This value is stored in stack
161812 ** variable nLeafEst.
161814 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
161815 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
161816 ** array of leaf nodes starts at the first block allocated. The array
161817 ** of interior nodes that are parents of the leaf nodes start at block
161818 ** (start_block + (1 + end_block - start_block) / 16). And so on.
161820 ** In the actual code below, the value "16" is replaced with the
161821 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
161823 static int fts3IncrmergeWriter(
161824 Fts3Table *p, /* Fts3 table handle */
161825 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
161826 int iIdx, /* Index of new output segment */
161827 Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
161828 IncrmergeWriter *pWriter /* Populate this object */
161830 int rc; /* Return Code */
161831 int i; /* Iterator variable */
161832 int nLeafEst = 0; /* Blocks allocated for leaf nodes */
161833 sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
161834 sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
161836 /* Calculate nLeafEst. */
161837 rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
161838 if( rc==SQLITE_OK ){
161839 sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
161840 sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
161841 if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
161842 nLeafEst = sqlite3_column_int(pLeafEst, 0);
161844 rc = sqlite3_reset(pLeafEst);
161846 if( rc!=SQLITE_OK ) return rc;
161848 /* Calculate the first block to use in the output segment */
161849 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
161850 if( rc==SQLITE_OK ){
161851 if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
161852 pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
161853 pWriter->iEnd = pWriter->iStart - 1;
161854 pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
161856 rc = sqlite3_reset(pFirstBlock);
161858 if( rc!=SQLITE_OK ) return rc;
161860 /* Insert the marker in the %_segments table to make sure nobody tries
161861 ** to steal the space just allocated. This is also used to identify
161862 ** appendable segments. */
161863 rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
161864 if( rc!=SQLITE_OK ) return rc;
161866 pWriter->iAbsLevel = iAbsLevel;
161867 pWriter->nLeafEst = nLeafEst;
161868 pWriter->iIdx = iIdx;
161870 /* Set up the array of NodeWriter objects */
161871 for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
161872 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
161874 return SQLITE_OK;
161878 ** Remove an entry from the %_segdir table. This involves running the
161879 ** following two statements:
161881 ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
161882 ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
161884 ** The DELETE statement removes the specific %_segdir level. The UPDATE
161885 ** statement ensures that the remaining segments have contiguously allocated
161886 ** idx values.
161888 static int fts3RemoveSegdirEntry(
161889 Fts3Table *p, /* FTS3 table handle */
161890 sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
161891 int iIdx /* Index of %_segdir entry to delete */
161893 int rc; /* Return code */
161894 sqlite3_stmt *pDelete = 0; /* DELETE statement */
161896 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
161897 if( rc==SQLITE_OK ){
161898 sqlite3_bind_int64(pDelete, 1, iAbsLevel);
161899 sqlite3_bind_int(pDelete, 2, iIdx);
161900 sqlite3_step(pDelete);
161901 rc = sqlite3_reset(pDelete);
161904 return rc;
161908 ** One or more segments have just been removed from absolute level iAbsLevel.
161909 ** Update the 'idx' values of the remaining segments in the level so that
161910 ** the idx values are a contiguous sequence starting from 0.
161912 static int fts3RepackSegdirLevel(
161913 Fts3Table *p, /* FTS3 table handle */
161914 sqlite3_int64 iAbsLevel /* Absolute level to repack */
161916 int rc; /* Return code */
161917 int *aIdx = 0; /* Array of remaining idx values */
161918 int nIdx = 0; /* Valid entries in aIdx[] */
161919 int nAlloc = 0; /* Allocated size of aIdx[] */
161920 int i; /* Iterator variable */
161921 sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
161922 sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
161924 rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
161925 if( rc==SQLITE_OK ){
161926 int rc2;
161927 sqlite3_bind_int64(pSelect, 1, iAbsLevel);
161928 while( SQLITE_ROW==sqlite3_step(pSelect) ){
161929 if( nIdx>=nAlloc ){
161930 int *aNew;
161931 nAlloc += 16;
161932 aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
161933 if( !aNew ){
161934 rc = SQLITE_NOMEM;
161935 break;
161937 aIdx = aNew;
161939 aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
161941 rc2 = sqlite3_reset(pSelect);
161942 if( rc==SQLITE_OK ) rc = rc2;
161945 if( rc==SQLITE_OK ){
161946 rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
161948 if( rc==SQLITE_OK ){
161949 sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
161952 assert( p->bIgnoreSavepoint==0 );
161953 p->bIgnoreSavepoint = 1;
161954 for(i=0; rc==SQLITE_OK && i<nIdx; i++){
161955 if( aIdx[i]!=i ){
161956 sqlite3_bind_int(pUpdate, 3, aIdx[i]);
161957 sqlite3_bind_int(pUpdate, 1, i);
161958 sqlite3_step(pUpdate);
161959 rc = sqlite3_reset(pUpdate);
161962 p->bIgnoreSavepoint = 0;
161964 sqlite3_free(aIdx);
161965 return rc;
161968 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
161969 pNode->a[0] = (char)iHeight;
161970 if( iChild ){
161971 assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
161972 pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
161973 }else{
161974 assert( pNode->nAlloc>=1 );
161975 pNode->n = 1;
161980 ** The first two arguments are a pointer to and the size of a segment b-tree
161981 ** node. The node may be a leaf or an internal node.
161983 ** This function creates a new node image in blob object *pNew by copying
161984 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
161985 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
161987 static int fts3TruncateNode(
161988 const char *aNode, /* Current node image */
161989 int nNode, /* Size of aNode in bytes */
161990 Blob *pNew, /* OUT: Write new node image here */
161991 const char *zTerm, /* Omit all terms smaller than this */
161992 int nTerm, /* Size of zTerm in bytes */
161993 sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
161995 NodeReader reader; /* Reader object */
161996 Blob prev = {0, 0, 0}; /* Previous term written to new node */
161997 int rc = SQLITE_OK; /* Return code */
161998 int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
162000 /* Allocate required output space */
162001 blobGrowBuffer(pNew, nNode, &rc);
162002 if( rc!=SQLITE_OK ) return rc;
162003 pNew->n = 0;
162005 /* Populate new node buffer */
162006 for(rc = nodeReaderInit(&reader, aNode, nNode);
162007 rc==SQLITE_OK && reader.aNode;
162008 rc = nodeReaderNext(&reader)
162010 if( pNew->n==0 ){
162011 int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
162012 if( res<0 || (bLeaf==0 && res==0) ) continue;
162013 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
162014 *piBlock = reader.iChild;
162016 rc = fts3AppendToNode(
162017 pNew, &prev, reader.term.a, reader.term.n,
162018 reader.aDoclist, reader.nDoclist
162020 if( rc!=SQLITE_OK ) break;
162022 if( pNew->n==0 ){
162023 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
162024 *piBlock = reader.iChild;
162026 assert( pNew->n<=pNew->nAlloc );
162028 nodeReaderRelease(&reader);
162029 sqlite3_free(prev.a);
162030 return rc;
162034 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
162035 ** level iAbsLevel. This may involve deleting entries from the %_segments
162036 ** table, and modifying existing entries in both the %_segments and %_segdir
162037 ** tables.
162039 ** SQLITE_OK is returned if the segment is updated successfully. Or an
162040 ** SQLite error code otherwise.
162042 static int fts3TruncateSegment(
162043 Fts3Table *p, /* FTS3 table handle */
162044 sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
162045 int iIdx, /* Index within level of segment to modify */
162046 const char *zTerm, /* Remove terms smaller than this */
162047 int nTerm /* Number of bytes in buffer zTerm */
162049 int rc = SQLITE_OK; /* Return code */
162050 Blob root = {0,0,0}; /* New root page image */
162051 Blob block = {0,0,0}; /* Buffer used for any other block */
162052 sqlite3_int64 iBlock = 0; /* Block id */
162053 sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
162054 sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
162055 sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
162057 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
162058 if( rc==SQLITE_OK ){
162059 int rc2; /* sqlite3_reset() return code */
162060 sqlite3_bind_int64(pFetch, 1, iAbsLevel);
162061 sqlite3_bind_int(pFetch, 2, iIdx);
162062 if( SQLITE_ROW==sqlite3_step(pFetch) ){
162063 const char *aRoot = sqlite3_column_blob(pFetch, 4);
162064 int nRoot = sqlite3_column_bytes(pFetch, 4);
162065 iOldStart = sqlite3_column_int64(pFetch, 1);
162066 rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
162068 rc2 = sqlite3_reset(pFetch);
162069 if( rc==SQLITE_OK ) rc = rc2;
162072 while( rc==SQLITE_OK && iBlock ){
162073 char *aBlock = 0;
162074 int nBlock = 0;
162075 iNewStart = iBlock;
162077 rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
162078 if( rc==SQLITE_OK ){
162079 rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
162081 if( rc==SQLITE_OK ){
162082 rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
162084 sqlite3_free(aBlock);
162087 /* Variable iNewStart now contains the first valid leaf node. */
162088 if( rc==SQLITE_OK && iNewStart ){
162089 sqlite3_stmt *pDel = 0;
162090 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
162091 if( rc==SQLITE_OK ){
162092 sqlite3_bind_int64(pDel, 1, iOldStart);
162093 sqlite3_bind_int64(pDel, 2, iNewStart-1);
162094 sqlite3_step(pDel);
162095 rc = sqlite3_reset(pDel);
162099 if( rc==SQLITE_OK ){
162100 sqlite3_stmt *pChomp = 0;
162101 rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
162102 if( rc==SQLITE_OK ){
162103 sqlite3_bind_int64(pChomp, 1, iNewStart);
162104 sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
162105 sqlite3_bind_int64(pChomp, 3, iAbsLevel);
162106 sqlite3_bind_int(pChomp, 4, iIdx);
162107 sqlite3_step(pChomp);
162108 rc = sqlite3_reset(pChomp);
162112 sqlite3_free(root.a);
162113 sqlite3_free(block.a);
162114 return rc;
162118 ** This function is called after an incrmental-merge operation has run to
162119 ** merge (or partially merge) two or more segments from absolute level
162120 ** iAbsLevel.
162122 ** Each input segment is either removed from the db completely (if all of
162123 ** its data was copied to the output segment by the incrmerge operation)
162124 ** or modified in place so that it no longer contains those entries that
162125 ** have been duplicated in the output segment.
162127 static int fts3IncrmergeChomp(
162128 Fts3Table *p, /* FTS table handle */
162129 sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
162130 Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
162131 int *pnRem /* Number of segments not deleted */
162133 int i;
162134 int nRem = 0;
162135 int rc = SQLITE_OK;
162137 for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
162138 Fts3SegReader *pSeg = 0;
162139 int j;
162141 /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
162142 ** somewhere in the pCsr->apSegment[] array. */
162143 for(j=0; ALWAYS(j<pCsr->nSegment); j++){
162144 pSeg = pCsr->apSegment[j];
162145 if( pSeg->iIdx==i ) break;
162147 assert( j<pCsr->nSegment && pSeg->iIdx==i );
162149 if( pSeg->aNode==0 ){
162150 /* Seg-reader is at EOF. Remove the entire input segment. */
162151 rc = fts3DeleteSegment(p, pSeg);
162152 if( rc==SQLITE_OK ){
162153 rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
162155 *pnRem = 0;
162156 }else{
162157 /* The incremental merge did not copy all the data from this
162158 ** segment to the upper level. The segment is modified in place
162159 ** so that it contains no keys smaller than zTerm/nTerm. */
162160 const char *zTerm = pSeg->zTerm;
162161 int nTerm = pSeg->nTerm;
162162 rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
162163 nRem++;
162167 if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
162168 rc = fts3RepackSegdirLevel(p, iAbsLevel);
162171 *pnRem = nRem;
162172 return rc;
162176 ** Store an incr-merge hint in the database.
162178 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
162179 sqlite3_stmt *pReplace = 0;
162180 int rc; /* Return code */
162182 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
162183 if( rc==SQLITE_OK ){
162184 sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
162185 sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
162186 sqlite3_step(pReplace);
162187 rc = sqlite3_reset(pReplace);
162190 return rc;
162194 ** Load an incr-merge hint from the database. The incr-merge hint, if one
162195 ** exists, is stored in the rowid==1 row of the %_stat table.
162197 ** If successful, populate blob *pHint with the value read from the %_stat
162198 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
162199 ** SQLite error code.
162201 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
162202 sqlite3_stmt *pSelect = 0;
162203 int rc;
162205 pHint->n = 0;
162206 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
162207 if( rc==SQLITE_OK ){
162208 int rc2;
162209 sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
162210 if( SQLITE_ROW==sqlite3_step(pSelect) ){
162211 const char *aHint = sqlite3_column_blob(pSelect, 0);
162212 int nHint = sqlite3_column_bytes(pSelect, 0);
162213 if( aHint ){
162214 blobGrowBuffer(pHint, nHint, &rc);
162215 if( rc==SQLITE_OK ){
162216 memcpy(pHint->a, aHint, nHint);
162217 pHint->n = nHint;
162221 rc2 = sqlite3_reset(pSelect);
162222 if( rc==SQLITE_OK ) rc = rc2;
162225 return rc;
162229 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
162230 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
162231 ** consists of two varints, the absolute level number of the input segments
162232 ** and the number of input segments.
162234 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
162235 ** set *pRc to an SQLite error code before returning.
162237 static void fts3IncrmergeHintPush(
162238 Blob *pHint, /* Hint blob to append to */
162239 i64 iAbsLevel, /* First varint to store in hint */
162240 int nInput, /* Second varint to store in hint */
162241 int *pRc /* IN/OUT: Error code */
162243 blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
162244 if( *pRc==SQLITE_OK ){
162245 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
162246 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
162251 ** Read the last entry (most recently pushed) from the hint blob *pHint
162252 ** and then remove the entry. Write the two values read to *piAbsLevel and
162253 ** *pnInput before returning.
162255 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
162256 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
162258 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
162259 const int nHint = pHint->n;
162260 int i;
162262 i = pHint->n-2;
162263 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
162264 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
162266 pHint->n = i;
162267 i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
162268 i += fts3GetVarint32(&pHint->a[i], pnInput);
162269 if( i!=nHint ) return FTS_CORRUPT_VTAB;
162271 return SQLITE_OK;
162276 ** Attempt an incremental merge that writes nMerge leaf blocks.
162278 ** Incremental merges happen nMin segments at a time. The segments
162279 ** to be merged are the nMin oldest segments (the ones with the smallest
162280 ** values for the _segdir.idx field) in the highest level that contains
162281 ** at least nMin segments. Multiple merges might occur in an attempt to
162282 ** write the quota of nMerge leaf blocks.
162284 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
162285 int rc; /* Return code */
162286 int nRem = nMerge; /* Number of leaf pages yet to be written */
162287 Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
162288 Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
162289 IncrmergeWriter *pWriter; /* Writer object */
162290 int nSeg = 0; /* Number of input segments */
162291 sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
162292 Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
162293 int bDirtyHint = 0; /* True if blob 'hint' has been modified */
162295 /* Allocate space for the cursor, filter and writer objects */
162296 const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
162297 pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
162298 if( !pWriter ) return SQLITE_NOMEM;
162299 pFilter = (Fts3SegFilter *)&pWriter[1];
162300 pCsr = (Fts3MultiSegReader *)&pFilter[1];
162302 rc = fts3IncrmergeHintLoad(p, &hint);
162303 while( rc==SQLITE_OK && nRem>0 ){
162304 const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
162305 sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
162306 int bUseHint = 0; /* True if attempting to append */
162307 int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
162309 /* Search the %_segdir table for the absolute level with the smallest
162310 ** relative level number that contains at least nMin segments, if any.
162311 ** If one is found, set iAbsLevel to the absolute level number and
162312 ** nSeg to nMin. If no level with at least nMin segments can be found,
162313 ** set nSeg to -1.
162315 rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
162316 sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
162317 if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
162318 iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
162319 nSeg = sqlite3_column_int(pFindLevel, 1);
162320 assert( nSeg>=2 );
162321 }else{
162322 nSeg = -1;
162324 rc = sqlite3_reset(pFindLevel);
162326 /* If the hint read from the %_stat table is not empty, check if the
162327 ** last entry in it specifies a relative level smaller than or equal
162328 ** to the level identified by the block above (if any). If so, this
162329 ** iteration of the loop will work on merging at the hinted level.
162331 if( rc==SQLITE_OK && hint.n ){
162332 int nHint = hint.n;
162333 sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
162334 int nHintSeg = 0; /* Hint number of segments */
162336 rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
162337 if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
162338 iAbsLevel = iHintAbsLevel;
162339 nSeg = nHintSeg;
162340 bUseHint = 1;
162341 bDirtyHint = 1;
162342 }else{
162343 /* This undoes the effect of the HintPop() above - so that no entry
162344 ** is removed from the hint blob. */
162345 hint.n = nHint;
162349 /* If nSeg is less that zero, then there is no level with at least
162350 ** nMin segments and no hint in the %_stat table. No work to do.
162351 ** Exit early in this case. */
162352 if( nSeg<0 ) break;
162354 /* Open a cursor to iterate through the contents of the oldest nSeg
162355 ** indexes of absolute level iAbsLevel. If this cursor is opened using
162356 ** the 'hint' parameters, it is possible that there are less than nSeg
162357 ** segments available in level iAbsLevel. In this case, no work is
162358 ** done on iAbsLevel - fall through to the next iteration of the loop
162359 ** to start work on some other level. */
162360 memset(pWriter, 0, nAlloc);
162361 pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
162363 if( rc==SQLITE_OK ){
162364 rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
162365 assert( bUseHint==1 || bUseHint==0 );
162366 if( iIdx==0 || (bUseHint && iIdx==1) ){
162367 int bIgnore = 0;
162368 rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
162369 if( bIgnore ){
162370 pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
162375 if( rc==SQLITE_OK ){
162376 rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
162378 if( SQLITE_OK==rc && pCsr->nSegment==nSeg
162379 && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
162380 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
162382 if( bUseHint && iIdx>0 ){
162383 const char *zKey = pCsr->zTerm;
162384 int nKey = pCsr->nTerm;
162385 rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
162386 }else{
162387 rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
162390 if( rc==SQLITE_OK && pWriter->nLeafEst ){
162391 fts3LogMerge(nSeg, iAbsLevel);
162393 rc = fts3IncrmergeAppend(p, pWriter, pCsr);
162394 if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
162395 if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
162396 }while( rc==SQLITE_ROW );
162398 /* Update or delete the input segments */
162399 if( rc==SQLITE_OK ){
162400 nRem -= (1 + pWriter->nWork);
162401 rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
162402 if( nSeg!=0 ){
162403 bDirtyHint = 1;
162404 fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
162409 if( nSeg!=0 ){
162410 pWriter->nLeafData = pWriter->nLeafData * -1;
162412 fts3IncrmergeRelease(p, pWriter, &rc);
162413 if( nSeg==0 && pWriter->bNoLeafData==0 ){
162414 fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
162418 sqlite3Fts3SegReaderFinish(pCsr);
162421 /* Write the hint values into the %_stat table for the next incr-merger */
162422 if( bDirtyHint && rc==SQLITE_OK ){
162423 rc = fts3IncrmergeHintStore(p, &hint);
162426 sqlite3_free(pWriter);
162427 sqlite3_free(hint.a);
162428 return rc;
162432 ** Convert the text beginning at *pz into an integer and return
162433 ** its value. Advance *pz to point to the first character past
162434 ** the integer.
162436 ** This function used for parameters to merge= and incrmerge=
162437 ** commands.
162439 static int fts3Getint(const char **pz){
162440 const char *z = *pz;
162441 int i = 0;
162442 while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
162443 *pz = z;
162444 return i;
162448 ** Process statements of the form:
162450 ** INSERT INTO table(table) VALUES('merge=A,B');
162452 ** A and B are integers that decode to be the number of leaf pages
162453 ** written for the merge, and the minimum number of segments on a level
162454 ** before it will be selected for a merge, respectively.
162456 static int fts3DoIncrmerge(
162457 Fts3Table *p, /* FTS3 table handle */
162458 const char *zParam /* Nul-terminated string containing "A,B" */
162460 int rc;
162461 int nMin = (FTS3_MERGE_COUNT / 2);
162462 int nMerge = 0;
162463 const char *z = zParam;
162465 /* Read the first integer value */
162466 nMerge = fts3Getint(&z);
162468 /* If the first integer value is followed by a ',', read the second
162469 ** integer value. */
162470 if( z[0]==',' && z[1]!='\0' ){
162472 nMin = fts3Getint(&z);
162475 if( z[0]!='\0' || nMin<2 ){
162476 rc = SQLITE_ERROR;
162477 }else{
162478 rc = SQLITE_OK;
162479 if( !p->bHasStat ){
162480 assert( p->bFts4==0 );
162481 sqlite3Fts3CreateStatTable(&rc, p);
162483 if( rc==SQLITE_OK ){
162484 rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
162486 sqlite3Fts3SegmentsClose(p);
162488 return rc;
162492 ** Process statements of the form:
162494 ** INSERT INTO table(table) VALUES('automerge=X');
162496 ** where X is an integer. X==0 means to turn automerge off. X!=0 means
162497 ** turn it on. The setting is persistent.
162499 static int fts3DoAutoincrmerge(
162500 Fts3Table *p, /* FTS3 table handle */
162501 const char *zParam /* Nul-terminated string containing boolean */
162503 int rc = SQLITE_OK;
162504 sqlite3_stmt *pStmt = 0;
162505 p->nAutoincrmerge = fts3Getint(&zParam);
162506 if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
162507 p->nAutoincrmerge = 8;
162509 if( !p->bHasStat ){
162510 assert( p->bFts4==0 );
162511 sqlite3Fts3CreateStatTable(&rc, p);
162512 if( rc ) return rc;
162514 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
162515 if( rc ) return rc;
162516 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
162517 sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
162518 sqlite3_step(pStmt);
162519 rc = sqlite3_reset(pStmt);
162520 return rc;
162524 ** Return a 64-bit checksum for the FTS index entry specified by the
162525 ** arguments to this function.
162527 static u64 fts3ChecksumEntry(
162528 const char *zTerm, /* Pointer to buffer containing term */
162529 int nTerm, /* Size of zTerm in bytes */
162530 int iLangid, /* Language id for current row */
162531 int iIndex, /* Index (0..Fts3Table.nIndex-1) */
162532 i64 iDocid, /* Docid for current row. */
162533 int iCol, /* Column number */
162534 int iPos /* Position */
162536 int i;
162537 u64 ret = (u64)iDocid;
162539 ret += (ret<<3) + iLangid;
162540 ret += (ret<<3) + iIndex;
162541 ret += (ret<<3) + iCol;
162542 ret += (ret<<3) + iPos;
162543 for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
162545 return ret;
162549 ** Return a checksum of all entries in the FTS index that correspond to
162550 ** language id iLangid. The checksum is calculated by XORing the checksums
162551 ** of each individual entry (see fts3ChecksumEntry()) together.
162553 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
162554 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
162555 ** return value is undefined in this case.
162557 static u64 fts3ChecksumIndex(
162558 Fts3Table *p, /* FTS3 table handle */
162559 int iLangid, /* Language id to return cksum for */
162560 int iIndex, /* Index to cksum (0..p->nIndex-1) */
162561 int *pRc /* OUT: Return code */
162563 Fts3SegFilter filter;
162564 Fts3MultiSegReader csr;
162565 int rc;
162566 u64 cksum = 0;
162568 assert( *pRc==SQLITE_OK );
162570 memset(&filter, 0, sizeof(filter));
162571 memset(&csr, 0, sizeof(csr));
162572 filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
162573 filter.flags |= FTS3_SEGMENT_SCAN;
162575 rc = sqlite3Fts3SegReaderCursor(
162576 p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
162578 if( rc==SQLITE_OK ){
162579 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
162582 if( rc==SQLITE_OK ){
162583 while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
162584 char *pCsr = csr.aDoclist;
162585 char *pEnd = &pCsr[csr.nDoclist];
162587 i64 iDocid = 0;
162588 i64 iCol = 0;
162589 i64 iPos = 0;
162591 pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
162592 while( pCsr<pEnd ){
162593 i64 iVal = 0;
162594 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
162595 if( pCsr<pEnd ){
162596 if( iVal==0 || iVal==1 ){
162597 iCol = 0;
162598 iPos = 0;
162599 if( iVal ){
162600 pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
162601 }else{
162602 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
162603 iDocid += iVal;
162605 }else{
162606 iPos += (iVal - 2);
162607 cksum = cksum ^ fts3ChecksumEntry(
162608 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
162609 (int)iCol, (int)iPos
162616 sqlite3Fts3SegReaderFinish(&csr);
162618 *pRc = rc;
162619 return cksum;
162623 ** Check if the contents of the FTS index match the current contents of the
162624 ** content table. If no error occurs and the contents do match, set *pbOk
162625 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
162626 ** to false before returning.
162628 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
162629 ** code. The final value of *pbOk is undefined in this case.
162631 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
162632 int rc = SQLITE_OK; /* Return code */
162633 u64 cksum1 = 0; /* Checksum based on FTS index contents */
162634 u64 cksum2 = 0; /* Checksum based on %_content contents */
162635 sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
162637 /* This block calculates the checksum according to the FTS index. */
162638 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
162639 if( rc==SQLITE_OK ){
162640 int rc2;
162641 sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
162642 sqlite3_bind_int(pAllLangid, 2, p->nIndex);
162643 while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
162644 int iLangid = sqlite3_column_int(pAllLangid, 0);
162645 int i;
162646 for(i=0; i<p->nIndex; i++){
162647 cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
162650 rc2 = sqlite3_reset(pAllLangid);
162651 if( rc==SQLITE_OK ) rc = rc2;
162654 /* This block calculates the checksum according to the %_content table */
162655 if( rc==SQLITE_OK ){
162656 sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
162657 sqlite3_stmt *pStmt = 0;
162658 char *zSql;
162660 zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
162661 if( !zSql ){
162662 rc = SQLITE_NOMEM;
162663 }else{
162664 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
162665 sqlite3_free(zSql);
162668 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
162669 i64 iDocid = sqlite3_column_int64(pStmt, 0);
162670 int iLang = langidFromSelect(p, pStmt);
162671 int iCol;
162673 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
162674 if( p->abNotindexed[iCol]==0 ){
162675 const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
162676 int nText = sqlite3_column_bytes(pStmt, iCol+1);
162677 sqlite3_tokenizer_cursor *pT = 0;
162679 rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
162680 while( rc==SQLITE_OK ){
162681 char const *zToken; /* Buffer containing token */
162682 int nToken = 0; /* Number of bytes in token */
162683 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
162684 int iPos = 0; /* Position of token in zText */
162686 rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
162687 if( rc==SQLITE_OK ){
162688 int i;
162689 cksum2 = cksum2 ^ fts3ChecksumEntry(
162690 zToken, nToken, iLang, 0, iDocid, iCol, iPos
162692 for(i=1; i<p->nIndex; i++){
162693 if( p->aIndex[i].nPrefix<=nToken ){
162694 cksum2 = cksum2 ^ fts3ChecksumEntry(
162695 zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
162701 if( pT ) pModule->xClose(pT);
162702 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
162707 sqlite3_finalize(pStmt);
162710 *pbOk = (cksum1==cksum2);
162711 return rc;
162715 ** Run the integrity-check. If no error occurs and the current contents of
162716 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
162717 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
162719 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
162720 ** error code.
162722 ** The integrity-check works as follows. For each token and indexed token
162723 ** prefix in the document set, a 64-bit checksum is calculated (by code
162724 ** in fts3ChecksumEntry()) based on the following:
162726 ** + The index number (0 for the main index, 1 for the first prefix
162727 ** index etc.),
162728 ** + The token (or token prefix) text itself,
162729 ** + The language-id of the row it appears in,
162730 ** + The docid of the row it appears in,
162731 ** + The column it appears in, and
162732 ** + The tokens position within that column.
162734 ** The checksums for all entries in the index are XORed together to create
162735 ** a single checksum for the entire index.
162737 ** The integrity-check code calculates the same checksum in two ways:
162739 ** 1. By scanning the contents of the FTS index, and
162740 ** 2. By scanning and tokenizing the content table.
162742 ** If the two checksums are identical, the integrity-check is deemed to have
162743 ** passed.
162745 static int fts3DoIntegrityCheck(
162746 Fts3Table *p /* FTS3 table handle */
162748 int rc;
162749 int bOk = 0;
162750 rc = fts3IntegrityCheck(p, &bOk);
162751 if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
162752 return rc;
162756 ** Handle a 'special' INSERT of the form:
162758 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
162760 ** Argument pVal contains the result of <expr>. Currently the only
162761 ** meaningful value to insert is the text 'optimize'.
162763 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
162764 int rc; /* Return Code */
162765 const char *zVal = (const char *)sqlite3_value_text(pVal);
162766 int nVal = sqlite3_value_bytes(pVal);
162768 if( !zVal ){
162769 return SQLITE_NOMEM;
162770 }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
162771 rc = fts3DoOptimize(p, 0);
162772 }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
162773 rc = fts3DoRebuild(p);
162774 }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
162775 rc = fts3DoIntegrityCheck(p);
162776 }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
162777 rc = fts3DoIncrmerge(p, &zVal[6]);
162778 }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
162779 rc = fts3DoAutoincrmerge(p, &zVal[10]);
162780 #ifdef SQLITE_TEST
162781 }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
162782 p->nNodeSize = atoi(&zVal[9]);
162783 rc = SQLITE_OK;
162784 }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
162785 p->nMaxPendingData = atoi(&zVal[11]);
162786 rc = SQLITE_OK;
162787 }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
162788 p->bNoIncrDoclist = atoi(&zVal[21]);
162789 rc = SQLITE_OK;
162790 #endif
162791 }else{
162792 rc = SQLITE_ERROR;
162795 return rc;
162798 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
162800 ** Delete all cached deferred doclists. Deferred doclists are cached
162801 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
162803 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
162804 Fts3DeferredToken *pDef;
162805 for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
162806 fts3PendingListDelete(pDef->pList);
162807 pDef->pList = 0;
162812 ** Free all entries in the pCsr->pDeffered list. Entries are added to
162813 ** this list using sqlite3Fts3DeferToken().
162815 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
162816 Fts3DeferredToken *pDef;
162817 Fts3DeferredToken *pNext;
162818 for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
162819 pNext = pDef->pNext;
162820 fts3PendingListDelete(pDef->pList);
162821 sqlite3_free(pDef);
162823 pCsr->pDeferred = 0;
162827 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
162828 ** based on the row that pCsr currently points to.
162830 ** A deferred-doclist is like any other doclist with position information
162831 ** included, except that it only contains entries for a single row of the
162832 ** table, not for all rows.
162834 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
162835 int rc = SQLITE_OK; /* Return code */
162836 if( pCsr->pDeferred ){
162837 int i; /* Used to iterate through table columns */
162838 sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
162839 Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
162841 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
162842 sqlite3_tokenizer *pT = p->pTokenizer;
162843 sqlite3_tokenizer_module const *pModule = pT->pModule;
162845 assert( pCsr->isRequireSeek==0 );
162846 iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
162848 for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
162849 if( p->abNotindexed[i]==0 ){
162850 const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
162851 sqlite3_tokenizer_cursor *pTC = 0;
162853 rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
162854 while( rc==SQLITE_OK ){
162855 char const *zToken; /* Buffer containing token */
162856 int nToken = 0; /* Number of bytes in token */
162857 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
162858 int iPos = 0; /* Position of token in zText */
162860 rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
162861 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
162862 Fts3PhraseToken *pPT = pDef->pToken;
162863 if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
162864 && (pPT->bFirst==0 || iPos==0)
162865 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
162866 && (0==memcmp(zToken, pPT->z, pPT->n))
162868 fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
162872 if( pTC ) pModule->xClose(pTC);
162873 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
162877 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
162878 if( pDef->pList ){
162879 rc = fts3PendingListAppendVarint(&pDef->pList, 0);
162884 return rc;
162887 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
162888 Fts3DeferredToken *p,
162889 char **ppData,
162890 int *pnData
162892 char *pRet;
162893 int nSkip;
162894 sqlite3_int64 dummy;
162896 *ppData = 0;
162897 *pnData = 0;
162899 if( p->pList==0 ){
162900 return SQLITE_OK;
162903 pRet = (char *)sqlite3_malloc(p->pList->nData);
162904 if( !pRet ) return SQLITE_NOMEM;
162906 nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
162907 *pnData = p->pList->nData - nSkip;
162908 *ppData = pRet;
162910 memcpy(pRet, &p->pList->aData[nSkip], *pnData);
162911 return SQLITE_OK;
162915 ** Add an entry for token pToken to the pCsr->pDeferred list.
162917 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
162918 Fts3Cursor *pCsr, /* Fts3 table cursor */
162919 Fts3PhraseToken *pToken, /* Token to defer */
162920 int iCol /* Column that token must appear in (or -1) */
162922 Fts3DeferredToken *pDeferred;
162923 pDeferred = sqlite3_malloc(sizeof(*pDeferred));
162924 if( !pDeferred ){
162925 return SQLITE_NOMEM;
162927 memset(pDeferred, 0, sizeof(*pDeferred));
162928 pDeferred->pToken = pToken;
162929 pDeferred->pNext = pCsr->pDeferred;
162930 pDeferred->iCol = iCol;
162931 pCsr->pDeferred = pDeferred;
162933 assert( pToken->pDeferred==0 );
162934 pToken->pDeferred = pDeferred;
162936 return SQLITE_OK;
162938 #endif
162941 ** SQLite value pRowid contains the rowid of a row that may or may not be
162942 ** present in the FTS3 table. If it is, delete it and adjust the contents
162943 ** of subsiduary data structures accordingly.
162945 static int fts3DeleteByRowid(
162946 Fts3Table *p,
162947 sqlite3_value *pRowid,
162948 int *pnChng, /* IN/OUT: Decrement if row is deleted */
162949 u32 *aSzDel
162951 int rc = SQLITE_OK; /* Return code */
162952 int bFound = 0; /* True if *pRowid really is in the table */
162954 fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
162955 if( bFound && rc==SQLITE_OK ){
162956 int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
162957 rc = fts3IsEmpty(p, pRowid, &isEmpty);
162958 if( rc==SQLITE_OK ){
162959 if( isEmpty ){
162960 /* Deleting this row means the whole table is empty. In this case
162961 ** delete the contents of all three tables and throw away any
162962 ** data in the pendingTerms hash table. */
162963 rc = fts3DeleteAll(p, 1);
162964 *pnChng = 0;
162965 memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
162966 }else{
162967 *pnChng = *pnChng - 1;
162968 if( p->zContentTbl==0 ){
162969 fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
162971 if( p->bHasDocsize ){
162972 fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
162978 return rc;
162982 ** This function does the work for the xUpdate method of FTS3 virtual
162983 ** tables. The schema of the virtual table being:
162985 ** CREATE TABLE <table name>(
162986 ** <user columns>,
162987 ** <table name> HIDDEN,
162988 ** docid HIDDEN,
162989 ** <langid> HIDDEN
162990 ** );
162994 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
162995 sqlite3_vtab *pVtab, /* FTS3 vtab object */
162996 int nArg, /* Size of argument array */
162997 sqlite3_value **apVal, /* Array of arguments */
162998 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
163000 Fts3Table *p = (Fts3Table *)pVtab;
163001 int rc = SQLITE_OK; /* Return Code */
163002 int isRemove = 0; /* True for an UPDATE or DELETE */
163003 u32 *aSzIns = 0; /* Sizes of inserted documents */
163004 u32 *aSzDel = 0; /* Sizes of deleted documents */
163005 int nChng = 0; /* Net change in number of documents */
163006 int bInsertDone = 0;
163008 /* At this point it must be known if the %_stat table exists or not.
163009 ** So bHasStat may not be 2. */
163010 assert( p->bHasStat==0 || p->bHasStat==1 );
163012 assert( p->pSegments==0 );
163013 assert(
163014 nArg==1 /* DELETE operations */
163015 || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
163018 /* Check for a "special" INSERT operation. One of the form:
163020 ** INSERT INTO xyz(xyz) VALUES('command');
163022 if( nArg>1
163023 && sqlite3_value_type(apVal[0])==SQLITE_NULL
163024 && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
163026 rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
163027 goto update_out;
163030 if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
163031 rc = SQLITE_CONSTRAINT;
163032 goto update_out;
163035 /* Allocate space to hold the change in document sizes */
163036 aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
163037 if( aSzDel==0 ){
163038 rc = SQLITE_NOMEM;
163039 goto update_out;
163041 aSzIns = &aSzDel[p->nColumn+1];
163042 memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
163044 rc = fts3Writelock(p);
163045 if( rc!=SQLITE_OK ) goto update_out;
163047 /* If this is an INSERT operation, or an UPDATE that modifies the rowid
163048 ** value, then this operation requires constraint handling.
163050 ** If the on-conflict mode is REPLACE, this means that the existing row
163051 ** should be deleted from the database before inserting the new row. Or,
163052 ** if the on-conflict mode is other than REPLACE, then this method must
163053 ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
163054 ** modify the database file.
163056 if( nArg>1 && p->zContentTbl==0 ){
163057 /* Find the value object that holds the new rowid value. */
163058 sqlite3_value *pNewRowid = apVal[3+p->nColumn];
163059 if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
163060 pNewRowid = apVal[1];
163063 if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
163064 sqlite3_value_type(apVal[0])==SQLITE_NULL
163065 || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
163067 /* The new rowid is not NULL (in this case the rowid will be
163068 ** automatically assigned and there is no chance of a conflict), and
163069 ** the statement is either an INSERT or an UPDATE that modifies the
163070 ** rowid column. So if the conflict mode is REPLACE, then delete any
163071 ** existing row with rowid=pNewRowid.
163073 ** Or, if the conflict mode is not REPLACE, insert the new record into
163074 ** the %_content table. If we hit the duplicate rowid constraint (or any
163075 ** other error) while doing so, return immediately.
163077 ** This branch may also run if pNewRowid contains a value that cannot
163078 ** be losslessly converted to an integer. In this case, the eventual
163079 ** call to fts3InsertData() (either just below or further on in this
163080 ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
163081 ** invoked, it will delete zero rows (since no row will have
163082 ** docid=$pNewRowid if $pNewRowid is not an integer value).
163084 if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
163085 rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
163086 }else{
163087 rc = fts3InsertData(p, apVal, pRowid);
163088 bInsertDone = 1;
163092 if( rc!=SQLITE_OK ){
163093 goto update_out;
163096 /* If this is a DELETE or UPDATE operation, remove the old record. */
163097 if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
163098 assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
163099 rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
163100 isRemove = 1;
163103 /* If this is an INSERT or UPDATE operation, insert the new record. */
163104 if( nArg>1 && rc==SQLITE_OK ){
163105 int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
163106 if( bInsertDone==0 ){
163107 rc = fts3InsertData(p, apVal, pRowid);
163108 if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
163109 rc = FTS_CORRUPT_VTAB;
163112 if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
163113 rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
163115 if( rc==SQLITE_OK ){
163116 assert( p->iPrevDocid==*pRowid );
163117 rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
163119 if( p->bHasDocsize ){
163120 fts3InsertDocsize(&rc, p, aSzIns);
163122 nChng++;
163125 if( p->bFts4 ){
163126 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
163129 update_out:
163130 sqlite3_free(aSzDel);
163131 sqlite3Fts3SegmentsClose(p);
163132 return rc;
163136 ** Flush any data in the pending-terms hash table to disk. If successful,
163137 ** merge all segments in the database (including the new segment, if
163138 ** there was any data to flush) into a single segment.
163140 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
163141 int rc;
163142 rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
163143 if( rc==SQLITE_OK ){
163144 rc = fts3DoOptimize(p, 1);
163145 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
163146 int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
163147 if( rc2!=SQLITE_OK ) rc = rc2;
163148 }else{
163149 sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
163150 sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
163153 sqlite3Fts3SegmentsClose(p);
163154 return rc;
163157 #endif
163159 /************** End of fts3_write.c ******************************************/
163160 /************** Begin file fts3_snippet.c ************************************/
163162 ** 2009 Oct 23
163164 ** The author disclaims copyright to this source code. In place of
163165 ** a legal notice, here is a blessing:
163167 ** May you do good and not evil.
163168 ** May you find forgiveness for yourself and forgive others.
163169 ** May you share freely, never taking more than you give.
163171 ******************************************************************************
163174 /* #include "fts3Int.h" */
163175 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
163177 /* #include <string.h> */
163178 /* #include <assert.h> */
163181 ** Characters that may appear in the second argument to matchinfo().
163183 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
163184 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
163185 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
163186 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
163187 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
163188 #define FTS3_MATCHINFO_LCS 's' /* nCol values */
163189 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
163190 #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
163191 #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
163194 ** The default value for the second argument to matchinfo().
163196 #define FTS3_MATCHINFO_DEFAULT "pcx"
163200 ** Used as an fts3ExprIterate() context when loading phrase doclists to
163201 ** Fts3Expr.aDoclist[]/nDoclist.
163203 typedef struct LoadDoclistCtx LoadDoclistCtx;
163204 struct LoadDoclistCtx {
163205 Fts3Cursor *pCsr; /* FTS3 Cursor */
163206 int nPhrase; /* Number of phrases seen so far */
163207 int nToken; /* Number of tokens seen so far */
163211 ** The following types are used as part of the implementation of the
163212 ** fts3BestSnippet() routine.
163214 typedef struct SnippetIter SnippetIter;
163215 typedef struct SnippetPhrase SnippetPhrase;
163216 typedef struct SnippetFragment SnippetFragment;
163218 struct SnippetIter {
163219 Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
163220 int iCol; /* Extract snippet from this column */
163221 int nSnippet; /* Requested snippet length (in tokens) */
163222 int nPhrase; /* Number of phrases in query */
163223 SnippetPhrase *aPhrase; /* Array of size nPhrase */
163224 int iCurrent; /* First token of current snippet */
163227 struct SnippetPhrase {
163228 int nToken; /* Number of tokens in phrase */
163229 char *pList; /* Pointer to start of phrase position list */
163230 int iHead; /* Next value in position list */
163231 char *pHead; /* Position list data following iHead */
163232 int iTail; /* Next value in trailing position list */
163233 char *pTail; /* Position list data following iTail */
163236 struct SnippetFragment {
163237 int iCol; /* Column snippet is extracted from */
163238 int iPos; /* Index of first token in snippet */
163239 u64 covered; /* Mask of query phrases covered */
163240 u64 hlmask; /* Mask of snippet terms to highlight */
163244 ** This type is used as an fts3ExprIterate() context object while
163245 ** accumulating the data returned by the matchinfo() function.
163247 typedef struct MatchInfo MatchInfo;
163248 struct MatchInfo {
163249 Fts3Cursor *pCursor; /* FTS3 Cursor */
163250 int nCol; /* Number of columns in table */
163251 int nPhrase; /* Number of matchable phrases in query */
163252 sqlite3_int64 nDoc; /* Number of docs in database */
163253 char flag;
163254 u32 *aMatchinfo; /* Pre-allocated buffer */
163258 ** An instance of this structure is used to manage a pair of buffers, each
163259 ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
163260 ** for details.
163262 struct MatchinfoBuffer {
163263 u8 aRef[3];
163264 int nElem;
163265 int bGlobal; /* Set if global data is loaded */
163266 char *zMatchinfo;
163267 u32 aMatchinfo[1];
163272 ** The snippet() and offsets() functions both return text values. An instance
163273 ** of the following structure is used to accumulate those values while the
163274 ** functions are running. See fts3StringAppend() for details.
163276 typedef struct StrBuffer StrBuffer;
163277 struct StrBuffer {
163278 char *z; /* Pointer to buffer containing string */
163279 int n; /* Length of z in bytes (excl. nul-term) */
163280 int nAlloc; /* Allocated size of buffer z in bytes */
163284 /*************************************************************************
163285 ** Start of MatchinfoBuffer code.
163289 ** Allocate a two-slot MatchinfoBuffer object.
163291 static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
163292 MatchinfoBuffer *pRet;
163293 int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
163294 int nStr = (int)strlen(zMatchinfo);
163296 pRet = sqlite3_malloc(nByte + nStr+1);
163297 if( pRet ){
163298 memset(pRet, 0, nByte);
163299 pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
163300 pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
163301 pRet->nElem = nElem;
163302 pRet->zMatchinfo = ((char*)pRet) + nByte;
163303 memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
163304 pRet->aRef[0] = 1;
163307 return pRet;
163310 static void fts3MIBufferFree(void *p){
163311 MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
163313 assert( (u32*)p==&pBuf->aMatchinfo[1]
163314 || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
163316 if( (u32*)p==&pBuf->aMatchinfo[1] ){
163317 pBuf->aRef[1] = 0;
163318 }else{
163319 pBuf->aRef[2] = 0;
163322 if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
163323 sqlite3_free(pBuf);
163327 static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
163328 void (*xRet)(void*) = 0;
163329 u32 *aOut = 0;
163331 if( p->aRef[1]==0 ){
163332 p->aRef[1] = 1;
163333 aOut = &p->aMatchinfo[1];
163334 xRet = fts3MIBufferFree;
163336 else if( p->aRef[2]==0 ){
163337 p->aRef[2] = 1;
163338 aOut = &p->aMatchinfo[p->nElem+2];
163339 xRet = fts3MIBufferFree;
163340 }else{
163341 aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
163342 if( aOut ){
163343 xRet = sqlite3_free;
163344 if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
163348 *paOut = aOut;
163349 return xRet;
163352 static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
163353 p->bGlobal = 1;
163354 memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
163358 ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
163360 SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
163361 if( p ){
163362 assert( p->aRef[0]==1 );
163363 p->aRef[0] = 0;
163364 if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
163365 sqlite3_free(p);
163371 ** End of MatchinfoBuffer code.
163372 *************************************************************************/
163376 ** This function is used to help iterate through a position-list. A position
163377 ** list is a list of unique integers, sorted from smallest to largest. Each
163378 ** element of the list is represented by an FTS3 varint that takes the value
163379 ** of the difference between the current element and the previous one plus
163380 ** two. For example, to store the position-list:
163382 ** 4 9 113
163384 ** the three varints:
163386 ** 6 7 106
163388 ** are encoded.
163390 ** When this function is called, *pp points to the start of an element of
163391 ** the list. *piPos contains the value of the previous entry in the list.
163392 ** After it returns, *piPos contains the value of the next element of the
163393 ** list and *pp is advanced to the following varint.
163395 static void fts3GetDeltaPosition(char **pp, int *piPos){
163396 int iVal;
163397 *pp += fts3GetVarint32(*pp, &iVal);
163398 *piPos += (iVal-2);
163402 ** Helper function for fts3ExprIterate() (see below).
163404 static int fts3ExprIterate2(
163405 Fts3Expr *pExpr, /* Expression to iterate phrases of */
163406 int *piPhrase, /* Pointer to phrase counter */
163407 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
163408 void *pCtx /* Second argument to pass to callback */
163410 int rc; /* Return code */
163411 int eType = pExpr->eType; /* Type of expression node pExpr */
163413 if( eType!=FTSQUERY_PHRASE ){
163414 assert( pExpr->pLeft && pExpr->pRight );
163415 rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
163416 if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
163417 rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
163419 }else{
163420 rc = x(pExpr, *piPhrase, pCtx);
163421 (*piPhrase)++;
163423 return rc;
163427 ** Iterate through all phrase nodes in an FTS3 query, except those that
163428 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
163429 ** For each phrase node found, the supplied callback function is invoked.
163431 ** If the callback function returns anything other than SQLITE_OK,
163432 ** the iteration is abandoned and the error code returned immediately.
163433 ** Otherwise, SQLITE_OK is returned after a callback has been made for
163434 ** all eligible phrase nodes.
163436 static int fts3ExprIterate(
163437 Fts3Expr *pExpr, /* Expression to iterate phrases of */
163438 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
163439 void *pCtx /* Second argument to pass to callback */
163441 int iPhrase = 0; /* Variable used as the phrase counter */
163442 return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
163447 ** This is an fts3ExprIterate() callback used while loading the doclists
163448 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
163449 ** fts3ExprLoadDoclists().
163451 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
163452 int rc = SQLITE_OK;
163453 Fts3Phrase *pPhrase = pExpr->pPhrase;
163454 LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
163456 UNUSED_PARAMETER(iPhrase);
163458 p->nPhrase++;
163459 p->nToken += pPhrase->nToken;
163461 return rc;
163465 ** Load the doclists for each phrase in the query associated with FTS3 cursor
163466 ** pCsr.
163468 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
163469 ** phrases in the expression (all phrases except those directly or
163470 ** indirectly descended from the right-hand-side of a NOT operator). If
163471 ** pnToken is not NULL, then it is set to the number of tokens in all
163472 ** matchable phrases of the expression.
163474 static int fts3ExprLoadDoclists(
163475 Fts3Cursor *pCsr, /* Fts3 cursor for current query */
163476 int *pnPhrase, /* OUT: Number of phrases in query */
163477 int *pnToken /* OUT: Number of tokens in query */
163479 int rc; /* Return Code */
163480 LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
163481 sCtx.pCsr = pCsr;
163482 rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
163483 if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
163484 if( pnToken ) *pnToken = sCtx.nToken;
163485 return rc;
163488 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
163489 (*(int *)ctx)++;
163490 pExpr->iPhrase = iPhrase;
163491 return SQLITE_OK;
163493 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
163494 int nPhrase = 0;
163495 (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
163496 return nPhrase;
163500 ** Advance the position list iterator specified by the first two
163501 ** arguments so that it points to the first element with a value greater
163502 ** than or equal to parameter iNext.
163504 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
163505 char *pIter = *ppIter;
163506 if( pIter ){
163507 int iIter = *piIter;
163509 while( iIter<iNext ){
163510 if( 0==(*pIter & 0xFE) ){
163511 iIter = -1;
163512 pIter = 0;
163513 break;
163515 fts3GetDeltaPosition(&pIter, &iIter);
163518 *piIter = iIter;
163519 *ppIter = pIter;
163524 ** Advance the snippet iterator to the next candidate snippet.
163526 static int fts3SnippetNextCandidate(SnippetIter *pIter){
163527 int i; /* Loop counter */
163529 if( pIter->iCurrent<0 ){
163530 /* The SnippetIter object has just been initialized. The first snippet
163531 ** candidate always starts at offset 0 (even if this candidate has a
163532 ** score of 0.0).
163534 pIter->iCurrent = 0;
163536 /* Advance the 'head' iterator of each phrase to the first offset that
163537 ** is greater than or equal to (iNext+nSnippet).
163539 for(i=0; i<pIter->nPhrase; i++){
163540 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163541 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
163543 }else{
163544 int iStart;
163545 int iEnd = 0x7FFFFFFF;
163547 for(i=0; i<pIter->nPhrase; i++){
163548 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163549 if( pPhrase->pHead && pPhrase->iHead<iEnd ){
163550 iEnd = pPhrase->iHead;
163553 if( iEnd==0x7FFFFFFF ){
163554 return 1;
163557 pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
163558 for(i=0; i<pIter->nPhrase; i++){
163559 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163560 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
163561 fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
163565 return 0;
163569 ** Retrieve information about the current candidate snippet of snippet
163570 ** iterator pIter.
163572 static void fts3SnippetDetails(
163573 SnippetIter *pIter, /* Snippet iterator */
163574 u64 mCovered, /* Bitmask of phrases already covered */
163575 int *piToken, /* OUT: First token of proposed snippet */
163576 int *piScore, /* OUT: "Score" for this snippet */
163577 u64 *pmCover, /* OUT: Bitmask of phrases covered */
163578 u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
163580 int iStart = pIter->iCurrent; /* First token of snippet */
163581 int iScore = 0; /* Score of this snippet */
163582 int i; /* Loop counter */
163583 u64 mCover = 0; /* Mask of phrases covered by this snippet */
163584 u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
163586 for(i=0; i<pIter->nPhrase; i++){
163587 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163588 if( pPhrase->pTail ){
163589 char *pCsr = pPhrase->pTail;
163590 int iCsr = pPhrase->iTail;
163592 while( iCsr<(iStart+pIter->nSnippet) ){
163593 int j;
163594 u64 mPhrase = (u64)1 << i;
163595 u64 mPos = (u64)1 << (iCsr - iStart);
163596 assert( iCsr>=iStart );
163597 if( (mCover|mCovered)&mPhrase ){
163598 iScore++;
163599 }else{
163600 iScore += 1000;
163602 mCover |= mPhrase;
163604 for(j=0; j<pPhrase->nToken; j++){
163605 mHighlight |= (mPos>>j);
163608 if( 0==(*pCsr & 0x0FE) ) break;
163609 fts3GetDeltaPosition(&pCsr, &iCsr);
163614 /* Set the output variables before returning. */
163615 *piToken = iStart;
163616 *piScore = iScore;
163617 *pmCover = mCover;
163618 *pmHighlight = mHighlight;
163622 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
163623 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
163625 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
163626 SnippetIter *p = (SnippetIter *)ctx;
163627 SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
163628 char *pCsr;
163629 int rc;
163631 pPhrase->nToken = pExpr->pPhrase->nToken;
163632 rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
163633 assert( rc==SQLITE_OK || pCsr==0 );
163634 if( pCsr ){
163635 int iFirst = 0;
163636 pPhrase->pList = pCsr;
163637 fts3GetDeltaPosition(&pCsr, &iFirst);
163638 assert( iFirst>=0 );
163639 pPhrase->pHead = pCsr;
163640 pPhrase->pTail = pCsr;
163641 pPhrase->iHead = iFirst;
163642 pPhrase->iTail = iFirst;
163643 }else{
163644 assert( rc!=SQLITE_OK || (
163645 pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
163649 return rc;
163653 ** Select the fragment of text consisting of nFragment contiguous tokens
163654 ** from column iCol that represent the "best" snippet. The best snippet
163655 ** is the snippet with the highest score, where scores are calculated
163656 ** by adding:
163658 ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
163660 ** (b) +1000 points for the first occurrence of each matchable phrase in
163661 ** the snippet for which the corresponding mCovered bit is not set.
163663 ** The selected snippet parameters are stored in structure *pFragment before
163664 ** returning. The score of the selected snippet is stored in *piScore
163665 ** before returning.
163667 static int fts3BestSnippet(
163668 int nSnippet, /* Desired snippet length */
163669 Fts3Cursor *pCsr, /* Cursor to create snippet for */
163670 int iCol, /* Index of column to create snippet from */
163671 u64 mCovered, /* Mask of phrases already covered */
163672 u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
163673 SnippetFragment *pFragment, /* OUT: Best snippet found */
163674 int *piScore /* OUT: Score of snippet pFragment */
163676 int rc; /* Return Code */
163677 int nList; /* Number of phrases in expression */
163678 SnippetIter sIter; /* Iterates through snippet candidates */
163679 int nByte; /* Number of bytes of space to allocate */
163680 int iBestScore = -1; /* Best snippet score found so far */
163681 int i; /* Loop counter */
163683 memset(&sIter, 0, sizeof(sIter));
163685 /* Iterate through the phrases in the expression to count them. The same
163686 ** callback makes sure the doclists are loaded for each phrase.
163688 rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
163689 if( rc!=SQLITE_OK ){
163690 return rc;
163693 /* Now that it is known how many phrases there are, allocate and zero
163694 ** the required space using malloc().
163696 nByte = sizeof(SnippetPhrase) * nList;
163697 sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
163698 if( !sIter.aPhrase ){
163699 return SQLITE_NOMEM;
163701 memset(sIter.aPhrase, 0, nByte);
163703 /* Initialize the contents of the SnippetIter object. Then iterate through
163704 ** the set of phrases in the expression to populate the aPhrase[] array.
163706 sIter.pCsr = pCsr;
163707 sIter.iCol = iCol;
163708 sIter.nSnippet = nSnippet;
163709 sIter.nPhrase = nList;
163710 sIter.iCurrent = -1;
163711 rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
163712 if( rc==SQLITE_OK ){
163714 /* Set the *pmSeen output variable. */
163715 for(i=0; i<nList; i++){
163716 if( sIter.aPhrase[i].pHead ){
163717 *pmSeen |= (u64)1 << i;
163721 /* Loop through all candidate snippets. Store the best snippet in
163722 ** *pFragment. Store its associated 'score' in iBestScore.
163724 pFragment->iCol = iCol;
163725 while( !fts3SnippetNextCandidate(&sIter) ){
163726 int iPos;
163727 int iScore;
163728 u64 mCover;
163729 u64 mHighlite;
163730 fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
163731 assert( iScore>=0 );
163732 if( iScore>iBestScore ){
163733 pFragment->iPos = iPos;
163734 pFragment->hlmask = mHighlite;
163735 pFragment->covered = mCover;
163736 iBestScore = iScore;
163740 *piScore = iBestScore;
163742 sqlite3_free(sIter.aPhrase);
163743 return rc;
163748 ** Append a string to the string-buffer passed as the first argument.
163750 ** If nAppend is negative, then the length of the string zAppend is
163751 ** determined using strlen().
163753 static int fts3StringAppend(
163754 StrBuffer *pStr, /* Buffer to append to */
163755 const char *zAppend, /* Pointer to data to append to buffer */
163756 int nAppend /* Size of zAppend in bytes (or -1) */
163758 if( nAppend<0 ){
163759 nAppend = (int)strlen(zAppend);
163762 /* If there is insufficient space allocated at StrBuffer.z, use realloc()
163763 ** to grow the buffer until so that it is big enough to accomadate the
163764 ** appended data.
163766 if( pStr->n+nAppend+1>=pStr->nAlloc ){
163767 int nAlloc = pStr->nAlloc+nAppend+100;
163768 char *zNew = sqlite3_realloc(pStr->z, nAlloc);
163769 if( !zNew ){
163770 return SQLITE_NOMEM;
163772 pStr->z = zNew;
163773 pStr->nAlloc = nAlloc;
163775 assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
163777 /* Append the data to the string buffer. */
163778 memcpy(&pStr->z[pStr->n], zAppend, nAppend);
163779 pStr->n += nAppend;
163780 pStr->z[pStr->n] = '\0';
163782 return SQLITE_OK;
163786 ** The fts3BestSnippet() function often selects snippets that end with a
163787 ** query term. That is, the final term of the snippet is always a term
163788 ** that requires highlighting. For example, if 'X' is a highlighted term
163789 ** and '.' is a non-highlighted term, BestSnippet() may select:
163791 ** ........X.....X
163793 ** This function "shifts" the beginning of the snippet forward in the
163794 ** document so that there are approximately the same number of
163795 ** non-highlighted terms to the right of the final highlighted term as there
163796 ** are to the left of the first highlighted term. For example, to this:
163798 ** ....X.....X....
163800 ** This is done as part of extracting the snippet text, not when selecting
163801 ** the snippet. Snippet selection is done based on doclists only, so there
163802 ** is no way for fts3BestSnippet() to know whether or not the document
163803 ** actually contains terms that follow the final highlighted term.
163805 static int fts3SnippetShift(
163806 Fts3Table *pTab, /* FTS3 table snippet comes from */
163807 int iLangid, /* Language id to use in tokenizing */
163808 int nSnippet, /* Number of tokens desired for snippet */
163809 const char *zDoc, /* Document text to extract snippet from */
163810 int nDoc, /* Size of buffer zDoc in bytes */
163811 int *piPos, /* IN/OUT: First token of snippet */
163812 u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
163814 u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
163816 if( hlmask ){
163817 int nLeft; /* Tokens to the left of first highlight */
163818 int nRight; /* Tokens to the right of last highlight */
163819 int nDesired; /* Ideal number of tokens to shift forward */
163821 for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
163822 for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
163823 nDesired = (nLeft-nRight)/2;
163825 /* Ideally, the start of the snippet should be pushed forward in the
163826 ** document nDesired tokens. This block checks if there are actually
163827 ** nDesired tokens to the right of the snippet. If so, *piPos and
163828 ** *pHlMask are updated to shift the snippet nDesired tokens to the
163829 ** right. Otherwise, the snippet is shifted by the number of tokens
163830 ** available.
163832 if( nDesired>0 ){
163833 int nShift; /* Number of tokens to shift snippet by */
163834 int iCurrent = 0; /* Token counter */
163835 int rc; /* Return Code */
163836 sqlite3_tokenizer_module *pMod;
163837 sqlite3_tokenizer_cursor *pC;
163838 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
163840 /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
163841 ** or more tokens in zDoc/nDoc.
163843 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
163844 if( rc!=SQLITE_OK ){
163845 return rc;
163847 while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
163848 const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
163849 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
163851 pMod->xClose(pC);
163852 if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
163854 nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
163855 assert( nShift<=nDesired );
163856 if( nShift>0 ){
163857 *piPos += nShift;
163858 *pHlmask = hlmask >> nShift;
163862 return SQLITE_OK;
163866 ** Extract the snippet text for fragment pFragment from cursor pCsr and
163867 ** append it to string buffer pOut.
163869 static int fts3SnippetText(
163870 Fts3Cursor *pCsr, /* FTS3 Cursor */
163871 SnippetFragment *pFragment, /* Snippet to extract */
163872 int iFragment, /* Fragment number */
163873 int isLast, /* True for final fragment in snippet */
163874 int nSnippet, /* Number of tokens in extracted snippet */
163875 const char *zOpen, /* String inserted before highlighted term */
163876 const char *zClose, /* String inserted after highlighted term */
163877 const char *zEllipsis, /* String inserted between snippets */
163878 StrBuffer *pOut /* Write output here */
163880 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
163881 int rc; /* Return code */
163882 const char *zDoc; /* Document text to extract snippet from */
163883 int nDoc; /* Size of zDoc in bytes */
163884 int iCurrent = 0; /* Current token number of document */
163885 int iEnd = 0; /* Byte offset of end of current token */
163886 int isShiftDone = 0; /* True after snippet is shifted */
163887 int iPos = pFragment->iPos; /* First token of snippet */
163888 u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
163889 int iCol = pFragment->iCol+1; /* Query column to extract text from */
163890 sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
163891 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
163893 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
163894 if( zDoc==0 ){
163895 if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
163896 return SQLITE_NOMEM;
163898 return SQLITE_OK;
163900 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
163902 /* Open a token cursor on the document. */
163903 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
163904 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
163905 if( rc!=SQLITE_OK ){
163906 return rc;
163909 while( rc==SQLITE_OK ){
163910 const char *ZDUMMY; /* Dummy argument used with tokenizer */
163911 int DUMMY1 = -1; /* Dummy argument used with tokenizer */
163912 int iBegin = 0; /* Offset in zDoc of start of token */
163913 int iFin = 0; /* Offset in zDoc of end of token */
163914 int isHighlight = 0; /* True for highlighted terms */
163916 /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
163917 ** in the FTS code the variable that the third argument to xNext points to
163918 ** is initialized to zero before the first (*but not necessarily
163919 ** subsequent*) call to xNext(). This is done for a particular application
163920 ** that needs to know whether or not the tokenizer is being used for
163921 ** snippet generation or for some other purpose.
163923 ** Extreme care is required when writing code to depend on this
163924 ** initialization. It is not a documented part of the tokenizer interface.
163925 ** If a tokenizer is used directly by any code outside of FTS, this
163926 ** convention might not be respected. */
163927 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
163928 if( rc!=SQLITE_OK ){
163929 if( rc==SQLITE_DONE ){
163930 /* Special case - the last token of the snippet is also the last token
163931 ** of the column. Append any punctuation that occurred between the end
163932 ** of the previous token and the end of the document to the output.
163933 ** Then break out of the loop. */
163934 rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
163936 break;
163938 if( iCurrent<iPos ){ continue; }
163940 if( !isShiftDone ){
163941 int n = nDoc - iBegin;
163942 rc = fts3SnippetShift(
163943 pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
163945 isShiftDone = 1;
163947 /* Now that the shift has been done, check if the initial "..." are
163948 ** required. They are required if (a) this is not the first fragment,
163949 ** or (b) this fragment does not begin at position 0 of its column.
163951 if( rc==SQLITE_OK ){
163952 if( iPos>0 || iFragment>0 ){
163953 rc = fts3StringAppend(pOut, zEllipsis, -1);
163954 }else if( iBegin ){
163955 rc = fts3StringAppend(pOut, zDoc, iBegin);
163958 if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
163961 if( iCurrent>=(iPos+nSnippet) ){
163962 if( isLast ){
163963 rc = fts3StringAppend(pOut, zEllipsis, -1);
163965 break;
163968 /* Set isHighlight to true if this term should be highlighted. */
163969 isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
163971 if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
163972 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
163973 if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
163974 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
163976 iEnd = iFin;
163979 pMod->xClose(pC);
163980 return rc;
163985 ** This function is used to count the entries in a column-list (a
163986 ** delta-encoded list of term offsets within a single column of a single
163987 ** row). When this function is called, *ppCollist should point to the
163988 ** beginning of the first varint in the column-list (the varint that
163989 ** contains the position of the first matching term in the column data).
163990 ** Before returning, *ppCollist is set to point to the first byte after
163991 ** the last varint in the column-list (either the 0x00 signifying the end
163992 ** of the position-list, or the 0x01 that precedes the column number of
163993 ** the next column in the position-list).
163995 ** The number of elements in the column-list is returned.
163997 static int fts3ColumnlistCount(char **ppCollist){
163998 char *pEnd = *ppCollist;
163999 char c = 0;
164000 int nEntry = 0;
164002 /* A column-list is terminated by either a 0x01 or 0x00. */
164003 while( 0xFE & (*pEnd | c) ){
164004 c = *pEnd++ & 0x80;
164005 if( !c ) nEntry++;
164008 *ppCollist = pEnd;
164009 return nEntry;
164013 ** This function gathers 'y' or 'b' data for a single phrase.
164015 static void fts3ExprLHits(
164016 Fts3Expr *pExpr, /* Phrase expression node */
164017 MatchInfo *p /* Matchinfo context */
164019 Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
164020 int iStart;
164021 Fts3Phrase *pPhrase = pExpr->pPhrase;
164022 char *pIter = pPhrase->doclist.pList;
164023 int iCol = 0;
164025 assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
164026 if( p->flag==FTS3_MATCHINFO_LHITS ){
164027 iStart = pExpr->iPhrase * p->nCol;
164028 }else{
164029 iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
164032 while( 1 ){
164033 int nHit = fts3ColumnlistCount(&pIter);
164034 if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
164035 if( p->flag==FTS3_MATCHINFO_LHITS ){
164036 p->aMatchinfo[iStart + iCol] = (u32)nHit;
164037 }else if( nHit ){
164038 p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
164041 assert( *pIter==0x00 || *pIter==0x01 );
164042 if( *pIter!=0x01 ) break;
164043 pIter++;
164044 pIter += fts3GetVarint32(pIter, &iCol);
164049 ** Gather the results for matchinfo directives 'y' and 'b'.
164051 static void fts3ExprLHitGather(
164052 Fts3Expr *pExpr,
164053 MatchInfo *p
164055 assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
164056 if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
164057 if( pExpr->pLeft ){
164058 fts3ExprLHitGather(pExpr->pLeft, p);
164059 fts3ExprLHitGather(pExpr->pRight, p);
164060 }else{
164061 fts3ExprLHits(pExpr, p);
164067 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
164068 ** for a single query.
164070 ** fts3ExprIterate() callback to load the 'global' elements of a
164071 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
164072 ** of the matchinfo array that are constant for all rows returned by the
164073 ** current query.
164075 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
164076 ** function populates Matchinfo.aMatchinfo[] as follows:
164078 ** for(iCol=0; iCol<nCol; iCol++){
164079 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
164080 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
164083 ** where X is the number of matches for phrase iPhrase is column iCol of all
164084 ** rows of the table. Y is the number of rows for which column iCol contains
164085 ** at least one instance of phrase iPhrase.
164087 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
164088 ** Y values are set to nDoc, where nDoc is the number of documents in the
164089 ** file system. This is done because the full-text index doclist is required
164090 ** to calculate these values properly, and the full-text index doclist is
164091 ** not available for deferred tokens.
164093 static int fts3ExprGlobalHitsCb(
164094 Fts3Expr *pExpr, /* Phrase expression node */
164095 int iPhrase, /* Phrase number (numbered from zero) */
164096 void *pCtx /* Pointer to MatchInfo structure */
164098 MatchInfo *p = (MatchInfo *)pCtx;
164099 return sqlite3Fts3EvalPhraseStats(
164100 p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
164105 ** fts3ExprIterate() callback used to collect the "local" part of the
164106 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
164107 ** array that are different for each row returned by the query.
164109 static int fts3ExprLocalHitsCb(
164110 Fts3Expr *pExpr, /* Phrase expression node */
164111 int iPhrase, /* Phrase number */
164112 void *pCtx /* Pointer to MatchInfo structure */
164114 int rc = SQLITE_OK;
164115 MatchInfo *p = (MatchInfo *)pCtx;
164116 int iStart = iPhrase * p->nCol * 3;
164117 int i;
164119 for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
164120 char *pCsr;
164121 rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
164122 if( pCsr ){
164123 p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
164124 }else{
164125 p->aMatchinfo[iStart+i*3] = 0;
164129 return rc;
164132 static int fts3MatchinfoCheck(
164133 Fts3Table *pTab,
164134 char cArg,
164135 char **pzErr
164137 if( (cArg==FTS3_MATCHINFO_NPHRASE)
164138 || (cArg==FTS3_MATCHINFO_NCOL)
164139 || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
164140 || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
164141 || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
164142 || (cArg==FTS3_MATCHINFO_LCS)
164143 || (cArg==FTS3_MATCHINFO_HITS)
164144 || (cArg==FTS3_MATCHINFO_LHITS)
164145 || (cArg==FTS3_MATCHINFO_LHITS_BM)
164147 return SQLITE_OK;
164149 sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
164150 return SQLITE_ERROR;
164153 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
164154 int nVal; /* Number of integers output by cArg */
164156 switch( cArg ){
164157 case FTS3_MATCHINFO_NDOC:
164158 case FTS3_MATCHINFO_NPHRASE:
164159 case FTS3_MATCHINFO_NCOL:
164160 nVal = 1;
164161 break;
164163 case FTS3_MATCHINFO_AVGLENGTH:
164164 case FTS3_MATCHINFO_LENGTH:
164165 case FTS3_MATCHINFO_LCS:
164166 nVal = pInfo->nCol;
164167 break;
164169 case FTS3_MATCHINFO_LHITS:
164170 nVal = pInfo->nCol * pInfo->nPhrase;
164171 break;
164173 case FTS3_MATCHINFO_LHITS_BM:
164174 nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
164175 break;
164177 default:
164178 assert( cArg==FTS3_MATCHINFO_HITS );
164179 nVal = pInfo->nCol * pInfo->nPhrase * 3;
164180 break;
164183 return nVal;
164186 static int fts3MatchinfoSelectDoctotal(
164187 Fts3Table *pTab,
164188 sqlite3_stmt **ppStmt,
164189 sqlite3_int64 *pnDoc,
164190 const char **paLen
164192 sqlite3_stmt *pStmt;
164193 const char *a;
164194 sqlite3_int64 nDoc;
164196 if( !*ppStmt ){
164197 int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
164198 if( rc!=SQLITE_OK ) return rc;
164200 pStmt = *ppStmt;
164201 assert( sqlite3_data_count(pStmt)==1 );
164203 a = sqlite3_column_blob(pStmt, 0);
164204 a += sqlite3Fts3GetVarint(a, &nDoc);
164205 if( nDoc==0 ) return FTS_CORRUPT_VTAB;
164206 *pnDoc = (u32)nDoc;
164208 if( paLen ) *paLen = a;
164209 return SQLITE_OK;
164213 ** An instance of the following structure is used to store state while
164214 ** iterating through a multi-column position-list corresponding to the
164215 ** hits for a single phrase on a single row in order to calculate the
164216 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
164218 typedef struct LcsIterator LcsIterator;
164219 struct LcsIterator {
164220 Fts3Expr *pExpr; /* Pointer to phrase expression */
164221 int iPosOffset; /* Tokens count up to end of this phrase */
164222 char *pRead; /* Cursor used to iterate through aDoclist */
164223 int iPos; /* Current position */
164227 ** If LcsIterator.iCol is set to the following value, the iterator has
164228 ** finished iterating through all offsets for all columns.
164230 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
164232 static int fts3MatchinfoLcsCb(
164233 Fts3Expr *pExpr, /* Phrase expression node */
164234 int iPhrase, /* Phrase number (numbered from zero) */
164235 void *pCtx /* Pointer to MatchInfo structure */
164237 LcsIterator *aIter = (LcsIterator *)pCtx;
164238 aIter[iPhrase].pExpr = pExpr;
164239 return SQLITE_OK;
164243 ** Advance the iterator passed as an argument to the next position. Return
164244 ** 1 if the iterator is at EOF or if it now points to the start of the
164245 ** position list for the next column.
164247 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
164248 char *pRead = pIter->pRead;
164249 sqlite3_int64 iRead;
164250 int rc = 0;
164252 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
164253 if( iRead==0 || iRead==1 ){
164254 pRead = 0;
164255 rc = 1;
164256 }else{
164257 pIter->iPos += (int)(iRead-2);
164260 pIter->pRead = pRead;
164261 return rc;
164265 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
164267 ** If the call is successful, the longest-common-substring lengths for each
164268 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
164269 ** array before returning. SQLITE_OK is returned in this case.
164271 ** Otherwise, if an error occurs, an SQLite error code is returned and the
164272 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
164273 ** undefined.
164275 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
164276 LcsIterator *aIter;
164277 int i;
164278 int iCol;
164279 int nToken = 0;
164281 /* Allocate and populate the array of LcsIterator objects. The array
164282 ** contains one element for each matchable phrase in the query.
164284 aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
164285 if( !aIter ) return SQLITE_NOMEM;
164286 memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
164287 (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
164289 for(i=0; i<pInfo->nPhrase; i++){
164290 LcsIterator *pIter = &aIter[i];
164291 nToken -= pIter->pExpr->pPhrase->nToken;
164292 pIter->iPosOffset = nToken;
164295 for(iCol=0; iCol<pInfo->nCol; iCol++){
164296 int nLcs = 0; /* LCS value for this column */
164297 int nLive = 0; /* Number of iterators in aIter not at EOF */
164299 for(i=0; i<pInfo->nPhrase; i++){
164300 int rc;
164301 LcsIterator *pIt = &aIter[i];
164302 rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
164303 if( rc!=SQLITE_OK ) return rc;
164304 if( pIt->pRead ){
164305 pIt->iPos = pIt->iPosOffset;
164306 fts3LcsIteratorAdvance(&aIter[i]);
164307 nLive++;
164311 while( nLive>0 ){
164312 LcsIterator *pAdv = 0; /* The iterator to advance by one position */
164313 int nThisLcs = 0; /* LCS for the current iterator positions */
164315 for(i=0; i<pInfo->nPhrase; i++){
164316 LcsIterator *pIter = &aIter[i];
164317 if( pIter->pRead==0 ){
164318 /* This iterator is already at EOF for this column. */
164319 nThisLcs = 0;
164320 }else{
164321 if( pAdv==0 || pIter->iPos<pAdv->iPos ){
164322 pAdv = pIter;
164324 if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
164325 nThisLcs++;
164326 }else{
164327 nThisLcs = 1;
164329 if( nThisLcs>nLcs ) nLcs = nThisLcs;
164332 if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
164335 pInfo->aMatchinfo[iCol] = nLcs;
164338 sqlite3_free(aIter);
164339 return SQLITE_OK;
164343 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
164344 ** be returned by the matchinfo() function. Argument zArg contains the
164345 ** format string passed as the second argument to matchinfo (or the
164346 ** default value "pcx" if no second argument was specified). The format
164347 ** string has already been validated and the pInfo->aMatchinfo[] array
164348 ** is guaranteed to be large enough for the output.
164350 ** If bGlobal is true, then populate all fields of the matchinfo() output.
164351 ** If it is false, then assume that those fields that do not change between
164352 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
164353 ** have already been populated.
164355 ** Return SQLITE_OK if successful, or an SQLite error code if an error
164356 ** occurs. If a value other than SQLITE_OK is returned, the state the
164357 ** pInfo->aMatchinfo[] buffer is left in is undefined.
164359 static int fts3MatchinfoValues(
164360 Fts3Cursor *pCsr, /* FTS3 cursor object */
164361 int bGlobal, /* True to grab the global stats */
164362 MatchInfo *pInfo, /* Matchinfo context object */
164363 const char *zArg /* Matchinfo format string */
164365 int rc = SQLITE_OK;
164366 int i;
164367 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164368 sqlite3_stmt *pSelect = 0;
164370 for(i=0; rc==SQLITE_OK && zArg[i]; i++){
164371 pInfo->flag = zArg[i];
164372 switch( zArg[i] ){
164373 case FTS3_MATCHINFO_NPHRASE:
164374 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
164375 break;
164377 case FTS3_MATCHINFO_NCOL:
164378 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
164379 break;
164381 case FTS3_MATCHINFO_NDOC:
164382 if( bGlobal ){
164383 sqlite3_int64 nDoc = 0;
164384 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
164385 pInfo->aMatchinfo[0] = (u32)nDoc;
164387 break;
164389 case FTS3_MATCHINFO_AVGLENGTH:
164390 if( bGlobal ){
164391 sqlite3_int64 nDoc; /* Number of rows in table */
164392 const char *a; /* Aggregate column length array */
164394 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
164395 if( rc==SQLITE_OK ){
164396 int iCol;
164397 for(iCol=0; iCol<pInfo->nCol; iCol++){
164398 u32 iVal;
164399 sqlite3_int64 nToken;
164400 a += sqlite3Fts3GetVarint(a, &nToken);
164401 iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
164402 pInfo->aMatchinfo[iCol] = iVal;
164406 break;
164408 case FTS3_MATCHINFO_LENGTH: {
164409 sqlite3_stmt *pSelectDocsize = 0;
164410 rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
164411 if( rc==SQLITE_OK ){
164412 int iCol;
164413 const char *a = sqlite3_column_blob(pSelectDocsize, 0);
164414 for(iCol=0; iCol<pInfo->nCol; iCol++){
164415 sqlite3_int64 nToken;
164416 a += sqlite3Fts3GetVarint(a, &nToken);
164417 pInfo->aMatchinfo[iCol] = (u32)nToken;
164420 sqlite3_reset(pSelectDocsize);
164421 break;
164424 case FTS3_MATCHINFO_LCS:
164425 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
164426 if( rc==SQLITE_OK ){
164427 rc = fts3MatchinfoLcs(pCsr, pInfo);
164429 break;
164431 case FTS3_MATCHINFO_LHITS_BM:
164432 case FTS3_MATCHINFO_LHITS: {
164433 int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
164434 memset(pInfo->aMatchinfo, 0, nZero);
164435 fts3ExprLHitGather(pCsr->pExpr, pInfo);
164436 break;
164439 default: {
164440 Fts3Expr *pExpr;
164441 assert( zArg[i]==FTS3_MATCHINFO_HITS );
164442 pExpr = pCsr->pExpr;
164443 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
164444 if( rc!=SQLITE_OK ) break;
164445 if( bGlobal ){
164446 if( pCsr->pDeferred ){
164447 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
164448 if( rc!=SQLITE_OK ) break;
164450 rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
164451 sqlite3Fts3EvalTestDeferred(pCsr, &rc);
164452 if( rc!=SQLITE_OK ) break;
164454 (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
164455 break;
164459 pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
164462 sqlite3_reset(pSelect);
164463 return rc;
164468 ** Populate pCsr->aMatchinfo[] with data for the current row. The
164469 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
164471 static void fts3GetMatchinfo(
164472 sqlite3_context *pCtx, /* Return results here */
164473 Fts3Cursor *pCsr, /* FTS3 Cursor object */
164474 const char *zArg /* Second argument to matchinfo() function */
164476 MatchInfo sInfo;
164477 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164478 int rc = SQLITE_OK;
164479 int bGlobal = 0; /* Collect 'global' stats as well as local */
164481 u32 *aOut = 0;
164482 void (*xDestroyOut)(void*) = 0;
164484 memset(&sInfo, 0, sizeof(MatchInfo));
164485 sInfo.pCursor = pCsr;
164486 sInfo.nCol = pTab->nColumn;
164488 /* If there is cached matchinfo() data, but the format string for the
164489 ** cache does not match the format string for this request, discard
164490 ** the cached data. */
164491 if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
164492 sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
164493 pCsr->pMIBuffer = 0;
164496 /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
164497 ** matchinfo function has been called for this query. In this case
164498 ** allocate the array used to accumulate the matchinfo data and
164499 ** initialize those elements that are constant for every row.
164501 if( pCsr->pMIBuffer==0 ){
164502 int nMatchinfo = 0; /* Number of u32 elements in match-info */
164503 int i; /* Used to iterate through zArg */
164505 /* Determine the number of phrases in the query */
164506 pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
164507 sInfo.nPhrase = pCsr->nPhrase;
164509 /* Determine the number of integers in the buffer returned by this call. */
164510 for(i=0; zArg[i]; i++){
164511 char *zErr = 0;
164512 if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
164513 sqlite3_result_error(pCtx, zErr, -1);
164514 sqlite3_free(zErr);
164515 return;
164517 nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
164520 /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
164521 pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
164522 if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
164524 pCsr->isMatchinfoNeeded = 1;
164525 bGlobal = 1;
164528 if( rc==SQLITE_OK ){
164529 xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
164530 if( xDestroyOut==0 ){
164531 rc = SQLITE_NOMEM;
164535 if( rc==SQLITE_OK ){
164536 sInfo.aMatchinfo = aOut;
164537 sInfo.nPhrase = pCsr->nPhrase;
164538 rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
164539 if( bGlobal ){
164540 fts3MIBufferSetGlobal(pCsr->pMIBuffer);
164544 if( rc!=SQLITE_OK ){
164545 sqlite3_result_error_code(pCtx, rc);
164546 if( xDestroyOut ) xDestroyOut(aOut);
164547 }else{
164548 int n = pCsr->pMIBuffer->nElem * sizeof(u32);
164549 sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
164554 ** Implementation of snippet() function.
164556 SQLITE_PRIVATE void sqlite3Fts3Snippet(
164557 sqlite3_context *pCtx, /* SQLite function call context */
164558 Fts3Cursor *pCsr, /* Cursor object */
164559 const char *zStart, /* Snippet start text - "<b>" */
164560 const char *zEnd, /* Snippet end text - "</b>" */
164561 const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
164562 int iCol, /* Extract snippet from this column */
164563 int nToken /* Approximate number of tokens in snippet */
164565 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164566 int rc = SQLITE_OK;
164567 int i;
164568 StrBuffer res = {0, 0, 0};
164570 /* The returned text includes up to four fragments of text extracted from
164571 ** the data in the current row. The first iteration of the for(...) loop
164572 ** below attempts to locate a single fragment of text nToken tokens in
164573 ** size that contains at least one instance of all phrases in the query
164574 ** expression that appear in the current row. If such a fragment of text
164575 ** cannot be found, the second iteration of the loop attempts to locate
164576 ** a pair of fragments, and so on.
164578 int nSnippet = 0; /* Number of fragments in this snippet */
164579 SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
164580 int nFToken = -1; /* Number of tokens in each fragment */
164582 if( !pCsr->pExpr ){
164583 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
164584 return;
164587 for(nSnippet=1; 1; nSnippet++){
164589 int iSnip; /* Loop counter 0..nSnippet-1 */
164590 u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
164591 u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
164593 if( nToken>=0 ){
164594 nFToken = (nToken+nSnippet-1) / nSnippet;
164595 }else{
164596 nFToken = -1 * nToken;
164599 for(iSnip=0; iSnip<nSnippet; iSnip++){
164600 int iBestScore = -1; /* Best score of columns checked so far */
164601 int iRead; /* Used to iterate through columns */
164602 SnippetFragment *pFragment = &aSnippet[iSnip];
164604 memset(pFragment, 0, sizeof(*pFragment));
164606 /* Loop through all columns of the table being considered for snippets.
164607 ** If the iCol argument to this function was negative, this means all
164608 ** columns of the FTS3 table. Otherwise, only column iCol is considered.
164610 for(iRead=0; iRead<pTab->nColumn; iRead++){
164611 SnippetFragment sF = {0, 0, 0, 0};
164612 int iS = 0;
164613 if( iCol>=0 && iRead!=iCol ) continue;
164615 /* Find the best snippet of nFToken tokens in column iRead. */
164616 rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
164617 if( rc!=SQLITE_OK ){
164618 goto snippet_out;
164620 if( iS>iBestScore ){
164621 *pFragment = sF;
164622 iBestScore = iS;
164626 mCovered |= pFragment->covered;
164629 /* If all query phrases seen by fts3BestSnippet() are present in at least
164630 ** one of the nSnippet snippet fragments, break out of the loop.
164632 assert( (mCovered&mSeen)==mCovered );
164633 if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
164636 assert( nFToken>0 );
164638 for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
164639 rc = fts3SnippetText(pCsr, &aSnippet[i],
164640 i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
164644 snippet_out:
164645 sqlite3Fts3SegmentsClose(pTab);
164646 if( rc!=SQLITE_OK ){
164647 sqlite3_result_error_code(pCtx, rc);
164648 sqlite3_free(res.z);
164649 }else{
164650 sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
164655 typedef struct TermOffset TermOffset;
164656 typedef struct TermOffsetCtx TermOffsetCtx;
164658 struct TermOffset {
164659 char *pList; /* Position-list */
164660 int iPos; /* Position just read from pList */
164661 int iOff; /* Offset of this term from read positions */
164664 struct TermOffsetCtx {
164665 Fts3Cursor *pCsr;
164666 int iCol; /* Column of table to populate aTerm for */
164667 int iTerm;
164668 sqlite3_int64 iDocid;
164669 TermOffset *aTerm;
164673 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
164675 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
164676 TermOffsetCtx *p = (TermOffsetCtx *)ctx;
164677 int nTerm; /* Number of tokens in phrase */
164678 int iTerm; /* For looping through nTerm phrase terms */
164679 char *pList; /* Pointer to position list for phrase */
164680 int iPos = 0; /* First position in position-list */
164681 int rc;
164683 UNUSED_PARAMETER(iPhrase);
164684 rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
164685 nTerm = pExpr->pPhrase->nToken;
164686 if( pList ){
164687 fts3GetDeltaPosition(&pList, &iPos);
164688 assert( iPos>=0 );
164691 for(iTerm=0; iTerm<nTerm; iTerm++){
164692 TermOffset *pT = &p->aTerm[p->iTerm++];
164693 pT->iOff = nTerm-iTerm-1;
164694 pT->pList = pList;
164695 pT->iPos = iPos;
164698 return rc;
164702 ** Implementation of offsets() function.
164704 SQLITE_PRIVATE void sqlite3Fts3Offsets(
164705 sqlite3_context *pCtx, /* SQLite function call context */
164706 Fts3Cursor *pCsr /* Cursor object */
164708 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164709 sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
164710 int rc; /* Return Code */
164711 int nToken; /* Number of tokens in query */
164712 int iCol; /* Column currently being processed */
164713 StrBuffer res = {0, 0, 0}; /* Result string */
164714 TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
164716 if( !pCsr->pExpr ){
164717 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
164718 return;
164721 memset(&sCtx, 0, sizeof(sCtx));
164722 assert( pCsr->isRequireSeek==0 );
164724 /* Count the number of terms in the query */
164725 rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
164726 if( rc!=SQLITE_OK ) goto offsets_out;
164728 /* Allocate the array of TermOffset iterators. */
164729 sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
164730 if( 0==sCtx.aTerm ){
164731 rc = SQLITE_NOMEM;
164732 goto offsets_out;
164734 sCtx.iDocid = pCsr->iPrevId;
164735 sCtx.pCsr = pCsr;
164737 /* Loop through the table columns, appending offset information to
164738 ** string-buffer res for each column.
164740 for(iCol=0; iCol<pTab->nColumn; iCol++){
164741 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
164742 const char *ZDUMMY; /* Dummy argument used with xNext() */
164743 int NDUMMY = 0; /* Dummy argument used with xNext() */
164744 int iStart = 0;
164745 int iEnd = 0;
164746 int iCurrent = 0;
164747 const char *zDoc;
164748 int nDoc;
164750 /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
164751 ** no way that this operation can fail, so the return code from
164752 ** fts3ExprIterate() can be discarded.
164754 sCtx.iCol = iCol;
164755 sCtx.iTerm = 0;
164756 (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
164758 /* Retreive the text stored in column iCol. If an SQL NULL is stored
164759 ** in column iCol, jump immediately to the next iteration of the loop.
164760 ** If an OOM occurs while retrieving the data (this can happen if SQLite
164761 ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
164762 ** to the caller.
164764 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
164765 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
164766 if( zDoc==0 ){
164767 if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
164768 continue;
164770 rc = SQLITE_NOMEM;
164771 goto offsets_out;
164774 /* Initialize a tokenizer iterator to iterate through column iCol. */
164775 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
164776 zDoc, nDoc, &pC
164778 if( rc!=SQLITE_OK ) goto offsets_out;
164780 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
164781 while( rc==SQLITE_OK ){
164782 int i; /* Used to loop through terms */
164783 int iMinPos = 0x7FFFFFFF; /* Position of next token */
164784 TermOffset *pTerm = 0; /* TermOffset associated with next token */
164786 for(i=0; i<nToken; i++){
164787 TermOffset *pT = &sCtx.aTerm[i];
164788 if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
164789 iMinPos = pT->iPos-pT->iOff;
164790 pTerm = pT;
164794 if( !pTerm ){
164795 /* All offsets for this column have been gathered. */
164796 rc = SQLITE_DONE;
164797 }else{
164798 assert( iCurrent<=iMinPos );
164799 if( 0==(0xFE&*pTerm->pList) ){
164800 pTerm->pList = 0;
164801 }else{
164802 fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
164804 while( rc==SQLITE_OK && iCurrent<iMinPos ){
164805 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
164807 if( rc==SQLITE_OK ){
164808 char aBuffer[64];
164809 sqlite3_snprintf(sizeof(aBuffer), aBuffer,
164810 "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
164812 rc = fts3StringAppend(&res, aBuffer, -1);
164813 }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
164814 rc = FTS_CORRUPT_VTAB;
164818 if( rc==SQLITE_DONE ){
164819 rc = SQLITE_OK;
164822 pMod->xClose(pC);
164823 if( rc!=SQLITE_OK ) goto offsets_out;
164826 offsets_out:
164827 sqlite3_free(sCtx.aTerm);
164828 assert( rc!=SQLITE_DONE );
164829 sqlite3Fts3SegmentsClose(pTab);
164830 if( rc!=SQLITE_OK ){
164831 sqlite3_result_error_code(pCtx, rc);
164832 sqlite3_free(res.z);
164833 }else{
164834 sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
164836 return;
164840 ** Implementation of matchinfo() function.
164842 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
164843 sqlite3_context *pContext, /* Function call context */
164844 Fts3Cursor *pCsr, /* FTS3 table cursor */
164845 const char *zArg /* Second arg to matchinfo() function */
164847 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164848 const char *zFormat;
164850 if( zArg ){
164851 zFormat = zArg;
164852 }else{
164853 zFormat = FTS3_MATCHINFO_DEFAULT;
164856 if( !pCsr->pExpr ){
164857 sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
164858 return;
164859 }else{
164860 /* Retrieve matchinfo() data. */
164861 fts3GetMatchinfo(pContext, pCsr, zFormat);
164862 sqlite3Fts3SegmentsClose(pTab);
164866 #endif
164868 /************** End of fts3_snippet.c ****************************************/
164869 /************** Begin file fts3_unicode.c ************************************/
164871 ** 2012 May 24
164873 ** The author disclaims copyright to this source code. In place of
164874 ** a legal notice, here is a blessing:
164876 ** May you do good and not evil.
164877 ** May you find forgiveness for yourself and forgive others.
164878 ** May you share freely, never taking more than you give.
164880 ******************************************************************************
164882 ** Implementation of the "unicode" full-text-search tokenizer.
164885 #ifndef SQLITE_DISABLE_FTS3_UNICODE
164887 /* #include "fts3Int.h" */
164888 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
164890 /* #include <assert.h> */
164891 /* #include <stdlib.h> */
164892 /* #include <stdio.h> */
164893 /* #include <string.h> */
164895 /* #include "fts3_tokenizer.h" */
164898 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
164899 ** from the sqlite3 source file utf.c. If this file is compiled as part
164900 ** of the amalgamation, they are not required.
164902 #ifndef SQLITE_AMALGAMATION
164904 static const unsigned char sqlite3Utf8Trans1[] = {
164905 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164906 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
164907 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
164908 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
164909 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164910 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
164911 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164912 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
164915 #define READ_UTF8(zIn, zTerm, c) \
164916 c = *(zIn++); \
164917 if( c>=0xc0 ){ \
164918 c = sqlite3Utf8Trans1[c-0xc0]; \
164919 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
164920 c = (c<<6) + (0x3f & *(zIn++)); \
164922 if( c<0x80 \
164923 || (c&0xFFFFF800)==0xD800 \
164924 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
164927 #define WRITE_UTF8(zOut, c) { \
164928 if( c<0x00080 ){ \
164929 *zOut++ = (u8)(c&0xFF); \
164931 else if( c<0x00800 ){ \
164932 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
164933 *zOut++ = 0x80 + (u8)(c & 0x3F); \
164935 else if( c<0x10000 ){ \
164936 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
164937 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
164938 *zOut++ = 0x80 + (u8)(c & 0x3F); \
164939 }else{ \
164940 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
164941 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
164942 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
164943 *zOut++ = 0x80 + (u8)(c & 0x3F); \
164947 #endif /* ifndef SQLITE_AMALGAMATION */
164949 typedef struct unicode_tokenizer unicode_tokenizer;
164950 typedef struct unicode_cursor unicode_cursor;
164952 struct unicode_tokenizer {
164953 sqlite3_tokenizer base;
164954 int bRemoveDiacritic;
164955 int nException;
164956 int *aiException;
164959 struct unicode_cursor {
164960 sqlite3_tokenizer_cursor base;
164961 const unsigned char *aInput; /* Input text being tokenized */
164962 int nInput; /* Size of aInput[] in bytes */
164963 int iOff; /* Current offset within aInput[] */
164964 int iToken; /* Index of next token to be returned */
164965 char *zToken; /* storage for current token */
164966 int nAlloc; /* space allocated at zToken */
164971 ** Destroy a tokenizer allocated by unicodeCreate().
164973 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
164974 if( pTokenizer ){
164975 unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
164976 sqlite3_free(p->aiException);
164977 sqlite3_free(p);
164979 return SQLITE_OK;
164983 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
164984 ** statement has specified that the tokenizer for this table shall consider
164985 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
164986 ** token characters (if bAlnum==1).
164988 ** For each codepoint in the zIn/nIn string, this function checks if the
164989 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
164990 ** If so, no action is taken. Otherwise, the codepoint is added to the
164991 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
164992 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
164993 ** codepoints in the aiException[] array.
164995 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
164996 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
164997 ** It is not possible to change the behavior of the tokenizer with respect
164998 ** to these codepoints.
165000 static int unicodeAddExceptions(
165001 unicode_tokenizer *p, /* Tokenizer to add exceptions to */
165002 int bAlnum, /* Replace Isalnum() return value with this */
165003 const char *zIn, /* Array of characters to make exceptions */
165004 int nIn /* Length of z in bytes */
165006 const unsigned char *z = (const unsigned char *)zIn;
165007 const unsigned char *zTerm = &z[nIn];
165008 unsigned int iCode;
165009 int nEntry = 0;
165011 assert( bAlnum==0 || bAlnum==1 );
165013 while( z<zTerm ){
165014 READ_UTF8(z, zTerm, iCode);
165015 assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
165016 if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
165017 && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
165019 nEntry++;
165023 if( nEntry ){
165024 int *aNew; /* New aiException[] array */
165025 int nNew; /* Number of valid entries in array aNew[] */
165027 aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
165028 if( aNew==0 ) return SQLITE_NOMEM;
165029 nNew = p->nException;
165031 z = (const unsigned char *)zIn;
165032 while( z<zTerm ){
165033 READ_UTF8(z, zTerm, iCode);
165034 if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
165035 && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
165037 int i, j;
165038 for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
165039 for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
165040 aNew[i] = (int)iCode;
165041 nNew++;
165044 p->aiException = aNew;
165045 p->nException = nNew;
165048 return SQLITE_OK;
165052 ** Return true if the p->aiException[] array contains the value iCode.
165054 static int unicodeIsException(unicode_tokenizer *p, int iCode){
165055 if( p->nException>0 ){
165056 int *a = p->aiException;
165057 int iLo = 0;
165058 int iHi = p->nException-1;
165060 while( iHi>=iLo ){
165061 int iTest = (iHi + iLo) / 2;
165062 if( iCode==a[iTest] ){
165063 return 1;
165064 }else if( iCode>a[iTest] ){
165065 iLo = iTest+1;
165066 }else{
165067 iHi = iTest-1;
165072 return 0;
165076 ** Return true if, for the purposes of tokenization, codepoint iCode is
165077 ** considered a token character (not a separator).
165079 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
165080 assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
165081 return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
165085 ** Create a new tokenizer instance.
165087 static int unicodeCreate(
165088 int nArg, /* Size of array argv[] */
165089 const char * const *azArg, /* Tokenizer creation arguments */
165090 sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
165092 unicode_tokenizer *pNew; /* New tokenizer object */
165093 int i;
165094 int rc = SQLITE_OK;
165096 pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
165097 if( pNew==NULL ) return SQLITE_NOMEM;
165098 memset(pNew, 0, sizeof(unicode_tokenizer));
165099 pNew->bRemoveDiacritic = 1;
165101 for(i=0; rc==SQLITE_OK && i<nArg; i++){
165102 const char *z = azArg[i];
165103 int n = (int)strlen(z);
165105 if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
165106 pNew->bRemoveDiacritic = 1;
165108 else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
165109 pNew->bRemoveDiacritic = 0;
165111 else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
165112 rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
165114 else if( n>=11 && memcmp("separators=", z, 11)==0 ){
165115 rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
165117 else{
165118 /* Unrecognized argument */
165119 rc = SQLITE_ERROR;
165123 if( rc!=SQLITE_OK ){
165124 unicodeDestroy((sqlite3_tokenizer *)pNew);
165125 pNew = 0;
165127 *pp = (sqlite3_tokenizer *)pNew;
165128 return rc;
165132 ** Prepare to begin tokenizing a particular string. The input
165133 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
165134 ** used to incrementally tokenize this string is returned in
165135 ** *ppCursor.
165137 static int unicodeOpen(
165138 sqlite3_tokenizer *p, /* The tokenizer */
165139 const char *aInput, /* Input string */
165140 int nInput, /* Size of string aInput in bytes */
165141 sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
165143 unicode_cursor *pCsr;
165145 pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
165146 if( pCsr==0 ){
165147 return SQLITE_NOMEM;
165149 memset(pCsr, 0, sizeof(unicode_cursor));
165151 pCsr->aInput = (const unsigned char *)aInput;
165152 if( aInput==0 ){
165153 pCsr->nInput = 0;
165154 }else if( nInput<0 ){
165155 pCsr->nInput = (int)strlen(aInput);
165156 }else{
165157 pCsr->nInput = nInput;
165160 *pp = &pCsr->base;
165161 UNUSED_PARAMETER(p);
165162 return SQLITE_OK;
165166 ** Close a tokenization cursor previously opened by a call to
165167 ** simpleOpen() above.
165169 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
165170 unicode_cursor *pCsr = (unicode_cursor *) pCursor;
165171 sqlite3_free(pCsr->zToken);
165172 sqlite3_free(pCsr);
165173 return SQLITE_OK;
165177 ** Extract the next token from a tokenization cursor. The cursor must
165178 ** have been opened by a prior call to simpleOpen().
165180 static int unicodeNext(
165181 sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
165182 const char **paToken, /* OUT: Token text */
165183 int *pnToken, /* OUT: Number of bytes at *paToken */
165184 int *piStart, /* OUT: Starting offset of token */
165185 int *piEnd, /* OUT: Ending offset of token */
165186 int *piPos /* OUT: Position integer of token */
165188 unicode_cursor *pCsr = (unicode_cursor *)pC;
165189 unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
165190 unsigned int iCode = 0;
165191 char *zOut;
165192 const unsigned char *z = &pCsr->aInput[pCsr->iOff];
165193 const unsigned char *zStart = z;
165194 const unsigned char *zEnd;
165195 const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
165197 /* Scan past any delimiter characters before the start of the next token.
165198 ** Return SQLITE_DONE early if this takes us all the way to the end of
165199 ** the input. */
165200 while( z<zTerm ){
165201 READ_UTF8(z, zTerm, iCode);
165202 if( unicodeIsAlnum(p, (int)iCode) ) break;
165203 zStart = z;
165205 if( zStart>=zTerm ) return SQLITE_DONE;
165207 zOut = pCsr->zToken;
165209 int iOut;
165211 /* Grow the output buffer if required. */
165212 if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
165213 char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
165214 if( !zNew ) return SQLITE_NOMEM;
165215 zOut = &zNew[zOut - pCsr->zToken];
165216 pCsr->zToken = zNew;
165217 pCsr->nAlloc += 64;
165220 /* Write the folded case of the last character read to the output */
165221 zEnd = z;
165222 iOut = sqlite3FtsUnicodeFold((int)iCode, p->bRemoveDiacritic);
165223 if( iOut ){
165224 WRITE_UTF8(zOut, iOut);
165227 /* If the cursor is not at EOF, read the next character */
165228 if( z>=zTerm ) break;
165229 READ_UTF8(z, zTerm, iCode);
165230 }while( unicodeIsAlnum(p, (int)iCode)
165231 || sqlite3FtsUnicodeIsdiacritic((int)iCode)
165234 /* Set the output variables and return. */
165235 pCsr->iOff = (int)(z - pCsr->aInput);
165236 *paToken = pCsr->zToken;
165237 *pnToken = (int)(zOut - pCsr->zToken);
165238 *piStart = (int)(zStart - pCsr->aInput);
165239 *piEnd = (int)(zEnd - pCsr->aInput);
165240 *piPos = pCsr->iToken++;
165241 return SQLITE_OK;
165245 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
165246 ** structure for the unicode tokenizer.
165248 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
165249 static const sqlite3_tokenizer_module module = {
165251 unicodeCreate,
165252 unicodeDestroy,
165253 unicodeOpen,
165254 unicodeClose,
165255 unicodeNext,
165258 *ppModule = &module;
165261 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
165262 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
165264 /************** End of fts3_unicode.c ****************************************/
165265 /************** Begin file fts3_unicode2.c ***********************************/
165267 ** 2012 May 25
165269 ** The author disclaims copyright to this source code. In place of
165270 ** a legal notice, here is a blessing:
165272 ** May you do good and not evil.
165273 ** May you find forgiveness for yourself and forgive others.
165274 ** May you share freely, never taking more than you give.
165276 ******************************************************************************
165280 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
165283 #ifndef SQLITE_DISABLE_FTS3_UNICODE
165284 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
165286 /* #include <assert.h> */
165289 ** Return true if the argument corresponds to a unicode codepoint
165290 ** classified as either a letter or a number. Otherwise false.
165292 ** The results are undefined if the value passed to this function
165293 ** is less than zero.
165295 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
165296 /* Each unsigned integer in the following array corresponds to a contiguous
165297 ** range of unicode codepoints that are not either letters or numbers (i.e.
165298 ** codepoints for which this function should return 0).
165300 ** The most significant 22 bits in each 32-bit value contain the first
165301 ** codepoint in the range. The least significant 10 bits are used to store
165302 ** the size of the range (always at least 1). In other words, the value
165303 ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
165304 ** C. It is not possible to represent a range larger than 1023 codepoints
165305 ** using this format.
165307 static const unsigned int aEntry[] = {
165308 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
165309 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
165310 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
165311 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
165312 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
165313 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
165314 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
165315 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
165316 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
165317 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
165318 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
165319 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
165320 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
165321 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
165322 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
165323 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
165324 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
165325 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
165326 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
165327 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
165328 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
165329 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
165330 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
165331 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
165332 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
165333 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
165334 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
165335 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
165336 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
165337 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
165338 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
165339 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
165340 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
165341 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
165342 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
165343 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
165344 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
165345 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
165346 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
165347 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
165348 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
165349 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
165350 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
165351 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
165352 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
165353 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
165354 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
165355 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
165356 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
165357 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
165358 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
165359 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
165360 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
165361 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
165362 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
165363 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
165364 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
165365 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
165366 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
165367 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
165368 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
165369 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
165370 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
165371 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
165372 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
165373 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
165374 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
165375 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
165376 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
165377 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
165378 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
165379 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
165380 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
165381 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
165382 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
165383 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
165384 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
165385 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
165386 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
165387 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
165388 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
165389 0x380400F0,
165391 static const unsigned int aAscii[4] = {
165392 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
165395 if( (unsigned int)c<128 ){
165396 return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
165397 }else if( (unsigned int)c<(1<<22) ){
165398 unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
165399 int iRes = 0;
165400 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
165401 int iLo = 0;
165402 while( iHi>=iLo ){
165403 int iTest = (iHi + iLo) / 2;
165404 if( key >= aEntry[iTest] ){
165405 iRes = iTest;
165406 iLo = iTest+1;
165407 }else{
165408 iHi = iTest-1;
165411 assert( aEntry[0]<key );
165412 assert( key>=aEntry[iRes] );
165413 return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
165415 return 1;
165420 ** If the argument is a codepoint corresponding to a lowercase letter
165421 ** in the ASCII range with a diacritic added, return the codepoint
165422 ** of the ASCII letter only. For example, if passed 235 - "LATIN
165423 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
165424 ** E"). The resuls of passing a codepoint that corresponds to an
165425 ** uppercase letter are undefined.
165427 static int remove_diacritic(int c){
165428 unsigned short aDia[] = {
165429 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
165430 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
165431 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
165432 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
165433 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
165434 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
165435 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
165436 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
165437 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
165438 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
165439 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
165440 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
165441 62924, 63050, 63082, 63274, 63390,
165443 char aChar[] = {
165444 '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
165445 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
165446 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
165447 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
165448 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
165449 '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
165450 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
165451 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
165452 'e', 'i', 'o', 'u', 'y',
165455 unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
165456 int iRes = 0;
165457 int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
165458 int iLo = 0;
165459 while( iHi>=iLo ){
165460 int iTest = (iHi + iLo) / 2;
165461 if( key >= aDia[iTest] ){
165462 iRes = iTest;
165463 iLo = iTest+1;
165464 }else{
165465 iHi = iTest-1;
165468 assert( key>=aDia[iRes] );
165469 return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
165474 ** Return true if the argument interpreted as a unicode codepoint
165475 ** is a diacritical modifier character.
165477 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
165478 unsigned int mask0 = 0x08029FDF;
165479 unsigned int mask1 = 0x000361F8;
165480 if( c<768 || c>817 ) return 0;
165481 return (c < 768+32) ?
165482 (mask0 & (1 << (c-768))) :
165483 (mask1 & (1 << (c-768-32)));
165488 ** Interpret the argument as a unicode codepoint. If the codepoint
165489 ** is an upper case character that has a lower case equivalent,
165490 ** return the codepoint corresponding to the lower case version.
165491 ** Otherwise, return a copy of the argument.
165493 ** The results are undefined if the value passed to this function
165494 ** is less than zero.
165496 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
165497 /* Each entry in the following array defines a rule for folding a range
165498 ** of codepoints to lower case. The rule applies to a range of nRange
165499 ** codepoints starting at codepoint iCode.
165501 ** If the least significant bit in flags is clear, then the rule applies
165502 ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
165503 ** need to be folded). Or, if it is set, then the rule only applies to
165504 ** every second codepoint in the range, starting with codepoint C.
165506 ** The 7 most significant bits in flags are an index into the aiOff[]
165507 ** array. If a specific codepoint C does require folding, then its lower
165508 ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
165510 ** The contents of this array are generated by parsing the CaseFolding.txt
165511 ** file distributed as part of the "Unicode Character Database". See
165512 ** http://www.unicode.org for details.
165514 static const struct TableEntry {
165515 unsigned short iCode;
165516 unsigned char flags;
165517 unsigned char nRange;
165518 } aEntry[] = {
165519 {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
165520 {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
165521 {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
165522 {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
165523 {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
165524 {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
165525 {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
165526 {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
165527 {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
165528 {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
165529 {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
165530 {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
165531 {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
165532 {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
165533 {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
165534 {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
165535 {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
165536 {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
165537 {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
165538 {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
165539 {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
165540 {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
165541 {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
165542 {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
165543 {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
165544 {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
165545 {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
165546 {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
165547 {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
165548 {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
165549 {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
165550 {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
165551 {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
165552 {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
165553 {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
165554 {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
165555 {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
165556 {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
165557 {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
165558 {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
165559 {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
165560 {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
165561 {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
165562 {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
165563 {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
165564 {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
165565 {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
165566 {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
165567 {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
165568 {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
165569 {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
165570 {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
165571 {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
165572 {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
165573 {65313, 14, 26},
165575 static const unsigned short aiOff[] = {
165576 1, 2, 8, 15, 16, 26, 28, 32,
165577 37, 38, 40, 48, 63, 64, 69, 71,
165578 79, 80, 116, 202, 203, 205, 206, 207,
165579 209, 210, 211, 213, 214, 217, 218, 219,
165580 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
165581 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
165582 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
165583 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
165584 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
165585 65514, 65521, 65527, 65528, 65529,
165588 int ret = c;
165590 assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
165592 if( c<128 ){
165593 if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
165594 }else if( c<65536 ){
165595 const struct TableEntry *p;
165596 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
165597 int iLo = 0;
165598 int iRes = -1;
165600 assert( c>aEntry[0].iCode );
165601 while( iHi>=iLo ){
165602 int iTest = (iHi + iLo) / 2;
165603 int cmp = (c - aEntry[iTest].iCode);
165604 if( cmp>=0 ){
165605 iRes = iTest;
165606 iLo = iTest+1;
165607 }else{
165608 iHi = iTest-1;
165612 assert( iRes>=0 && c>=aEntry[iRes].iCode );
165613 p = &aEntry[iRes];
165614 if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
165615 ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
165616 assert( ret>0 );
165619 if( bRemoveDiacritic ) ret = remove_diacritic(ret);
165622 else if( c>=66560 && c<66600 ){
165623 ret = c + 40;
165626 return ret;
165628 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
165629 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
165631 /************** End of fts3_unicode2.c ***************************************/
165632 /************** Begin file rtree.c *******************************************/
165634 ** 2001 September 15
165636 ** The author disclaims copyright to this source code. In place of
165637 ** a legal notice, here is a blessing:
165639 ** May you do good and not evil.
165640 ** May you find forgiveness for yourself and forgive others.
165641 ** May you share freely, never taking more than you give.
165643 *************************************************************************
165644 ** This file contains code for implementations of the r-tree and r*-tree
165645 ** algorithms packaged as an SQLite virtual table module.
165649 ** Database Format of R-Tree Tables
165650 ** --------------------------------
165652 ** The data structure for a single virtual r-tree table is stored in three
165653 ** native SQLite tables declared as follows. In each case, the '%' character
165654 ** in the table name is replaced with the user-supplied name of the r-tree
165655 ** table.
165657 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
165658 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
165659 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
165661 ** The data for each node of the r-tree structure is stored in the %_node
165662 ** table. For each node that is not the root node of the r-tree, there is
165663 ** an entry in the %_parent table associating the node with its parent.
165664 ** And for each row of data in the table, there is an entry in the %_rowid
165665 ** table that maps from the entries rowid to the id of the node that it
165666 ** is stored on.
165668 ** The root node of an r-tree always exists, even if the r-tree table is
165669 ** empty. The nodeno of the root node is always 1. All other nodes in the
165670 ** table must be the same size as the root node. The content of each node
165671 ** is formatted as follows:
165673 ** 1. If the node is the root node (node 1), then the first 2 bytes
165674 ** of the node contain the tree depth as a big-endian integer.
165675 ** For non-root nodes, the first 2 bytes are left unused.
165677 ** 2. The next 2 bytes contain the number of entries currently
165678 ** stored in the node.
165680 ** 3. The remainder of the node contains the node entries. Each entry
165681 ** consists of a single 8-byte integer followed by an even number
165682 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
165683 ** of a record. For internal nodes it is the node number of a
165684 ** child page.
165687 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
165689 #ifndef SQLITE_CORE
165690 /* #include "sqlite3ext.h" */
165691 SQLITE_EXTENSION_INIT1
165692 #else
165693 /* #include "sqlite3.h" */
165694 #endif
165696 /* #include <string.h> */
165697 /* #include <assert.h> */
165698 /* #include <stdio.h> */
165700 #ifndef SQLITE_AMALGAMATION
165701 #include "sqlite3rtree.h"
165702 typedef sqlite3_int64 i64;
165703 typedef sqlite3_uint64 u64;
165704 typedef unsigned char u8;
165705 typedef unsigned short u16;
165706 typedef unsigned int u32;
165707 #endif
165709 /* The following macro is used to suppress compiler warnings.
165711 #ifndef UNUSED_PARAMETER
165712 # define UNUSED_PARAMETER(x) (void)(x)
165713 #endif
165715 typedef struct Rtree Rtree;
165716 typedef struct RtreeCursor RtreeCursor;
165717 typedef struct RtreeNode RtreeNode;
165718 typedef struct RtreeCell RtreeCell;
165719 typedef struct RtreeConstraint RtreeConstraint;
165720 typedef struct RtreeMatchArg RtreeMatchArg;
165721 typedef struct RtreeGeomCallback RtreeGeomCallback;
165722 typedef union RtreeCoord RtreeCoord;
165723 typedef struct RtreeSearchPoint RtreeSearchPoint;
165725 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
165726 #define RTREE_MAX_DIMENSIONS 5
165728 /* Size of hash table Rtree.aHash. This hash table is not expected to
165729 ** ever contain very many entries, so a fixed number of buckets is
165730 ** used.
165732 #define HASHSIZE 97
165734 /* The xBestIndex method of this virtual table requires an estimate of
165735 ** the number of rows in the virtual table to calculate the costs of
165736 ** various strategies. If possible, this estimate is loaded from the
165737 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
165738 ** Otherwise, if no sqlite_stat1 entry is available, use
165739 ** RTREE_DEFAULT_ROWEST.
165741 #define RTREE_DEFAULT_ROWEST 1048576
165742 #define RTREE_MIN_ROWEST 100
165745 ** An rtree virtual-table object.
165747 struct Rtree {
165748 sqlite3_vtab base; /* Base class. Must be first */
165749 sqlite3 *db; /* Host database connection */
165750 int iNodeSize; /* Size in bytes of each node in the node table */
165751 u8 nDim; /* Number of dimensions */
165752 u8 nDim2; /* Twice the number of dimensions */
165753 u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
165754 u8 nBytesPerCell; /* Bytes consumed per cell */
165755 u8 inWrTrans; /* True if inside write transaction */
165756 int iDepth; /* Current depth of the r-tree structure */
165757 char *zDb; /* Name of database containing r-tree table */
165758 char *zName; /* Name of r-tree table */
165759 u32 nBusy; /* Current number of users of this structure */
165760 i64 nRowEst; /* Estimated number of rows in this table */
165761 u32 nCursor; /* Number of open cursors */
165763 /* List of nodes removed during a CondenseTree operation. List is
165764 ** linked together via the pointer normally used for hash chains -
165765 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
165766 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
165768 RtreeNode *pDeleted;
165769 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
165771 /* Blob I/O on xxx_node */
165772 sqlite3_blob *pNodeBlob;
165774 /* Statements to read/write/delete a record from xxx_node */
165775 sqlite3_stmt *pWriteNode;
165776 sqlite3_stmt *pDeleteNode;
165778 /* Statements to read/write/delete a record from xxx_rowid */
165779 sqlite3_stmt *pReadRowid;
165780 sqlite3_stmt *pWriteRowid;
165781 sqlite3_stmt *pDeleteRowid;
165783 /* Statements to read/write/delete a record from xxx_parent */
165784 sqlite3_stmt *pReadParent;
165785 sqlite3_stmt *pWriteParent;
165786 sqlite3_stmt *pDeleteParent;
165788 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
165791 /* Possible values for Rtree.eCoordType: */
165792 #define RTREE_COORD_REAL32 0
165793 #define RTREE_COORD_INT32 1
165796 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
165797 ** only deal with integer coordinates. No floating point operations
165798 ** will be done.
165800 #ifdef SQLITE_RTREE_INT_ONLY
165801 typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
165802 typedef int RtreeValue; /* Low accuracy coordinate */
165803 # define RTREE_ZERO 0
165804 #else
165805 typedef double RtreeDValue; /* High accuracy coordinate */
165806 typedef float RtreeValue; /* Low accuracy coordinate */
165807 # define RTREE_ZERO 0.0
165808 #endif
165811 ** When doing a search of an r-tree, instances of the following structure
165812 ** record intermediate results from the tree walk.
165814 ** The id is always a node-id. For iLevel>=1 the id is the node-id of
165815 ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
165816 ** the id is of the parent node and the cell that RtreeSearchPoint
165817 ** represents is the iCell-th entry in the parent node.
165819 struct RtreeSearchPoint {
165820 RtreeDValue rScore; /* The score for this node. Smallest goes first. */
165821 sqlite3_int64 id; /* Node ID */
165822 u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
165823 u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
165824 u8 iCell; /* Cell index within the node */
165828 ** The minimum number of cells allowed for a node is a third of the
165829 ** maximum. In Gutman's notation:
165831 ** m = M/3
165833 ** If an R*-tree "Reinsert" operation is required, the same number of
165834 ** cells are removed from the overfull node and reinserted into the tree.
165836 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
165837 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
165838 #define RTREE_MAXCELLS 51
165841 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
165842 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
165843 ** Therefore all non-root nodes must contain at least 3 entries. Since
165844 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
165845 ** 40 or less.
165847 #define RTREE_MAX_DEPTH 40
165851 ** Number of entries in the cursor RtreeNode cache. The first entry is
165852 ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
165853 ** entries cache the RtreeNode for the first elements of the priority queue.
165855 #define RTREE_CACHE_SZ 5
165858 ** An rtree cursor object.
165860 struct RtreeCursor {
165861 sqlite3_vtab_cursor base; /* Base class. Must be first */
165862 u8 atEOF; /* True if at end of search */
165863 u8 bPoint; /* True if sPoint is valid */
165864 int iStrategy; /* Copy of idxNum search parameter */
165865 int nConstraint; /* Number of entries in aConstraint */
165866 RtreeConstraint *aConstraint; /* Search constraints. */
165867 int nPointAlloc; /* Number of slots allocated for aPoint[] */
165868 int nPoint; /* Number of slots used in aPoint[] */
165869 int mxLevel; /* iLevel value for root of the tree */
165870 RtreeSearchPoint *aPoint; /* Priority queue for search points */
165871 RtreeSearchPoint sPoint; /* Cached next search point */
165872 RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
165873 u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
165876 /* Return the Rtree of a RtreeCursor */
165877 #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
165880 ** A coordinate can be either a floating point number or a integer. All
165881 ** coordinates within a single R-Tree are always of the same time.
165883 union RtreeCoord {
165884 RtreeValue f; /* Floating point value */
165885 int i; /* Integer value */
165886 u32 u; /* Unsigned for byte-order conversions */
165890 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
165891 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
165892 ** variable pRtree points to the Rtree structure associated with the
165893 ** RtreeCoord.
165895 #ifdef SQLITE_RTREE_INT_ONLY
165896 # define DCOORD(coord) ((RtreeDValue)coord.i)
165897 #else
165898 # define DCOORD(coord) ( \
165899 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
165900 ((double)coord.f) : \
165901 ((double)coord.i) \
165903 #endif
165906 ** A search constraint.
165908 struct RtreeConstraint {
165909 int iCoord; /* Index of constrained coordinate */
165910 int op; /* Constraining operation */
165911 union {
165912 RtreeDValue rValue; /* Constraint value. */
165913 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
165914 int (*xQueryFunc)(sqlite3_rtree_query_info*);
165916 sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
165919 /* Possible values for RtreeConstraint.op */
165920 #define RTREE_EQ 0x41 /* A */
165921 #define RTREE_LE 0x42 /* B */
165922 #define RTREE_LT 0x43 /* C */
165923 #define RTREE_GE 0x44 /* D */
165924 #define RTREE_GT 0x45 /* E */
165925 #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
165926 #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
165930 ** An rtree structure node.
165932 struct RtreeNode {
165933 RtreeNode *pParent; /* Parent node */
165934 i64 iNode; /* The node number */
165935 int nRef; /* Number of references to this node */
165936 int isDirty; /* True if the node needs to be written to disk */
165937 u8 *zData; /* Content of the node, as should be on disk */
165938 RtreeNode *pNext; /* Next node in this hash collision chain */
165941 /* Return the number of cells in a node */
165942 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
165945 ** A single cell from a node, deserialized
165947 struct RtreeCell {
165948 i64 iRowid; /* Node or entry ID */
165949 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
165954 ** This object becomes the sqlite3_user_data() for the SQL functions
165955 ** that are created by sqlite3_rtree_geometry_callback() and
165956 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
165957 ** operators in order to constrain a search.
165959 ** xGeom and xQueryFunc are the callback functions. Exactly one of
165960 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
165961 ** SQL function was created using sqlite3_rtree_geometry_callback() or
165962 ** sqlite3_rtree_query_callback().
165964 ** This object is deleted automatically by the destructor mechanism in
165965 ** sqlite3_create_function_v2().
165967 struct RtreeGeomCallback {
165968 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
165969 int (*xQueryFunc)(sqlite3_rtree_query_info*);
165970 void (*xDestructor)(void*);
165971 void *pContext;
165975 ** An instance of this structure (in the form of a BLOB) is returned by
165976 ** the SQL functions that sqlite3_rtree_geometry_callback() and
165977 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
165978 ** operand to the MATCH operator of an R-Tree.
165980 struct RtreeMatchArg {
165981 u32 iSize; /* Size of this object */
165982 RtreeGeomCallback cb; /* Info about the callback functions */
165983 int nParam; /* Number of parameters to the SQL function */
165984 sqlite3_value **apSqlParam; /* Original SQL parameter values */
165985 RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
165988 #ifndef MAX
165989 # define MAX(x,y) ((x) < (y) ? (y) : (x))
165990 #endif
165991 #ifndef MIN
165992 # define MIN(x,y) ((x) > (y) ? (y) : (x))
165993 #endif
165995 /* What version of GCC is being used. 0 means GCC is not being used .
165996 ** Note that the GCC_VERSION macro will also be set correctly when using
165997 ** clang, since clang works hard to be gcc compatible. So the gcc
165998 ** optimizations will also work when compiling with clang.
166000 #ifndef GCC_VERSION
166001 #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
166002 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
166003 #else
166004 # define GCC_VERSION 0
166005 #endif
166006 #endif
166008 /* The testcase() macro should already be defined in the amalgamation. If
166009 ** it is not, make it a no-op.
166011 #ifndef SQLITE_AMALGAMATION
166012 # define testcase(X)
166013 #endif
166016 ** Macros to determine whether the machine is big or little endian,
166017 ** and whether or not that determination is run-time or compile-time.
166019 ** For best performance, an attempt is made to guess at the byte-order
166020 ** using C-preprocessor macros. If that is unsuccessful, or if
166021 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
166022 ** at run-time.
166024 #ifndef SQLITE_BYTEORDER
166025 #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
166026 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
166027 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
166028 defined(__arm__)
166029 # define SQLITE_BYTEORDER 1234
166030 #elif defined(sparc) || defined(__ppc__)
166031 # define SQLITE_BYTEORDER 4321
166032 #else
166033 # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
166034 #endif
166035 #endif
166038 /* What version of MSVC is being used. 0 means MSVC is not being used */
166039 #ifndef MSVC_VERSION
166040 #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
166041 # define MSVC_VERSION _MSC_VER
166042 #else
166043 # define MSVC_VERSION 0
166044 #endif
166045 #endif
166048 ** Functions to deserialize a 16 bit integer, 32 bit real number and
166049 ** 64 bit integer. The deserialized value is returned.
166051 static int readInt16(u8 *p){
166052 return (p[0]<<8) + p[1];
166054 static void readCoord(u8 *p, RtreeCoord *pCoord){
166055 assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
166056 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
166057 pCoord->u = _byteswap_ulong(*(u32*)p);
166058 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
166059 pCoord->u = __builtin_bswap32(*(u32*)p);
166060 #elif SQLITE_BYTEORDER==4321
166061 pCoord->u = *(u32*)p;
166062 #else
166063 pCoord->u = (
166064 (((u32)p[0]) << 24) +
166065 (((u32)p[1]) << 16) +
166066 (((u32)p[2]) << 8) +
166067 (((u32)p[3]) << 0)
166069 #endif
166071 static i64 readInt64(u8 *p){
166072 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
166073 u64 x;
166074 memcpy(&x, p, 8);
166075 return (i64)_byteswap_uint64(x);
166076 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
166077 u64 x;
166078 memcpy(&x, p, 8);
166079 return (i64)__builtin_bswap64(x);
166080 #elif SQLITE_BYTEORDER==4321
166081 i64 x;
166082 memcpy(&x, p, 8);
166083 return x;
166084 #else
166085 return (i64)(
166086 (((u64)p[0]) << 56) +
166087 (((u64)p[1]) << 48) +
166088 (((u64)p[2]) << 40) +
166089 (((u64)p[3]) << 32) +
166090 (((u64)p[4]) << 24) +
166091 (((u64)p[5]) << 16) +
166092 (((u64)p[6]) << 8) +
166093 (((u64)p[7]) << 0)
166095 #endif
166099 ** Functions to serialize a 16 bit integer, 32 bit real number and
166100 ** 64 bit integer. The value returned is the number of bytes written
166101 ** to the argument buffer (always 2, 4 and 8 respectively).
166103 static void writeInt16(u8 *p, int i){
166104 p[0] = (i>> 8)&0xFF;
166105 p[1] = (i>> 0)&0xFF;
166107 static int writeCoord(u8 *p, RtreeCoord *pCoord){
166108 u32 i;
166109 assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
166110 assert( sizeof(RtreeCoord)==4 );
166111 assert( sizeof(u32)==4 );
166112 #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
166113 i = __builtin_bswap32(pCoord->u);
166114 memcpy(p, &i, 4);
166115 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
166116 i = _byteswap_ulong(pCoord->u);
166117 memcpy(p, &i, 4);
166118 #elif SQLITE_BYTEORDER==4321
166119 i = pCoord->u;
166120 memcpy(p, &i, 4);
166121 #else
166122 i = pCoord->u;
166123 p[0] = (i>>24)&0xFF;
166124 p[1] = (i>>16)&0xFF;
166125 p[2] = (i>> 8)&0xFF;
166126 p[3] = (i>> 0)&0xFF;
166127 #endif
166128 return 4;
166130 static int writeInt64(u8 *p, i64 i){
166131 #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
166132 i = (i64)__builtin_bswap64((u64)i);
166133 memcpy(p, &i, 8);
166134 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
166135 i = (i64)_byteswap_uint64((u64)i);
166136 memcpy(p, &i, 8);
166137 #elif SQLITE_BYTEORDER==4321
166138 memcpy(p, &i, 8);
166139 #else
166140 p[0] = (i>>56)&0xFF;
166141 p[1] = (i>>48)&0xFF;
166142 p[2] = (i>>40)&0xFF;
166143 p[3] = (i>>32)&0xFF;
166144 p[4] = (i>>24)&0xFF;
166145 p[5] = (i>>16)&0xFF;
166146 p[6] = (i>> 8)&0xFF;
166147 p[7] = (i>> 0)&0xFF;
166148 #endif
166149 return 8;
166153 ** Increment the reference count of node p.
166155 static void nodeReference(RtreeNode *p){
166156 if( p ){
166157 p->nRef++;
166162 ** Clear the content of node p (set all bytes to 0x00).
166164 static void nodeZero(Rtree *pRtree, RtreeNode *p){
166165 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
166166 p->isDirty = 1;
166170 ** Given a node number iNode, return the corresponding key to use
166171 ** in the Rtree.aHash table.
166173 static int nodeHash(i64 iNode){
166174 return iNode % HASHSIZE;
166178 ** Search the node hash table for node iNode. If found, return a pointer
166179 ** to it. Otherwise, return 0.
166181 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
166182 RtreeNode *p;
166183 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
166184 return p;
166188 ** Add node pNode to the node hash table.
166190 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
166191 int iHash;
166192 assert( pNode->pNext==0 );
166193 iHash = nodeHash(pNode->iNode);
166194 pNode->pNext = pRtree->aHash[iHash];
166195 pRtree->aHash[iHash] = pNode;
166199 ** Remove node pNode from the node hash table.
166201 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
166202 RtreeNode **pp;
166203 if( pNode->iNode!=0 ){
166204 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
166205 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
166206 *pp = pNode->pNext;
166207 pNode->pNext = 0;
166212 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
166213 ** indicating that node has not yet been assigned a node number. It is
166214 ** assigned a node number when nodeWrite() is called to write the
166215 ** node contents out to the database.
166217 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
166218 RtreeNode *pNode;
166219 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
166220 if( pNode ){
166221 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
166222 pNode->zData = (u8 *)&pNode[1];
166223 pNode->nRef = 1;
166224 pNode->pParent = pParent;
166225 pNode->isDirty = 1;
166226 nodeReference(pParent);
166228 return pNode;
166232 ** Clear the Rtree.pNodeBlob object
166234 static void nodeBlobReset(Rtree *pRtree){
166235 if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
166236 sqlite3_blob *pBlob = pRtree->pNodeBlob;
166237 pRtree->pNodeBlob = 0;
166238 sqlite3_blob_close(pBlob);
166243 ** Obtain a reference to an r-tree node.
166245 static int nodeAcquire(
166246 Rtree *pRtree, /* R-tree structure */
166247 i64 iNode, /* Node number to load */
166248 RtreeNode *pParent, /* Either the parent node or NULL */
166249 RtreeNode **ppNode /* OUT: Acquired node */
166251 int rc = SQLITE_OK;
166252 RtreeNode *pNode = 0;
166254 /* Check if the requested node is already in the hash table. If so,
166255 ** increase its reference count and return it.
166257 if( (pNode = nodeHashLookup(pRtree, iNode)) ){
166258 assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
166259 if( pParent && !pNode->pParent ){
166260 nodeReference(pParent);
166261 pNode->pParent = pParent;
166263 pNode->nRef++;
166264 *ppNode = pNode;
166265 return SQLITE_OK;
166268 if( pRtree->pNodeBlob ){
166269 sqlite3_blob *pBlob = pRtree->pNodeBlob;
166270 pRtree->pNodeBlob = 0;
166271 rc = sqlite3_blob_reopen(pBlob, iNode);
166272 pRtree->pNodeBlob = pBlob;
166273 if( rc ){
166274 nodeBlobReset(pRtree);
166275 if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
166278 if( pRtree->pNodeBlob==0 ){
166279 char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
166280 if( zTab==0 ) return SQLITE_NOMEM;
166281 rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
166282 &pRtree->pNodeBlob);
166283 sqlite3_free(zTab);
166285 if( rc ){
166286 nodeBlobReset(pRtree);
166287 *ppNode = 0;
166288 /* If unable to open an sqlite3_blob on the desired row, that can only
166289 ** be because the shadow tables hold erroneous data. */
166290 if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB;
166291 }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
166292 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
166293 if( !pNode ){
166294 rc = SQLITE_NOMEM;
166295 }else{
166296 pNode->pParent = pParent;
166297 pNode->zData = (u8 *)&pNode[1];
166298 pNode->nRef = 1;
166299 pNode->iNode = iNode;
166300 pNode->isDirty = 0;
166301 pNode->pNext = 0;
166302 rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
166303 pRtree->iNodeSize, 0);
166304 nodeReference(pParent);
166308 /* If the root node was just loaded, set pRtree->iDepth to the height
166309 ** of the r-tree structure. A height of zero means all data is stored on
166310 ** the root node. A height of one means the children of the root node
166311 ** are the leaves, and so on. If the depth as specified on the root node
166312 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
166314 if( pNode && iNode==1 ){
166315 pRtree->iDepth = readInt16(pNode->zData);
166316 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
166317 rc = SQLITE_CORRUPT_VTAB;
166321 /* If no error has occurred so far, check if the "number of entries"
166322 ** field on the node is too large. If so, set the return code to
166323 ** SQLITE_CORRUPT_VTAB.
166325 if( pNode && rc==SQLITE_OK ){
166326 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
166327 rc = SQLITE_CORRUPT_VTAB;
166331 if( rc==SQLITE_OK ){
166332 if( pNode!=0 ){
166333 nodeHashInsert(pRtree, pNode);
166334 }else{
166335 rc = SQLITE_CORRUPT_VTAB;
166337 *ppNode = pNode;
166338 }else{
166339 sqlite3_free(pNode);
166340 *ppNode = 0;
166343 return rc;
166347 ** Overwrite cell iCell of node pNode with the contents of pCell.
166349 static void nodeOverwriteCell(
166350 Rtree *pRtree, /* The overall R-Tree */
166351 RtreeNode *pNode, /* The node into which the cell is to be written */
166352 RtreeCell *pCell, /* The cell to write */
166353 int iCell /* Index into pNode into which pCell is written */
166355 int ii;
166356 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
166357 p += writeInt64(p, pCell->iRowid);
166358 for(ii=0; ii<pRtree->nDim2; ii++){
166359 p += writeCoord(p, &pCell->aCoord[ii]);
166361 pNode->isDirty = 1;
166365 ** Remove the cell with index iCell from node pNode.
166367 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
166368 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
166369 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
166370 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
166371 memmove(pDst, pSrc, nByte);
166372 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
166373 pNode->isDirty = 1;
166377 ** Insert the contents of cell pCell into node pNode. If the insert
166378 ** is successful, return SQLITE_OK.
166380 ** If there is not enough free space in pNode, return SQLITE_FULL.
166382 static int nodeInsertCell(
166383 Rtree *pRtree, /* The overall R-Tree */
166384 RtreeNode *pNode, /* Write new cell into this node */
166385 RtreeCell *pCell /* The cell to be inserted */
166387 int nCell; /* Current number of cells in pNode */
166388 int nMaxCell; /* Maximum number of cells for pNode */
166390 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
166391 nCell = NCELL(pNode);
166393 assert( nCell<=nMaxCell );
166394 if( nCell<nMaxCell ){
166395 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
166396 writeInt16(&pNode->zData[2], nCell+1);
166397 pNode->isDirty = 1;
166400 return (nCell==nMaxCell);
166404 ** If the node is dirty, write it out to the database.
166406 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
166407 int rc = SQLITE_OK;
166408 if( pNode->isDirty ){
166409 sqlite3_stmt *p = pRtree->pWriteNode;
166410 if( pNode->iNode ){
166411 sqlite3_bind_int64(p, 1, pNode->iNode);
166412 }else{
166413 sqlite3_bind_null(p, 1);
166415 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
166416 sqlite3_step(p);
166417 pNode->isDirty = 0;
166418 rc = sqlite3_reset(p);
166419 if( pNode->iNode==0 && rc==SQLITE_OK ){
166420 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
166421 nodeHashInsert(pRtree, pNode);
166424 return rc;
166428 ** Release a reference to a node. If the node is dirty and the reference
166429 ** count drops to zero, the node data is written to the database.
166431 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
166432 int rc = SQLITE_OK;
166433 if( pNode ){
166434 assert( pNode->nRef>0 );
166435 pNode->nRef--;
166436 if( pNode->nRef==0 ){
166437 if( pNode->iNode==1 ){
166438 pRtree->iDepth = -1;
166440 if( pNode->pParent ){
166441 rc = nodeRelease(pRtree, pNode->pParent);
166443 if( rc==SQLITE_OK ){
166444 rc = nodeWrite(pRtree, pNode);
166446 nodeHashDelete(pRtree, pNode);
166447 sqlite3_free(pNode);
166450 return rc;
166454 ** Return the 64-bit integer value associated with cell iCell of
166455 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
166456 ** an internal node, then the 64-bit integer is a child page number.
166458 static i64 nodeGetRowid(
166459 Rtree *pRtree, /* The overall R-Tree */
166460 RtreeNode *pNode, /* The node from which to extract the ID */
166461 int iCell /* The cell index from which to extract the ID */
166463 assert( iCell<NCELL(pNode) );
166464 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
166468 ** Return coordinate iCoord from cell iCell in node pNode.
166470 static void nodeGetCoord(
166471 Rtree *pRtree, /* The overall R-Tree */
166472 RtreeNode *pNode, /* The node from which to extract a coordinate */
166473 int iCell, /* The index of the cell within the node */
166474 int iCoord, /* Which coordinate to extract */
166475 RtreeCoord *pCoord /* OUT: Space to write result to */
166477 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
166481 ** Deserialize cell iCell of node pNode. Populate the structure pointed
166482 ** to by pCell with the results.
166484 static void nodeGetCell(
166485 Rtree *pRtree, /* The overall R-Tree */
166486 RtreeNode *pNode, /* The node containing the cell to be read */
166487 int iCell, /* Index of the cell within the node */
166488 RtreeCell *pCell /* OUT: Write the cell contents here */
166490 u8 *pData;
166491 RtreeCoord *pCoord;
166492 int ii = 0;
166493 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
166494 pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
166495 pCoord = pCell->aCoord;
166497 readCoord(pData, &pCoord[ii]);
166498 readCoord(pData+4, &pCoord[ii+1]);
166499 pData += 8;
166500 ii += 2;
166501 }while( ii<pRtree->nDim2 );
166505 /* Forward declaration for the function that does the work of
166506 ** the virtual table module xCreate() and xConnect() methods.
166508 static int rtreeInit(
166509 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
166513 ** Rtree virtual table module xCreate method.
166515 static int rtreeCreate(
166516 sqlite3 *db,
166517 void *pAux,
166518 int argc, const char *const*argv,
166519 sqlite3_vtab **ppVtab,
166520 char **pzErr
166522 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
166526 ** Rtree virtual table module xConnect method.
166528 static int rtreeConnect(
166529 sqlite3 *db,
166530 void *pAux,
166531 int argc, const char *const*argv,
166532 sqlite3_vtab **ppVtab,
166533 char **pzErr
166535 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
166539 ** Increment the r-tree reference count.
166541 static void rtreeReference(Rtree *pRtree){
166542 pRtree->nBusy++;
166546 ** Decrement the r-tree reference count. When the reference count reaches
166547 ** zero the structure is deleted.
166549 static void rtreeRelease(Rtree *pRtree){
166550 pRtree->nBusy--;
166551 if( pRtree->nBusy==0 ){
166552 pRtree->inWrTrans = 0;
166553 pRtree->nCursor = 0;
166554 nodeBlobReset(pRtree);
166555 sqlite3_finalize(pRtree->pWriteNode);
166556 sqlite3_finalize(pRtree->pDeleteNode);
166557 sqlite3_finalize(pRtree->pReadRowid);
166558 sqlite3_finalize(pRtree->pWriteRowid);
166559 sqlite3_finalize(pRtree->pDeleteRowid);
166560 sqlite3_finalize(pRtree->pReadParent);
166561 sqlite3_finalize(pRtree->pWriteParent);
166562 sqlite3_finalize(pRtree->pDeleteParent);
166563 sqlite3_free(pRtree);
166568 ** Rtree virtual table module xDisconnect method.
166570 static int rtreeDisconnect(sqlite3_vtab *pVtab){
166571 rtreeRelease((Rtree *)pVtab);
166572 return SQLITE_OK;
166576 ** Rtree virtual table module xDestroy method.
166578 static int rtreeDestroy(sqlite3_vtab *pVtab){
166579 Rtree *pRtree = (Rtree *)pVtab;
166580 int rc;
166581 char *zCreate = sqlite3_mprintf(
166582 "DROP TABLE '%q'.'%q_node';"
166583 "DROP TABLE '%q'.'%q_rowid';"
166584 "DROP TABLE '%q'.'%q_parent';",
166585 pRtree->zDb, pRtree->zName,
166586 pRtree->zDb, pRtree->zName,
166587 pRtree->zDb, pRtree->zName
166589 if( !zCreate ){
166590 rc = SQLITE_NOMEM;
166591 }else{
166592 nodeBlobReset(pRtree);
166593 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
166594 sqlite3_free(zCreate);
166596 if( rc==SQLITE_OK ){
166597 rtreeRelease(pRtree);
166600 return rc;
166604 ** Rtree virtual table module xOpen method.
166606 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
166607 int rc = SQLITE_NOMEM;
166608 Rtree *pRtree = (Rtree *)pVTab;
166609 RtreeCursor *pCsr;
166611 pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
166612 if( pCsr ){
166613 memset(pCsr, 0, sizeof(RtreeCursor));
166614 pCsr->base.pVtab = pVTab;
166615 rc = SQLITE_OK;
166616 pRtree->nCursor++;
166618 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
166620 return rc;
166625 ** Free the RtreeCursor.aConstraint[] array and its contents.
166627 static void freeCursorConstraints(RtreeCursor *pCsr){
166628 if( pCsr->aConstraint ){
166629 int i; /* Used to iterate through constraint array */
166630 for(i=0; i<pCsr->nConstraint; i++){
166631 sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
166632 if( pInfo ){
166633 if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
166634 sqlite3_free(pInfo);
166637 sqlite3_free(pCsr->aConstraint);
166638 pCsr->aConstraint = 0;
166643 ** Rtree virtual table module xClose method.
166645 static int rtreeClose(sqlite3_vtab_cursor *cur){
166646 Rtree *pRtree = (Rtree *)(cur->pVtab);
166647 int ii;
166648 RtreeCursor *pCsr = (RtreeCursor *)cur;
166649 assert( pRtree->nCursor>0 );
166650 freeCursorConstraints(pCsr);
166651 sqlite3_free(pCsr->aPoint);
166652 for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
166653 sqlite3_free(pCsr);
166654 pRtree->nCursor--;
166655 nodeBlobReset(pRtree);
166656 return SQLITE_OK;
166660 ** Rtree virtual table module xEof method.
166662 ** Return non-zero if the cursor does not currently point to a valid
166663 ** record (i.e if the scan has finished), or zero otherwise.
166665 static int rtreeEof(sqlite3_vtab_cursor *cur){
166666 RtreeCursor *pCsr = (RtreeCursor *)cur;
166667 return pCsr->atEOF;
166671 ** Convert raw bits from the on-disk RTree record into a coordinate value.
166672 ** The on-disk format is big-endian and needs to be converted for little-
166673 ** endian platforms. The on-disk record stores integer coordinates if
166674 ** eInt is true and it stores 32-bit floating point records if eInt is
166675 ** false. a[] is the four bytes of the on-disk record to be decoded.
166676 ** Store the results in "r".
166678 ** There are five versions of this macro. The last one is generic. The
166679 ** other four are various architectures-specific optimizations.
166681 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
166682 #define RTREE_DECODE_COORD(eInt, a, r) { \
166683 RtreeCoord c; /* Coordinate decoded */ \
166684 c.u = _byteswap_ulong(*(u32*)a); \
166685 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166687 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
166688 #define RTREE_DECODE_COORD(eInt, a, r) { \
166689 RtreeCoord c; /* Coordinate decoded */ \
166690 c.u = __builtin_bswap32(*(u32*)a); \
166691 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166693 #elif SQLITE_BYTEORDER==1234
166694 #define RTREE_DECODE_COORD(eInt, a, r) { \
166695 RtreeCoord c; /* Coordinate decoded */ \
166696 memcpy(&c.u,a,4); \
166697 c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
166698 ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
166699 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166701 #elif SQLITE_BYTEORDER==4321
166702 #define RTREE_DECODE_COORD(eInt, a, r) { \
166703 RtreeCoord c; /* Coordinate decoded */ \
166704 memcpy(&c.u,a,4); \
166705 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166707 #else
166708 #define RTREE_DECODE_COORD(eInt, a, r) { \
166709 RtreeCoord c; /* Coordinate decoded */ \
166710 c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
166711 +((u32)a[2]<<8) + a[3]; \
166712 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166714 #endif
166717 ** Check the RTree node or entry given by pCellData and p against the MATCH
166718 ** constraint pConstraint.
166720 static int rtreeCallbackConstraint(
166721 RtreeConstraint *pConstraint, /* The constraint to test */
166722 int eInt, /* True if RTree holding integer coordinates */
166723 u8 *pCellData, /* Raw cell content */
166724 RtreeSearchPoint *pSearch, /* Container of this cell */
166725 sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
166726 int *peWithin /* OUT: visibility of the cell */
166728 sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
166729 int nCoord = pInfo->nCoord; /* No. of coordinates */
166730 int rc; /* Callback return code */
166731 RtreeCoord c; /* Translator union */
166732 sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
166734 assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
166735 assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
166737 if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
166738 pInfo->iRowid = readInt64(pCellData);
166740 pCellData += 8;
166741 #ifndef SQLITE_RTREE_INT_ONLY
166742 if( eInt==0 ){
166743 switch( nCoord ){
166744 case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
166745 readCoord(pCellData+32, &c); aCoord[8] = c.f;
166746 case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
166747 readCoord(pCellData+24, &c); aCoord[6] = c.f;
166748 case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
166749 readCoord(pCellData+16, &c); aCoord[4] = c.f;
166750 case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
166751 readCoord(pCellData+8, &c); aCoord[2] = c.f;
166752 default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
166753 readCoord(pCellData, &c); aCoord[0] = c.f;
166755 }else
166756 #endif
166758 switch( nCoord ){
166759 case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
166760 readCoord(pCellData+32, &c); aCoord[8] = c.i;
166761 case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
166762 readCoord(pCellData+24, &c); aCoord[6] = c.i;
166763 case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
166764 readCoord(pCellData+16, &c); aCoord[4] = c.i;
166765 case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
166766 readCoord(pCellData+8, &c); aCoord[2] = c.i;
166767 default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
166768 readCoord(pCellData, &c); aCoord[0] = c.i;
166771 if( pConstraint->op==RTREE_MATCH ){
166772 int eWithin = 0;
166773 rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
166774 nCoord, aCoord, &eWithin);
166775 if( eWithin==0 ) *peWithin = NOT_WITHIN;
166776 *prScore = RTREE_ZERO;
166777 }else{
166778 pInfo->aCoord = aCoord;
166779 pInfo->iLevel = pSearch->iLevel - 1;
166780 pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
166781 pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
166782 rc = pConstraint->u.xQueryFunc(pInfo);
166783 if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
166784 if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
166785 *prScore = pInfo->rScore;
166788 return rc;
166792 ** Check the internal RTree node given by pCellData against constraint p.
166793 ** If this constraint cannot be satisfied by any child within the node,
166794 ** set *peWithin to NOT_WITHIN.
166796 static void rtreeNonleafConstraint(
166797 RtreeConstraint *p, /* The constraint to test */
166798 int eInt, /* True if RTree holds integer coordinates */
166799 u8 *pCellData, /* Raw cell content as appears on disk */
166800 int *peWithin /* Adjust downward, as appropriate */
166802 sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
166804 /* p->iCoord might point to either a lower or upper bound coordinate
166805 ** in a coordinate pair. But make pCellData point to the lower bound.
166807 pCellData += 8 + 4*(p->iCoord&0xfe);
166809 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
166810 || p->op==RTREE_GT || p->op==RTREE_EQ );
166811 assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
166812 switch( p->op ){
166813 case RTREE_LE:
166814 case RTREE_LT:
166815 case RTREE_EQ:
166816 RTREE_DECODE_COORD(eInt, pCellData, val);
166817 /* val now holds the lower bound of the coordinate pair */
166818 if( p->u.rValue>=val ) return;
166819 if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
166820 /* Fall through for the RTREE_EQ case */
166822 default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
166823 pCellData += 4;
166824 RTREE_DECODE_COORD(eInt, pCellData, val);
166825 /* val now holds the upper bound of the coordinate pair */
166826 if( p->u.rValue<=val ) return;
166828 *peWithin = NOT_WITHIN;
166832 ** Check the leaf RTree cell given by pCellData against constraint p.
166833 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
166834 ** If the constraint is satisfied, leave *peWithin unchanged.
166836 ** The constraint is of the form: xN op $val
166838 ** The op is given by p->op. The xN is p->iCoord-th coordinate in
166839 ** pCellData. $val is given by p->u.rValue.
166841 static void rtreeLeafConstraint(
166842 RtreeConstraint *p, /* The constraint to test */
166843 int eInt, /* True if RTree holds integer coordinates */
166844 u8 *pCellData, /* Raw cell content as appears on disk */
166845 int *peWithin /* Adjust downward, as appropriate */
166847 RtreeDValue xN; /* Coordinate value converted to a double */
166849 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
166850 || p->op==RTREE_GT || p->op==RTREE_EQ );
166851 pCellData += 8 + p->iCoord*4;
166852 assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
166853 RTREE_DECODE_COORD(eInt, pCellData, xN);
166854 switch( p->op ){
166855 case RTREE_LE: if( xN <= p->u.rValue ) return; break;
166856 case RTREE_LT: if( xN < p->u.rValue ) return; break;
166857 case RTREE_GE: if( xN >= p->u.rValue ) return; break;
166858 case RTREE_GT: if( xN > p->u.rValue ) return; break;
166859 default: if( xN == p->u.rValue ) return; break;
166861 *peWithin = NOT_WITHIN;
166865 ** One of the cells in node pNode is guaranteed to have a 64-bit
166866 ** integer value equal to iRowid. Return the index of this cell.
166868 static int nodeRowidIndex(
166869 Rtree *pRtree,
166870 RtreeNode *pNode,
166871 i64 iRowid,
166872 int *piIndex
166874 int ii;
166875 int nCell = NCELL(pNode);
166876 assert( nCell<200 );
166877 for(ii=0; ii<nCell; ii++){
166878 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
166879 *piIndex = ii;
166880 return SQLITE_OK;
166883 return SQLITE_CORRUPT_VTAB;
166887 ** Return the index of the cell containing a pointer to node pNode
166888 ** in its parent. If pNode is the root node, return -1.
166890 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
166891 RtreeNode *pParent = pNode->pParent;
166892 if( pParent ){
166893 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
166895 *piIndex = -1;
166896 return SQLITE_OK;
166900 ** Compare two search points. Return negative, zero, or positive if the first
166901 ** is less than, equal to, or greater than the second.
166903 ** The rScore is the primary key. Smaller rScore values come first.
166904 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
166905 ** iLevel values coming first. In this way, if rScore is the same for all
166906 ** SearchPoints, then iLevel becomes the deciding factor and the result
166907 ** is a depth-first search, which is the desired default behavior.
166909 static int rtreeSearchPointCompare(
166910 const RtreeSearchPoint *pA,
166911 const RtreeSearchPoint *pB
166913 if( pA->rScore<pB->rScore ) return -1;
166914 if( pA->rScore>pB->rScore ) return +1;
166915 if( pA->iLevel<pB->iLevel ) return -1;
166916 if( pA->iLevel>pB->iLevel ) return +1;
166917 return 0;
166921 ** Interchange two search points in a cursor.
166923 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
166924 RtreeSearchPoint t = p->aPoint[i];
166925 assert( i<j );
166926 p->aPoint[i] = p->aPoint[j];
166927 p->aPoint[j] = t;
166928 i++; j++;
166929 if( i<RTREE_CACHE_SZ ){
166930 if( j>=RTREE_CACHE_SZ ){
166931 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
166932 p->aNode[i] = 0;
166933 }else{
166934 RtreeNode *pTemp = p->aNode[i];
166935 p->aNode[i] = p->aNode[j];
166936 p->aNode[j] = pTemp;
166942 ** Return the search point with the lowest current score.
166944 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
166945 return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
166949 ** Get the RtreeNode for the search point with the lowest score.
166951 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
166952 sqlite3_int64 id;
166953 int ii = 1 - pCur->bPoint;
166954 assert( ii==0 || ii==1 );
166955 assert( pCur->bPoint || pCur->nPoint );
166956 if( pCur->aNode[ii]==0 ){
166957 assert( pRC!=0 );
166958 id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
166959 *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
166961 return pCur->aNode[ii];
166965 ** Push a new element onto the priority queue
166967 static RtreeSearchPoint *rtreeEnqueue(
166968 RtreeCursor *pCur, /* The cursor */
166969 RtreeDValue rScore, /* Score for the new search point */
166970 u8 iLevel /* Level for the new search point */
166972 int i, j;
166973 RtreeSearchPoint *pNew;
166974 if( pCur->nPoint>=pCur->nPointAlloc ){
166975 int nNew = pCur->nPointAlloc*2 + 8;
166976 pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
166977 if( pNew==0 ) return 0;
166978 pCur->aPoint = pNew;
166979 pCur->nPointAlloc = nNew;
166981 i = pCur->nPoint++;
166982 pNew = pCur->aPoint + i;
166983 pNew->rScore = rScore;
166984 pNew->iLevel = iLevel;
166985 assert( iLevel<=RTREE_MAX_DEPTH );
166986 while( i>0 ){
166987 RtreeSearchPoint *pParent;
166988 j = (i-1)/2;
166989 pParent = pCur->aPoint + j;
166990 if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
166991 rtreeSearchPointSwap(pCur, j, i);
166992 i = j;
166993 pNew = pParent;
166995 return pNew;
166999 ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
167000 ** NULL if malloc fails.
167002 static RtreeSearchPoint *rtreeSearchPointNew(
167003 RtreeCursor *pCur, /* The cursor */
167004 RtreeDValue rScore, /* Score for the new search point */
167005 u8 iLevel /* Level for the new search point */
167007 RtreeSearchPoint *pNew, *pFirst;
167008 pFirst = rtreeSearchPointFirst(pCur);
167009 pCur->anQueue[iLevel]++;
167010 if( pFirst==0
167011 || pFirst->rScore>rScore
167012 || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
167014 if( pCur->bPoint ){
167015 int ii;
167016 pNew = rtreeEnqueue(pCur, rScore, iLevel);
167017 if( pNew==0 ) return 0;
167018 ii = (int)(pNew - pCur->aPoint) + 1;
167019 if( ii<RTREE_CACHE_SZ ){
167020 assert( pCur->aNode[ii]==0 );
167021 pCur->aNode[ii] = pCur->aNode[0];
167022 }else{
167023 nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
167025 pCur->aNode[0] = 0;
167026 *pNew = pCur->sPoint;
167028 pCur->sPoint.rScore = rScore;
167029 pCur->sPoint.iLevel = iLevel;
167030 pCur->bPoint = 1;
167031 return &pCur->sPoint;
167032 }else{
167033 return rtreeEnqueue(pCur, rScore, iLevel);
167037 #if 0
167038 /* Tracing routines for the RtreeSearchPoint queue */
167039 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
167040 if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
167041 printf(" %d.%05lld.%02d %g %d",
167042 p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
167044 idx++;
167045 if( idx<RTREE_CACHE_SZ ){
167046 printf(" %p\n", pCur->aNode[idx]);
167047 }else{
167048 printf("\n");
167051 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
167052 int ii;
167053 printf("=== %9s ", zPrefix);
167054 if( pCur->bPoint ){
167055 tracePoint(&pCur->sPoint, -1, pCur);
167057 for(ii=0; ii<pCur->nPoint; ii++){
167058 if( ii>0 || pCur->bPoint ) printf(" ");
167059 tracePoint(&pCur->aPoint[ii], ii, pCur);
167062 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
167063 #else
167064 # define RTREE_QUEUE_TRACE(A,B) /* no-op */
167065 #endif
167067 /* Remove the search point with the lowest current score.
167069 static void rtreeSearchPointPop(RtreeCursor *p){
167070 int i, j, k, n;
167071 i = 1 - p->bPoint;
167072 assert( i==0 || i==1 );
167073 if( p->aNode[i] ){
167074 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
167075 p->aNode[i] = 0;
167077 if( p->bPoint ){
167078 p->anQueue[p->sPoint.iLevel]--;
167079 p->bPoint = 0;
167080 }else if( p->nPoint ){
167081 p->anQueue[p->aPoint[0].iLevel]--;
167082 n = --p->nPoint;
167083 p->aPoint[0] = p->aPoint[n];
167084 if( n<RTREE_CACHE_SZ-1 ){
167085 p->aNode[1] = p->aNode[n+1];
167086 p->aNode[n+1] = 0;
167088 i = 0;
167089 while( (j = i*2+1)<n ){
167090 k = j+1;
167091 if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
167092 if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
167093 rtreeSearchPointSwap(p, i, k);
167094 i = k;
167095 }else{
167096 break;
167098 }else{
167099 if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
167100 rtreeSearchPointSwap(p, i, j);
167101 i = j;
167102 }else{
167103 break;
167112 ** Continue the search on cursor pCur until the front of the queue
167113 ** contains an entry suitable for returning as a result-set row,
167114 ** or until the RtreeSearchPoint queue is empty, indicating that the
167115 ** query has completed.
167117 static int rtreeStepToLeaf(RtreeCursor *pCur){
167118 RtreeSearchPoint *p;
167119 Rtree *pRtree = RTREE_OF_CURSOR(pCur);
167120 RtreeNode *pNode;
167121 int eWithin;
167122 int rc = SQLITE_OK;
167123 int nCell;
167124 int nConstraint = pCur->nConstraint;
167125 int ii;
167126 int eInt;
167127 RtreeSearchPoint x;
167129 eInt = pRtree->eCoordType==RTREE_COORD_INT32;
167130 while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
167131 pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
167132 if( rc ) return rc;
167133 nCell = NCELL(pNode);
167134 assert( nCell<200 );
167135 while( p->iCell<nCell ){
167136 sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
167137 u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
167138 eWithin = FULLY_WITHIN;
167139 for(ii=0; ii<nConstraint; ii++){
167140 RtreeConstraint *pConstraint = pCur->aConstraint + ii;
167141 if( pConstraint->op>=RTREE_MATCH ){
167142 rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
167143 &rScore, &eWithin);
167144 if( rc ) return rc;
167145 }else if( p->iLevel==1 ){
167146 rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
167147 }else{
167148 rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
167150 if( eWithin==NOT_WITHIN ) break;
167152 p->iCell++;
167153 if( eWithin==NOT_WITHIN ) continue;
167154 x.iLevel = p->iLevel - 1;
167155 if( x.iLevel ){
167156 x.id = readInt64(pCellData);
167157 x.iCell = 0;
167158 }else{
167159 x.id = p->id;
167160 x.iCell = p->iCell - 1;
167162 if( p->iCell>=nCell ){
167163 RTREE_QUEUE_TRACE(pCur, "POP-S:");
167164 rtreeSearchPointPop(pCur);
167166 if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
167167 p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
167168 if( p==0 ) return SQLITE_NOMEM;
167169 p->eWithin = (u8)eWithin;
167170 p->id = x.id;
167171 p->iCell = x.iCell;
167172 RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
167173 break;
167175 if( p->iCell>=nCell ){
167176 RTREE_QUEUE_TRACE(pCur, "POP-Se:");
167177 rtreeSearchPointPop(pCur);
167180 pCur->atEOF = p==0;
167181 return SQLITE_OK;
167185 ** Rtree virtual table module xNext method.
167187 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
167188 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
167189 int rc = SQLITE_OK;
167191 /* Move to the next entry that matches the configured constraints. */
167192 RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
167193 rtreeSearchPointPop(pCsr);
167194 rc = rtreeStepToLeaf(pCsr);
167195 return rc;
167199 ** Rtree virtual table module xRowid method.
167201 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
167202 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
167203 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
167204 int rc = SQLITE_OK;
167205 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
167206 if( rc==SQLITE_OK && p ){
167207 *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
167209 return rc;
167213 ** Rtree virtual table module xColumn method.
167215 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
167216 Rtree *pRtree = (Rtree *)cur->pVtab;
167217 RtreeCursor *pCsr = (RtreeCursor *)cur;
167218 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
167219 RtreeCoord c;
167220 int rc = SQLITE_OK;
167221 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
167223 if( rc ) return rc;
167224 if( p==0 ) return SQLITE_OK;
167225 if( i==0 ){
167226 sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
167227 }else{
167228 nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
167229 #ifndef SQLITE_RTREE_INT_ONLY
167230 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
167231 sqlite3_result_double(ctx, c.f);
167232 }else
167233 #endif
167235 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
167236 sqlite3_result_int(ctx, c.i);
167239 return SQLITE_OK;
167243 ** Use nodeAcquire() to obtain the leaf node containing the record with
167244 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
167245 ** return SQLITE_OK. If there is no such record in the table, set
167246 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
167247 ** to zero and return an SQLite error code.
167249 static int findLeafNode(
167250 Rtree *pRtree, /* RTree to search */
167251 i64 iRowid, /* The rowid searching for */
167252 RtreeNode **ppLeaf, /* Write the node here */
167253 sqlite3_int64 *piNode /* Write the node-id here */
167255 int rc;
167256 *ppLeaf = 0;
167257 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
167258 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
167259 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
167260 if( piNode ) *piNode = iNode;
167261 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
167262 sqlite3_reset(pRtree->pReadRowid);
167263 }else{
167264 rc = sqlite3_reset(pRtree->pReadRowid);
167266 return rc;
167270 ** This function is called to configure the RtreeConstraint object passed
167271 ** as the second argument for a MATCH constraint. The value passed as the
167272 ** first argument to this function is the right-hand operand to the MATCH
167273 ** operator.
167275 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
167276 RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
167277 sqlite3_rtree_query_info *pInfo; /* Callback information */
167279 pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
167280 if( pSrc==0 ) return SQLITE_ERROR;
167281 pInfo = (sqlite3_rtree_query_info*)
167282 sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
167283 if( !pInfo ) return SQLITE_NOMEM;
167284 memset(pInfo, 0, sizeof(*pInfo));
167285 pBlob = (RtreeMatchArg*)&pInfo[1];
167286 memcpy(pBlob, pSrc, pSrc->iSize);
167287 pInfo->pContext = pBlob->cb.pContext;
167288 pInfo->nParam = pBlob->nParam;
167289 pInfo->aParam = pBlob->aParam;
167290 pInfo->apSqlParam = pBlob->apSqlParam;
167292 if( pBlob->cb.xGeom ){
167293 pCons->u.xGeom = pBlob->cb.xGeom;
167294 }else{
167295 pCons->op = RTREE_QUERY;
167296 pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
167298 pCons->pInfo = pInfo;
167299 return SQLITE_OK;
167303 ** Rtree virtual table module xFilter method.
167305 static int rtreeFilter(
167306 sqlite3_vtab_cursor *pVtabCursor,
167307 int idxNum, const char *idxStr,
167308 int argc, sqlite3_value **argv
167310 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
167311 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
167312 RtreeNode *pRoot = 0;
167313 int ii;
167314 int rc = SQLITE_OK;
167315 int iCell = 0;
167317 rtreeReference(pRtree);
167319 /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
167320 freeCursorConstraints(pCsr);
167321 sqlite3_free(pCsr->aPoint);
167322 memset(pCsr, 0, sizeof(RtreeCursor));
167323 pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
167325 pCsr->iStrategy = idxNum;
167326 if( idxNum==1 ){
167327 /* Special case - lookup by rowid. */
167328 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
167329 RtreeSearchPoint *p; /* Search point for the leaf */
167330 i64 iRowid = sqlite3_value_int64(argv[0]);
167331 i64 iNode = 0;
167332 rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
167333 if( rc==SQLITE_OK && pLeaf!=0 ){
167334 p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
167335 assert( p!=0 ); /* Always returns pCsr->sPoint */
167336 pCsr->aNode[0] = pLeaf;
167337 p->id = iNode;
167338 p->eWithin = PARTLY_WITHIN;
167339 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
167340 p->iCell = (u8)iCell;
167341 RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
167342 }else{
167343 pCsr->atEOF = 1;
167345 }else{
167346 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
167347 ** with the configured constraints.
167349 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
167350 if( rc==SQLITE_OK && argc>0 ){
167351 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
167352 pCsr->nConstraint = argc;
167353 if( !pCsr->aConstraint ){
167354 rc = SQLITE_NOMEM;
167355 }else{
167356 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
167357 memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
167358 assert( (idxStr==0 && argc==0)
167359 || (idxStr && (int)strlen(idxStr)==argc*2) );
167360 for(ii=0; ii<argc; ii++){
167361 RtreeConstraint *p = &pCsr->aConstraint[ii];
167362 p->op = idxStr[ii*2];
167363 p->iCoord = idxStr[ii*2+1]-'0';
167364 if( p->op>=RTREE_MATCH ){
167365 /* A MATCH operator. The right-hand-side must be a blob that
167366 ** can be cast into an RtreeMatchArg object. One created using
167367 ** an sqlite3_rtree_geometry_callback() SQL user function.
167369 rc = deserializeGeometry(argv[ii], p);
167370 if( rc!=SQLITE_OK ){
167371 break;
167373 p->pInfo->nCoord = pRtree->nDim2;
167374 p->pInfo->anQueue = pCsr->anQueue;
167375 p->pInfo->mxLevel = pRtree->iDepth + 1;
167376 }else{
167377 #ifdef SQLITE_RTREE_INT_ONLY
167378 p->u.rValue = sqlite3_value_int64(argv[ii]);
167379 #else
167380 p->u.rValue = sqlite3_value_double(argv[ii]);
167381 #endif
167386 if( rc==SQLITE_OK ){
167387 RtreeSearchPoint *pNew;
167388 pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
167389 if( pNew==0 ) return SQLITE_NOMEM;
167390 pNew->id = 1;
167391 pNew->iCell = 0;
167392 pNew->eWithin = PARTLY_WITHIN;
167393 assert( pCsr->bPoint==1 );
167394 pCsr->aNode[0] = pRoot;
167395 pRoot = 0;
167396 RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
167397 rc = rtreeStepToLeaf(pCsr);
167401 nodeRelease(pRtree, pRoot);
167402 rtreeRelease(pRtree);
167403 return rc;
167407 ** Rtree virtual table module xBestIndex method. There are three
167408 ** table scan strategies to choose from (in order from most to
167409 ** least desirable):
167411 ** idxNum idxStr Strategy
167412 ** ------------------------------------------------
167413 ** 1 Unused Direct lookup by rowid.
167414 ** 2 See below R-tree query or full-table scan.
167415 ** ------------------------------------------------
167417 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
167418 ** 2 is used, idxStr is formatted to contain 2 bytes for each
167419 ** constraint used. The first two bytes of idxStr correspond to
167420 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
167421 ** (argvIndex==1) etc.
167423 ** The first of each pair of bytes in idxStr identifies the constraint
167424 ** operator as follows:
167426 ** Operator Byte Value
167427 ** ----------------------
167428 ** = 0x41 ('A')
167429 ** <= 0x42 ('B')
167430 ** < 0x43 ('C')
167431 ** >= 0x44 ('D')
167432 ** > 0x45 ('E')
167433 ** MATCH 0x46 ('F')
167434 ** ----------------------
167436 ** The second of each pair of bytes identifies the coordinate column
167437 ** to which the constraint applies. The leftmost coordinate column
167438 ** is 'a', the second from the left 'b' etc.
167440 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
167441 Rtree *pRtree = (Rtree*)tab;
167442 int rc = SQLITE_OK;
167443 int ii;
167444 int bMatch = 0; /* True if there exists a MATCH constraint */
167445 i64 nRow; /* Estimated rows returned by this scan */
167447 int iIdx = 0;
167448 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
167449 memset(zIdxStr, 0, sizeof(zIdxStr));
167451 /* Check if there exists a MATCH constraint - even an unusable one. If there
167452 ** is, do not consider the lookup-by-rowid plan as using such a plan would
167453 ** require the VDBE to evaluate the MATCH constraint, which is not currently
167454 ** possible. */
167455 for(ii=0; ii<pIdxInfo->nConstraint; ii++){
167456 if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
167457 bMatch = 1;
167461 assert( pIdxInfo->idxStr==0 );
167462 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
167463 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
167465 if( bMatch==0 && p->usable
167466 && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
167468 /* We have an equality constraint on the rowid. Use strategy 1. */
167469 int jj;
167470 for(jj=0; jj<ii; jj++){
167471 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
167472 pIdxInfo->aConstraintUsage[jj].omit = 0;
167474 pIdxInfo->idxNum = 1;
167475 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
167476 pIdxInfo->aConstraintUsage[jj].omit = 1;
167478 /* This strategy involves a two rowid lookups on an B-Tree structures
167479 ** and then a linear search of an R-Tree node. This should be
167480 ** considered almost as quick as a direct rowid lookup (for which
167481 ** sqlite uses an internal cost of 0.0). It is expected to return
167482 ** a single row.
167484 pIdxInfo->estimatedCost = 30.0;
167485 pIdxInfo->estimatedRows = 1;
167486 return SQLITE_OK;
167489 if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
167490 u8 op;
167491 switch( p->op ){
167492 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
167493 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
167494 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
167495 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
167496 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
167497 default:
167498 assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
167499 op = RTREE_MATCH;
167500 break;
167502 zIdxStr[iIdx++] = op;
167503 zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
167504 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
167505 pIdxInfo->aConstraintUsage[ii].omit = 1;
167509 pIdxInfo->idxNum = 2;
167510 pIdxInfo->needToFreeIdxStr = 1;
167511 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
167512 return SQLITE_NOMEM;
167515 nRow = pRtree->nRowEst >> (iIdx/2);
167516 pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
167517 pIdxInfo->estimatedRows = nRow;
167519 return rc;
167523 ** Return the N-dimensional volumn of the cell stored in *p.
167525 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
167526 RtreeDValue area = (RtreeDValue)1;
167527 assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
167528 #ifndef SQLITE_RTREE_INT_ONLY
167529 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
167530 switch( pRtree->nDim ){
167531 case 5: area = p->aCoord[9].f - p->aCoord[8].f;
167532 case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
167533 case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
167534 case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
167535 default: area *= p->aCoord[1].f - p->aCoord[0].f;
167537 }else
167538 #endif
167540 switch( pRtree->nDim ){
167541 case 5: area = p->aCoord[9].i - p->aCoord[8].i;
167542 case 4: area *= p->aCoord[7].i - p->aCoord[6].i;
167543 case 3: area *= p->aCoord[5].i - p->aCoord[4].i;
167544 case 2: area *= p->aCoord[3].i - p->aCoord[2].i;
167545 default: area *= p->aCoord[1].i - p->aCoord[0].i;
167548 return area;
167552 ** Return the margin length of cell p. The margin length is the sum
167553 ** of the objects size in each dimension.
167555 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
167556 RtreeDValue margin = 0;
167557 int ii = pRtree->nDim2 - 2;
167559 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
167560 ii -= 2;
167561 }while( ii>=0 );
167562 return margin;
167566 ** Store the union of cells p1 and p2 in p1.
167568 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
167569 int ii = 0;
167570 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
167572 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
167573 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
167574 ii += 2;
167575 }while( ii<pRtree->nDim2 );
167576 }else{
167578 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
167579 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
167580 ii += 2;
167581 }while( ii<pRtree->nDim2 );
167586 ** Return true if the area covered by p2 is a subset of the area covered
167587 ** by p1. False otherwise.
167589 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
167590 int ii;
167591 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
167592 for(ii=0; ii<pRtree->nDim2; ii+=2){
167593 RtreeCoord *a1 = &p1->aCoord[ii];
167594 RtreeCoord *a2 = &p2->aCoord[ii];
167595 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
167596 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
167598 return 0;
167601 return 1;
167605 ** Return the amount cell p would grow by if it were unioned with pCell.
167607 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
167608 RtreeDValue area;
167609 RtreeCell cell;
167610 memcpy(&cell, p, sizeof(RtreeCell));
167611 area = cellArea(pRtree, &cell);
167612 cellUnion(pRtree, &cell, pCell);
167613 return (cellArea(pRtree, &cell)-area);
167616 static RtreeDValue cellOverlap(
167617 Rtree *pRtree,
167618 RtreeCell *p,
167619 RtreeCell *aCell,
167620 int nCell
167622 int ii;
167623 RtreeDValue overlap = RTREE_ZERO;
167624 for(ii=0; ii<nCell; ii++){
167625 int jj;
167626 RtreeDValue o = (RtreeDValue)1;
167627 for(jj=0; jj<pRtree->nDim2; jj+=2){
167628 RtreeDValue x1, x2;
167629 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
167630 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
167631 if( x2<x1 ){
167632 o = (RtreeDValue)0;
167633 break;
167634 }else{
167635 o = o * (x2-x1);
167638 overlap += o;
167640 return overlap;
167645 ** This function implements the ChooseLeaf algorithm from Gutman[84].
167646 ** ChooseSubTree in r*tree terminology.
167648 static int ChooseLeaf(
167649 Rtree *pRtree, /* Rtree table */
167650 RtreeCell *pCell, /* Cell to insert into rtree */
167651 int iHeight, /* Height of sub-tree rooted at pCell */
167652 RtreeNode **ppLeaf /* OUT: Selected leaf page */
167654 int rc;
167655 int ii;
167656 RtreeNode *pNode;
167657 rc = nodeAcquire(pRtree, 1, 0, &pNode);
167659 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
167660 int iCell;
167661 sqlite3_int64 iBest = 0;
167663 RtreeDValue fMinGrowth = RTREE_ZERO;
167664 RtreeDValue fMinArea = RTREE_ZERO;
167666 int nCell = NCELL(pNode);
167667 RtreeCell cell;
167668 RtreeNode *pChild;
167670 RtreeCell *aCell = 0;
167672 /* Select the child node which will be enlarged the least if pCell
167673 ** is inserted into it. Resolve ties by choosing the entry with
167674 ** the smallest area.
167676 for(iCell=0; iCell<nCell; iCell++){
167677 int bBest = 0;
167678 RtreeDValue growth;
167679 RtreeDValue area;
167680 nodeGetCell(pRtree, pNode, iCell, &cell);
167681 growth = cellGrowth(pRtree, &cell, pCell);
167682 area = cellArea(pRtree, &cell);
167683 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
167684 bBest = 1;
167686 if( bBest ){
167687 fMinGrowth = growth;
167688 fMinArea = area;
167689 iBest = cell.iRowid;
167693 sqlite3_free(aCell);
167694 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
167695 nodeRelease(pRtree, pNode);
167696 pNode = pChild;
167699 *ppLeaf = pNode;
167700 return rc;
167704 ** A cell with the same content as pCell has just been inserted into
167705 ** the node pNode. This function updates the bounding box cells in
167706 ** all ancestor elements.
167708 static int AdjustTree(
167709 Rtree *pRtree, /* Rtree table */
167710 RtreeNode *pNode, /* Adjust ancestry of this node. */
167711 RtreeCell *pCell /* This cell was just inserted */
167713 RtreeNode *p = pNode;
167714 while( p->pParent ){
167715 RtreeNode *pParent = p->pParent;
167716 RtreeCell cell;
167717 int iCell;
167719 if( nodeParentIndex(pRtree, p, &iCell) ){
167720 return SQLITE_CORRUPT_VTAB;
167723 nodeGetCell(pRtree, pParent, iCell, &cell);
167724 if( !cellContains(pRtree, &cell, pCell) ){
167725 cellUnion(pRtree, &cell, pCell);
167726 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
167729 p = pParent;
167731 return SQLITE_OK;
167735 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
167737 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
167738 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
167739 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
167740 sqlite3_step(pRtree->pWriteRowid);
167741 return sqlite3_reset(pRtree->pWriteRowid);
167745 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
167747 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
167748 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
167749 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
167750 sqlite3_step(pRtree->pWriteParent);
167751 return sqlite3_reset(pRtree->pWriteParent);
167754 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
167758 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
167759 ** nIdx. The aIdx array contains the set of integers from 0 to
167760 ** (nIdx-1) in no particular order. This function sorts the values
167761 ** in aIdx according to the indexed values in aDistance. For
167762 ** example, assuming the inputs:
167764 ** aIdx = { 0, 1, 2, 3 }
167765 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
167767 ** this function sets the aIdx array to contain:
167769 ** aIdx = { 0, 1, 2, 3 }
167771 ** The aSpare array is used as temporary working space by the
167772 ** sorting algorithm.
167774 static void SortByDistance(
167775 int *aIdx,
167776 int nIdx,
167777 RtreeDValue *aDistance,
167778 int *aSpare
167780 if( nIdx>1 ){
167781 int iLeft = 0;
167782 int iRight = 0;
167784 int nLeft = nIdx/2;
167785 int nRight = nIdx-nLeft;
167786 int *aLeft = aIdx;
167787 int *aRight = &aIdx[nLeft];
167789 SortByDistance(aLeft, nLeft, aDistance, aSpare);
167790 SortByDistance(aRight, nRight, aDistance, aSpare);
167792 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
167793 aLeft = aSpare;
167795 while( iLeft<nLeft || iRight<nRight ){
167796 if( iLeft==nLeft ){
167797 aIdx[iLeft+iRight] = aRight[iRight];
167798 iRight++;
167799 }else if( iRight==nRight ){
167800 aIdx[iLeft+iRight] = aLeft[iLeft];
167801 iLeft++;
167802 }else{
167803 RtreeDValue fLeft = aDistance[aLeft[iLeft]];
167804 RtreeDValue fRight = aDistance[aRight[iRight]];
167805 if( fLeft<fRight ){
167806 aIdx[iLeft+iRight] = aLeft[iLeft];
167807 iLeft++;
167808 }else{
167809 aIdx[iLeft+iRight] = aRight[iRight];
167810 iRight++;
167815 #if 0
167816 /* Check that the sort worked */
167818 int jj;
167819 for(jj=1; jj<nIdx; jj++){
167820 RtreeDValue left = aDistance[aIdx[jj-1]];
167821 RtreeDValue right = aDistance[aIdx[jj]];
167822 assert( left<=right );
167825 #endif
167830 ** Arguments aIdx, aCell and aSpare all point to arrays of size
167831 ** nIdx. The aIdx array contains the set of integers from 0 to
167832 ** (nIdx-1) in no particular order. This function sorts the values
167833 ** in aIdx according to dimension iDim of the cells in aCell. The
167834 ** minimum value of dimension iDim is considered first, the
167835 ** maximum used to break ties.
167837 ** The aSpare array is used as temporary working space by the
167838 ** sorting algorithm.
167840 static void SortByDimension(
167841 Rtree *pRtree,
167842 int *aIdx,
167843 int nIdx,
167844 int iDim,
167845 RtreeCell *aCell,
167846 int *aSpare
167848 if( nIdx>1 ){
167850 int iLeft = 0;
167851 int iRight = 0;
167853 int nLeft = nIdx/2;
167854 int nRight = nIdx-nLeft;
167855 int *aLeft = aIdx;
167856 int *aRight = &aIdx[nLeft];
167858 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
167859 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
167861 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
167862 aLeft = aSpare;
167863 while( iLeft<nLeft || iRight<nRight ){
167864 RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
167865 RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
167866 RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
167867 RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
167868 if( (iLeft!=nLeft) && ((iRight==nRight)
167869 || (xleft1<xright1)
167870 || (xleft1==xright1 && xleft2<xright2)
167872 aIdx[iLeft+iRight] = aLeft[iLeft];
167873 iLeft++;
167874 }else{
167875 aIdx[iLeft+iRight] = aRight[iRight];
167876 iRight++;
167880 #if 0
167881 /* Check that the sort worked */
167883 int jj;
167884 for(jj=1; jj<nIdx; jj++){
167885 RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
167886 RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
167887 RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
167888 RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
167889 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
167892 #endif
167897 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
167899 static int splitNodeStartree(
167900 Rtree *pRtree,
167901 RtreeCell *aCell,
167902 int nCell,
167903 RtreeNode *pLeft,
167904 RtreeNode *pRight,
167905 RtreeCell *pBboxLeft,
167906 RtreeCell *pBboxRight
167908 int **aaSorted;
167909 int *aSpare;
167910 int ii;
167912 int iBestDim = 0;
167913 int iBestSplit = 0;
167914 RtreeDValue fBestMargin = RTREE_ZERO;
167916 int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
167918 aaSorted = (int **)sqlite3_malloc(nByte);
167919 if( !aaSorted ){
167920 return SQLITE_NOMEM;
167923 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
167924 memset(aaSorted, 0, nByte);
167925 for(ii=0; ii<pRtree->nDim; ii++){
167926 int jj;
167927 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
167928 for(jj=0; jj<nCell; jj++){
167929 aaSorted[ii][jj] = jj;
167931 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
167934 for(ii=0; ii<pRtree->nDim; ii++){
167935 RtreeDValue margin = RTREE_ZERO;
167936 RtreeDValue fBestOverlap = RTREE_ZERO;
167937 RtreeDValue fBestArea = RTREE_ZERO;
167938 int iBestLeft = 0;
167939 int nLeft;
167942 nLeft=RTREE_MINCELLS(pRtree);
167943 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
167944 nLeft++
167946 RtreeCell left;
167947 RtreeCell right;
167948 int kk;
167949 RtreeDValue overlap;
167950 RtreeDValue area;
167952 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
167953 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
167954 for(kk=1; kk<(nCell-1); kk++){
167955 if( kk<nLeft ){
167956 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
167957 }else{
167958 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
167961 margin += cellMargin(pRtree, &left);
167962 margin += cellMargin(pRtree, &right);
167963 overlap = cellOverlap(pRtree, &left, &right, 1);
167964 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
167965 if( (nLeft==RTREE_MINCELLS(pRtree))
167966 || (overlap<fBestOverlap)
167967 || (overlap==fBestOverlap && area<fBestArea)
167969 iBestLeft = nLeft;
167970 fBestOverlap = overlap;
167971 fBestArea = area;
167975 if( ii==0 || margin<fBestMargin ){
167976 iBestDim = ii;
167977 fBestMargin = margin;
167978 iBestSplit = iBestLeft;
167982 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
167983 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
167984 for(ii=0; ii<nCell; ii++){
167985 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
167986 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
167987 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
167988 nodeInsertCell(pRtree, pTarget, pCell);
167989 cellUnion(pRtree, pBbox, pCell);
167992 sqlite3_free(aaSorted);
167993 return SQLITE_OK;
167997 static int updateMapping(
167998 Rtree *pRtree,
167999 i64 iRowid,
168000 RtreeNode *pNode,
168001 int iHeight
168003 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
168004 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
168005 if( iHeight>0 ){
168006 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
168007 if( pChild ){
168008 nodeRelease(pRtree, pChild->pParent);
168009 nodeReference(pNode);
168010 pChild->pParent = pNode;
168013 return xSetMapping(pRtree, iRowid, pNode->iNode);
168016 static int SplitNode(
168017 Rtree *pRtree,
168018 RtreeNode *pNode,
168019 RtreeCell *pCell,
168020 int iHeight
168022 int i;
168023 int newCellIsRight = 0;
168025 int rc = SQLITE_OK;
168026 int nCell = NCELL(pNode);
168027 RtreeCell *aCell;
168028 int *aiUsed;
168030 RtreeNode *pLeft = 0;
168031 RtreeNode *pRight = 0;
168033 RtreeCell leftbbox;
168034 RtreeCell rightbbox;
168036 /* Allocate an array and populate it with a copy of pCell and
168037 ** all cells from node pLeft. Then zero the original node.
168039 aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
168040 if( !aCell ){
168041 rc = SQLITE_NOMEM;
168042 goto splitnode_out;
168044 aiUsed = (int *)&aCell[nCell+1];
168045 memset(aiUsed, 0, sizeof(int)*(nCell+1));
168046 for(i=0; i<nCell; i++){
168047 nodeGetCell(pRtree, pNode, i, &aCell[i]);
168049 nodeZero(pRtree, pNode);
168050 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
168051 nCell++;
168053 if( pNode->iNode==1 ){
168054 pRight = nodeNew(pRtree, pNode);
168055 pLeft = nodeNew(pRtree, pNode);
168056 pRtree->iDepth++;
168057 pNode->isDirty = 1;
168058 writeInt16(pNode->zData, pRtree->iDepth);
168059 }else{
168060 pLeft = pNode;
168061 pRight = nodeNew(pRtree, pLeft->pParent);
168062 nodeReference(pLeft);
168065 if( !pLeft || !pRight ){
168066 rc = SQLITE_NOMEM;
168067 goto splitnode_out;
168070 memset(pLeft->zData, 0, pRtree->iNodeSize);
168071 memset(pRight->zData, 0, pRtree->iNodeSize);
168073 rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
168074 &leftbbox, &rightbbox);
168075 if( rc!=SQLITE_OK ){
168076 goto splitnode_out;
168079 /* Ensure both child nodes have node numbers assigned to them by calling
168080 ** nodeWrite(). Node pRight always needs a node number, as it was created
168081 ** by nodeNew() above. But node pLeft sometimes already has a node number.
168082 ** In this case avoid the all to nodeWrite().
168084 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
168085 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
168087 goto splitnode_out;
168090 rightbbox.iRowid = pRight->iNode;
168091 leftbbox.iRowid = pLeft->iNode;
168093 if( pNode->iNode==1 ){
168094 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
168095 if( rc!=SQLITE_OK ){
168096 goto splitnode_out;
168098 }else{
168099 RtreeNode *pParent = pLeft->pParent;
168100 int iCell;
168101 rc = nodeParentIndex(pRtree, pLeft, &iCell);
168102 if( rc==SQLITE_OK ){
168103 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
168104 rc = AdjustTree(pRtree, pParent, &leftbbox);
168106 if( rc!=SQLITE_OK ){
168107 goto splitnode_out;
168110 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
168111 goto splitnode_out;
168114 for(i=0; i<NCELL(pRight); i++){
168115 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
168116 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
168117 if( iRowid==pCell->iRowid ){
168118 newCellIsRight = 1;
168120 if( rc!=SQLITE_OK ){
168121 goto splitnode_out;
168124 if( pNode->iNode==1 ){
168125 for(i=0; i<NCELL(pLeft); i++){
168126 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
168127 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
168128 if( rc!=SQLITE_OK ){
168129 goto splitnode_out;
168132 }else if( newCellIsRight==0 ){
168133 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
168136 if( rc==SQLITE_OK ){
168137 rc = nodeRelease(pRtree, pRight);
168138 pRight = 0;
168140 if( rc==SQLITE_OK ){
168141 rc = nodeRelease(pRtree, pLeft);
168142 pLeft = 0;
168145 splitnode_out:
168146 nodeRelease(pRtree, pRight);
168147 nodeRelease(pRtree, pLeft);
168148 sqlite3_free(aCell);
168149 return rc;
168153 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
168154 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
168155 ** the pLeaf->pParent chain all the way up to the root node.
168157 ** This operation is required when a row is deleted (or updated - an update
168158 ** is implemented as a delete followed by an insert). SQLite provides the
168159 ** rowid of the row to delete, which can be used to find the leaf on which
168160 ** the entry resides (argument pLeaf). Once the leaf is located, this
168161 ** function is called to determine its ancestry.
168163 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
168164 int rc = SQLITE_OK;
168165 RtreeNode *pChild = pLeaf;
168166 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
168167 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
168168 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
168169 rc = sqlite3_step(pRtree->pReadParent);
168170 if( rc==SQLITE_ROW ){
168171 RtreeNode *pTest; /* Used to test for reference loops */
168172 i64 iNode; /* Node number of parent node */
168174 /* Before setting pChild->pParent, test that we are not creating a
168175 ** loop of references (as we would if, say, pChild==pParent). We don't
168176 ** want to do this as it leads to a memory leak when trying to delete
168177 ** the referenced counted node structures.
168179 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
168180 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
168181 if( !pTest ){
168182 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
168185 rc = sqlite3_reset(pRtree->pReadParent);
168186 if( rc==SQLITE_OK ) rc = rc2;
168187 if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
168188 pChild = pChild->pParent;
168190 return rc;
168193 static int deleteCell(Rtree *, RtreeNode *, int, int);
168195 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
168196 int rc;
168197 int rc2;
168198 RtreeNode *pParent = 0;
168199 int iCell;
168201 assert( pNode->nRef==1 );
168203 /* Remove the entry in the parent cell. */
168204 rc = nodeParentIndex(pRtree, pNode, &iCell);
168205 if( rc==SQLITE_OK ){
168206 pParent = pNode->pParent;
168207 pNode->pParent = 0;
168208 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
168210 rc2 = nodeRelease(pRtree, pParent);
168211 if( rc==SQLITE_OK ){
168212 rc = rc2;
168214 if( rc!=SQLITE_OK ){
168215 return rc;
168218 /* Remove the xxx_node entry. */
168219 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
168220 sqlite3_step(pRtree->pDeleteNode);
168221 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
168222 return rc;
168225 /* Remove the xxx_parent entry. */
168226 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
168227 sqlite3_step(pRtree->pDeleteParent);
168228 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
168229 return rc;
168232 /* Remove the node from the in-memory hash table and link it into
168233 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
168235 nodeHashDelete(pRtree, pNode);
168236 pNode->iNode = iHeight;
168237 pNode->pNext = pRtree->pDeleted;
168238 pNode->nRef++;
168239 pRtree->pDeleted = pNode;
168241 return SQLITE_OK;
168244 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
168245 RtreeNode *pParent = pNode->pParent;
168246 int rc = SQLITE_OK;
168247 if( pParent ){
168248 int ii;
168249 int nCell = NCELL(pNode);
168250 RtreeCell box; /* Bounding box for pNode */
168251 nodeGetCell(pRtree, pNode, 0, &box);
168252 for(ii=1; ii<nCell; ii++){
168253 RtreeCell cell;
168254 nodeGetCell(pRtree, pNode, ii, &cell);
168255 cellUnion(pRtree, &box, &cell);
168257 box.iRowid = pNode->iNode;
168258 rc = nodeParentIndex(pRtree, pNode, &ii);
168259 if( rc==SQLITE_OK ){
168260 nodeOverwriteCell(pRtree, pParent, &box, ii);
168261 rc = fixBoundingBox(pRtree, pParent);
168264 return rc;
168268 ** Delete the cell at index iCell of node pNode. After removing the
168269 ** cell, adjust the r-tree data structure if required.
168271 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
168272 RtreeNode *pParent;
168273 int rc;
168275 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
168276 return rc;
168279 /* Remove the cell from the node. This call just moves bytes around
168280 ** the in-memory node image, so it cannot fail.
168282 nodeDeleteCell(pRtree, pNode, iCell);
168284 /* If the node is not the tree root and now has less than the minimum
168285 ** number of cells, remove it from the tree. Otherwise, update the
168286 ** cell in the parent node so that it tightly contains the updated
168287 ** node.
168289 pParent = pNode->pParent;
168290 assert( pParent || pNode->iNode==1 );
168291 if( pParent ){
168292 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
168293 rc = removeNode(pRtree, pNode, iHeight);
168294 }else{
168295 rc = fixBoundingBox(pRtree, pNode);
168299 return rc;
168302 static int Reinsert(
168303 Rtree *pRtree,
168304 RtreeNode *pNode,
168305 RtreeCell *pCell,
168306 int iHeight
168308 int *aOrder;
168309 int *aSpare;
168310 RtreeCell *aCell;
168311 RtreeDValue *aDistance;
168312 int nCell;
168313 RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
168314 int iDim;
168315 int ii;
168316 int rc = SQLITE_OK;
168317 int n;
168319 memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
168321 nCell = NCELL(pNode)+1;
168322 n = (nCell+1)&(~1);
168324 /* Allocate the buffers used by this operation. The allocation is
168325 ** relinquished before this function returns.
168327 aCell = (RtreeCell *)sqlite3_malloc(n * (
168328 sizeof(RtreeCell) + /* aCell array */
168329 sizeof(int) + /* aOrder array */
168330 sizeof(int) + /* aSpare array */
168331 sizeof(RtreeDValue) /* aDistance array */
168333 if( !aCell ){
168334 return SQLITE_NOMEM;
168336 aOrder = (int *)&aCell[n];
168337 aSpare = (int *)&aOrder[n];
168338 aDistance = (RtreeDValue *)&aSpare[n];
168340 for(ii=0; ii<nCell; ii++){
168341 if( ii==(nCell-1) ){
168342 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
168343 }else{
168344 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
168346 aOrder[ii] = ii;
168347 for(iDim=0; iDim<pRtree->nDim; iDim++){
168348 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
168349 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
168352 for(iDim=0; iDim<pRtree->nDim; iDim++){
168353 aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
168356 for(ii=0; ii<nCell; ii++){
168357 aDistance[ii] = RTREE_ZERO;
168358 for(iDim=0; iDim<pRtree->nDim; iDim++){
168359 RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
168360 DCOORD(aCell[ii].aCoord[iDim*2]));
168361 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
168365 SortByDistance(aOrder, nCell, aDistance, aSpare);
168366 nodeZero(pRtree, pNode);
168368 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
168369 RtreeCell *p = &aCell[aOrder[ii]];
168370 nodeInsertCell(pRtree, pNode, p);
168371 if( p->iRowid==pCell->iRowid ){
168372 if( iHeight==0 ){
168373 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
168374 }else{
168375 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
168379 if( rc==SQLITE_OK ){
168380 rc = fixBoundingBox(pRtree, pNode);
168382 for(; rc==SQLITE_OK && ii<nCell; ii++){
168383 /* Find a node to store this cell in. pNode->iNode currently contains
168384 ** the height of the sub-tree headed by the cell.
168386 RtreeNode *pInsert;
168387 RtreeCell *p = &aCell[aOrder[ii]];
168388 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
168389 if( rc==SQLITE_OK ){
168390 int rc2;
168391 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
168392 rc2 = nodeRelease(pRtree, pInsert);
168393 if( rc==SQLITE_OK ){
168394 rc = rc2;
168399 sqlite3_free(aCell);
168400 return rc;
168404 ** Insert cell pCell into node pNode. Node pNode is the head of a
168405 ** subtree iHeight high (leaf nodes have iHeight==0).
168407 static int rtreeInsertCell(
168408 Rtree *pRtree,
168409 RtreeNode *pNode,
168410 RtreeCell *pCell,
168411 int iHeight
168413 int rc = SQLITE_OK;
168414 if( iHeight>0 ){
168415 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
168416 if( pChild ){
168417 nodeRelease(pRtree, pChild->pParent);
168418 nodeReference(pNode);
168419 pChild->pParent = pNode;
168422 if( nodeInsertCell(pRtree, pNode, pCell) ){
168423 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
168424 rc = SplitNode(pRtree, pNode, pCell, iHeight);
168425 }else{
168426 pRtree->iReinsertHeight = iHeight;
168427 rc = Reinsert(pRtree, pNode, pCell, iHeight);
168429 }else{
168430 rc = AdjustTree(pRtree, pNode, pCell);
168431 if( rc==SQLITE_OK ){
168432 if( iHeight==0 ){
168433 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
168434 }else{
168435 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
168439 return rc;
168442 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
168443 int ii;
168444 int rc = SQLITE_OK;
168445 int nCell = NCELL(pNode);
168447 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
168448 RtreeNode *pInsert;
168449 RtreeCell cell;
168450 nodeGetCell(pRtree, pNode, ii, &cell);
168452 /* Find a node to store this cell in. pNode->iNode currently contains
168453 ** the height of the sub-tree headed by the cell.
168455 rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
168456 if( rc==SQLITE_OK ){
168457 int rc2;
168458 rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
168459 rc2 = nodeRelease(pRtree, pInsert);
168460 if( rc==SQLITE_OK ){
168461 rc = rc2;
168465 return rc;
168469 ** Select a currently unused rowid for a new r-tree record.
168471 static int newRowid(Rtree *pRtree, i64 *piRowid){
168472 int rc;
168473 sqlite3_bind_null(pRtree->pWriteRowid, 1);
168474 sqlite3_bind_null(pRtree->pWriteRowid, 2);
168475 sqlite3_step(pRtree->pWriteRowid);
168476 rc = sqlite3_reset(pRtree->pWriteRowid);
168477 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
168478 return rc;
168482 ** Remove the entry with rowid=iDelete from the r-tree structure.
168484 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
168485 int rc; /* Return code */
168486 RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
168487 int iCell; /* Index of iDelete cell in pLeaf */
168488 RtreeNode *pRoot = 0; /* Root node of rtree structure */
168491 /* Obtain a reference to the root node to initialize Rtree.iDepth */
168492 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
168494 /* Obtain a reference to the leaf node that contains the entry
168495 ** about to be deleted.
168497 if( rc==SQLITE_OK ){
168498 rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
168501 /* Delete the cell in question from the leaf node. */
168502 if( rc==SQLITE_OK ){
168503 int rc2;
168504 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
168505 if( rc==SQLITE_OK ){
168506 rc = deleteCell(pRtree, pLeaf, iCell, 0);
168508 rc2 = nodeRelease(pRtree, pLeaf);
168509 if( rc==SQLITE_OK ){
168510 rc = rc2;
168514 /* Delete the corresponding entry in the <rtree>_rowid table. */
168515 if( rc==SQLITE_OK ){
168516 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
168517 sqlite3_step(pRtree->pDeleteRowid);
168518 rc = sqlite3_reset(pRtree->pDeleteRowid);
168521 /* Check if the root node now has exactly one child. If so, remove
168522 ** it, schedule the contents of the child for reinsertion and
168523 ** reduce the tree height by one.
168525 ** This is equivalent to copying the contents of the child into
168526 ** the root node (the operation that Gutman's paper says to perform
168527 ** in this scenario).
168529 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
168530 int rc2;
168531 RtreeNode *pChild;
168532 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
168533 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
168534 if( rc==SQLITE_OK ){
168535 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
168537 rc2 = nodeRelease(pRtree, pChild);
168538 if( rc==SQLITE_OK ) rc = rc2;
168539 if( rc==SQLITE_OK ){
168540 pRtree->iDepth--;
168541 writeInt16(pRoot->zData, pRtree->iDepth);
168542 pRoot->isDirty = 1;
168546 /* Re-insert the contents of any underfull nodes removed from the tree. */
168547 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
168548 if( rc==SQLITE_OK ){
168549 rc = reinsertNodeContent(pRtree, pLeaf);
168551 pRtree->pDeleted = pLeaf->pNext;
168552 sqlite3_free(pLeaf);
168555 /* Release the reference to the root node. */
168556 if( rc==SQLITE_OK ){
168557 rc = nodeRelease(pRtree, pRoot);
168558 }else{
168559 nodeRelease(pRtree, pRoot);
168562 return rc;
168566 ** Rounding constants for float->double conversion.
168568 #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
168569 #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
168571 #if !defined(SQLITE_RTREE_INT_ONLY)
168573 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
168574 ** while taking care to round toward negative or positive, respectively.
168576 static RtreeValue rtreeValueDown(sqlite3_value *v){
168577 double d = sqlite3_value_double(v);
168578 float f = (float)d;
168579 if( f>d ){
168580 f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
168582 return f;
168584 static RtreeValue rtreeValueUp(sqlite3_value *v){
168585 double d = sqlite3_value_double(v);
168586 float f = (float)d;
168587 if( f<d ){
168588 f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
168590 return f;
168592 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
168595 ** A constraint has failed while inserting a row into an rtree table.
168596 ** Assuming no OOM error occurs, this function sets the error message
168597 ** (at pRtree->base.zErrMsg) to an appropriate value and returns
168598 ** SQLITE_CONSTRAINT.
168600 ** Parameter iCol is the index of the leftmost column involved in the
168601 ** constraint failure. If it is 0, then the constraint that failed is
168602 ** the unique constraint on the id column. Otherwise, it is the rtree
168603 ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
168605 ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
168607 static int rtreeConstraintError(Rtree *pRtree, int iCol){
168608 sqlite3_stmt *pStmt = 0;
168609 char *zSql;
168610 int rc;
168612 assert( iCol==0 || iCol%2 );
168613 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
168614 if( zSql ){
168615 rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
168616 }else{
168617 rc = SQLITE_NOMEM;
168619 sqlite3_free(zSql);
168621 if( rc==SQLITE_OK ){
168622 if( iCol==0 ){
168623 const char *zCol = sqlite3_column_name(pStmt, 0);
168624 pRtree->base.zErrMsg = sqlite3_mprintf(
168625 "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
168627 }else{
168628 const char *zCol1 = sqlite3_column_name(pStmt, iCol);
168629 const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
168630 pRtree->base.zErrMsg = sqlite3_mprintf(
168631 "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
168636 sqlite3_finalize(pStmt);
168637 return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
168643 ** The xUpdate method for rtree module virtual tables.
168645 static int rtreeUpdate(
168646 sqlite3_vtab *pVtab,
168647 int nData,
168648 sqlite3_value **azData,
168649 sqlite_int64 *pRowid
168651 Rtree *pRtree = (Rtree *)pVtab;
168652 int rc = SQLITE_OK;
168653 RtreeCell cell; /* New cell to insert if nData>1 */
168654 int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
168656 rtreeReference(pRtree);
168657 assert(nData>=1);
168659 cell.iRowid = 0; /* Used only to suppress a compiler warning */
168661 /* Constraint handling. A write operation on an r-tree table may return
168662 ** SQLITE_CONSTRAINT for two reasons:
168664 ** 1. A duplicate rowid value, or
168665 ** 2. The supplied data violates the "x2>=x1" constraint.
168667 ** In the first case, if the conflict-handling mode is REPLACE, then
168668 ** the conflicting row can be removed before proceeding. In the second
168669 ** case, SQLITE_CONSTRAINT must be returned regardless of the
168670 ** conflict-handling mode specified by the user.
168672 if( nData>1 ){
168673 int ii;
168675 /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
168677 ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
168678 ** with "column" that are interpreted as table constraints.
168679 ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
168680 ** This problem was discovered after years of use, so we silently ignore
168681 ** these kinds of misdeclared tables to avoid breaking any legacy.
168683 assert( nData<=(pRtree->nDim2 + 3) );
168685 #ifndef SQLITE_RTREE_INT_ONLY
168686 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
168687 for(ii=0; ii<nData-4; ii+=2){
168688 cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
168689 cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
168690 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
168691 rc = rtreeConstraintError(pRtree, ii+1);
168692 goto constraint;
168695 }else
168696 #endif
168698 for(ii=0; ii<nData-4; ii+=2){
168699 cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
168700 cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
168701 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
168702 rc = rtreeConstraintError(pRtree, ii+1);
168703 goto constraint;
168708 /* If a rowid value was supplied, check if it is already present in
168709 ** the table. If so, the constraint has failed. */
168710 if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
168711 cell.iRowid = sqlite3_value_int64(azData[2]);
168712 if( sqlite3_value_type(azData[0])==SQLITE_NULL
168713 || sqlite3_value_int64(azData[0])!=cell.iRowid
168715 int steprc;
168716 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
168717 steprc = sqlite3_step(pRtree->pReadRowid);
168718 rc = sqlite3_reset(pRtree->pReadRowid);
168719 if( SQLITE_ROW==steprc ){
168720 if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
168721 rc = rtreeDeleteRowid(pRtree, cell.iRowid);
168722 }else{
168723 rc = rtreeConstraintError(pRtree, 0);
168724 goto constraint;
168728 bHaveRowid = 1;
168732 /* If azData[0] is not an SQL NULL value, it is the rowid of a
168733 ** record to delete from the r-tree table. The following block does
168734 ** just that.
168736 if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
168737 rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
168740 /* If the azData[] array contains more than one element, elements
168741 ** (azData[2]..azData[argc-1]) contain a new record to insert into
168742 ** the r-tree structure.
168744 if( rc==SQLITE_OK && nData>1 ){
168745 /* Insert the new record into the r-tree */
168746 RtreeNode *pLeaf = 0;
168748 /* Figure out the rowid of the new row. */
168749 if( bHaveRowid==0 ){
168750 rc = newRowid(pRtree, &cell.iRowid);
168752 *pRowid = cell.iRowid;
168754 if( rc==SQLITE_OK ){
168755 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
168757 if( rc==SQLITE_OK ){
168758 int rc2;
168759 pRtree->iReinsertHeight = -1;
168760 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
168761 rc2 = nodeRelease(pRtree, pLeaf);
168762 if( rc==SQLITE_OK ){
168763 rc = rc2;
168768 constraint:
168769 rtreeRelease(pRtree);
168770 return rc;
168774 ** Called when a transaction starts.
168776 static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
168777 Rtree *pRtree = (Rtree *)pVtab;
168778 assert( pRtree->inWrTrans==0 );
168779 pRtree->inWrTrans++;
168780 return SQLITE_OK;
168784 ** Called when a transaction completes (either by COMMIT or ROLLBACK).
168785 ** The sqlite3_blob object should be released at this point.
168787 static int rtreeEndTransaction(sqlite3_vtab *pVtab){
168788 Rtree *pRtree = (Rtree *)pVtab;
168789 pRtree->inWrTrans = 0;
168790 nodeBlobReset(pRtree);
168791 return SQLITE_OK;
168795 ** The xRename method for rtree module virtual tables.
168797 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
168798 Rtree *pRtree = (Rtree *)pVtab;
168799 int rc = SQLITE_NOMEM;
168800 char *zSql = sqlite3_mprintf(
168801 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
168802 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
168803 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
168804 , pRtree->zDb, pRtree->zName, zNewName
168805 , pRtree->zDb, pRtree->zName, zNewName
168806 , pRtree->zDb, pRtree->zName, zNewName
168808 if( zSql ){
168809 nodeBlobReset(pRtree);
168810 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
168811 sqlite3_free(zSql);
168813 return rc;
168817 ** The xSavepoint method.
168819 ** This module does not need to do anything to support savepoints. However,
168820 ** it uses this hook to close any open blob handle. This is done because a
168821 ** DROP TABLE command - which fortunately always opens a savepoint - cannot
168822 ** succeed if there are any open blob handles. i.e. if the blob handle were
168823 ** not closed here, the following would fail:
168825 ** BEGIN;
168826 ** INSERT INTO rtree...
168827 ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
168828 ** COMMIT;
168830 static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
168831 Rtree *pRtree = (Rtree *)pVtab;
168832 int iwt = pRtree->inWrTrans;
168833 UNUSED_PARAMETER(iSavepoint);
168834 pRtree->inWrTrans = 0;
168835 nodeBlobReset(pRtree);
168836 pRtree->inWrTrans = iwt;
168837 return SQLITE_OK;
168841 ** This function populates the pRtree->nRowEst variable with an estimate
168842 ** of the number of rows in the virtual table. If possible, this is based
168843 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
168845 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
168846 const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
168847 char *zSql;
168848 sqlite3_stmt *p;
168849 int rc;
168850 i64 nRow = 0;
168852 rc = sqlite3_table_column_metadata(
168853 db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
168855 if( rc!=SQLITE_OK ){
168856 pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
168857 return rc==SQLITE_ERROR ? SQLITE_OK : rc;
168859 zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
168860 if( zSql==0 ){
168861 rc = SQLITE_NOMEM;
168862 }else{
168863 rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
168864 if( rc==SQLITE_OK ){
168865 if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
168866 rc = sqlite3_finalize(p);
168867 }else if( rc!=SQLITE_NOMEM ){
168868 rc = SQLITE_OK;
168871 if( rc==SQLITE_OK ){
168872 if( nRow==0 ){
168873 pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
168874 }else{
168875 pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
168878 sqlite3_free(zSql);
168881 return rc;
168884 static sqlite3_module rtreeModule = {
168885 2, /* iVersion */
168886 rtreeCreate, /* xCreate - create a table */
168887 rtreeConnect, /* xConnect - connect to an existing table */
168888 rtreeBestIndex, /* xBestIndex - Determine search strategy */
168889 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
168890 rtreeDestroy, /* xDestroy - Drop a table */
168891 rtreeOpen, /* xOpen - open a cursor */
168892 rtreeClose, /* xClose - close a cursor */
168893 rtreeFilter, /* xFilter - configure scan constraints */
168894 rtreeNext, /* xNext - advance a cursor */
168895 rtreeEof, /* xEof */
168896 rtreeColumn, /* xColumn - read data */
168897 rtreeRowid, /* xRowid - read data */
168898 rtreeUpdate, /* xUpdate - write data */
168899 rtreeBeginTransaction, /* xBegin - begin transaction */
168900 rtreeEndTransaction, /* xSync - sync transaction */
168901 rtreeEndTransaction, /* xCommit - commit transaction */
168902 rtreeEndTransaction, /* xRollback - rollback transaction */
168903 0, /* xFindFunction - function overloading */
168904 rtreeRename, /* xRename - rename the table */
168905 rtreeSavepoint, /* xSavepoint */
168906 0, /* xRelease */
168907 0, /* xRollbackTo */
168910 static int rtreeSqlInit(
168911 Rtree *pRtree,
168912 sqlite3 *db,
168913 const char *zDb,
168914 const char *zPrefix,
168915 int isCreate
168917 int rc = SQLITE_OK;
168919 #define N_STATEMENT 8
168920 static const char *azSql[N_STATEMENT] = {
168921 /* Write the xxx_node table */
168922 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
168923 "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
168925 /* Read and write the xxx_rowid table */
168926 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
168927 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
168928 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
168930 /* Read and write the xxx_parent table */
168931 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
168932 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
168933 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
168935 sqlite3_stmt **appStmt[N_STATEMENT];
168936 int i;
168938 pRtree->db = db;
168940 if( isCreate ){
168941 char *zCreate = sqlite3_mprintf(
168942 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
168943 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
168944 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
168945 " parentnode INTEGER);"
168946 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
168947 zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
168949 if( !zCreate ){
168950 return SQLITE_NOMEM;
168952 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
168953 sqlite3_free(zCreate);
168954 if( rc!=SQLITE_OK ){
168955 return rc;
168959 appStmt[0] = &pRtree->pWriteNode;
168960 appStmt[1] = &pRtree->pDeleteNode;
168961 appStmt[2] = &pRtree->pReadRowid;
168962 appStmt[3] = &pRtree->pWriteRowid;
168963 appStmt[4] = &pRtree->pDeleteRowid;
168964 appStmt[5] = &pRtree->pReadParent;
168965 appStmt[6] = &pRtree->pWriteParent;
168966 appStmt[7] = &pRtree->pDeleteParent;
168968 rc = rtreeQueryStat1(db, pRtree);
168969 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
168970 char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
168971 if( zSql ){
168972 rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
168973 appStmt[i], 0);
168974 }else{
168975 rc = SQLITE_NOMEM;
168977 sqlite3_free(zSql);
168980 return rc;
168984 ** The second argument to this function contains the text of an SQL statement
168985 ** that returns a single integer value. The statement is compiled and executed
168986 ** using database connection db. If successful, the integer value returned
168987 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
168988 ** code is returned and the value of *piVal after returning is not defined.
168990 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
168991 int rc = SQLITE_NOMEM;
168992 if( zSql ){
168993 sqlite3_stmt *pStmt = 0;
168994 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
168995 if( rc==SQLITE_OK ){
168996 if( SQLITE_ROW==sqlite3_step(pStmt) ){
168997 *piVal = sqlite3_column_int(pStmt, 0);
168999 rc = sqlite3_finalize(pStmt);
169002 return rc;
169006 ** This function is called from within the xConnect() or xCreate() method to
169007 ** determine the node-size used by the rtree table being created or connected
169008 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
169009 ** Otherwise, an SQLite error code is returned.
169011 ** If this function is being called as part of an xConnect(), then the rtree
169012 ** table already exists. In this case the node-size is determined by inspecting
169013 ** the root node of the tree.
169015 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
169016 ** This ensures that each node is stored on a single database page. If the
169017 ** database page-size is so large that more than RTREE_MAXCELLS entries
169018 ** would fit in a single node, use a smaller node-size.
169020 static int getNodeSize(
169021 sqlite3 *db, /* Database handle */
169022 Rtree *pRtree, /* Rtree handle */
169023 int isCreate, /* True for xCreate, false for xConnect */
169024 char **pzErr /* OUT: Error message, if any */
169026 int rc;
169027 char *zSql;
169028 if( isCreate ){
169029 int iPageSize = 0;
169030 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
169031 rc = getIntFromStmt(db, zSql, &iPageSize);
169032 if( rc==SQLITE_OK ){
169033 pRtree->iNodeSize = iPageSize-64;
169034 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
169035 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
169037 }else{
169038 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
169040 }else{
169041 zSql = sqlite3_mprintf(
169042 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
169043 pRtree->zDb, pRtree->zName
169045 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
169046 if( rc!=SQLITE_OK ){
169047 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
169048 }else if( pRtree->iNodeSize<(512-64) ){
169049 rc = SQLITE_CORRUPT_VTAB;
169050 *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
169051 pRtree->zName);
169055 sqlite3_free(zSql);
169056 return rc;
169060 ** This function is the implementation of both the xConnect and xCreate
169061 ** methods of the r-tree virtual table.
169063 ** argv[0] -> module name
169064 ** argv[1] -> database name
169065 ** argv[2] -> table name
169066 ** argv[...] -> column names...
169068 static int rtreeInit(
169069 sqlite3 *db, /* Database connection */
169070 void *pAux, /* One of the RTREE_COORD_* constants */
169071 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
169072 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
169073 char **pzErr, /* OUT: Error message, if any */
169074 int isCreate /* True for xCreate, false for xConnect */
169076 int rc = SQLITE_OK;
169077 Rtree *pRtree;
169078 int nDb; /* Length of string argv[1] */
169079 int nName; /* Length of string argv[2] */
169080 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
169082 const char *aErrMsg[] = {
169083 0, /* 0 */
169084 "Wrong number of columns for an rtree table", /* 1 */
169085 "Too few columns for an rtree table", /* 2 */
169086 "Too many columns for an rtree table" /* 3 */
169089 int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
169090 if( aErrMsg[iErr] ){
169091 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
169092 return SQLITE_ERROR;
169095 sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
169097 /* Allocate the sqlite3_vtab structure */
169098 nDb = (int)strlen(argv[1]);
169099 nName = (int)strlen(argv[2]);
169100 pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
169101 if( !pRtree ){
169102 return SQLITE_NOMEM;
169104 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
169105 pRtree->nBusy = 1;
169106 pRtree->base.pModule = &rtreeModule;
169107 pRtree->zDb = (char *)&pRtree[1];
169108 pRtree->zName = &pRtree->zDb[nDb+1];
169109 pRtree->nDim = (u8)((argc-4)/2);
169110 pRtree->nDim2 = pRtree->nDim*2;
169111 pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
169112 pRtree->eCoordType = (u8)eCoordType;
169113 memcpy(pRtree->zDb, argv[1], nDb);
169114 memcpy(pRtree->zName, argv[2], nName);
169116 /* Figure out the node size to use. */
169117 rc = getNodeSize(db, pRtree, isCreate, pzErr);
169119 /* Create/Connect to the underlying relational database schema. If
169120 ** that is successful, call sqlite3_declare_vtab() to configure
169121 ** the r-tree table schema.
169123 if( rc==SQLITE_OK ){
169124 if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
169125 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
169126 }else{
169127 char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
169128 char *zTmp;
169129 int ii;
169130 for(ii=4; zSql && ii<argc; ii++){
169131 zTmp = zSql;
169132 zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
169133 sqlite3_free(zTmp);
169135 if( zSql ){
169136 zTmp = zSql;
169137 zSql = sqlite3_mprintf("%s);", zTmp);
169138 sqlite3_free(zTmp);
169140 if( !zSql ){
169141 rc = SQLITE_NOMEM;
169142 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
169143 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
169145 sqlite3_free(zSql);
169149 if( rc==SQLITE_OK ){
169150 *ppVtab = (sqlite3_vtab *)pRtree;
169151 }else{
169152 assert( *ppVtab==0 );
169153 assert( pRtree->nBusy==1 );
169154 rtreeRelease(pRtree);
169156 return rc;
169161 ** Implementation of a scalar function that decodes r-tree nodes to
169162 ** human readable strings. This can be used for debugging and analysis.
169164 ** The scalar function takes two arguments: (1) the number of dimensions
169165 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
169166 ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
169167 ** deserialize all nodes, a statement like:
169169 ** SELECT rtreenode(2, data) FROM rt_node;
169171 ** The human readable string takes the form of a Tcl list with one
169172 ** entry for each cell in the r-tree node. Each entry is itself a
169173 ** list, containing the 8-byte rowid/pageno followed by the
169174 ** <num-dimension>*2 coordinates.
169176 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
169177 char *zText = 0;
169178 RtreeNode node;
169179 Rtree tree;
169180 int ii;
169182 UNUSED_PARAMETER(nArg);
169183 memset(&node, 0, sizeof(RtreeNode));
169184 memset(&tree, 0, sizeof(Rtree));
169185 tree.nDim = (u8)sqlite3_value_int(apArg[0]);
169186 tree.nDim2 = tree.nDim*2;
169187 tree.nBytesPerCell = 8 + 8 * tree.nDim;
169188 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
169190 for(ii=0; ii<NCELL(&node); ii++){
169191 char zCell[512];
169192 int nCell = 0;
169193 RtreeCell cell;
169194 int jj;
169196 nodeGetCell(&tree, &node, ii, &cell);
169197 sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
169198 nCell = (int)strlen(zCell);
169199 for(jj=0; jj<tree.nDim2; jj++){
169200 #ifndef SQLITE_RTREE_INT_ONLY
169201 sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
169202 (double)cell.aCoord[jj].f);
169203 #else
169204 sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
169205 cell.aCoord[jj].i);
169206 #endif
169207 nCell = (int)strlen(zCell);
169210 if( zText ){
169211 char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
169212 sqlite3_free(zText);
169213 zText = zTextNew;
169214 }else{
169215 zText = sqlite3_mprintf("{%s}", zCell);
169219 sqlite3_result_text(ctx, zText, -1, sqlite3_free);
169222 /* This routine implements an SQL function that returns the "depth" parameter
169223 ** from the front of a blob that is an r-tree node. For example:
169225 ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
169227 ** The depth value is 0 for all nodes other than the root node, and the root
169228 ** node always has nodeno=1, so the example above is the primary use for this
169229 ** routine. This routine is intended for testing and analysis only.
169231 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
169232 UNUSED_PARAMETER(nArg);
169233 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
169234 || sqlite3_value_bytes(apArg[0])<2
169236 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
169237 }else{
169238 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
169239 sqlite3_result_int(ctx, readInt16(zBlob));
169244 ** Register the r-tree module with database handle db. This creates the
169245 ** virtual table module "rtree" and the debugging/analysis scalar
169246 ** function "rtreenode".
169248 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
169249 const int utf8 = SQLITE_UTF8;
169250 int rc;
169252 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
169253 if( rc==SQLITE_OK ){
169254 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
169256 if( rc==SQLITE_OK ){
169257 #ifdef SQLITE_RTREE_INT_ONLY
169258 void *c = (void *)RTREE_COORD_INT32;
169259 #else
169260 void *c = (void *)RTREE_COORD_REAL32;
169261 #endif
169262 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
169264 if( rc==SQLITE_OK ){
169265 void *c = (void *)RTREE_COORD_INT32;
169266 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
169269 return rc;
169273 ** This routine deletes the RtreeGeomCallback object that was attached
169274 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
169275 ** or sqlite3_rtree_query_callback(). In other words, this routine is the
169276 ** destructor for an RtreeGeomCallback objecct. This routine is called when
169277 ** the corresponding SQL function is deleted.
169279 static void rtreeFreeCallback(void *p){
169280 RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
169281 if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
169282 sqlite3_free(p);
169286 ** This routine frees the BLOB that is returned by geomCallback().
169288 static void rtreeMatchArgFree(void *pArg){
169289 int i;
169290 RtreeMatchArg *p = (RtreeMatchArg*)pArg;
169291 for(i=0; i<p->nParam; i++){
169292 sqlite3_value_free(p->apSqlParam[i]);
169294 sqlite3_free(p);
169298 ** Each call to sqlite3_rtree_geometry_callback() or
169299 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
169300 ** scalar function that is implemented by this routine.
169302 ** All this function does is construct an RtreeMatchArg object that
169303 ** contains the geometry-checking callback routines and a list of
169304 ** parameters to this function, then return that RtreeMatchArg object
169305 ** as a BLOB.
169307 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
169308 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
169309 ** out which elements of the R-Tree should be returned by the query.
169311 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
169312 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
169313 RtreeMatchArg *pBlob;
169314 int nBlob;
169315 int memErr = 0;
169317 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
169318 + nArg*sizeof(sqlite3_value*);
169319 pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
169320 if( !pBlob ){
169321 sqlite3_result_error_nomem(ctx);
169322 }else{
169323 int i;
169324 pBlob->iSize = nBlob;
169325 pBlob->cb = pGeomCtx[0];
169326 pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
169327 pBlob->nParam = nArg;
169328 for(i=0; i<nArg; i++){
169329 pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
169330 if( pBlob->apSqlParam[i]==0 ) memErr = 1;
169331 #ifdef SQLITE_RTREE_INT_ONLY
169332 pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
169333 #else
169334 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
169335 #endif
169337 if( memErr ){
169338 sqlite3_result_error_nomem(ctx);
169339 rtreeMatchArgFree(pBlob);
169340 }else{
169341 sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
169347 ** Register a new geometry function for use with the r-tree MATCH operator.
169349 SQLITE_API int sqlite3_rtree_geometry_callback(
169350 sqlite3 *db, /* Register SQL function on this connection */
169351 const char *zGeom, /* Name of the new SQL function */
169352 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
169353 void *pContext /* Extra data associated with the callback */
169355 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
169357 /* Allocate and populate the context object. */
169358 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
169359 if( !pGeomCtx ) return SQLITE_NOMEM;
169360 pGeomCtx->xGeom = xGeom;
169361 pGeomCtx->xQueryFunc = 0;
169362 pGeomCtx->xDestructor = 0;
169363 pGeomCtx->pContext = pContext;
169364 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
169365 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
169370 ** Register a new 2nd-generation geometry function for use with the
169371 ** r-tree MATCH operator.
169373 SQLITE_API int sqlite3_rtree_query_callback(
169374 sqlite3 *db, /* Register SQL function on this connection */
169375 const char *zQueryFunc, /* Name of new SQL function */
169376 int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
169377 void *pContext, /* Extra data passed into the callback */
169378 void (*xDestructor)(void*) /* Destructor for the extra data */
169380 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
169382 /* Allocate and populate the context object. */
169383 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
169384 if( !pGeomCtx ) return SQLITE_NOMEM;
169385 pGeomCtx->xGeom = 0;
169386 pGeomCtx->xQueryFunc = xQueryFunc;
169387 pGeomCtx->xDestructor = xDestructor;
169388 pGeomCtx->pContext = pContext;
169389 return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
169390 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
169394 #if !SQLITE_CORE
169395 #ifdef _WIN32
169396 __declspec(dllexport)
169397 #endif
169398 SQLITE_API int sqlite3_rtree_init(
169399 sqlite3 *db,
169400 char **pzErrMsg,
169401 const sqlite3_api_routines *pApi
169403 SQLITE_EXTENSION_INIT2(pApi)
169404 return sqlite3RtreeInit(db);
169406 #endif
169408 #endif
169410 /************** End of rtree.c ***********************************************/
169411 /************** Begin file icu.c *********************************************/
169413 ** 2007 May 6
169415 ** The author disclaims copyright to this source code. In place of
169416 ** a legal notice, here is a blessing:
169418 ** May you do good and not evil.
169419 ** May you find forgiveness for yourself and forgive others.
169420 ** May you share freely, never taking more than you give.
169422 *************************************************************************
169423 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
169425 ** This file implements an integration between the ICU library
169426 ** ("International Components for Unicode", an open-source library
169427 ** for handling unicode data) and SQLite. The integration uses
169428 ** ICU to provide the following to SQLite:
169430 ** * An implementation of the SQL regexp() function (and hence REGEXP
169431 ** operator) using the ICU uregex_XX() APIs.
169433 ** * Implementations of the SQL scalar upper() and lower() functions
169434 ** for case mapping.
169436 ** * Integration of ICU and SQLite collation sequences.
169438 ** * An implementation of the LIKE operator that uses ICU to
169439 ** provide case-independent matching.
169442 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
169444 /* Include ICU headers */
169445 #include <unicode/utypes.h>
169446 #include <unicode/uregex.h>
169447 #include <unicode/ustring.h>
169448 #include <unicode/ucol.h>
169450 /* #include <assert.h> */
169452 #ifndef SQLITE_CORE
169453 /* #include "sqlite3ext.h" */
169454 SQLITE_EXTENSION_INIT1
169455 #else
169456 /* #include "sqlite3.h" */
169457 #endif
169460 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
169461 ** operator.
169463 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
169464 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
169465 #endif
169468 ** Version of sqlite3_free() that is always a function, never a macro.
169470 static void xFree(void *p){
169471 sqlite3_free(p);
169475 ** This lookup table is used to help decode the first byte of
169476 ** a multi-byte UTF8 character. It is copied here from SQLite source
169477 ** code file utf8.c.
169479 static const unsigned char icuUtf8Trans1[] = {
169480 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
169481 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
169482 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
169483 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
169484 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
169485 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
169486 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
169487 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
169490 #define SQLITE_ICU_READ_UTF8(zIn, c) \
169491 c = *(zIn++); \
169492 if( c>=0xc0 ){ \
169493 c = icuUtf8Trans1[c-0xc0]; \
169494 while( (*zIn & 0xc0)==0x80 ){ \
169495 c = (c<<6) + (0x3f & *(zIn++)); \
169499 #define SQLITE_ICU_SKIP_UTF8(zIn) \
169500 assert( *zIn ); \
169501 if( *(zIn++)>=0xc0 ){ \
169502 while( (*zIn & 0xc0)==0x80 ){zIn++;} \
169507 ** Compare two UTF-8 strings for equality where the first string is
169508 ** a "LIKE" expression. Return true (1) if they are the same and
169509 ** false (0) if they are different.
169511 static int icuLikeCompare(
169512 const uint8_t *zPattern, /* LIKE pattern */
169513 const uint8_t *zString, /* The UTF-8 string to compare against */
169514 const UChar32 uEsc /* The escape character */
169516 static const uint32_t MATCH_ONE = (uint32_t)'_';
169517 static const uint32_t MATCH_ALL = (uint32_t)'%';
169519 int prevEscape = 0; /* True if the previous character was uEsc */
169521 while( 1 ){
169523 /* Read (and consume) the next character from the input pattern. */
169524 uint32_t uPattern;
169525 SQLITE_ICU_READ_UTF8(zPattern, uPattern);
169526 if( uPattern==0 ) break;
169528 /* There are now 4 possibilities:
169530 ** 1. uPattern is an unescaped match-all character "%",
169531 ** 2. uPattern is an unescaped match-one character "_",
169532 ** 3. uPattern is an unescaped escape character, or
169533 ** 4. uPattern is to be handled as an ordinary character
169535 if( !prevEscape && uPattern==MATCH_ALL ){
169536 /* Case 1. */
169537 uint8_t c;
169539 /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
169540 ** MATCH_ALL. For each MATCH_ONE, skip one character in the
169541 ** test string.
169543 while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
169544 if( c==MATCH_ONE ){
169545 if( *zString==0 ) return 0;
169546 SQLITE_ICU_SKIP_UTF8(zString);
169548 zPattern++;
169551 if( *zPattern==0 ) return 1;
169553 while( *zString ){
169554 if( icuLikeCompare(zPattern, zString, uEsc) ){
169555 return 1;
169557 SQLITE_ICU_SKIP_UTF8(zString);
169559 return 0;
169561 }else if( !prevEscape && uPattern==MATCH_ONE ){
169562 /* Case 2. */
169563 if( *zString==0 ) return 0;
169564 SQLITE_ICU_SKIP_UTF8(zString);
169566 }else if( !prevEscape && uPattern==(uint32_t)uEsc){
169567 /* Case 3. */
169568 prevEscape = 1;
169570 }else{
169571 /* Case 4. */
169572 uint32_t uString;
169573 SQLITE_ICU_READ_UTF8(zString, uString);
169574 uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
169575 uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
169576 if( uString!=uPattern ){
169577 return 0;
169579 prevEscape = 0;
169583 return *zString==0;
169587 ** Implementation of the like() SQL function. This function implements
169588 ** the build-in LIKE operator. The first argument to the function is the
169589 ** pattern and the second argument is the string. So, the SQL statements:
169591 ** A LIKE B
169593 ** is implemented as like(B, A). If there is an escape character E,
169595 ** A LIKE B ESCAPE E
169597 ** is mapped to like(B, A, E).
169599 static void icuLikeFunc(
169600 sqlite3_context *context,
169601 int argc,
169602 sqlite3_value **argv
169604 const unsigned char *zA = sqlite3_value_text(argv[0]);
169605 const unsigned char *zB = sqlite3_value_text(argv[1]);
169606 UChar32 uEsc = 0;
169608 /* Limit the length of the LIKE or GLOB pattern to avoid problems
169609 ** of deep recursion and N*N behavior in patternCompare().
169611 if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
169612 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
169613 return;
169617 if( argc==3 ){
169618 /* The escape character string must consist of a single UTF-8 character.
169619 ** Otherwise, return an error.
169621 int nE= sqlite3_value_bytes(argv[2]);
169622 const unsigned char *zE = sqlite3_value_text(argv[2]);
169623 int i = 0;
169624 if( zE==0 ) return;
169625 U8_NEXT(zE, i, nE, uEsc);
169626 if( i!=nE){
169627 sqlite3_result_error(context,
169628 "ESCAPE expression must be a single character", -1);
169629 return;
169633 if( zA && zB ){
169634 sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
169639 ** This function is called when an ICU function called from within
169640 ** the implementation of an SQL scalar function returns an error.
169642 ** The scalar function context passed as the first argument is
169643 ** loaded with an error message based on the following two args.
169645 static void icuFunctionError(
169646 sqlite3_context *pCtx, /* SQLite scalar function context */
169647 const char *zName, /* Name of ICU function that failed */
169648 UErrorCode e /* Error code returned by ICU function */
169650 char zBuf[128];
169651 sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
169652 zBuf[127] = '\0';
169653 sqlite3_result_error(pCtx, zBuf, -1);
169657 ** Function to delete compiled regexp objects. Registered as
169658 ** a destructor function with sqlite3_set_auxdata().
169660 static void icuRegexpDelete(void *p){
169661 URegularExpression *pExpr = (URegularExpression *)p;
169662 uregex_close(pExpr);
169666 ** Implementation of SQLite REGEXP operator. This scalar function takes
169667 ** two arguments. The first is a regular expression pattern to compile
169668 ** the second is a string to match against that pattern. If either
169669 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
169670 ** is 1 if the string matches the pattern, or 0 otherwise.
169672 ** SQLite maps the regexp() function to the regexp() operator such
169673 ** that the following two are equivalent:
169675 ** zString REGEXP zPattern
169676 ** regexp(zPattern, zString)
169678 ** Uses the following ICU regexp APIs:
169680 ** uregex_open()
169681 ** uregex_matches()
169682 ** uregex_close()
169684 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
169685 UErrorCode status = U_ZERO_ERROR;
169686 URegularExpression *pExpr;
169687 UBool res;
169688 const UChar *zString = sqlite3_value_text16(apArg[1]);
169690 (void)nArg; /* Unused parameter */
169692 /* If the left hand side of the regexp operator is NULL,
169693 ** then the result is also NULL.
169695 if( !zString ){
169696 return;
169699 pExpr = sqlite3_get_auxdata(p, 0);
169700 if( !pExpr ){
169701 const UChar *zPattern = sqlite3_value_text16(apArg[0]);
169702 if( !zPattern ){
169703 return;
169705 pExpr = uregex_open(zPattern, -1, 0, 0, &status);
169707 if( U_SUCCESS(status) ){
169708 sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
169709 }else{
169710 assert(!pExpr);
169711 icuFunctionError(p, "uregex_open", status);
169712 return;
169716 /* Configure the text that the regular expression operates on. */
169717 uregex_setText(pExpr, zString, -1, &status);
169718 if( !U_SUCCESS(status) ){
169719 icuFunctionError(p, "uregex_setText", status);
169720 return;
169723 /* Attempt the match */
169724 res = uregex_matches(pExpr, 0, &status);
169725 if( !U_SUCCESS(status) ){
169726 icuFunctionError(p, "uregex_matches", status);
169727 return;
169730 /* Set the text that the regular expression operates on to a NULL
169731 ** pointer. This is not really necessary, but it is tidier than
169732 ** leaving the regular expression object configured with an invalid
169733 ** pointer after this function returns.
169735 uregex_setText(pExpr, 0, 0, &status);
169737 /* Return 1 or 0. */
169738 sqlite3_result_int(p, res ? 1 : 0);
169742 ** Implementations of scalar functions for case mapping - upper() and
169743 ** lower(). Function upper() converts its input to upper-case (ABC).
169744 ** Function lower() converts to lower-case (abc).
169746 ** ICU provides two types of case mapping, "general" case mapping and
169747 ** "language specific". Refer to ICU documentation for the differences
169748 ** between the two.
169750 ** To utilise "general" case mapping, the upper() or lower() scalar
169751 ** functions are invoked with one argument:
169753 ** upper('ABC') -> 'abc'
169754 ** lower('abc') -> 'ABC'
169756 ** To access ICU "language specific" case mapping, upper() or lower()
169757 ** should be invoked with two arguments. The second argument is the name
169758 ** of the locale to use. Passing an empty string ("") or SQL NULL value
169759 ** as the second argument is the same as invoking the 1 argument version
169760 ** of upper() or lower().
169762 ** lower('I', 'en_us') -> 'i'
169763 ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
169765 ** http://www.icu-project.org/userguide/posix.html#case_mappings
169767 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
169768 const UChar *zInput; /* Pointer to input string */
169769 UChar *zOutput = 0; /* Pointer to output buffer */
169770 int nInput; /* Size of utf-16 input string in bytes */
169771 int nOut; /* Size of output buffer in bytes */
169772 int cnt;
169773 int bToUpper; /* True for toupper(), false for tolower() */
169774 UErrorCode status;
169775 const char *zLocale = 0;
169777 assert(nArg==1 || nArg==2);
169778 bToUpper = (sqlite3_user_data(p)!=0);
169779 if( nArg==2 ){
169780 zLocale = (const char *)sqlite3_value_text(apArg[1]);
169783 zInput = sqlite3_value_text16(apArg[0]);
169784 if( !zInput ){
169785 return;
169787 nOut = nInput = sqlite3_value_bytes16(apArg[0]);
169788 if( nOut==0 ){
169789 sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
169790 return;
169793 for(cnt=0; cnt<2; cnt++){
169794 UChar *zNew = sqlite3_realloc(zOutput, nOut);
169795 if( zNew==0 ){
169796 sqlite3_free(zOutput);
169797 sqlite3_result_error_nomem(p);
169798 return;
169800 zOutput = zNew;
169801 status = U_ZERO_ERROR;
169802 if( bToUpper ){
169803 nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
169804 }else{
169805 nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
169808 if( U_SUCCESS(status) ){
169809 sqlite3_result_text16(p, zOutput, nOut, xFree);
169810 }else if( status==U_BUFFER_OVERFLOW_ERROR ){
169811 assert( cnt==0 );
169812 continue;
169813 }else{
169814 icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
169816 return;
169818 assert( 0 ); /* Unreachable */
169822 ** Collation sequence destructor function. The pCtx argument points to
169823 ** a UCollator structure previously allocated using ucol_open().
169825 static void icuCollationDel(void *pCtx){
169826 UCollator *p = (UCollator *)pCtx;
169827 ucol_close(p);
169831 ** Collation sequence comparison function. The pCtx argument points to
169832 ** a UCollator structure previously allocated using ucol_open().
169834 static int icuCollationColl(
169835 void *pCtx,
169836 int nLeft,
169837 const void *zLeft,
169838 int nRight,
169839 const void *zRight
169841 UCollationResult res;
169842 UCollator *p = (UCollator *)pCtx;
169843 res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
169844 switch( res ){
169845 case UCOL_LESS: return -1;
169846 case UCOL_GREATER: return +1;
169847 case UCOL_EQUAL: return 0;
169849 assert(!"Unexpected return value from ucol_strcoll()");
169850 return 0;
169854 ** Implementation of the scalar function icu_load_collation().
169856 ** This scalar function is used to add ICU collation based collation
169857 ** types to an SQLite database connection. It is intended to be called
169858 ** as follows:
169860 ** SELECT icu_load_collation(<locale>, <collation-name>);
169862 ** Where <locale> is a string containing an ICU locale identifier (i.e.
169863 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
169864 ** collation sequence to create.
169866 static void icuLoadCollation(
169867 sqlite3_context *p,
169868 int nArg,
169869 sqlite3_value **apArg
169871 sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
169872 UErrorCode status = U_ZERO_ERROR;
169873 const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
169874 const char *zName; /* SQL Collation sequence name (eg. "japanese") */
169875 UCollator *pUCollator; /* ICU library collation object */
169876 int rc; /* Return code from sqlite3_create_collation_x() */
169878 assert(nArg==2);
169879 (void)nArg; /* Unused parameter */
169880 zLocale = (const char *)sqlite3_value_text(apArg[0]);
169881 zName = (const char *)sqlite3_value_text(apArg[1]);
169883 if( !zLocale || !zName ){
169884 return;
169887 pUCollator = ucol_open(zLocale, &status);
169888 if( !U_SUCCESS(status) ){
169889 icuFunctionError(p, "ucol_open", status);
169890 return;
169892 assert(p);
169894 rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
169895 icuCollationColl, icuCollationDel
169897 if( rc!=SQLITE_OK ){
169898 ucol_close(pUCollator);
169899 sqlite3_result_error(p, "Error registering collation function", -1);
169904 ** Register the ICU extension functions with database db.
169906 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
169907 static const struct IcuScalar {
169908 const char *zName; /* Function name */
169909 unsigned char nArg; /* Number of arguments */
169910 unsigned short enc; /* Optimal text encoding */
169911 unsigned char iContext; /* sqlite3_user_data() context */
169912 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
169913 } scalars[] = {
169914 {"icu_load_collation", 2, SQLITE_UTF8, 1, icuLoadCollation},
169915 {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc},
169916 {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
169917 {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
169918 {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
169919 {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
169920 {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
169921 {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
169922 {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
169923 {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
169924 {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
169925 {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
169927 int rc = SQLITE_OK;
169928 int i;
169931 for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
169932 const struct IcuScalar *p = &scalars[i];
169933 rc = sqlite3_create_function(
169934 db, p->zName, p->nArg, p->enc,
169935 p->iContext ? (void*)db : (void*)0,
169936 p->xFunc, 0, 0
169940 return rc;
169943 #if !SQLITE_CORE
169944 #ifdef _WIN32
169945 __declspec(dllexport)
169946 #endif
169947 SQLITE_API int sqlite3_icu_init(
169948 sqlite3 *db,
169949 char **pzErrMsg,
169950 const sqlite3_api_routines *pApi
169952 SQLITE_EXTENSION_INIT2(pApi)
169953 return sqlite3IcuInit(db);
169955 #endif
169957 #endif
169959 /************** End of icu.c *************************************************/
169960 /************** Begin file fts3_icu.c ****************************************/
169962 ** 2007 June 22
169964 ** The author disclaims copyright to this source code. In place of
169965 ** a legal notice, here is a blessing:
169967 ** May you do good and not evil.
169968 ** May you find forgiveness for yourself and forgive others.
169969 ** May you share freely, never taking more than you give.
169971 *************************************************************************
169972 ** This file implements a tokenizer for fts3 based on the ICU library.
169974 /* #include "fts3Int.h" */
169975 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
169976 #ifdef SQLITE_ENABLE_ICU
169978 /* #include <assert.h> */
169979 /* #include <string.h> */
169980 /* #include "fts3_tokenizer.h" */
169982 #include <unicode/ubrk.h>
169983 /* #include <unicode/ucol.h> */
169984 /* #include <unicode/ustring.h> */
169985 #include <unicode/utf16.h>
169987 typedef struct IcuTokenizer IcuTokenizer;
169988 typedef struct IcuCursor IcuCursor;
169990 struct IcuTokenizer {
169991 sqlite3_tokenizer base;
169992 char *zLocale;
169995 struct IcuCursor {
169996 sqlite3_tokenizer_cursor base;
169998 UBreakIterator *pIter; /* ICU break-iterator object */
169999 int nChar; /* Number of UChar elements in pInput */
170000 UChar *aChar; /* Copy of input using utf-16 encoding */
170001 int *aOffset; /* Offsets of each character in utf-8 input */
170003 int nBuffer;
170004 char *zBuffer;
170006 int iToken;
170010 ** Create a new tokenizer instance.
170012 static int icuCreate(
170013 int argc, /* Number of entries in argv[] */
170014 const char * const *argv, /* Tokenizer creation arguments */
170015 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
170017 IcuTokenizer *p;
170018 int n = 0;
170020 if( argc>0 ){
170021 n = strlen(argv[0])+1;
170023 p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
170024 if( !p ){
170025 return SQLITE_NOMEM;
170027 memset(p, 0, sizeof(IcuTokenizer));
170029 if( n ){
170030 p->zLocale = (char *)&p[1];
170031 memcpy(p->zLocale, argv[0], n);
170034 *ppTokenizer = (sqlite3_tokenizer *)p;
170036 return SQLITE_OK;
170040 ** Destroy a tokenizer
170042 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
170043 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
170044 sqlite3_free(p);
170045 return SQLITE_OK;
170049 ** Prepare to begin tokenizing a particular string. The input
170050 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
170051 ** used to incrementally tokenize this string is returned in
170052 ** *ppCursor.
170054 static int icuOpen(
170055 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
170056 const char *zInput, /* Input string */
170057 int nInput, /* Length of zInput in bytes */
170058 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
170060 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
170061 IcuCursor *pCsr;
170063 const int32_t opt = U_FOLD_CASE_DEFAULT;
170064 UErrorCode status = U_ZERO_ERROR;
170065 int nChar;
170067 UChar32 c;
170068 int iInput = 0;
170069 int iOut = 0;
170071 *ppCursor = 0;
170073 if( zInput==0 ){
170074 nInput = 0;
170075 zInput = "";
170076 }else if( nInput<0 ){
170077 nInput = strlen(zInput);
170079 nChar = nInput+1;
170080 pCsr = (IcuCursor *)sqlite3_malloc(
170081 sizeof(IcuCursor) + /* IcuCursor */
170082 ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
170083 (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
170085 if( !pCsr ){
170086 return SQLITE_NOMEM;
170088 memset(pCsr, 0, sizeof(IcuCursor));
170089 pCsr->aChar = (UChar *)&pCsr[1];
170090 pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
170092 pCsr->aOffset[iOut] = iInput;
170093 U8_NEXT(zInput, iInput, nInput, c);
170094 while( c>0 ){
170095 int isError = 0;
170096 c = u_foldCase(c, opt);
170097 U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
170098 if( isError ){
170099 sqlite3_free(pCsr);
170100 return SQLITE_ERROR;
170102 pCsr->aOffset[iOut] = iInput;
170104 if( iInput<nInput ){
170105 U8_NEXT(zInput, iInput, nInput, c);
170106 }else{
170107 c = 0;
170111 pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
170112 if( !U_SUCCESS(status) ){
170113 sqlite3_free(pCsr);
170114 return SQLITE_ERROR;
170116 pCsr->nChar = iOut;
170118 ubrk_first(pCsr->pIter);
170119 *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
170120 return SQLITE_OK;
170124 ** Close a tokenization cursor previously opened by a call to icuOpen().
170126 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
170127 IcuCursor *pCsr = (IcuCursor *)pCursor;
170128 ubrk_close(pCsr->pIter);
170129 sqlite3_free(pCsr->zBuffer);
170130 sqlite3_free(pCsr);
170131 return SQLITE_OK;
170135 ** Extract the next token from a tokenization cursor.
170137 static int icuNext(
170138 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
170139 const char **ppToken, /* OUT: *ppToken is the token text */
170140 int *pnBytes, /* OUT: Number of bytes in token */
170141 int *piStartOffset, /* OUT: Starting offset of token */
170142 int *piEndOffset, /* OUT: Ending offset of token */
170143 int *piPosition /* OUT: Position integer of token */
170145 IcuCursor *pCsr = (IcuCursor *)pCursor;
170147 int iStart = 0;
170148 int iEnd = 0;
170149 int nByte = 0;
170151 while( iStart==iEnd ){
170152 UChar32 c;
170154 iStart = ubrk_current(pCsr->pIter);
170155 iEnd = ubrk_next(pCsr->pIter);
170156 if( iEnd==UBRK_DONE ){
170157 return SQLITE_DONE;
170160 while( iStart<iEnd ){
170161 int iWhite = iStart;
170162 U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
170163 if( u_isspace(c) ){
170164 iStart = iWhite;
170165 }else{
170166 break;
170169 assert(iStart<=iEnd);
170173 UErrorCode status = U_ZERO_ERROR;
170174 if( nByte ){
170175 char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
170176 if( !zNew ){
170177 return SQLITE_NOMEM;
170179 pCsr->zBuffer = zNew;
170180 pCsr->nBuffer = nByte;
170183 u_strToUTF8(
170184 pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
170185 &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
170186 &status /* Output success/failure */
170188 } while( nByte>pCsr->nBuffer );
170190 *ppToken = pCsr->zBuffer;
170191 *pnBytes = nByte;
170192 *piStartOffset = pCsr->aOffset[iStart];
170193 *piEndOffset = pCsr->aOffset[iEnd];
170194 *piPosition = pCsr->iToken++;
170196 return SQLITE_OK;
170200 ** The set of routines that implement the simple tokenizer
170202 static const sqlite3_tokenizer_module icuTokenizerModule = {
170203 0, /* iVersion */
170204 icuCreate, /* xCreate */
170205 icuDestroy, /* xCreate */
170206 icuOpen, /* xOpen */
170207 icuClose, /* xClose */
170208 icuNext, /* xNext */
170209 0, /* xLanguageid */
170213 ** Set *ppModule to point at the implementation of the ICU tokenizer.
170215 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
170216 sqlite3_tokenizer_module const**ppModule
170218 *ppModule = &icuTokenizerModule;
170221 #endif /* defined(SQLITE_ENABLE_ICU) */
170222 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
170224 /************** End of fts3_icu.c ********************************************/
170225 /************** Begin file sqlite3rbu.c **************************************/
170227 ** 2014 August 30
170229 ** The author disclaims copyright to this source code. In place of
170230 ** a legal notice, here is a blessing:
170232 ** May you do good and not evil.
170233 ** May you find forgiveness for yourself and forgive others.
170234 ** May you share freely, never taking more than you give.
170236 *************************************************************************
170239 ** OVERVIEW
170241 ** The RBU extension requires that the RBU update be packaged as an
170242 ** SQLite database. The tables it expects to find are described in
170243 ** sqlite3rbu.h. Essentially, for each table xyz in the target database
170244 ** that the user wishes to write to, a corresponding data_xyz table is
170245 ** created in the RBU database and populated with one row for each row to
170246 ** update, insert or delete from the target table.
170248 ** The update proceeds in three stages:
170250 ** 1) The database is updated. The modified database pages are written
170251 ** to a *-oal file. A *-oal file is just like a *-wal file, except
170252 ** that it is named "<database>-oal" instead of "<database>-wal".
170253 ** Because regular SQLite clients do not look for file named
170254 ** "<database>-oal", they go on using the original database in
170255 ** rollback mode while the *-oal file is being generated.
170257 ** During this stage RBU does not update the database by writing
170258 ** directly to the target tables. Instead it creates "imposter"
170259 ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
170260 ** to update each b-tree individually. All updates required by each
170261 ** b-tree are completed before moving on to the next, and all
170262 ** updates are done in sorted key order.
170264 ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
170265 ** location using a call to rename(2). Before doing this the RBU
170266 ** module takes an EXCLUSIVE lock on the database file, ensuring
170267 ** that there are no other active readers.
170269 ** Once the EXCLUSIVE lock is released, any other database readers
170270 ** detect the new *-wal file and read the database in wal mode. At
170271 ** this point they see the new version of the database - including
170272 ** the updates made as part of the RBU update.
170274 ** 3) The new *-wal file is checkpointed. This proceeds in the same way
170275 ** as a regular database checkpoint, except that a single frame is
170276 ** checkpointed each time sqlite3rbu_step() is called. If the RBU
170277 ** handle is closed before the entire *-wal file is checkpointed,
170278 ** the checkpoint progress is saved in the RBU database and the
170279 ** checkpoint can be resumed by another RBU client at some point in
170280 ** the future.
170282 ** POTENTIAL PROBLEMS
170284 ** The rename() call might not be portable. And RBU is not currently
170285 ** syncing the directory after renaming the file.
170287 ** When state is saved, any commit to the *-oal file and the commit to
170288 ** the RBU update database are not atomic. So if the power fails at the
170289 ** wrong moment they might get out of sync. As the main database will be
170290 ** committed before the RBU update database this will likely either just
170291 ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
170292 ** constraint violations).
170294 ** If some client does modify the target database mid RBU update, or some
170295 ** other error occurs, the RBU extension will keep throwing errors. It's
170296 ** not really clear how to get out of this state. The system could just
170297 ** by delete the RBU update database and *-oal file and have the device
170298 ** download the update again and start over.
170300 ** At present, for an UPDATE, both the new.* and old.* records are
170301 ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
170302 ** fields are collected. This means we're probably writing a lot more
170303 ** data to disk when saving the state of an ongoing update to the RBU
170304 ** update database than is strictly necessary.
170308 /* #include <assert.h> */
170309 /* #include <string.h> */
170310 /* #include <stdio.h> */
170312 /* #include "sqlite3.h" */
170314 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
170315 /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
170316 /************** Begin file sqlite3rbu.h **************************************/
170318 ** 2014 August 30
170320 ** The author disclaims copyright to this source code. In place of
170321 ** a legal notice, here is a blessing:
170323 ** May you do good and not evil.
170324 ** May you find forgiveness for yourself and forgive others.
170325 ** May you share freely, never taking more than you give.
170327 *************************************************************************
170329 ** This file contains the public interface for the RBU extension.
170333 ** SUMMARY
170335 ** Writing a transaction containing a large number of operations on
170336 ** b-tree indexes that are collectively larger than the available cache
170337 ** memory can be very inefficient.
170339 ** The problem is that in order to update a b-tree, the leaf page (at least)
170340 ** containing the entry being inserted or deleted must be modified. If the
170341 ** working set of leaves is larger than the available cache memory, then a
170342 ** single leaf that is modified more than once as part of the transaction
170343 ** may be loaded from or written to the persistent media multiple times.
170344 ** Additionally, because the index updates are likely to be applied in
170345 ** random order, access to pages within the database is also likely to be in
170346 ** random order, which is itself quite inefficient.
170348 ** One way to improve the situation is to sort the operations on each index
170349 ** by index key before applying them to the b-tree. This leads to an IO
170350 ** pattern that resembles a single linear scan through the index b-tree,
170351 ** and all but guarantees each modified leaf page is loaded and stored
170352 ** exactly once. SQLite uses this trick to improve the performance of
170353 ** CREATE INDEX commands. This extension allows it to be used to improve
170354 ** the performance of large transactions on existing databases.
170356 ** Additionally, this extension allows the work involved in writing the
170357 ** large transaction to be broken down into sub-transactions performed
170358 ** sequentially by separate processes. This is useful if the system cannot
170359 ** guarantee that a single update process will run for long enough to apply
170360 ** the entire update, for example because the update is being applied on a
170361 ** mobile device that is frequently rebooted. Even after the writer process
170362 ** has committed one or more sub-transactions, other database clients continue
170363 ** to read from the original database snapshot. In other words, partially
170364 ** applied transactions are not visible to other clients.
170366 ** "RBU" stands for "Resumable Bulk Update". As in a large database update
170367 ** transmitted via a wireless network to a mobile device. A transaction
170368 ** applied using this extension is hence refered to as an "RBU update".
170371 ** LIMITATIONS
170373 ** An "RBU update" transaction is subject to the following limitations:
170375 ** * The transaction must consist of INSERT, UPDATE and DELETE operations
170376 ** only.
170378 ** * INSERT statements may not use any default values.
170380 ** * UPDATE and DELETE statements must identify their target rows by
170381 ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
170382 ** KEY fields may not be updated or deleted. If the table being written
170383 ** has no PRIMARY KEY, affected rows must be identified by rowid.
170385 ** * UPDATE statements may not modify PRIMARY KEY columns.
170387 ** * No triggers will be fired.
170389 ** * No foreign key violations are detected or reported.
170391 ** * CHECK constraints are not enforced.
170393 ** * No constraint handling mode except for "OR ROLLBACK" is supported.
170396 ** PREPARATION
170398 ** An "RBU update" is stored as a separate SQLite database. A database
170399 ** containing an RBU update is an "RBU database". For each table in the
170400 ** target database to be updated, the RBU database should contain a table
170401 ** named "data_<target name>" containing the same set of columns as the
170402 ** target table, and one more - "rbu_control". The data_% table should
170403 ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
170404 ** the same type as the corresponding column in the target database.
170405 ** The "rbu_control" column should have no type at all. For example, if
170406 ** the target database contains:
170408 ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
170410 ** Then the RBU database should contain:
170412 ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
170414 ** The order of the columns in the data_% table does not matter.
170416 ** Instead of a regular table, the RBU database may also contain virtual
170417 ** tables or view named using the data_<target> naming scheme.
170419 ** Instead of the plain data_<target> naming scheme, RBU database tables
170420 ** may also be named data<integer>_<target>, where <integer> is any sequence
170421 ** of zero or more numeric characters (0-9). This can be significant because
170422 ** tables within the RBU database are always processed in order sorted by
170423 ** name. By judicious selection of the <integer> portion of the names
170424 ** of the RBU tables the user can therefore control the order in which they
170425 ** are processed. This can be useful, for example, to ensure that "external
170426 ** content" FTS4 tables are updated before their underlying content tables.
170428 ** If the target database table is a virtual table or a table that has no
170429 ** PRIMARY KEY declaration, the data_% table must also contain a column
170430 ** named "rbu_rowid". This column is mapped to the tables implicit primary
170431 ** key column - "rowid". Virtual tables for which the "rowid" column does
170432 ** not function like a primary key value cannot be updated using RBU. For
170433 ** example, if the target db contains either of the following:
170435 ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
170436 ** CREATE TABLE x1(a, b)
170438 ** then the RBU database should contain:
170440 ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
170442 ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
170443 ** target table must be present in the input table. For virtual tables,
170444 ** hidden columns are optional - they are updated by RBU if present in
170445 ** the input table, or not otherwise. For example, to write to an fts4
170446 ** table with a hidden languageid column such as:
170448 ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
170450 ** Either of the following input table schemas may be used:
170452 ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
170453 ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
170455 ** For each row to INSERT into the target database as part of the RBU
170456 ** update, the corresponding data_% table should contain a single record
170457 ** with the "rbu_control" column set to contain integer value 0. The
170458 ** other columns should be set to the values that make up the new record
170459 ** to insert.
170461 ** If the target database table has an INTEGER PRIMARY KEY, it is not
170462 ** possible to insert a NULL value into the IPK column. Attempting to
170463 ** do so results in an SQLITE_MISMATCH error.
170465 ** For each row to DELETE from the target database as part of the RBU
170466 ** update, the corresponding data_% table should contain a single record
170467 ** with the "rbu_control" column set to contain integer value 1. The
170468 ** real primary key values of the row to delete should be stored in the
170469 ** corresponding columns of the data_% table. The values stored in the
170470 ** other columns are not used.
170472 ** For each row to UPDATE from the target database as part of the RBU
170473 ** update, the corresponding data_% table should contain a single record
170474 ** with the "rbu_control" column set to contain a value of type text.
170475 ** The real primary key values identifying the row to update should be
170476 ** stored in the corresponding columns of the data_% table row, as should
170477 ** the new values of all columns being update. The text value in the
170478 ** "rbu_control" column must contain the same number of characters as
170479 ** there are columns in the target database table, and must consist entirely
170480 ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
170481 ** each column that is being updated, the corresponding character is set to
170482 ** 'x'. For those that remain as they are, the corresponding character of the
170483 ** rbu_control value should be set to '.'. For example, given the tables
170484 ** above, the update statement:
170486 ** UPDATE t1 SET c = 'usa' WHERE a = 4;
170488 ** is represented by the data_t1 row created by:
170490 ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
170492 ** Instead of an 'x' character, characters of the rbu_control value specified
170493 ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
170494 ** target table with the value stored in the corresponding data_% column, the
170495 ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
170496 ** the target table column. rbu_delta() is invoked with two arguments - the
170497 ** original value currently stored in the target table column and the
170498 ** value specified in the data_xxx table.
170500 ** For example, this row:
170502 ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
170504 ** is similar to an UPDATE statement such as:
170506 ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
170508 ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
170509 ** ota_control string, the contents of the data_xxx table column is assumed
170510 ** to be a "fossil delta" - a patch to be applied to a blob value in the
170511 ** format used by the fossil source-code management system. In this case
170512 ** the existing value within the target database table must be of type BLOB.
170513 ** It is replaced by the result of applying the specified fossil delta to
170514 ** itself.
170516 ** If the target database table is a virtual table or a table with no PRIMARY
170517 ** KEY, the rbu_control value should not include a character corresponding
170518 ** to the rbu_rowid value. For example, this:
170520 ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
170521 ** VALUES(NULL, 'usa', 12, '.x');
170523 ** causes a result similar to:
170525 ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
170527 ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
170528 ** However, RBU is more efficient if reading the rows in from each data_xxx
170529 ** table in "rowid" order is roughly the same as reading them sorted by
170530 ** the PRIMARY KEY of the corresponding target database table. In other
170531 ** words, rows should be sorted using the destination table PRIMARY KEY
170532 ** fields before they are inserted into the data_xxx tables.
170534 ** USAGE
170536 ** The API declared below allows an application to apply an RBU update
170537 ** stored on disk to an existing target database. Essentially, the
170538 ** application:
170540 ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
170542 ** 2) Registers any required virtual table modules with the database
170543 ** handle returned by sqlite3rbu_db(). Also, if required, register
170544 ** the rbu_delta() implementation.
170546 ** 3) Calls the sqlite3rbu_step() function one or more times on
170547 ** the new handle. Each call to sqlite3rbu_step() performs a single
170548 ** b-tree operation, so thousands of calls may be required to apply
170549 ** a complete update.
170551 ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
170552 ** sqlite3rbu_step() has been called enough times to completely
170553 ** apply the update to the target database, then the RBU database
170554 ** is marked as fully applied. Otherwise, the state of the RBU
170555 ** update application is saved in the RBU database for later
170556 ** resumption.
170558 ** See comments below for more detail on APIs.
170560 ** If an update is only partially applied to the target database by the
170561 ** time sqlite3rbu_close() is called, various state information is saved
170562 ** within the RBU database. This allows subsequent processes to automatically
170563 ** resume the RBU update from where it left off.
170565 ** To remove all RBU extension state information, returning an RBU database
170566 ** to its original contents, it is sufficient to drop all tables that begin
170567 ** with the prefix "rbu_"
170569 ** DATABASE LOCKING
170571 ** An RBU update may not be applied to a database in WAL mode. Attempting
170572 ** to do so is an error (SQLITE_ERROR).
170574 ** While an RBU handle is open, a SHARED lock may be held on the target
170575 ** database file. This means it is possible for other clients to read the
170576 ** database, but not to write it.
170578 ** If an RBU update is started and then suspended before it is completed,
170579 ** then an external client writes to the database, then attempting to resume
170580 ** the suspended RBU update is also an error (SQLITE_BUSY).
170583 #ifndef _SQLITE3RBU_H
170584 #define _SQLITE3RBU_H
170586 /* #include "sqlite3.h" ** Required for error code definitions ** */
170588 #if 0
170589 extern "C" {
170590 #endif
170592 typedef struct sqlite3rbu sqlite3rbu;
170595 ** Open an RBU handle.
170597 ** Argument zTarget is the path to the target database. Argument zRbu is
170598 ** the path to the RBU database. Each call to this function must be matched
170599 ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
170600 ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
170601 ** or zRbu begin with "file:", it will be interpreted as an SQLite
170602 ** database URI, not a regular file name.
170604 ** If the zState argument is passed a NULL value, the RBU extension stores
170605 ** the current state of the update (how many rows have been updated, which
170606 ** indexes are yet to be updated etc.) within the RBU database itself. This
170607 ** can be convenient, as it means that the RBU application does not need to
170608 ** organize removing a separate state file after the update is concluded.
170609 ** Or, if zState is non-NULL, it must be a path to a database file in which
170610 ** the RBU extension can store the state of the update.
170612 ** When resuming an RBU update, the zState argument must be passed the same
170613 ** value as when the RBU update was started.
170615 ** Once the RBU update is finished, the RBU extension does not
170616 ** automatically remove any zState database file, even if it created it.
170618 ** By default, RBU uses the default VFS to access the files on disk. To
170619 ** use a VFS other than the default, an SQLite "file:" URI containing a
170620 ** "vfs=..." option may be passed as the zTarget option.
170622 ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
170623 ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
170624 ** not work out of the box with zipvfs. Refer to the comment describing
170625 ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
170627 SQLITE_API sqlite3rbu *sqlite3rbu_open(
170628 const char *zTarget,
170629 const char *zRbu,
170630 const char *zState
170634 ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
170635 ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
170636 ** that it can be suspended and resumed like an RBU update.
170638 ** The second argument to this function identifies a database in which
170639 ** to store the state of the RBU vacuum operation if it is suspended. The
170640 ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
170641 ** operation, the state database should either not exist or be empty
170642 ** (contain no tables). If an RBU vacuum is suspended by calling
170643 ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
170644 ** returned SQLITE_DONE, the vacuum state is stored in the state database.
170645 ** The vacuum can be resumed by calling this function to open a new RBU
170646 ** handle specifying the same target and state databases.
170648 ** If the second argument passed to this function is NULL, then the
170649 ** name of the state database is "<database>-vacuum", where <database>
170650 ** is the name of the target database file. In this case, on UNIX, if the
170651 ** state database is not already present in the file-system, it is created
170652 ** with the same permissions as the target db is made.
170654 ** This function does not delete the state database after an RBU vacuum
170655 ** is completed, even if it created it. However, if the call to
170656 ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
170657 ** of the state tables within the state database are zeroed. This way,
170658 ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
170659 ** new RBU vacuum operation.
170661 ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
170662 ** describing the sqlite3rbu_create_vfs() API function below for
170663 ** a description of the complications associated with using RBU with
170664 ** zipvfs databases.
170666 SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
170667 const char *zTarget,
170668 const char *zState
170672 ** Configure a limit for the amount of temp space that may be used by
170673 ** the RBU handle passed as the first argument. The new limit is specified
170674 ** in bytes by the second parameter. If it is positive, the limit is updated.
170675 ** If the second parameter to this function is passed zero, then the limit
170676 ** is removed entirely. If the second parameter is negative, the limit is
170677 ** not modified (this is useful for querying the current limit).
170679 ** In all cases the returned value is the current limit in bytes (zero
170680 ** indicates unlimited).
170682 ** If the temp space limit is exceeded during operation, an SQLITE_FULL
170683 ** error is returned.
170685 SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
170688 ** Return the current amount of temp file space, in bytes, currently used by
170689 ** the RBU handle passed as the only argument.
170691 SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
170694 ** Internally, each RBU connection uses a separate SQLite database
170695 ** connection to access the target and rbu update databases. This
170696 ** API allows the application direct access to these database handles.
170698 ** The first argument passed to this function must be a valid, open, RBU
170699 ** handle. The second argument should be passed zero to access the target
170700 ** database handle, or non-zero to access the rbu update database handle.
170701 ** Accessing the underlying database handles may be useful in the
170702 ** following scenarios:
170704 ** * If any target tables are virtual tables, it may be necessary to
170705 ** call sqlite3_create_module() on the target database handle to
170706 ** register the required virtual table implementations.
170708 ** * If the data_xxx tables in the RBU source database are virtual
170709 ** tables, the application may need to call sqlite3_create_module() on
170710 ** the rbu update db handle to any required virtual table
170711 ** implementations.
170713 ** * If the application uses the "rbu_delta()" feature described above,
170714 ** it must use sqlite3_create_function() or similar to register the
170715 ** rbu_delta() implementation with the target database handle.
170717 ** If an error has occurred, either while opening or stepping the RBU object,
170718 ** this function may return NULL. The error code and message may be collected
170719 ** when sqlite3rbu_close() is called.
170721 ** Database handles returned by this function remain valid until the next
170722 ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
170724 SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
170727 ** Do some work towards applying the RBU update to the target db.
170729 ** Return SQLITE_DONE if the update has been completely applied, or
170730 ** SQLITE_OK if no error occurs but there remains work to do to apply
170731 ** the RBU update. If an error does occur, some other error code is
170732 ** returned.
170734 ** Once a call to sqlite3rbu_step() has returned a value other than
170735 ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
170736 ** that immediately return the same value.
170738 SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
170741 ** Force RBU to save its state to disk.
170743 ** If a power failure or application crash occurs during an update, following
170744 ** system recovery RBU may resume the update from the point at which the state
170745 ** was last saved. In other words, from the most recent successful call to
170746 ** sqlite3rbu_close() or this function.
170748 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
170750 SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
170753 ** Close an RBU handle.
170755 ** If the RBU update has been completely applied, mark the RBU database
170756 ** as fully applied. Otherwise, assuming no error has occurred, save the
170757 ** current state of the RBU update appliation to the RBU database.
170759 ** If an error has already occurred as part of an sqlite3rbu_step()
170760 ** or sqlite3rbu_open() call, or if one occurs within this function, an
170761 ** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
170762 ** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
170763 ** English language error message. It is the responsibility of the caller to
170764 ** eventually free any such buffer using sqlite3_free().
170766 ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
170767 ** update has been partially applied, or SQLITE_DONE if it has been
170768 ** completely applied.
170770 SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
170773 ** Return the total number of key-value operations (inserts, deletes or
170774 ** updates) that have been performed on the target database since the
170775 ** current RBU update was started.
170777 SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
170780 ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
170781 ** progress indications for the two stages of an RBU update. This API may
170782 ** be useful for driving GUI progress indicators and similar.
170784 ** An RBU update is divided into two stages:
170786 ** * Stage 1, in which changes are accumulated in an oal/wal file, and
170787 ** * Stage 2, in which the contents of the wal file are copied into the
170788 ** main database.
170790 ** The update is visible to non-RBU clients during stage 2. During stage 1
170791 ** non-RBU reader clients may see the original database.
170793 ** If this API is called during stage 2 of the update, output variable
170794 ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
170795 ** to a value between 0 and 10000 to indicate the permyriadage progress of
170796 ** stage 2. A value of 5000 indicates that stage 2 is half finished,
170797 ** 9000 indicates that it is 90% finished, and so on.
170799 ** If this API is called during stage 1 of the update, output variable
170800 ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
170801 ** value to which (*pnOne) is set depends on whether or not the RBU
170802 ** database contains an "rbu_count" table. The rbu_count table, if it
170803 ** exists, must contain the same columns as the following:
170805 ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
170807 ** There must be one row in the table for each source (data_xxx) table within
170808 ** the RBU database. The 'tbl' column should contain the name of the source
170809 ** table. The 'cnt' column should contain the number of rows within the
170810 ** source table.
170812 ** If the rbu_count table is present and populated correctly and this
170813 ** API is called during stage 1, the *pnOne output variable is set to the
170814 ** permyriadage progress of the same stage. If the rbu_count table does
170815 ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
170816 ** table exists but is not correctly populated, the value of the *pnOne
170817 ** output variable during stage 1 is undefined.
170819 SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
170822 ** Obtain an indication as to the current stage of an RBU update or vacuum.
170823 ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
170824 ** defined in this file. Return values should be interpreted as follows:
170826 ** SQLITE_RBU_STATE_OAL:
170827 ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
170828 ** may either add further data to the *-oal file, or compute data that will
170829 ** be added by a subsequent call.
170831 ** SQLITE_RBU_STATE_MOVE:
170832 ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
170833 ** will move the *-oal file to the equivalent *-wal path. If the current
170834 ** operation is an RBU update, then the updated version of the database
170835 ** file will become visible to ordinary SQLite clients following the next
170836 ** call to sqlite3rbu_step().
170838 ** SQLITE_RBU_STATE_CHECKPOINT:
170839 ** RBU is currently performing an incremental checkpoint. The next call to
170840 ** sqlite3rbu_step() will copy a page of data from the *-wal file into
170841 ** the target database file.
170843 ** SQLITE_RBU_STATE_DONE:
170844 ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
170845 ** will immediately return SQLITE_DONE.
170847 ** SQLITE_RBU_STATE_ERROR:
170848 ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
170849 ** immediately return the SQLite error code associated with the error.
170851 #define SQLITE_RBU_STATE_OAL 1
170852 #define SQLITE_RBU_STATE_MOVE 2
170853 #define SQLITE_RBU_STATE_CHECKPOINT 3
170854 #define SQLITE_RBU_STATE_DONE 4
170855 #define SQLITE_RBU_STATE_ERROR 5
170857 SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
170860 ** Create an RBU VFS named zName that accesses the underlying file-system
170861 ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
170862 ** then the new RBU VFS uses the default system VFS to access the file-system.
170863 ** The new object is registered as a non-default VFS with SQLite before
170864 ** returning.
170866 ** Part of the RBU implementation uses a custom VFS object. Usually, this
170867 ** object is created and deleted automatically by RBU.
170869 ** The exception is for applications that also use zipvfs. In this case,
170870 ** the custom VFS must be explicitly created by the user before the RBU
170871 ** handle is opened. The RBU VFS should be installed so that the zipvfs
170872 ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
170873 ** (for example multiplexor) to access the file-system. For example,
170874 ** to assemble an RBU enabled VFS stack that uses both zipvfs and
170875 ** multiplexor (error checking omitted):
170877 ** // Create a VFS named "multiplex" (not the default).
170878 ** sqlite3_multiplex_initialize(0, 0);
170880 ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
170881 ** // second argument were replaced with NULL, the "rbu" VFS would
170882 ** // access the file-system via the system default VFS, bypassing the
170883 ** // multiplexor.
170884 ** sqlite3rbu_create_vfs("rbu", "multiplex");
170886 ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
170887 ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
170889 ** // Make zipvfs the default VFS.
170890 ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
170892 ** Because the default VFS created above includes a RBU functionality, it
170893 ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
170894 ** that does not include the RBU layer results in an error.
170896 ** The overhead of adding the "rbu" VFS to the system is negligible for
170897 ** non-RBU users. There is no harm in an application accessing the
170898 ** file-system via "rbu" all the time, even if it only uses RBU functionality
170899 ** occasionally.
170901 SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
170904 ** Deregister and destroy an RBU vfs created by an earlier call to
170905 ** sqlite3rbu_create_vfs().
170907 ** VFS objects are not reference counted. If a VFS object is destroyed
170908 ** before all database handles that use it have been closed, the results
170909 ** are undefined.
170911 SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
170913 #if 0
170914 } /* end of the 'extern "C"' block */
170915 #endif
170917 #endif /* _SQLITE3RBU_H */
170919 /************** End of sqlite3rbu.h ******************************************/
170920 /************** Continuing where we left off in sqlite3rbu.c *****************/
170922 #if defined(_WIN32_WCE)
170923 /* #include "windows.h" */
170924 #endif
170926 /* Maximum number of prepared UPDATE statements held by this module */
170927 #define SQLITE_RBU_UPDATE_CACHESIZE 16
170929 /* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM
170930 ** to enable checksum verification.
170932 #ifndef RBU_ENABLE_DELTA_CKSUM
170933 # define RBU_ENABLE_DELTA_CKSUM 0
170934 #endif
170937 ** Swap two objects of type TYPE.
170939 #if !defined(SQLITE_AMALGAMATION)
170940 # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
170941 #endif
170944 ** The rbu_state table is used to save the state of a partially applied
170945 ** update so that it can be resumed later. The table consists of integer
170946 ** keys mapped to values as follows:
170948 ** RBU_STATE_STAGE:
170949 ** May be set to integer values 1, 2, 4 or 5. As follows:
170950 ** 1: the *-rbu file is currently under construction.
170951 ** 2: the *-rbu file has been constructed, but not yet moved
170952 ** to the *-wal path.
170953 ** 4: the checkpoint is underway.
170954 ** 5: the rbu update has been checkpointed.
170956 ** RBU_STATE_TBL:
170957 ** Only valid if STAGE==1. The target database name of the table
170958 ** currently being written.
170960 ** RBU_STATE_IDX:
170961 ** Only valid if STAGE==1. The target database name of the index
170962 ** currently being written, or NULL if the main table is currently being
170963 ** updated.
170965 ** RBU_STATE_ROW:
170966 ** Only valid if STAGE==1. Number of rows already processed for the current
170967 ** table/index.
170969 ** RBU_STATE_PROGRESS:
170970 ** Trbul number of sqlite3rbu_step() calls made so far as part of this
170971 ** rbu update.
170973 ** RBU_STATE_CKPT:
170974 ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
170975 ** header created by recovering the *-wal file. This is used to detect
170976 ** cases when another client appends frames to the *-wal file in the
170977 ** middle of an incremental checkpoint (an incremental checkpoint cannot
170978 ** be continued if this happens).
170980 ** RBU_STATE_COOKIE:
170981 ** Valid if STAGE==1. The current change-counter cookie value in the
170982 ** target db file.
170984 ** RBU_STATE_OALSZ:
170985 ** Valid if STAGE==1. The size in bytes of the *-oal file.
170987 #define RBU_STATE_STAGE 1
170988 #define RBU_STATE_TBL 2
170989 #define RBU_STATE_IDX 3
170990 #define RBU_STATE_ROW 4
170991 #define RBU_STATE_PROGRESS 5
170992 #define RBU_STATE_CKPT 6
170993 #define RBU_STATE_COOKIE 7
170994 #define RBU_STATE_OALSZ 8
170995 #define RBU_STATE_PHASEONESTEP 9
170997 #define RBU_STAGE_OAL 1
170998 #define RBU_STAGE_MOVE 2
170999 #define RBU_STAGE_CAPTURE 3
171000 #define RBU_STAGE_CKPT 4
171001 #define RBU_STAGE_DONE 5
171004 #define RBU_CREATE_STATE \
171005 "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
171007 typedef struct RbuFrame RbuFrame;
171008 typedef struct RbuObjIter RbuObjIter;
171009 typedef struct RbuState RbuState;
171010 typedef struct rbu_vfs rbu_vfs;
171011 typedef struct rbu_file rbu_file;
171012 typedef struct RbuUpdateStmt RbuUpdateStmt;
171014 #if !defined(SQLITE_AMALGAMATION)
171015 typedef unsigned int u32;
171016 typedef unsigned short u16;
171017 typedef unsigned char u8;
171018 typedef sqlite3_int64 i64;
171019 #endif
171022 ** These values must match the values defined in wal.c for the equivalent
171023 ** locks. These are not magic numbers as they are part of the SQLite file
171024 ** format.
171026 #define WAL_LOCK_WRITE 0
171027 #define WAL_LOCK_CKPT 1
171028 #define WAL_LOCK_READ0 3
171030 #define SQLITE_FCNTL_RBUCNT 5149216
171033 ** A structure to store values read from the rbu_state table in memory.
171035 struct RbuState {
171036 int eStage;
171037 char *zTbl;
171038 char *zIdx;
171039 i64 iWalCksum;
171040 int nRow;
171041 i64 nProgress;
171042 u32 iCookie;
171043 i64 iOalSz;
171044 i64 nPhaseOneStep;
171047 struct RbuUpdateStmt {
171048 char *zMask; /* Copy of update mask used with pUpdate */
171049 sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
171050 RbuUpdateStmt *pNext;
171054 ** An iterator of this type is used to iterate through all objects in
171055 ** the target database that require updating. For each such table, the
171056 ** iterator visits, in order:
171058 ** * the table itself,
171059 ** * each index of the table (zero or more points to visit), and
171060 ** * a special "cleanup table" state.
171062 ** abIndexed:
171063 ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
171064 ** it points to an array of flags nTblCol elements in size. The flag is
171065 ** set for each column that is either a part of the PK or a part of an
171066 ** index. Or clear otherwise.
171069 struct RbuObjIter {
171070 sqlite3_stmt *pTblIter; /* Iterate through tables */
171071 sqlite3_stmt *pIdxIter; /* Index iterator */
171072 int nTblCol; /* Size of azTblCol[] array */
171073 char **azTblCol; /* Array of unquoted target column names */
171074 char **azTblType; /* Array of target column types */
171075 int *aiSrcOrder; /* src table col -> target table col */
171076 u8 *abTblPk; /* Array of flags, set on target PK columns */
171077 u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
171078 u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
171079 int eType; /* Table type - an RBU_PK_XXX value */
171081 /* Output variables. zTbl==0 implies EOF. */
171082 int bCleanup; /* True in "cleanup" state */
171083 const char *zTbl; /* Name of target db table */
171084 const char *zDataTbl; /* Name of rbu db table (or null) */
171085 const char *zIdx; /* Name of target db index (or null) */
171086 int iTnum; /* Root page of current object */
171087 int iPkTnum; /* If eType==EXTERNAL, root of PK index */
171088 int bUnique; /* Current index is unique */
171089 int nIndex; /* Number of aux. indexes on table zTbl */
171091 /* Statements created by rbuObjIterPrepareAll() */
171092 int nCol; /* Number of columns in current object */
171093 sqlite3_stmt *pSelect; /* Source data */
171094 sqlite3_stmt *pInsert; /* Statement for INSERT operations */
171095 sqlite3_stmt *pDelete; /* Statement for DELETE ops */
171096 sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
171098 /* Last UPDATE used (for PK b-tree updates only), or NULL. */
171099 RbuUpdateStmt *pRbuUpdate;
171103 ** Values for RbuObjIter.eType
171105 ** 0: Table does not exist (error)
171106 ** 1: Table has an implicit rowid.
171107 ** 2: Table has an explicit IPK column.
171108 ** 3: Table has an external PK index.
171109 ** 4: Table is WITHOUT ROWID.
171110 ** 5: Table is a virtual table.
171112 #define RBU_PK_NOTABLE 0
171113 #define RBU_PK_NONE 1
171114 #define RBU_PK_IPK 2
171115 #define RBU_PK_EXTERNAL 3
171116 #define RBU_PK_WITHOUT_ROWID 4
171117 #define RBU_PK_VTAB 5
171121 ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
171122 ** one of the following operations.
171124 #define RBU_INSERT 1 /* Insert on a main table b-tree */
171125 #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
171126 #define RBU_REPLACE 3 /* Delete and then insert a row */
171127 #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
171128 #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
171130 #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
171133 ** A single step of an incremental checkpoint - frame iWalFrame of the wal
171134 ** file should be copied to page iDbPage of the database file.
171136 struct RbuFrame {
171137 u32 iDbPage;
171138 u32 iWalFrame;
171142 ** RBU handle.
171144 ** nPhaseOneStep:
171145 ** If the RBU database contains an rbu_count table, this value is set to
171146 ** a running estimate of the number of b-tree operations required to
171147 ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
171148 ** API to calculate the permyriadage progress of populating the *-oal file
171149 ** using the formula:
171151 ** permyriadage = (10000 * nProgress) / nPhaseOneStep
171153 ** nPhaseOneStep is initialized to the sum of:
171155 ** nRow * (nIndex + 1)
171157 ** for all source tables in the RBU database, where nRow is the number
171158 ** of rows in the source table and nIndex the number of indexes on the
171159 ** corresponding target database table.
171161 ** This estimate is accurate if the RBU update consists entirely of
171162 ** INSERT operations. However, it is inaccurate if:
171164 ** * the RBU update contains any UPDATE operations. If the PK specified
171165 ** for an UPDATE operation does not exist in the target table, then
171166 ** no b-tree operations are required on index b-trees. Or if the
171167 ** specified PK does exist, then (nIndex*2) such operations are
171168 ** required (one delete and one insert on each index b-tree).
171170 ** * the RBU update contains any DELETE operations for which the specified
171171 ** PK does not exist. In this case no operations are required on index
171172 ** b-trees.
171174 ** * the RBU update contains REPLACE operations. These are similar to
171175 ** UPDATE operations.
171177 ** nPhaseOneStep is updated to account for the conditions above during the
171178 ** first pass of each source table. The updated nPhaseOneStep value is
171179 ** stored in the rbu_state table if the RBU update is suspended.
171181 struct sqlite3rbu {
171182 int eStage; /* Value of RBU_STATE_STAGE field */
171183 sqlite3 *dbMain; /* target database handle */
171184 sqlite3 *dbRbu; /* rbu database handle */
171185 char *zTarget; /* Path to target db */
171186 char *zRbu; /* Path to rbu db */
171187 char *zState; /* Path to state db (or NULL if zRbu) */
171188 char zStateDb[5]; /* Db name for state ("stat" or "main") */
171189 int rc; /* Value returned by last rbu_step() call */
171190 char *zErrmsg; /* Error message if rc!=SQLITE_OK */
171191 int nStep; /* Rows processed for current object */
171192 int nProgress; /* Rows processed for all objects */
171193 RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
171194 const char *zVfsName; /* Name of automatically created rbu vfs */
171195 rbu_file *pTargetFd; /* File handle open on target db */
171196 int nPagePerSector; /* Pages per sector for pTargetFd */
171197 i64 iOalSz;
171198 i64 nPhaseOneStep;
171200 /* The following state variables are used as part of the incremental
171201 ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
171202 ** function rbuSetupCheckpoint() for details. */
171203 u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
171204 u32 mLock;
171205 int nFrame; /* Entries in aFrame[] array */
171206 int nFrameAlloc; /* Allocated size of aFrame[] array */
171207 RbuFrame *aFrame;
171208 int pgsz;
171209 u8 *aBuf;
171210 i64 iWalCksum;
171211 i64 szTemp; /* Current size of all temp files in use */
171212 i64 szTempLimit; /* Total size limit for temp files */
171214 /* Used in RBU vacuum mode only */
171215 int nRbu; /* Number of RBU VFS in the stack */
171216 rbu_file *pRbuFd; /* Fd for main db of dbRbu */
171220 ** An rbu VFS is implemented using an instance of this structure.
171222 ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
171223 ** It is NULL for RBU VFS objects created explicitly using
171224 ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
171225 ** space used by the RBU handle.
171227 struct rbu_vfs {
171228 sqlite3_vfs base; /* rbu VFS shim methods */
171229 sqlite3_vfs *pRealVfs; /* Underlying VFS */
171230 sqlite3_mutex *mutex; /* Mutex to protect pMain */
171231 sqlite3rbu *pRbu; /* Owner RBU object */
171232 rbu_file *pMain; /* Linked list of main db files */
171236 ** Each file opened by an rbu VFS is represented by an instance of
171237 ** the following structure.
171239 ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
171240 ** "sz" is set to the current size of the database file.
171242 struct rbu_file {
171243 sqlite3_file base; /* sqlite3_file methods */
171244 sqlite3_file *pReal; /* Underlying file handle */
171245 rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
171246 sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
171247 i64 sz; /* Size of file in bytes (temp only) */
171249 int openFlags; /* Flags this file was opened with */
171250 u32 iCookie; /* Cookie value for main db files */
171251 u8 iWriteVer; /* "write-version" value for main db files */
171252 u8 bNolock; /* True to fail EXCLUSIVE locks */
171254 int nShm; /* Number of entries in apShm[] array */
171255 char **apShm; /* Array of mmap'd *-shm regions */
171256 char *zDel; /* Delete this when closing file */
171258 const char *zWal; /* Wal filename for this main db file */
171259 rbu_file *pWalFd; /* Wal file descriptor for this main db */
171260 rbu_file *pMainNext; /* Next MAIN_DB file */
171264 ** True for an RBU vacuum handle, or false otherwise.
171266 #define rbuIsVacuum(p) ((p)->zTarget==0)
171269 /*************************************************************************
171270 ** The following three functions, found below:
171272 ** rbuDeltaGetInt()
171273 ** rbuDeltaChecksum()
171274 ** rbuDeltaApply()
171276 ** are lifted from the fossil source code (http://fossil-scm.org). They
171277 ** are used to implement the scalar SQL function rbu_fossil_delta().
171281 ** Read bytes from *pz and convert them into a positive integer. When
171282 ** finished, leave *pz pointing to the first character past the end of
171283 ** the integer. The *pLen parameter holds the length of the string
171284 ** in *pz and is decremented once for each character in the integer.
171286 static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
171287 static const signed char zValue[] = {
171288 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
171289 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
171290 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
171291 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
171292 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
171293 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
171294 -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
171295 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
171297 unsigned int v = 0;
171298 int c;
171299 unsigned char *z = (unsigned char*)*pz;
171300 unsigned char *zStart = z;
171301 while( (c = zValue[0x7f&*(z++)])>=0 ){
171302 v = (v<<6) + c;
171305 *pLen -= z - zStart;
171306 *pz = (char*)z;
171307 return v;
171310 #if RBU_ENABLE_DELTA_CKSUM
171312 ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
171314 static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
171315 const unsigned char *z = (const unsigned char *)zIn;
171316 unsigned sum0 = 0;
171317 unsigned sum1 = 0;
171318 unsigned sum2 = 0;
171319 unsigned sum3 = 0;
171320 while(N >= 16){
171321 sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
171322 sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
171323 sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
171324 sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
171325 z += 16;
171326 N -= 16;
171328 while(N >= 4){
171329 sum0 += z[0];
171330 sum1 += z[1];
171331 sum2 += z[2];
171332 sum3 += z[3];
171333 z += 4;
171334 N -= 4;
171336 sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
171337 switch(N){
171338 case 3: sum3 += (z[2] << 8);
171339 case 2: sum3 += (z[1] << 16);
171340 case 1: sum3 += (z[0] << 24);
171341 default: ;
171343 return sum3;
171345 #endif
171348 ** Apply a delta.
171350 ** The output buffer should be big enough to hold the whole output
171351 ** file and a NUL terminator at the end. The delta_output_size()
171352 ** routine will determine this size for you.
171354 ** The delta string should be null-terminated. But the delta string
171355 ** may contain embedded NUL characters (if the input and output are
171356 ** binary files) so we also have to pass in the length of the delta in
171357 ** the lenDelta parameter.
171359 ** This function returns the size of the output file in bytes (excluding
171360 ** the final NUL terminator character). Except, if the delta string is
171361 ** malformed or intended for use with a source file other than zSrc,
171362 ** then this routine returns -1.
171364 ** Refer to the delta_create() documentation above for a description
171365 ** of the delta file format.
171367 static int rbuDeltaApply(
171368 const char *zSrc, /* The source or pattern file */
171369 int lenSrc, /* Length of the source file */
171370 const char *zDelta, /* Delta to apply to the pattern */
171371 int lenDelta, /* Length of the delta */
171372 char *zOut /* Write the output into this preallocated buffer */
171374 unsigned int limit;
171375 unsigned int total = 0;
171376 #if RBU_ENABLE_DELTA_CKSUM
171377 char *zOrigOut = zOut;
171378 #endif
171380 limit = rbuDeltaGetInt(&zDelta, &lenDelta);
171381 if( *zDelta!='\n' ){
171382 /* ERROR: size integer not terminated by "\n" */
171383 return -1;
171385 zDelta++; lenDelta--;
171386 while( *zDelta && lenDelta>0 ){
171387 unsigned int cnt, ofst;
171388 cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
171389 switch( zDelta[0] ){
171390 case '@': {
171391 zDelta++; lenDelta--;
171392 ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
171393 if( lenDelta>0 && zDelta[0]!=',' ){
171394 /* ERROR: copy command not terminated by ',' */
171395 return -1;
171397 zDelta++; lenDelta--;
171398 total += cnt;
171399 if( total>limit ){
171400 /* ERROR: copy exceeds output file size */
171401 return -1;
171403 if( (int)(ofst+cnt) > lenSrc ){
171404 /* ERROR: copy extends past end of input */
171405 return -1;
171407 memcpy(zOut, &zSrc[ofst], cnt);
171408 zOut += cnt;
171409 break;
171411 case ':': {
171412 zDelta++; lenDelta--;
171413 total += cnt;
171414 if( total>limit ){
171415 /* ERROR: insert command gives an output larger than predicted */
171416 return -1;
171418 if( (int)cnt>lenDelta ){
171419 /* ERROR: insert count exceeds size of delta */
171420 return -1;
171422 memcpy(zOut, zDelta, cnt);
171423 zOut += cnt;
171424 zDelta += cnt;
171425 lenDelta -= cnt;
171426 break;
171428 case ';': {
171429 zDelta++; lenDelta--;
171430 zOut[0] = 0;
171431 #if RBU_ENABLE_DELTA_CKSUM
171432 if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
171433 /* ERROR: bad checksum */
171434 return -1;
171436 #endif
171437 if( total!=limit ){
171438 /* ERROR: generated size does not match predicted size */
171439 return -1;
171441 return total;
171443 default: {
171444 /* ERROR: unknown delta operator */
171445 return -1;
171449 /* ERROR: unterminated delta */
171450 return -1;
171453 static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
171454 int size;
171455 size = rbuDeltaGetInt(&zDelta, &lenDelta);
171456 if( *zDelta!='\n' ){
171457 /* ERROR: size integer not terminated by "\n" */
171458 return -1;
171460 return size;
171464 ** End of code taken from fossil.
171465 *************************************************************************/
171468 ** Implementation of SQL scalar function rbu_fossil_delta().
171470 ** This function applies a fossil delta patch to a blob. Exactly two
171471 ** arguments must be passed to this function. The first is the blob to
171472 ** patch and the second the patch to apply. If no error occurs, this
171473 ** function returns the patched blob.
171475 static void rbuFossilDeltaFunc(
171476 sqlite3_context *context,
171477 int argc,
171478 sqlite3_value **argv
171480 const char *aDelta;
171481 int nDelta;
171482 const char *aOrig;
171483 int nOrig;
171485 int nOut;
171486 int nOut2;
171487 char *aOut;
171489 assert( argc==2 );
171491 nOrig = sqlite3_value_bytes(argv[0]);
171492 aOrig = (const char*)sqlite3_value_blob(argv[0]);
171493 nDelta = sqlite3_value_bytes(argv[1]);
171494 aDelta = (const char*)sqlite3_value_blob(argv[1]);
171496 /* Figure out the size of the output */
171497 nOut = rbuDeltaOutputSize(aDelta, nDelta);
171498 if( nOut<0 ){
171499 sqlite3_result_error(context, "corrupt fossil delta", -1);
171500 return;
171503 aOut = sqlite3_malloc(nOut+1);
171504 if( aOut==0 ){
171505 sqlite3_result_error_nomem(context);
171506 }else{
171507 nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
171508 if( nOut2!=nOut ){
171509 sqlite3_result_error(context, "corrupt fossil delta", -1);
171510 }else{
171511 sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
171518 ** Prepare the SQL statement in buffer zSql against database handle db.
171519 ** If successful, set *ppStmt to point to the new statement and return
171520 ** SQLITE_OK.
171522 ** Otherwise, if an error does occur, set *ppStmt to NULL and return
171523 ** an SQLite error code. Additionally, set output variable *pzErrmsg to
171524 ** point to a buffer containing an error message. It is the responsibility
171525 ** of the caller to (eventually) free this buffer using sqlite3_free().
171527 static int prepareAndCollectError(
171528 sqlite3 *db,
171529 sqlite3_stmt **ppStmt,
171530 char **pzErrmsg,
171531 const char *zSql
171533 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
171534 if( rc!=SQLITE_OK ){
171535 *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
171536 *ppStmt = 0;
171538 return rc;
171542 ** Reset the SQL statement passed as the first argument. Return a copy
171543 ** of the value returned by sqlite3_reset().
171545 ** If an error has occurred, then set *pzErrmsg to point to a buffer
171546 ** containing an error message. It is the responsibility of the caller
171547 ** to eventually free this buffer using sqlite3_free().
171549 static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
171550 int rc = sqlite3_reset(pStmt);
171551 if( rc!=SQLITE_OK ){
171552 *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
171554 return rc;
171558 ** Unless it is NULL, argument zSql points to a buffer allocated using
171559 ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
171560 ** statement against database db and frees the buffer. If statement
171561 ** compilation is successful, *ppStmt is set to point to the new statement
171562 ** handle and SQLITE_OK is returned.
171564 ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
171565 ** returned. In this case, *pzErrmsg may also be set to point to an error
171566 ** message. It is the responsibility of the caller to free this error message
171567 ** buffer using sqlite3_free().
171569 ** If argument zSql is NULL, this function assumes that an OOM has occurred.
171570 ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
171572 static int prepareFreeAndCollectError(
171573 sqlite3 *db,
171574 sqlite3_stmt **ppStmt,
171575 char **pzErrmsg,
171576 char *zSql
171578 int rc;
171579 assert( *pzErrmsg==0 );
171580 if( zSql==0 ){
171581 rc = SQLITE_NOMEM;
171582 *ppStmt = 0;
171583 }else{
171584 rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
171585 sqlite3_free(zSql);
171587 return rc;
171591 ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
171592 ** by an earlier call to rbuObjIterCacheTableInfo().
171594 static void rbuObjIterFreeCols(RbuObjIter *pIter){
171595 int i;
171596 for(i=0; i<pIter->nTblCol; i++){
171597 sqlite3_free(pIter->azTblCol[i]);
171598 sqlite3_free(pIter->azTblType[i]);
171600 sqlite3_free(pIter->azTblCol);
171601 pIter->azTblCol = 0;
171602 pIter->azTblType = 0;
171603 pIter->aiSrcOrder = 0;
171604 pIter->abTblPk = 0;
171605 pIter->abNotNull = 0;
171606 pIter->nTblCol = 0;
171607 pIter->eType = 0; /* Invalid value */
171611 ** Finalize all statements and free all allocations that are specific to
171612 ** the current object (table/index pair).
171614 static void rbuObjIterClearStatements(RbuObjIter *pIter){
171615 RbuUpdateStmt *pUp;
171617 sqlite3_finalize(pIter->pSelect);
171618 sqlite3_finalize(pIter->pInsert);
171619 sqlite3_finalize(pIter->pDelete);
171620 sqlite3_finalize(pIter->pTmpInsert);
171621 pUp = pIter->pRbuUpdate;
171622 while( pUp ){
171623 RbuUpdateStmt *pTmp = pUp->pNext;
171624 sqlite3_finalize(pUp->pUpdate);
171625 sqlite3_free(pUp);
171626 pUp = pTmp;
171629 pIter->pSelect = 0;
171630 pIter->pInsert = 0;
171631 pIter->pDelete = 0;
171632 pIter->pRbuUpdate = 0;
171633 pIter->pTmpInsert = 0;
171634 pIter->nCol = 0;
171638 ** Clean up any resources allocated as part of the iterator object passed
171639 ** as the only argument.
171641 static void rbuObjIterFinalize(RbuObjIter *pIter){
171642 rbuObjIterClearStatements(pIter);
171643 sqlite3_finalize(pIter->pTblIter);
171644 sqlite3_finalize(pIter->pIdxIter);
171645 rbuObjIterFreeCols(pIter);
171646 memset(pIter, 0, sizeof(RbuObjIter));
171650 ** Advance the iterator to the next position.
171652 ** If no error occurs, SQLITE_OK is returned and the iterator is left
171653 ** pointing to the next entry. Otherwise, an error code and message is
171654 ** left in the RBU handle passed as the first argument. A copy of the
171655 ** error code is returned.
171657 static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
171658 int rc = p->rc;
171659 if( rc==SQLITE_OK ){
171661 /* Free any SQLite statements used while processing the previous object */
171662 rbuObjIterClearStatements(pIter);
171663 if( pIter->zIdx==0 ){
171664 rc = sqlite3_exec(p->dbMain,
171665 "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
171666 "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
171667 "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
171668 "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
171669 , 0, 0, &p->zErrmsg
171673 if( rc==SQLITE_OK ){
171674 if( pIter->bCleanup ){
171675 rbuObjIterFreeCols(pIter);
171676 pIter->bCleanup = 0;
171677 rc = sqlite3_step(pIter->pTblIter);
171678 if( rc!=SQLITE_ROW ){
171679 rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
171680 pIter->zTbl = 0;
171681 }else{
171682 pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
171683 pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
171684 rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
171686 }else{
171687 if( pIter->zIdx==0 ){
171688 sqlite3_stmt *pIdx = pIter->pIdxIter;
171689 rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
171691 if( rc==SQLITE_OK ){
171692 rc = sqlite3_step(pIter->pIdxIter);
171693 if( rc!=SQLITE_ROW ){
171694 rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
171695 pIter->bCleanup = 1;
171696 pIter->zIdx = 0;
171697 }else{
171698 pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
171699 pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
171700 pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
171701 rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
171708 if( rc!=SQLITE_OK ){
171709 rbuObjIterFinalize(pIter);
171710 p->rc = rc;
171712 return rc;
171717 ** The implementation of the rbu_target_name() SQL function. This function
171718 ** accepts one or two arguments. The first argument is the name of a table -
171719 ** the name of a table in the RBU database. The second, if it is present, is 1
171720 ** for a view or 0 for a table.
171722 ** For a non-vacuum RBU handle, if the table name matches the pattern:
171724 ** data[0-9]_<name>
171726 ** where <name> is any sequence of 1 or more characters, <name> is returned.
171727 ** Otherwise, if the only argument does not match the above pattern, an SQL
171728 ** NULL is returned.
171730 ** "data_t1" -> "t1"
171731 ** "data0123_t2" -> "t2"
171732 ** "dataAB_t3" -> NULL
171734 ** For an rbu vacuum handle, a copy of the first argument is returned if
171735 ** the second argument is either missing or 0 (not a view).
171737 static void rbuTargetNameFunc(
171738 sqlite3_context *pCtx,
171739 int argc,
171740 sqlite3_value **argv
171742 sqlite3rbu *p = sqlite3_user_data(pCtx);
171743 const char *zIn;
171744 assert( argc==1 || argc==2 );
171746 zIn = (const char*)sqlite3_value_text(argv[0]);
171747 if( zIn ){
171748 if( rbuIsVacuum(p) ){
171749 if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
171750 sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
171752 }else{
171753 if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
171754 int i;
171755 for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
171756 if( zIn[i]=='_' && zIn[i+1] ){
171757 sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
171765 ** Initialize the iterator structure passed as the second argument.
171767 ** If no error occurs, SQLITE_OK is returned and the iterator is left
171768 ** pointing to the first entry. Otherwise, an error code and message is
171769 ** left in the RBU handle passed as the first argument. A copy of the
171770 ** error code is returned.
171772 static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
171773 int rc;
171774 memset(pIter, 0, sizeof(RbuObjIter));
171776 rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
171777 sqlite3_mprintf(
171778 "SELECT rbu_target_name(name, type='view') AS target, name "
171779 "FROM sqlite_master "
171780 "WHERE type IN ('table', 'view') AND target IS NOT NULL "
171781 " %s "
171782 "ORDER BY name"
171783 , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
171785 if( rc==SQLITE_OK ){
171786 rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
171787 "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
171788 " FROM main.sqlite_master "
171789 " WHERE type='index' AND tbl_name = ?"
171793 pIter->bCleanup = 1;
171794 p->rc = rc;
171795 return rbuObjIterNext(p, pIter);
171799 ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
171800 ** an error code is stored in the RBU handle passed as the first argument.
171802 ** If an error has already occurred (p->rc is already set to something other
171803 ** than SQLITE_OK), then this function returns NULL without modifying the
171804 ** stored error code. In this case it still calls sqlite3_free() on any
171805 ** printf() parameters associated with %z conversions.
171807 static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
171808 char *zSql = 0;
171809 va_list ap;
171810 va_start(ap, zFmt);
171811 zSql = sqlite3_vmprintf(zFmt, ap);
171812 if( p->rc==SQLITE_OK ){
171813 if( zSql==0 ) p->rc = SQLITE_NOMEM;
171814 }else{
171815 sqlite3_free(zSql);
171816 zSql = 0;
171818 va_end(ap);
171819 return zSql;
171823 ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
171824 ** arguments are the usual subsitution values. This function performs
171825 ** the printf() style substitutions and executes the result as an SQL
171826 ** statement on the RBU handles database.
171828 ** If an error occurs, an error code and error message is stored in the
171829 ** RBU handle. If an error has already occurred when this function is
171830 ** called, it is a no-op.
171832 static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
171833 va_list ap;
171834 char *zSql;
171835 va_start(ap, zFmt);
171836 zSql = sqlite3_vmprintf(zFmt, ap);
171837 if( p->rc==SQLITE_OK ){
171838 if( zSql==0 ){
171839 p->rc = SQLITE_NOMEM;
171840 }else{
171841 p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
171844 sqlite3_free(zSql);
171845 va_end(ap);
171846 return p->rc;
171850 ** Attempt to allocate and return a pointer to a zeroed block of nByte
171851 ** bytes.
171853 ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
171854 ** error code in the rbu handle passed as the first argument. Or, if an
171855 ** error has already occurred when this function is called, return NULL
171856 ** immediately without attempting the allocation or modifying the stored
171857 ** error code.
171859 static void *rbuMalloc(sqlite3rbu *p, int nByte){
171860 void *pRet = 0;
171861 if( p->rc==SQLITE_OK ){
171862 assert( nByte>0 );
171863 pRet = sqlite3_malloc64(nByte);
171864 if( pRet==0 ){
171865 p->rc = SQLITE_NOMEM;
171866 }else{
171867 memset(pRet, 0, nByte);
171870 return pRet;
171875 ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
171876 ** there is room for at least nCol elements. If an OOM occurs, store an
171877 ** error code in the RBU handle passed as the first argument.
171879 static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
171880 int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
171881 char **azNew;
171883 azNew = (char**)rbuMalloc(p, nByte);
171884 if( azNew ){
171885 pIter->azTblCol = azNew;
171886 pIter->azTblType = &azNew[nCol];
171887 pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
171888 pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
171889 pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
171890 pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
171895 ** The first argument must be a nul-terminated string. This function
171896 ** returns a copy of the string in memory obtained from sqlite3_malloc().
171897 ** It is the responsibility of the caller to eventually free this memory
171898 ** using sqlite3_free().
171900 ** If an OOM condition is encountered when attempting to allocate memory,
171901 ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
171902 ** if the allocation succeeds, (*pRc) is left unchanged.
171904 static char *rbuStrndup(const char *zStr, int *pRc){
171905 char *zRet = 0;
171907 assert( *pRc==SQLITE_OK );
171908 if( zStr ){
171909 size_t nCopy = strlen(zStr) + 1;
171910 zRet = (char*)sqlite3_malloc64(nCopy);
171911 if( zRet ){
171912 memcpy(zRet, zStr, nCopy);
171913 }else{
171914 *pRc = SQLITE_NOMEM;
171918 return zRet;
171922 ** Finalize the statement passed as the second argument.
171924 ** If the sqlite3_finalize() call indicates that an error occurs, and the
171925 ** rbu handle error code is not already set, set the error code and error
171926 ** message accordingly.
171928 static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
171929 sqlite3 *db = sqlite3_db_handle(pStmt);
171930 int rc = sqlite3_finalize(pStmt);
171931 if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
171932 p->rc = rc;
171933 p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
171937 /* Determine the type of a table.
171939 ** peType is of type (int*), a pointer to an output parameter of type
171940 ** (int). This call sets the output parameter as follows, depending
171941 ** on the type of the table specified by parameters dbName and zTbl.
171943 ** RBU_PK_NOTABLE: No such table.
171944 ** RBU_PK_NONE: Table has an implicit rowid.
171945 ** RBU_PK_IPK: Table has an explicit IPK column.
171946 ** RBU_PK_EXTERNAL: Table has an external PK index.
171947 ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
171948 ** RBU_PK_VTAB: Table is a virtual table.
171950 ** Argument *piPk is also of type (int*), and also points to an output
171951 ** parameter. Unless the table has an external primary key index
171952 ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
171953 ** if the table does have an external primary key index, then *piPk
171954 ** is set to the root page number of the primary key index before
171955 ** returning.
171957 ** ALGORITHM:
171959 ** if( no entry exists in sqlite_master ){
171960 ** return RBU_PK_NOTABLE
171961 ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
171962 ** return RBU_PK_VTAB
171963 ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
171964 ** if( the index that is the pk exists in sqlite_master ){
171965 ** *piPK = rootpage of that index.
171966 ** return RBU_PK_EXTERNAL
171967 ** }else{
171968 ** return RBU_PK_WITHOUT_ROWID
171970 ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
171971 ** return RBU_PK_IPK
171972 ** }else{
171973 ** return RBU_PK_NONE
171976 static void rbuTableType(
171977 sqlite3rbu *p,
171978 const char *zTab,
171979 int *peType,
171980 int *piTnum,
171981 int *piPk
171984 ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
171985 ** 1) PRAGMA index_list = ?
171986 ** 2) SELECT count(*) FROM sqlite_master where name=%Q
171987 ** 3) PRAGMA table_info = ?
171989 sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
171991 *peType = RBU_PK_NOTABLE;
171992 *piPk = 0;
171994 assert( p->rc==SQLITE_OK );
171995 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
171996 sqlite3_mprintf(
171997 "SELECT (sql LIKE 'create virtual%%'), rootpage"
171998 " FROM sqlite_master"
171999 " WHERE name=%Q", zTab
172001 if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
172002 /* Either an error, or no such table. */
172003 goto rbuTableType_end;
172005 if( sqlite3_column_int(aStmt[0], 0) ){
172006 *peType = RBU_PK_VTAB; /* virtual table */
172007 goto rbuTableType_end;
172009 *piTnum = sqlite3_column_int(aStmt[0], 1);
172011 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
172012 sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
172014 if( p->rc ) goto rbuTableType_end;
172015 while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
172016 const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
172017 const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
172018 if( zOrig && zIdx && zOrig[0]=='p' ){
172019 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
172020 sqlite3_mprintf(
172021 "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
172023 if( p->rc==SQLITE_OK ){
172024 if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
172025 *piPk = sqlite3_column_int(aStmt[2], 0);
172026 *peType = RBU_PK_EXTERNAL;
172027 }else{
172028 *peType = RBU_PK_WITHOUT_ROWID;
172031 goto rbuTableType_end;
172035 p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
172036 sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
172038 if( p->rc==SQLITE_OK ){
172039 while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
172040 if( sqlite3_column_int(aStmt[3],5)>0 ){
172041 *peType = RBU_PK_IPK; /* explicit IPK column */
172042 goto rbuTableType_end;
172045 *peType = RBU_PK_NONE;
172048 rbuTableType_end: {
172049 unsigned int i;
172050 for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
172051 rbuFinalize(p, aStmt[i]);
172057 ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
172058 ** the pIter->abIndexed[] array.
172060 static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
172061 sqlite3_stmt *pList = 0;
172062 int bIndex = 0;
172064 if( p->rc==SQLITE_OK ){
172065 memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
172066 p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
172067 sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
172071 pIter->nIndex = 0;
172072 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
172073 const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
172074 sqlite3_stmt *pXInfo = 0;
172075 if( zIdx==0 ) break;
172076 p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
172077 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
172079 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
172080 int iCid = sqlite3_column_int(pXInfo, 1);
172081 if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
172083 rbuFinalize(p, pXInfo);
172084 bIndex = 1;
172085 pIter->nIndex++;
172088 if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
172089 /* "PRAGMA index_list" includes the main PK b-tree */
172090 pIter->nIndex--;
172093 rbuFinalize(p, pList);
172094 if( bIndex==0 ) pIter->abIndexed = 0;
172099 ** If they are not already populated, populate the pIter->azTblCol[],
172100 ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
172101 ** the table (not index) that the iterator currently points to.
172103 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
172104 ** an error does occur, an error code and error message are also left in
172105 ** the RBU handle.
172107 static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
172108 if( pIter->azTblCol==0 ){
172109 sqlite3_stmt *pStmt = 0;
172110 int nCol = 0;
172111 int i; /* for() loop iterator variable */
172112 int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
172113 int iOrder = 0;
172114 int iTnum = 0;
172116 /* Figure out the type of table this step will deal with. */
172117 assert( pIter->eType==0 );
172118 rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
172119 if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
172120 p->rc = SQLITE_ERROR;
172121 p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
172123 if( p->rc ) return p->rc;
172124 if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
172126 assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
172127 || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
172128 || pIter->eType==RBU_PK_VTAB
172131 /* Populate the azTblCol[] and nTblCol variables based on the columns
172132 ** of the input table. Ignore any input table columns that begin with
172133 ** "rbu_". */
172134 p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
172135 sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
172137 if( p->rc==SQLITE_OK ){
172138 nCol = sqlite3_column_count(pStmt);
172139 rbuAllocateIterArrays(p, pIter, nCol);
172141 for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
172142 const char *zName = (const char*)sqlite3_column_name(pStmt, i);
172143 if( sqlite3_strnicmp("rbu_", zName, 4) ){
172144 char *zCopy = rbuStrndup(zName, &p->rc);
172145 pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
172146 pIter->azTblCol[pIter->nTblCol++] = zCopy;
172148 else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
172149 bRbuRowid = 1;
172152 sqlite3_finalize(pStmt);
172153 pStmt = 0;
172155 if( p->rc==SQLITE_OK
172156 && rbuIsVacuum(p)==0
172157 && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
172159 p->rc = SQLITE_ERROR;
172160 p->zErrmsg = sqlite3_mprintf(
172161 "table %q %s rbu_rowid column", pIter->zDataTbl,
172162 (bRbuRowid ? "may not have" : "requires")
172166 /* Check that all non-HIDDEN columns in the destination table are also
172167 ** present in the input table. Populate the abTblPk[], azTblType[] and
172168 ** aiTblOrder[] arrays at the same time. */
172169 if( p->rc==SQLITE_OK ){
172170 p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
172171 sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
172174 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
172175 const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
172176 if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
172177 for(i=iOrder; i<pIter->nTblCol; i++){
172178 if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
172180 if( i==pIter->nTblCol ){
172181 p->rc = SQLITE_ERROR;
172182 p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
172183 pIter->zDataTbl, zName
172185 }else{
172186 int iPk = sqlite3_column_int(pStmt, 5);
172187 int bNotNull = sqlite3_column_int(pStmt, 3);
172188 const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
172190 if( i!=iOrder ){
172191 SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
172192 SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
172195 pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
172196 pIter->abTblPk[iOrder] = (iPk!=0);
172197 pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
172198 iOrder++;
172202 rbuFinalize(p, pStmt);
172203 rbuObjIterCacheIndexedCols(p, pIter);
172204 assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
172205 assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
172208 return p->rc;
172212 ** This function constructs and returns a pointer to a nul-terminated
172213 ** string containing some SQL clause or list based on one or more of the
172214 ** column names currently stored in the pIter->azTblCol[] array.
172216 static char *rbuObjIterGetCollist(
172217 sqlite3rbu *p, /* RBU object */
172218 RbuObjIter *pIter /* Object iterator for column names */
172220 char *zList = 0;
172221 const char *zSep = "";
172222 int i;
172223 for(i=0; i<pIter->nTblCol; i++){
172224 const char *z = pIter->azTblCol[i];
172225 zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
172226 zSep = ", ";
172228 return zList;
172232 ** This function is used to create a SELECT list (the list of SQL
172233 ** expressions that follows a SELECT keyword) for a SELECT statement
172234 ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
172235 ** index object currently indicated by the iterator object passed as the
172236 ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
172237 ** to obtain the required information.
172239 ** If the index is of the following form:
172241 ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
172243 ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
172244 ** "ipk", the returned string is:
172246 ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
172248 ** As well as the returned string, three other malloc'd strings are
172249 ** returned via output parameters. As follows:
172251 ** pzImposterCols: ...
172252 ** pzImposterPk: ...
172253 ** pzWhere: ...
172255 static char *rbuObjIterGetIndexCols(
172256 sqlite3rbu *p, /* RBU object */
172257 RbuObjIter *pIter, /* Object iterator for column names */
172258 char **pzImposterCols, /* OUT: Columns for imposter table */
172259 char **pzImposterPk, /* OUT: Imposter PK clause */
172260 char **pzWhere, /* OUT: WHERE clause */
172261 int *pnBind /* OUT: Trbul number of columns */
172263 int rc = p->rc; /* Error code */
172264 int rc2; /* sqlite3_finalize() return code */
172265 char *zRet = 0; /* String to return */
172266 char *zImpCols = 0; /* String to return via *pzImposterCols */
172267 char *zImpPK = 0; /* String to return via *pzImposterPK */
172268 char *zWhere = 0; /* String to return via *pzWhere */
172269 int nBind = 0; /* Value to return via *pnBind */
172270 const char *zCom = ""; /* Set to ", " later on */
172271 const char *zAnd = ""; /* Set to " AND " later on */
172272 sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
172274 if( rc==SQLITE_OK ){
172275 assert( p->zErrmsg==0 );
172276 rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
172277 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
172281 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
172282 int iCid = sqlite3_column_int(pXInfo, 1);
172283 int bDesc = sqlite3_column_int(pXInfo, 3);
172284 const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
172285 const char *zCol;
172286 const char *zType;
172288 if( iCid<0 ){
172289 /* An integer primary key. If the table has an explicit IPK, use
172290 ** its name. Otherwise, use "rbu_rowid". */
172291 if( pIter->eType==RBU_PK_IPK ){
172292 int i;
172293 for(i=0; pIter->abTblPk[i]==0; i++);
172294 assert( i<pIter->nTblCol );
172295 zCol = pIter->azTblCol[i];
172296 }else if( rbuIsVacuum(p) ){
172297 zCol = "_rowid_";
172298 }else{
172299 zCol = "rbu_rowid";
172301 zType = "INTEGER";
172302 }else{
172303 zCol = pIter->azTblCol[iCid];
172304 zType = pIter->azTblType[iCid];
172307 zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
172308 if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
172309 const char *zOrder = (bDesc ? " DESC" : "");
172310 zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
172311 zImpPK, zCom, nBind, zCol, zOrder
172314 zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
172315 zImpCols, zCom, nBind, zCol, zType, zCollate
172317 zWhere = sqlite3_mprintf(
172318 "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
172320 if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
172321 zCom = ", ";
172322 zAnd = " AND ";
172323 nBind++;
172326 rc2 = sqlite3_finalize(pXInfo);
172327 if( rc==SQLITE_OK ) rc = rc2;
172329 if( rc!=SQLITE_OK ){
172330 sqlite3_free(zRet);
172331 sqlite3_free(zImpCols);
172332 sqlite3_free(zImpPK);
172333 sqlite3_free(zWhere);
172334 zRet = 0;
172335 zImpCols = 0;
172336 zImpPK = 0;
172337 zWhere = 0;
172338 p->rc = rc;
172341 *pzImposterCols = zImpCols;
172342 *pzImposterPk = zImpPK;
172343 *pzWhere = zWhere;
172344 *pnBind = nBind;
172345 return zRet;
172349 ** Assuming the current table columns are "a", "b" and "c", and the zObj
172350 ** paramter is passed "old", return a string of the form:
172352 ** "old.a, old.b, old.b"
172354 ** With the column names escaped.
172356 ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
172357 ** the text ", old._rowid_" to the returned value.
172359 static char *rbuObjIterGetOldlist(
172360 sqlite3rbu *p,
172361 RbuObjIter *pIter,
172362 const char *zObj
172364 char *zList = 0;
172365 if( p->rc==SQLITE_OK && pIter->abIndexed ){
172366 const char *zS = "";
172367 int i;
172368 for(i=0; i<pIter->nTblCol; i++){
172369 if( pIter->abIndexed[i] ){
172370 const char *zCol = pIter->azTblCol[i];
172371 zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
172372 }else{
172373 zList = sqlite3_mprintf("%z%sNULL", zList, zS);
172375 zS = ", ";
172376 if( zList==0 ){
172377 p->rc = SQLITE_NOMEM;
172378 break;
172382 /* For a table with implicit rowids, append "old._rowid_" to the list. */
172383 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
172384 zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
172387 return zList;
172391 ** Return an expression that can be used in a WHERE clause to match the
172392 ** primary key of the current table. For example, if the table is:
172394 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
172396 ** Return the string:
172398 ** "b = ?1 AND c = ?2"
172400 static char *rbuObjIterGetWhere(
172401 sqlite3rbu *p,
172402 RbuObjIter *pIter
172404 char *zList = 0;
172405 if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
172406 zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
172407 }else if( pIter->eType==RBU_PK_EXTERNAL ){
172408 const char *zSep = "";
172409 int i;
172410 for(i=0; i<pIter->nTblCol; i++){
172411 if( pIter->abTblPk[i] ){
172412 zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
172413 zSep = " AND ";
172416 zList = rbuMPrintf(p,
172417 "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
172420 }else{
172421 const char *zSep = "";
172422 int i;
172423 for(i=0; i<pIter->nTblCol; i++){
172424 if( pIter->abTblPk[i] ){
172425 const char *zCol = pIter->azTblCol[i];
172426 zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
172427 zSep = " AND ";
172431 return zList;
172435 ** The SELECT statement iterating through the keys for the current object
172436 ** (p->objiter.pSelect) currently points to a valid row. However, there
172437 ** is something wrong with the rbu_control value in the rbu_control value
172438 ** stored in the (p->nCol+1)'th column. Set the error code and error message
172439 ** of the RBU handle to something reflecting this.
172441 static void rbuBadControlError(sqlite3rbu *p){
172442 p->rc = SQLITE_ERROR;
172443 p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
172448 ** Return a nul-terminated string containing the comma separated list of
172449 ** assignments that should be included following the "SET" keyword of
172450 ** an UPDATE statement used to update the table object that the iterator
172451 ** passed as the second argument currently points to if the rbu_control
172452 ** column of the data_xxx table entry is set to zMask.
172454 ** The memory for the returned string is obtained from sqlite3_malloc().
172455 ** It is the responsibility of the caller to eventually free it using
172456 ** sqlite3_free().
172458 ** If an OOM error is encountered when allocating space for the new
172459 ** string, an error code is left in the rbu handle passed as the first
172460 ** argument and NULL is returned. Or, if an error has already occurred
172461 ** when this function is called, NULL is returned immediately, without
172462 ** attempting the allocation or modifying the stored error code.
172464 static char *rbuObjIterGetSetlist(
172465 sqlite3rbu *p,
172466 RbuObjIter *pIter,
172467 const char *zMask
172469 char *zList = 0;
172470 if( p->rc==SQLITE_OK ){
172471 int i;
172473 if( (int)strlen(zMask)!=pIter->nTblCol ){
172474 rbuBadControlError(p);
172475 }else{
172476 const char *zSep = "";
172477 for(i=0; i<pIter->nTblCol; i++){
172478 char c = zMask[pIter->aiSrcOrder[i]];
172479 if( c=='x' ){
172480 zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
172481 zList, zSep, pIter->azTblCol[i], i+1
172483 zSep = ", ";
172485 else if( c=='d' ){
172486 zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
172487 zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
172489 zSep = ", ";
172491 else if( c=='f' ){
172492 zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
172493 zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
172495 zSep = ", ";
172500 return zList;
172504 ** Return a nul-terminated string consisting of nByte comma separated
172505 ** "?" expressions. For example, if nByte is 3, return a pointer to
172506 ** a buffer containing the string "?,?,?".
172508 ** The memory for the returned string is obtained from sqlite3_malloc().
172509 ** It is the responsibility of the caller to eventually free it using
172510 ** sqlite3_free().
172512 ** If an OOM error is encountered when allocating space for the new
172513 ** string, an error code is left in the rbu handle passed as the first
172514 ** argument and NULL is returned. Or, if an error has already occurred
172515 ** when this function is called, NULL is returned immediately, without
172516 ** attempting the allocation or modifying the stored error code.
172518 static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
172519 char *zRet = 0;
172520 int nByte = nBind*2 + 1;
172522 zRet = (char*)rbuMalloc(p, nByte);
172523 if( zRet ){
172524 int i;
172525 for(i=0; i<nBind; i++){
172526 zRet[i*2] = '?';
172527 zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
172530 return zRet;
172534 ** The iterator currently points to a table (not index) of type
172535 ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
172536 ** declaration for the corresponding imposter table. For example,
172537 ** if the iterator points to a table created as:
172539 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
172541 ** this function returns:
172543 ** PRIMARY KEY("b", "a" DESC)
172545 static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
172546 char *z = 0;
172547 assert( pIter->zIdx==0 );
172548 if( p->rc==SQLITE_OK ){
172549 const char *zSep = "PRIMARY KEY(";
172550 sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
172551 sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
172553 p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
172554 sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
172556 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
172557 const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
172558 if( zOrig && strcmp(zOrig, "pk")==0 ){
172559 const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
172560 if( zIdx ){
172561 p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
172562 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
172565 break;
172568 rbuFinalize(p, pXList);
172570 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
172571 if( sqlite3_column_int(pXInfo, 5) ){
172572 /* int iCid = sqlite3_column_int(pXInfo, 0); */
172573 const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
172574 const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
172575 z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
172576 zSep = ", ";
172579 z = rbuMPrintf(p, "%z)", z);
172580 rbuFinalize(p, pXInfo);
172582 return z;
172586 ** This function creates the second imposter table used when writing to
172587 ** a table b-tree where the table has an external primary key. If the
172588 ** iterator passed as the second argument does not currently point to
172589 ** a table (not index) with an external primary key, this function is a
172590 ** no-op.
172592 ** Assuming the iterator does point to a table with an external PK, this
172593 ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
172594 ** used to access that PK index. For example, if the target table is
172595 ** declared as follows:
172597 ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
172599 ** then the imposter table schema is:
172601 ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
172604 static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
172605 if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
172606 int tnum = pIter->iPkTnum; /* Root page of PK index */
172607 sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
172608 const char *zIdx = 0; /* Name of PK index */
172609 sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
172610 const char *zComma = "";
172611 char *zCols = 0; /* Used to build up list of table cols */
172612 char *zPk = 0; /* Used to build up table PK declaration */
172614 /* Figure out the name of the primary key index for the current table.
172615 ** This is needed for the argument to "PRAGMA index_xinfo". Set
172616 ** zIdx to point to a nul-terminated string containing this name. */
172617 p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
172618 "SELECT name FROM sqlite_master WHERE rootpage = ?"
172620 if( p->rc==SQLITE_OK ){
172621 sqlite3_bind_int(pQuery, 1, tnum);
172622 if( SQLITE_ROW==sqlite3_step(pQuery) ){
172623 zIdx = (const char*)sqlite3_column_text(pQuery, 0);
172626 if( zIdx ){
172627 p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
172628 sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
172631 rbuFinalize(p, pQuery);
172633 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
172634 int bKey = sqlite3_column_int(pXInfo, 5);
172635 if( bKey ){
172636 int iCid = sqlite3_column_int(pXInfo, 1);
172637 int bDesc = sqlite3_column_int(pXInfo, 3);
172638 const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
172639 zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
172640 iCid, pIter->azTblType[iCid], zCollate
172642 zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
172643 zComma = ", ";
172646 zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
172647 rbuFinalize(p, pXInfo);
172649 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
172650 rbuMPrintfExec(p, p->dbMain,
172651 "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
172652 zCols, zPk
172654 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
172659 ** If an error has already occurred when this function is called, it
172660 ** immediately returns zero (without doing any work). Or, if an error
172661 ** occurs during the execution of this function, it sets the error code
172662 ** in the sqlite3rbu object indicated by the first argument and returns
172663 ** zero.
172665 ** The iterator passed as the second argument is guaranteed to point to
172666 ** a table (not an index) when this function is called. This function
172667 ** attempts to create any imposter table required to write to the main
172668 ** table b-tree of the table before returning. Non-zero is returned if
172669 ** an imposter table are created, or zero otherwise.
172671 ** An imposter table is required in all cases except RBU_PK_VTAB. Only
172672 ** virtual tables are written to directly. The imposter table has the
172673 ** same schema as the actual target table (less any UNIQUE constraints).
172674 ** More precisely, the "same schema" means the same columns, types,
172675 ** collation sequences. For tables that do not have an external PRIMARY
172676 ** KEY, it also means the same PRIMARY KEY declaration.
172678 static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
172679 if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
172680 int tnum = pIter->iTnum;
172681 const char *zComma = "";
172682 char *zSql = 0;
172683 int iCol;
172684 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
172686 for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
172687 const char *zPk = "";
172688 const char *zCol = pIter->azTblCol[iCol];
172689 const char *zColl = 0;
172691 p->rc = sqlite3_table_column_metadata(
172692 p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
172695 if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
172696 /* If the target table column is an "INTEGER PRIMARY KEY", add
172697 ** "PRIMARY KEY" to the imposter table column declaration. */
172698 zPk = "PRIMARY KEY ";
172700 zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
172701 zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
172702 (pIter->abNotNull[iCol] ? " NOT NULL" : "")
172704 zComma = ", ";
172707 if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
172708 char *zPk = rbuWithoutRowidPK(p, pIter);
172709 if( zPk ){
172710 zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
172714 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
172715 rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
172716 pIter->zTbl, zSql,
172717 (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
172719 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
172724 ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
172725 ** Specifically a statement of the form:
172727 ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
172729 ** The number of bound variables is equal to the number of columns in
172730 ** the target table, plus one (for the rbu_control column), plus one more
172731 ** (for the rbu_rowid column) if the target table is an implicit IPK or
172732 ** virtual table.
172734 static void rbuObjIterPrepareTmpInsert(
172735 sqlite3rbu *p,
172736 RbuObjIter *pIter,
172737 const char *zCollist,
172738 const char *zRbuRowid
172740 int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
172741 char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
172742 if( zBind ){
172743 assert( pIter->pTmpInsert==0 );
172744 p->rc = prepareFreeAndCollectError(
172745 p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
172746 "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
172747 p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
172752 static void rbuTmpInsertFunc(
172753 sqlite3_context *pCtx,
172754 int nVal,
172755 sqlite3_value **apVal
172757 sqlite3rbu *p = sqlite3_user_data(pCtx);
172758 int rc = SQLITE_OK;
172759 int i;
172761 assert( sqlite3_value_int(apVal[0])!=0
172762 || p->objiter.eType==RBU_PK_EXTERNAL
172763 || p->objiter.eType==RBU_PK_NONE
172765 if( sqlite3_value_int(apVal[0])!=0 ){
172766 p->nPhaseOneStep += p->objiter.nIndex;
172769 for(i=0; rc==SQLITE_OK && i<nVal; i++){
172770 rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
172772 if( rc==SQLITE_OK ){
172773 sqlite3_step(p->objiter.pTmpInsert);
172774 rc = sqlite3_reset(p->objiter.pTmpInsert);
172777 if( rc!=SQLITE_OK ){
172778 sqlite3_result_error_code(pCtx, rc);
172783 ** Ensure that the SQLite statement handles required to update the
172784 ** target database object currently indicated by the iterator passed
172785 ** as the second argument are available.
172787 static int rbuObjIterPrepareAll(
172788 sqlite3rbu *p,
172789 RbuObjIter *pIter,
172790 int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
172792 assert( pIter->bCleanup==0 );
172793 if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
172794 const int tnum = pIter->iTnum;
172795 char *zCollist = 0; /* List of indexed columns */
172796 char **pz = &p->zErrmsg;
172797 const char *zIdx = pIter->zIdx;
172798 char *zLimit = 0;
172800 if( nOffset ){
172801 zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
172802 if( !zLimit ) p->rc = SQLITE_NOMEM;
172805 if( zIdx ){
172806 const char *zTbl = pIter->zTbl;
172807 char *zImposterCols = 0; /* Columns for imposter table */
172808 char *zImposterPK = 0; /* Primary key declaration for imposter */
172809 char *zWhere = 0; /* WHERE clause on PK columns */
172810 char *zBind = 0;
172811 int nBind = 0;
172813 assert( pIter->eType!=RBU_PK_VTAB );
172814 zCollist = rbuObjIterGetIndexCols(
172815 p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
172817 zBind = rbuObjIterGetBindlist(p, nBind);
172819 /* Create the imposter table used to write to this index. */
172820 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
172821 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
172822 rbuMPrintfExec(p, p->dbMain,
172823 "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
172824 zTbl, zImposterCols, zImposterPK
172826 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
172828 /* Create the statement to insert index entries */
172829 pIter->nCol = nBind;
172830 if( p->rc==SQLITE_OK ){
172831 p->rc = prepareFreeAndCollectError(
172832 p->dbMain, &pIter->pInsert, &p->zErrmsg,
172833 sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
172837 /* And to delete index entries */
172838 if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
172839 p->rc = prepareFreeAndCollectError(
172840 p->dbMain, &pIter->pDelete, &p->zErrmsg,
172841 sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
172845 /* Create the SELECT statement to read keys in sorted order */
172846 if( p->rc==SQLITE_OK ){
172847 char *zSql;
172848 if( rbuIsVacuum(p) ){
172849 zSql = sqlite3_mprintf(
172850 "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
172851 zCollist,
172852 pIter->zDataTbl,
172853 zCollist, zLimit
172855 }else
172857 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
172858 zSql = sqlite3_mprintf(
172859 "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
172860 zCollist, p->zStateDb, pIter->zDataTbl,
172861 zCollist, zLimit
172863 }else{
172864 zSql = sqlite3_mprintf(
172865 "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
172866 "UNION ALL "
172867 "SELECT %s, rbu_control FROM '%q' "
172868 "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
172869 "ORDER BY %s%s",
172870 zCollist, p->zStateDb, pIter->zDataTbl,
172871 zCollist, pIter->zDataTbl,
172872 zCollist, zLimit
172875 p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
172878 sqlite3_free(zImposterCols);
172879 sqlite3_free(zImposterPK);
172880 sqlite3_free(zWhere);
172881 sqlite3_free(zBind);
172882 }else{
172883 int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
172884 ||(pIter->eType==RBU_PK_NONE)
172885 ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
172886 const char *zTbl = pIter->zTbl; /* Table this step applies to */
172887 const char *zWrite; /* Imposter table name */
172889 char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
172890 char *zWhere = rbuObjIterGetWhere(p, pIter);
172891 char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
172892 char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
172894 zCollist = rbuObjIterGetCollist(p, pIter);
172895 pIter->nCol = pIter->nTblCol;
172897 /* Create the imposter table or tables (if required). */
172898 rbuCreateImposterTable(p, pIter);
172899 rbuCreateImposterTable2(p, pIter);
172900 zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
172902 /* Create the INSERT statement to write to the target PK b-tree */
172903 if( p->rc==SQLITE_OK ){
172904 p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
172905 sqlite3_mprintf(
172906 "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
172907 zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
172912 /* Create the DELETE statement to write to the target PK b-tree.
172913 ** Because it only performs INSERT operations, this is not required for
172914 ** an rbu vacuum handle. */
172915 if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
172916 p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
172917 sqlite3_mprintf(
172918 "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
172923 if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
172924 const char *zRbuRowid = "";
172925 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
172926 zRbuRowid = ", rbu_rowid";
172929 /* Create the rbu_tmp_xxx table and the triggers to populate it. */
172930 rbuMPrintfExec(p, p->dbRbu,
172931 "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
172932 "SELECT *%s FROM '%q' WHERE 0;"
172933 , p->zStateDb, pIter->zDataTbl
172934 , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
172935 , pIter->zDataTbl
172938 rbuMPrintfExec(p, p->dbMain,
172939 "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
172940 "BEGIN "
172941 " SELECT rbu_tmp_insert(3, %s);"
172942 "END;"
172944 "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
172945 "BEGIN "
172946 " SELECT rbu_tmp_insert(3, %s);"
172947 "END;"
172949 "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
172950 "BEGIN "
172951 " SELECT rbu_tmp_insert(4, %s);"
172952 "END;",
172953 zWrite, zTbl, zOldlist,
172954 zWrite, zTbl, zOldlist,
172955 zWrite, zTbl, zNewlist
172958 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
172959 rbuMPrintfExec(p, p->dbMain,
172960 "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
172961 "BEGIN "
172962 " SELECT rbu_tmp_insert(0, %s);"
172963 "END;",
172964 zWrite, zTbl, zNewlist
172968 rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
172971 /* Create the SELECT statement to read keys from data_xxx */
172972 if( p->rc==SQLITE_OK ){
172973 const char *zRbuRowid = "";
172974 if( bRbuRowid ){
172975 zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
172977 p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
172978 sqlite3_mprintf(
172979 "SELECT %s,%s rbu_control%s FROM '%q'%s",
172980 zCollist,
172981 (rbuIsVacuum(p) ? "0 AS " : ""),
172982 zRbuRowid,
172983 pIter->zDataTbl, zLimit
172988 sqlite3_free(zWhere);
172989 sqlite3_free(zOldlist);
172990 sqlite3_free(zNewlist);
172991 sqlite3_free(zBindings);
172993 sqlite3_free(zCollist);
172994 sqlite3_free(zLimit);
172997 return p->rc;
173001 ** Set output variable *ppStmt to point to an UPDATE statement that may
173002 ** be used to update the imposter table for the main table b-tree of the
173003 ** table object that pIter currently points to, assuming that the
173004 ** rbu_control column of the data_xyz table contains zMask.
173006 ** If the zMask string does not specify any columns to update, then this
173007 ** is not an error. Output variable *ppStmt is set to NULL in this case.
173009 static int rbuGetUpdateStmt(
173010 sqlite3rbu *p, /* RBU handle */
173011 RbuObjIter *pIter, /* Object iterator */
173012 const char *zMask, /* rbu_control value ('x.x.') */
173013 sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
173015 RbuUpdateStmt **pp;
173016 RbuUpdateStmt *pUp = 0;
173017 int nUp = 0;
173019 /* In case an error occurs */
173020 *ppStmt = 0;
173022 /* Search for an existing statement. If one is found, shift it to the front
173023 ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
173024 ** to the number of statements currently in the cache and pUp to the
173025 ** last object in the list. */
173026 for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
173027 pUp = *pp;
173028 if( strcmp(pUp->zMask, zMask)==0 ){
173029 *pp = pUp->pNext;
173030 pUp->pNext = pIter->pRbuUpdate;
173031 pIter->pRbuUpdate = pUp;
173032 *ppStmt = pUp->pUpdate;
173033 return SQLITE_OK;
173035 nUp++;
173037 assert( pUp==0 || pUp->pNext==0 );
173039 if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
173040 for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
173041 *pp = 0;
173042 sqlite3_finalize(pUp->pUpdate);
173043 pUp->pUpdate = 0;
173044 }else{
173045 pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
173048 if( pUp ){
173049 char *zWhere = rbuObjIterGetWhere(p, pIter);
173050 char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
173051 char *zUpdate = 0;
173053 pUp->zMask = (char*)&pUp[1];
173054 memcpy(pUp->zMask, zMask, pIter->nTblCol);
173055 pUp->pNext = pIter->pRbuUpdate;
173056 pIter->pRbuUpdate = pUp;
173058 if( zSet ){
173059 const char *zPrefix = "";
173061 if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
173062 zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
173063 zPrefix, pIter->zTbl, zSet, zWhere
173065 p->rc = prepareFreeAndCollectError(
173066 p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
173068 *ppStmt = pUp->pUpdate;
173070 sqlite3_free(zWhere);
173071 sqlite3_free(zSet);
173074 return p->rc;
173077 static sqlite3 *rbuOpenDbhandle(
173078 sqlite3rbu *p,
173079 const char *zName,
173080 int bUseVfs
173082 sqlite3 *db = 0;
173083 if( p->rc==SQLITE_OK ){
173084 const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
173085 p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
173086 if( p->rc ){
173087 p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
173088 sqlite3_close(db);
173089 db = 0;
173092 return db;
173096 ** Free an RbuState object allocated by rbuLoadState().
173098 static void rbuFreeState(RbuState *p){
173099 if( p ){
173100 sqlite3_free(p->zTbl);
173101 sqlite3_free(p->zIdx);
173102 sqlite3_free(p);
173107 ** Allocate an RbuState object and load the contents of the rbu_state
173108 ** table into it. Return a pointer to the new object. It is the
173109 ** responsibility of the caller to eventually free the object using
173110 ** sqlite3_free().
173112 ** If an error occurs, leave an error code and message in the rbu handle
173113 ** and return NULL.
173115 static RbuState *rbuLoadState(sqlite3rbu *p){
173116 RbuState *pRet = 0;
173117 sqlite3_stmt *pStmt = 0;
173118 int rc;
173119 int rc2;
173121 pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
173122 if( pRet==0 ) return 0;
173124 rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
173125 sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
173127 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
173128 switch( sqlite3_column_int(pStmt, 0) ){
173129 case RBU_STATE_STAGE:
173130 pRet->eStage = sqlite3_column_int(pStmt, 1);
173131 if( pRet->eStage!=RBU_STAGE_OAL
173132 && pRet->eStage!=RBU_STAGE_MOVE
173133 && pRet->eStage!=RBU_STAGE_CKPT
173135 p->rc = SQLITE_CORRUPT;
173137 break;
173139 case RBU_STATE_TBL:
173140 pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
173141 break;
173143 case RBU_STATE_IDX:
173144 pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
173145 break;
173147 case RBU_STATE_ROW:
173148 pRet->nRow = sqlite3_column_int(pStmt, 1);
173149 break;
173151 case RBU_STATE_PROGRESS:
173152 pRet->nProgress = sqlite3_column_int64(pStmt, 1);
173153 break;
173155 case RBU_STATE_CKPT:
173156 pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
173157 break;
173159 case RBU_STATE_COOKIE:
173160 pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
173161 break;
173163 case RBU_STATE_OALSZ:
173164 pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
173165 break;
173167 case RBU_STATE_PHASEONESTEP:
173168 pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
173169 break;
173171 default:
173172 rc = SQLITE_CORRUPT;
173173 break;
173176 rc2 = sqlite3_finalize(pStmt);
173177 if( rc==SQLITE_OK ) rc = rc2;
173179 p->rc = rc;
173180 return pRet;
173185 ** Open the database handle and attach the RBU database as "rbu". If an
173186 ** error occurs, leave an error code and message in the RBU handle.
173188 static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
173189 assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
173190 assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
173192 /* Open the RBU database */
173193 p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
173195 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
173196 sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
173197 if( p->zState==0 ){
173198 const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
173199 p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
173203 /* If using separate RBU and state databases, attach the state database to
173204 ** the RBU db handle now. */
173205 if( p->zState ){
173206 rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
173207 memcpy(p->zStateDb, "stat", 4);
173208 }else{
173209 memcpy(p->zStateDb, "main", 4);
173212 #if 0
173213 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
173214 p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
173216 #endif
173218 /* If it has not already been created, create the rbu_state table */
173219 rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
173221 #if 0
173222 if( rbuIsVacuum(p) ){
173223 if( p->rc==SQLITE_OK ){
173224 int rc2;
173225 int bOk = 0;
173226 sqlite3_stmt *pCnt = 0;
173227 p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
173228 "SELECT count(*) FROM stat.sqlite_master"
173230 if( p->rc==SQLITE_OK
173231 && sqlite3_step(pCnt)==SQLITE_ROW
173232 && 1==sqlite3_column_int(pCnt, 0)
173234 bOk = 1;
173236 rc2 = sqlite3_finalize(pCnt);
173237 if( p->rc==SQLITE_OK ) p->rc = rc2;
173239 if( p->rc==SQLITE_OK && bOk==0 ){
173240 p->rc = SQLITE_ERROR;
173241 p->zErrmsg = sqlite3_mprintf("invalid state database");
173244 if( p->rc==SQLITE_OK ){
173245 p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
173249 #endif
173251 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
173252 int bOpen = 0;
173253 int rc;
173254 p->nRbu = 0;
173255 p->pRbuFd = 0;
173256 rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
173257 if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
173258 if( p->eStage>=RBU_STAGE_MOVE ){
173259 bOpen = 1;
173260 }else{
173261 RbuState *pState = rbuLoadState(p);
173262 if( pState ){
173263 bOpen = (pState->eStage>=RBU_STAGE_MOVE);
173264 rbuFreeState(pState);
173267 if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
173270 p->eStage = 0;
173271 if( p->rc==SQLITE_OK && p->dbMain==0 ){
173272 if( !rbuIsVacuum(p) ){
173273 p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
173274 }else if( p->pRbuFd->pWalFd ){
173275 if( pbRetry ){
173276 p->pRbuFd->bNolock = 0;
173277 sqlite3_close(p->dbRbu);
173278 sqlite3_close(p->dbMain);
173279 p->dbMain = 0;
173280 p->dbRbu = 0;
173281 *pbRetry = 1;
173282 return;
173284 p->rc = SQLITE_ERROR;
173285 p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
173286 }else{
173287 char *zTarget;
173288 char *zExtra = 0;
173289 if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
173290 zExtra = &p->zRbu[5];
173291 while( *zExtra ){
173292 if( *zExtra++=='?' ) break;
173294 if( *zExtra=='\0' ) zExtra = 0;
173297 zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
173298 sqlite3_db_filename(p->dbRbu, "main"),
173299 (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
173302 if( zTarget==0 ){
173303 p->rc = SQLITE_NOMEM;
173304 return;
173306 p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
173307 sqlite3_free(zTarget);
173311 if( p->rc==SQLITE_OK ){
173312 p->rc = sqlite3_create_function(p->dbMain,
173313 "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
173317 if( p->rc==SQLITE_OK ){
173318 p->rc = sqlite3_create_function(p->dbMain,
173319 "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
173323 if( p->rc==SQLITE_OK ){
173324 p->rc = sqlite3_create_function(p->dbRbu,
173325 "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
173329 if( p->rc==SQLITE_OK ){
173330 p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
173332 rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
173334 /* Mark the database file just opened as an RBU target database. If
173335 ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
173336 ** This is an error. */
173337 if( p->rc==SQLITE_OK ){
173338 p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
173341 if( p->rc==SQLITE_NOTFOUND ){
173342 p->rc = SQLITE_ERROR;
173343 p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
173348 ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
173349 ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
173351 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
173352 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
173353 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
173354 ** three characters, then shorten the suffix on z[] to be the last three
173355 ** characters of the original suffix.
173357 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
173358 ** do the suffix shortening regardless of URI parameter.
173360 ** Examples:
173362 ** test.db-journal => test.nal
173363 ** test.db-wal => test.wal
173364 ** test.db-shm => test.shm
173365 ** test.db-mj7f3319fa => test.9fa
173367 static void rbuFileSuffix3(const char *zBase, char *z){
173368 #ifdef SQLITE_ENABLE_8_3_NAMES
173369 #if SQLITE_ENABLE_8_3_NAMES<2
173370 if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
173371 #endif
173373 int i, sz;
173374 sz = (int)strlen(z)&0xffffff;
173375 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
173376 if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
173378 #endif
173382 ** Return the current wal-index header checksum for the target database
173383 ** as a 64-bit integer.
173385 ** The checksum is store in the first page of xShmMap memory as an 8-byte
173386 ** blob starting at byte offset 40.
173388 static i64 rbuShmChecksum(sqlite3rbu *p){
173389 i64 iRet = 0;
173390 if( p->rc==SQLITE_OK ){
173391 sqlite3_file *pDb = p->pTargetFd->pReal;
173392 u32 volatile *ptr;
173393 p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
173394 if( p->rc==SQLITE_OK ){
173395 iRet = ((i64)ptr[10] << 32) + ptr[11];
173398 return iRet;
173402 ** This function is called as part of initializing or reinitializing an
173403 ** incremental checkpoint.
173405 ** It populates the sqlite3rbu.aFrame[] array with the set of
173406 ** (wal frame -> db page) copy operations required to checkpoint the
173407 ** current wal file, and obtains the set of shm locks required to safely
173408 ** perform the copy operations directly on the file-system.
173410 ** If argument pState is not NULL, then the incremental checkpoint is
173411 ** being resumed. In this case, if the checksum of the wal-index-header
173412 ** following recovery is not the same as the checksum saved in the RbuState
173413 ** object, then the rbu handle is set to DONE state. This occurs if some
173414 ** other client appends a transaction to the wal file in the middle of
173415 ** an incremental checkpoint.
173417 static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
173419 /* If pState is NULL, then the wal file may not have been opened and
173420 ** recovered. Running a read-statement here to ensure that doing so
173421 ** does not interfere with the "capture" process below. */
173422 if( pState==0 ){
173423 p->eStage = 0;
173424 if( p->rc==SQLITE_OK ){
173425 p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
173429 /* Assuming no error has occurred, run a "restart" checkpoint with the
173430 ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
173431 ** special behaviour in the rbu VFS:
173433 ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
173434 ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
173435 ** proceed with running a passive checkpoint instead of failing).
173437 ** * Attempts to read from the *-wal file or write to the database file
173438 ** do not perform any IO. Instead, the frame/page combinations that
173439 ** would be read/written are recorded in the sqlite3rbu.aFrame[]
173440 ** array.
173442 ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
173443 ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
173444 ** no-ops. These locks will not be released until the connection
173445 ** is closed.
173447 ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
173448 ** error.
173450 ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
173451 ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
173452 ** array populated with a set of (frame -> page) mappings. Because the
173453 ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
173454 ** data from the wal file into the database file according to the
173455 ** contents of aFrame[].
173457 if( p->rc==SQLITE_OK ){
173458 int rc2;
173459 p->eStage = RBU_STAGE_CAPTURE;
173460 rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
173461 if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
173464 if( p->rc==SQLITE_OK && p->nFrame>0 ){
173465 p->eStage = RBU_STAGE_CKPT;
173466 p->nStep = (pState ? pState->nRow : 0);
173467 p->aBuf = rbuMalloc(p, p->pgsz);
173468 p->iWalCksum = rbuShmChecksum(p);
173471 if( p->rc==SQLITE_OK ){
173472 if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
173473 p->rc = SQLITE_DONE;
173474 p->eStage = RBU_STAGE_DONE;
173475 }else{
173476 int nSectorSize;
173477 sqlite3_file *pDb = p->pTargetFd->pReal;
173478 sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
173479 assert( p->nPagePerSector==0 );
173480 nSectorSize = pDb->pMethods->xSectorSize(pDb);
173481 if( nSectorSize>p->pgsz ){
173482 p->nPagePerSector = nSectorSize / p->pgsz;
173483 }else{
173484 p->nPagePerSector = 1;
173487 /* Call xSync() on the wal file. This causes SQLite to sync the
173488 ** directory in which the target database and the wal file reside, in
173489 ** case it has not been synced since the rename() call in
173490 ** rbuMoveOalFile(). */
173491 p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
173497 ** Called when iAmt bytes are read from offset iOff of the wal file while
173498 ** the rbu object is in capture mode. Record the frame number of the frame
173499 ** being read in the aFrame[] array.
173501 static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
173502 const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
173503 u32 iFrame;
173505 if( pRbu->mLock!=mReq ){
173506 pRbu->rc = SQLITE_BUSY;
173507 return SQLITE_INTERNAL;
173510 pRbu->pgsz = iAmt;
173511 if( pRbu->nFrame==pRbu->nFrameAlloc ){
173512 int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
173513 RbuFrame *aNew;
173514 aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
173515 if( aNew==0 ) return SQLITE_NOMEM;
173516 pRbu->aFrame = aNew;
173517 pRbu->nFrameAlloc = nNew;
173520 iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
173521 if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
173522 pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
173523 pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
173524 pRbu->nFrame++;
173525 return SQLITE_OK;
173529 ** Called when a page of data is written to offset iOff of the database
173530 ** file while the rbu handle is in capture mode. Record the page number
173531 ** of the page being written in the aFrame[] array.
173533 static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
173534 pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
173535 return SQLITE_OK;
173539 ** This is called as part of an incremental checkpoint operation. Copy
173540 ** a single frame of data from the wal file into the database file, as
173541 ** indicated by the RbuFrame object.
173543 static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
173544 sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
173545 sqlite3_file *pDb = p->pTargetFd->pReal;
173546 i64 iOff;
173548 assert( p->rc==SQLITE_OK );
173549 iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
173550 p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
173551 if( p->rc ) return;
173553 iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
173554 p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
173559 ** Take an EXCLUSIVE lock on the database file.
173561 static void rbuLockDatabase(sqlite3rbu *p){
173562 sqlite3_file *pReal = p->pTargetFd->pReal;
173563 assert( p->rc==SQLITE_OK );
173564 p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
173565 if( p->rc==SQLITE_OK ){
173566 p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
173570 #if defined(_WIN32_WCE)
173571 static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
173572 int nChar;
173573 LPWSTR zWideFilename;
173575 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
173576 if( nChar==0 ){
173577 return 0;
173579 zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
173580 if( zWideFilename==0 ){
173581 return 0;
173583 memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
173584 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
173585 nChar);
173586 if( nChar==0 ){
173587 sqlite3_free(zWideFilename);
173588 zWideFilename = 0;
173590 return zWideFilename;
173592 #endif
173595 ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
173596 ** on the database file. This proc moves the *-oal file to the *-wal path,
173597 ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
173598 ** If an error occurs, leave an error code and error message in the rbu
173599 ** handle.
173601 static void rbuMoveOalFile(sqlite3rbu *p){
173602 const char *zBase = sqlite3_db_filename(p->dbMain, "main");
173603 const char *zMove = zBase;
173604 char *zOal;
173605 char *zWal;
173607 if( rbuIsVacuum(p) ){
173608 zMove = sqlite3_db_filename(p->dbRbu, "main");
173610 zOal = sqlite3_mprintf("%s-oal", zMove);
173611 zWal = sqlite3_mprintf("%s-wal", zMove);
173613 assert( p->eStage==RBU_STAGE_MOVE );
173614 assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
173615 if( zWal==0 || zOal==0 ){
173616 p->rc = SQLITE_NOMEM;
173617 }else{
173618 /* Move the *-oal file to *-wal. At this point connection p->db is
173619 ** holding a SHARED lock on the target database file (because it is
173620 ** in WAL mode). So no other connection may be writing the db.
173622 ** In order to ensure that there are no database readers, an EXCLUSIVE
173623 ** lock is obtained here before the *-oal is moved to *-wal.
173625 rbuLockDatabase(p);
173626 if( p->rc==SQLITE_OK ){
173627 rbuFileSuffix3(zBase, zWal);
173628 rbuFileSuffix3(zBase, zOal);
173630 /* Re-open the databases. */
173631 rbuObjIterFinalize(&p->objiter);
173632 sqlite3_close(p->dbRbu);
173633 sqlite3_close(p->dbMain);
173634 p->dbMain = 0;
173635 p->dbRbu = 0;
173637 #if defined(_WIN32_WCE)
173639 LPWSTR zWideOal;
173640 LPWSTR zWideWal;
173642 zWideOal = rbuWinUtf8ToUnicode(zOal);
173643 if( zWideOal ){
173644 zWideWal = rbuWinUtf8ToUnicode(zWal);
173645 if( zWideWal ){
173646 if( MoveFileW(zWideOal, zWideWal) ){
173647 p->rc = SQLITE_OK;
173648 }else{
173649 p->rc = SQLITE_IOERR;
173651 sqlite3_free(zWideWal);
173652 }else{
173653 p->rc = SQLITE_IOERR_NOMEM;
173655 sqlite3_free(zWideOal);
173656 }else{
173657 p->rc = SQLITE_IOERR_NOMEM;
173660 #else
173661 p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
173662 #endif
173664 if( p->rc==SQLITE_OK ){
173665 rbuOpenDatabase(p, 0);
173666 rbuSetupCheckpoint(p, 0);
173671 sqlite3_free(zWal);
173672 sqlite3_free(zOal);
173676 ** The SELECT statement iterating through the keys for the current object
173677 ** (p->objiter.pSelect) currently points to a valid row. This function
173678 ** determines the type of operation requested by this row and returns
173679 ** one of the following values to indicate the result:
173681 ** * RBU_INSERT
173682 ** * RBU_DELETE
173683 ** * RBU_IDX_DELETE
173684 ** * RBU_UPDATE
173686 ** If RBU_UPDATE is returned, then output variable *pzMask is set to
173687 ** point to the text value indicating the columns to update.
173689 ** If the rbu_control field contains an invalid value, an error code and
173690 ** message are left in the RBU handle and zero returned.
173692 static int rbuStepType(sqlite3rbu *p, const char **pzMask){
173693 int iCol = p->objiter.nCol; /* Index of rbu_control column */
173694 int res = 0; /* Return value */
173696 switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
173697 case SQLITE_INTEGER: {
173698 int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
173699 switch( iVal ){
173700 case 0: res = RBU_INSERT; break;
173701 case 1: res = RBU_DELETE; break;
173702 case 2: res = RBU_REPLACE; break;
173703 case 3: res = RBU_IDX_DELETE; break;
173704 case 4: res = RBU_IDX_INSERT; break;
173706 break;
173709 case SQLITE_TEXT: {
173710 const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
173711 if( z==0 ){
173712 p->rc = SQLITE_NOMEM;
173713 }else{
173714 *pzMask = (const char*)z;
173716 res = RBU_UPDATE;
173718 break;
173721 default:
173722 break;
173725 if( res==0 ){
173726 rbuBadControlError(p);
173728 return res;
173731 #ifdef SQLITE_DEBUG
173733 ** Assert that column iCol of statement pStmt is named zName.
173735 static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
173736 const char *zCol = sqlite3_column_name(pStmt, iCol);
173737 assert( 0==sqlite3_stricmp(zName, zCol) );
173739 #else
173740 # define assertColumnName(x,y,z)
173741 #endif
173744 ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
173745 ** RBU_IDX_DELETE. This function performs the work of a single
173746 ** sqlite3rbu_step() call for the type of operation specified by eType.
173748 static void rbuStepOneOp(sqlite3rbu *p, int eType){
173749 RbuObjIter *pIter = &p->objiter;
173750 sqlite3_value *pVal;
173751 sqlite3_stmt *pWriter;
173752 int i;
173754 assert( p->rc==SQLITE_OK );
173755 assert( eType!=RBU_DELETE || pIter->zIdx==0 );
173756 assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
173757 || eType==RBU_INSERT || eType==RBU_IDX_INSERT
173760 /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
173761 ** statement below does actually delete a row, nPhaseOneStep will be
173762 ** incremented by the same amount when SQL function rbu_tmp_insert()
173763 ** is invoked by the trigger. */
173764 if( eType==RBU_DELETE ){
173765 p->nPhaseOneStep -= p->objiter.nIndex;
173768 if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
173769 pWriter = pIter->pDelete;
173770 }else{
173771 pWriter = pIter->pInsert;
173774 for(i=0; i<pIter->nCol; i++){
173775 /* If this is an INSERT into a table b-tree and the table has an
173776 ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
173777 ** to write a NULL into the IPK column. That is not permitted. */
173778 if( eType==RBU_INSERT
173779 && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
173780 && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
173782 p->rc = SQLITE_MISMATCH;
173783 p->zErrmsg = sqlite3_mprintf("datatype mismatch");
173784 return;
173787 if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
173788 continue;
173791 pVal = sqlite3_column_value(pIter->pSelect, i);
173792 p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
173793 if( p->rc ) return;
173795 if( pIter->zIdx==0 ){
173796 if( pIter->eType==RBU_PK_VTAB
173797 || pIter->eType==RBU_PK_NONE
173798 || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
173800 /* For a virtual table, or a table with no primary key, the
173801 ** SELECT statement is:
173803 ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
173805 ** Hence column_value(pIter->nCol+1).
173807 assertColumnName(pIter->pSelect, pIter->nCol+1,
173808 rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
173810 pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
173811 p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
173814 if( p->rc==SQLITE_OK ){
173815 sqlite3_step(pWriter);
173816 p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
173821 ** This function does the work for an sqlite3rbu_step() call.
173823 ** The object-iterator (p->objiter) currently points to a valid object,
173824 ** and the input cursor (p->objiter.pSelect) currently points to a valid
173825 ** input row. Perform whatever processing is required and return.
173827 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
173828 ** and message is left in the RBU handle and a copy of the error code
173829 ** returned.
173831 static int rbuStep(sqlite3rbu *p){
173832 RbuObjIter *pIter = &p->objiter;
173833 const char *zMask = 0;
173834 int eType = rbuStepType(p, &zMask);
173836 if( eType ){
173837 assert( eType==RBU_INSERT || eType==RBU_DELETE
173838 || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
173839 || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
173841 assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
173843 if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
173844 rbuBadControlError(p);
173846 else if( eType==RBU_REPLACE ){
173847 if( pIter->zIdx==0 ){
173848 p->nPhaseOneStep += p->objiter.nIndex;
173849 rbuStepOneOp(p, RBU_DELETE);
173851 if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
173853 else if( eType!=RBU_UPDATE ){
173854 rbuStepOneOp(p, eType);
173856 else{
173857 sqlite3_value *pVal;
173858 sqlite3_stmt *pUpdate = 0;
173859 assert( eType==RBU_UPDATE );
173860 p->nPhaseOneStep -= p->objiter.nIndex;
173861 rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
173862 if( pUpdate ){
173863 int i;
173864 for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
173865 char c = zMask[pIter->aiSrcOrder[i]];
173866 pVal = sqlite3_column_value(pIter->pSelect, i);
173867 if( pIter->abTblPk[i] || c!='.' ){
173868 p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
173871 if( p->rc==SQLITE_OK
173872 && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
173874 /* Bind the rbu_rowid value to column _rowid_ */
173875 assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
173876 pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
173877 p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
173879 if( p->rc==SQLITE_OK ){
173880 sqlite3_step(pUpdate);
173881 p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
173886 return p->rc;
173890 ** Increment the schema cookie of the main database opened by p->dbMain.
173892 ** Or, if this is an RBU vacuum, set the schema cookie of the main db
173893 ** opened by p->dbMain to one more than the schema cookie of the main
173894 ** db opened by p->dbRbu.
173896 static void rbuIncrSchemaCookie(sqlite3rbu *p){
173897 if( p->rc==SQLITE_OK ){
173898 sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
173899 int iCookie = 1000000;
173900 sqlite3_stmt *pStmt;
173902 p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
173903 "PRAGMA schema_version"
173905 if( p->rc==SQLITE_OK ){
173906 /* Coverage: it may be that this sqlite3_step() cannot fail. There
173907 ** is already a transaction open, so the prepared statement cannot
173908 ** throw an SQLITE_SCHEMA exception. The only database page the
173909 ** statement reads is page 1, which is guaranteed to be in the cache.
173910 ** And no memory allocations are required. */
173911 if( SQLITE_ROW==sqlite3_step(pStmt) ){
173912 iCookie = sqlite3_column_int(pStmt, 0);
173914 rbuFinalize(p, pStmt);
173916 if( p->rc==SQLITE_OK ){
173917 rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
173923 ** Update the contents of the rbu_state table within the rbu database. The
173924 ** value stored in the RBU_STATE_STAGE column is eStage. All other values
173925 ** are determined by inspecting the rbu handle passed as the first argument.
173927 static void rbuSaveState(sqlite3rbu *p, int eStage){
173928 if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
173929 sqlite3_stmt *pInsert = 0;
173930 rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
173931 int rc;
173933 assert( p->zErrmsg==0 );
173934 rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
173935 sqlite3_mprintf(
173936 "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
173937 "(%d, %d), "
173938 "(%d, %Q), "
173939 "(%d, %Q), "
173940 "(%d, %d), "
173941 "(%d, %d), "
173942 "(%d, %lld), "
173943 "(%d, %lld), "
173944 "(%d, %lld), "
173945 "(%d, %lld) ",
173946 p->zStateDb,
173947 RBU_STATE_STAGE, eStage,
173948 RBU_STATE_TBL, p->objiter.zTbl,
173949 RBU_STATE_IDX, p->objiter.zIdx,
173950 RBU_STATE_ROW, p->nStep,
173951 RBU_STATE_PROGRESS, p->nProgress,
173952 RBU_STATE_CKPT, p->iWalCksum,
173953 RBU_STATE_COOKIE, (i64)pFd->iCookie,
173954 RBU_STATE_OALSZ, p->iOalSz,
173955 RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
173958 assert( pInsert==0 || rc==SQLITE_OK );
173960 if( rc==SQLITE_OK ){
173961 sqlite3_step(pInsert);
173962 rc = sqlite3_finalize(pInsert);
173964 if( rc!=SQLITE_OK ) p->rc = rc;
173970 ** The second argument passed to this function is the name of a PRAGMA
173971 ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
173972 ** This function executes the following on sqlite3rbu.dbRbu:
173974 ** "PRAGMA main.$zPragma"
173976 ** where $zPragma is the string passed as the second argument, then
173977 ** on sqlite3rbu.dbMain:
173979 ** "PRAGMA main.$zPragma = $val"
173981 ** where $val is the value returned by the first PRAGMA invocation.
173983 ** In short, it copies the value of the specified PRAGMA setting from
173984 ** dbRbu to dbMain.
173986 static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
173987 if( p->rc==SQLITE_OK ){
173988 sqlite3_stmt *pPragma = 0;
173989 p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
173990 sqlite3_mprintf("PRAGMA main.%s", zPragma)
173992 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
173993 p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
173994 zPragma, sqlite3_column_int(pPragma, 0)
173997 rbuFinalize(p, pPragma);
174002 ** The RBU handle passed as the only argument has just been opened and
174003 ** the state database is empty. If this RBU handle was opened for an
174004 ** RBU vacuum operation, create the schema in the target db.
174006 static void rbuCreateTargetSchema(sqlite3rbu *p){
174007 sqlite3_stmt *pSql = 0;
174008 sqlite3_stmt *pInsert = 0;
174010 assert( rbuIsVacuum(p) );
174011 p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
174012 if( p->rc==SQLITE_OK ){
174013 p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
174014 "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
174015 " AND name!='sqlite_sequence' "
174016 " ORDER BY type DESC"
174020 while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
174021 const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
174022 p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
174024 rbuFinalize(p, pSql);
174025 if( p->rc!=SQLITE_OK ) return;
174027 if( p->rc==SQLITE_OK ){
174028 p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
174029 "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
174033 if( p->rc==SQLITE_OK ){
174034 p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
174035 "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
174039 while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
174040 int i;
174041 for(i=0; i<5; i++){
174042 sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
174044 sqlite3_step(pInsert);
174045 p->rc = sqlite3_reset(pInsert);
174047 if( p->rc==SQLITE_OK ){
174048 p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
174051 rbuFinalize(p, pSql);
174052 rbuFinalize(p, pInsert);
174056 ** Step the RBU object.
174058 SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
174059 if( p ){
174060 switch( p->eStage ){
174061 case RBU_STAGE_OAL: {
174062 RbuObjIter *pIter = &p->objiter;
174064 /* If this is an RBU vacuum operation and the state table was empty
174065 ** when this handle was opened, create the target database schema. */
174066 if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
174067 rbuCreateTargetSchema(p);
174068 rbuCopyPragma(p, "user_version");
174069 rbuCopyPragma(p, "application_id");
174072 while( p->rc==SQLITE_OK && pIter->zTbl ){
174074 if( pIter->bCleanup ){
174075 /* Clean up the rbu_tmp_xxx table for the previous table. It
174076 ** cannot be dropped as there are currently active SQL statements.
174077 ** But the contents can be deleted. */
174078 if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
174079 rbuMPrintfExec(p, p->dbRbu,
174080 "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
174083 }else{
174084 rbuObjIterPrepareAll(p, pIter, 0);
174086 /* Advance to the next row to process. */
174087 if( p->rc==SQLITE_OK ){
174088 int rc = sqlite3_step(pIter->pSelect);
174089 if( rc==SQLITE_ROW ){
174090 p->nProgress++;
174091 p->nStep++;
174092 return rbuStep(p);
174094 p->rc = sqlite3_reset(pIter->pSelect);
174095 p->nStep = 0;
174099 rbuObjIterNext(p, pIter);
174102 if( p->rc==SQLITE_OK ){
174103 assert( pIter->zTbl==0 );
174104 rbuSaveState(p, RBU_STAGE_MOVE);
174105 rbuIncrSchemaCookie(p);
174106 if( p->rc==SQLITE_OK ){
174107 p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
174109 if( p->rc==SQLITE_OK ){
174110 p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
174112 p->eStage = RBU_STAGE_MOVE;
174114 break;
174117 case RBU_STAGE_MOVE: {
174118 if( p->rc==SQLITE_OK ){
174119 rbuMoveOalFile(p);
174120 p->nProgress++;
174122 break;
174125 case RBU_STAGE_CKPT: {
174126 if( p->rc==SQLITE_OK ){
174127 if( p->nStep>=p->nFrame ){
174128 sqlite3_file *pDb = p->pTargetFd->pReal;
174130 /* Sync the db file */
174131 p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
174133 /* Update nBackfill */
174134 if( p->rc==SQLITE_OK ){
174135 void volatile *ptr;
174136 p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
174137 if( p->rc==SQLITE_OK ){
174138 ((u32 volatile*)ptr)[24] = p->iMaxFrame;
174142 if( p->rc==SQLITE_OK ){
174143 p->eStage = RBU_STAGE_DONE;
174144 p->rc = SQLITE_DONE;
174146 }else{
174147 /* At one point the following block copied a single frame from the
174148 ** wal file to the database file. So that one call to sqlite3rbu_step()
174149 ** checkpointed a single frame.
174151 ** However, if the sector-size is larger than the page-size, and the
174152 ** application calls sqlite3rbu_savestate() or close() immediately
174153 ** after this step, then rbu_step() again, then a power failure occurs,
174154 ** then the database page written here may be damaged. Work around
174155 ** this by checkpointing frames until the next page in the aFrame[]
174156 ** lies on a different disk sector to the current one. */
174157 u32 iSector;
174159 RbuFrame *pFrame = &p->aFrame[p->nStep];
174160 iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
174161 rbuCheckpointFrame(p, pFrame);
174162 p->nStep++;
174163 }while( p->nStep<p->nFrame
174164 && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
174165 && p->rc==SQLITE_OK
174168 p->nProgress++;
174170 break;
174173 default:
174174 break;
174176 return p->rc;
174177 }else{
174178 return SQLITE_NOMEM;
174183 ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
174184 ** otherwise. Either or both argument may be NULL. Two NULL values are
174185 ** considered equal, and NULL is considered distinct from all other values.
174187 static int rbuStrCompare(const char *z1, const char *z2){
174188 if( z1==0 && z2==0 ) return 0;
174189 if( z1==0 || z2==0 ) return 1;
174190 return (sqlite3_stricmp(z1, z2)!=0);
174194 ** This function is called as part of sqlite3rbu_open() when initializing
174195 ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
174196 ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
174197 ** things so that the next call to sqlite3rbu_step() continues on from
174198 ** where the previous rbu handle left off.
174200 ** If an error occurs, an error code and error message are left in the
174201 ** rbu handle passed as the first argument.
174203 static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
174204 assert( p->rc==SQLITE_OK );
174205 if( pState->zTbl ){
174206 RbuObjIter *pIter = &p->objiter;
174207 int rc = SQLITE_OK;
174209 while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
174210 || rbuStrCompare(pIter->zIdx, pState->zIdx)
174211 || rbuStrCompare(pIter->zTbl, pState->zTbl)
174213 rc = rbuObjIterNext(p, pIter);
174216 if( rc==SQLITE_OK && !pIter->zTbl ){
174217 rc = SQLITE_ERROR;
174218 p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
174221 if( rc==SQLITE_OK ){
174222 p->nStep = pState->nRow;
174223 rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
174226 p->rc = rc;
174231 ** If there is a "*-oal" file in the file-system corresponding to the
174232 ** target database in the file-system, delete it. If an error occurs,
174233 ** leave an error code and error message in the rbu handle.
174235 static void rbuDeleteOalFile(sqlite3rbu *p){
174236 char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
174237 if( zOal ){
174238 sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
174239 assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
174240 pVfs->xDelete(pVfs, zOal, 0);
174241 sqlite3_free(zOal);
174246 ** Allocate a private rbu VFS for the rbu handle passed as the only
174247 ** argument. This VFS will be used unless the call to sqlite3rbu_open()
174248 ** specified a URI with a vfs=? option in place of a target database
174249 ** file name.
174251 static void rbuCreateVfs(sqlite3rbu *p){
174252 int rnd;
174253 char zRnd[64];
174255 assert( p->rc==SQLITE_OK );
174256 sqlite3_randomness(sizeof(int), (void*)&rnd);
174257 sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
174258 p->rc = sqlite3rbu_create_vfs(zRnd, 0);
174259 if( p->rc==SQLITE_OK ){
174260 sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
174261 assert( pVfs );
174262 p->zVfsName = pVfs->zName;
174263 ((rbu_vfs*)pVfs)->pRbu = p;
174268 ** Destroy the private VFS created for the rbu handle passed as the only
174269 ** argument by an earlier call to rbuCreateVfs().
174271 static void rbuDeleteVfs(sqlite3rbu *p){
174272 if( p->zVfsName ){
174273 sqlite3rbu_destroy_vfs(p->zVfsName);
174274 p->zVfsName = 0;
174279 ** This user-defined SQL function is invoked with a single argument - the
174280 ** name of a table expected to appear in the target database. It returns
174281 ** the number of auxilliary indexes on the table.
174283 static void rbuIndexCntFunc(
174284 sqlite3_context *pCtx,
174285 int nVal,
174286 sqlite3_value **apVal
174288 sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
174289 sqlite3_stmt *pStmt = 0;
174290 char *zErrmsg = 0;
174291 int rc;
174293 assert( nVal==1 );
174295 rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
174296 sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
174297 "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
174299 if( rc!=SQLITE_OK ){
174300 sqlite3_result_error(pCtx, zErrmsg, -1);
174301 }else{
174302 int nIndex = 0;
174303 if( SQLITE_ROW==sqlite3_step(pStmt) ){
174304 nIndex = sqlite3_column_int(pStmt, 0);
174306 rc = sqlite3_finalize(pStmt);
174307 if( rc==SQLITE_OK ){
174308 sqlite3_result_int(pCtx, nIndex);
174309 }else{
174310 sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
174314 sqlite3_free(zErrmsg);
174318 ** If the RBU database contains the rbu_count table, use it to initialize
174319 ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
174320 ** is assumed to contain the same columns as:
174322 ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
174324 ** There should be one row in the table for each data_xxx table in the
174325 ** database. The 'tbl' column should contain the name of a data_xxx table,
174326 ** and the cnt column the number of rows it contains.
174328 ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
174329 ** for all rows in the rbu_count table, where nIndex is the number of
174330 ** indexes on the corresponding target database table.
174332 static void rbuInitPhaseOneSteps(sqlite3rbu *p){
174333 if( p->rc==SQLITE_OK ){
174334 sqlite3_stmt *pStmt = 0;
174335 int bExists = 0; /* True if rbu_count exists */
174337 p->nPhaseOneStep = -1;
174339 p->rc = sqlite3_create_function(p->dbRbu,
174340 "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
174343 /* Check for the rbu_count table. If it does not exist, or if an error
174344 ** occurs, nPhaseOneStep will be left set to -1. */
174345 if( p->rc==SQLITE_OK ){
174346 p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
174347 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
174350 if( p->rc==SQLITE_OK ){
174351 if( SQLITE_ROW==sqlite3_step(pStmt) ){
174352 bExists = 1;
174354 p->rc = sqlite3_finalize(pStmt);
174357 if( p->rc==SQLITE_OK && bExists ){
174358 p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
174359 "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
174360 "FROM rbu_count"
174362 if( p->rc==SQLITE_OK ){
174363 if( SQLITE_ROW==sqlite3_step(pStmt) ){
174364 p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
174366 p->rc = sqlite3_finalize(pStmt);
174373 static sqlite3rbu *openRbuHandle(
174374 const char *zTarget,
174375 const char *zRbu,
174376 const char *zState
174378 sqlite3rbu *p;
174379 size_t nTarget = zTarget ? strlen(zTarget) : 0;
174380 size_t nRbu = strlen(zRbu);
174381 size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
174383 p = (sqlite3rbu*)sqlite3_malloc64(nByte);
174384 if( p ){
174385 RbuState *pState = 0;
174387 /* Create the custom VFS. */
174388 memset(p, 0, sizeof(sqlite3rbu));
174389 rbuCreateVfs(p);
174391 /* Open the target, RBU and state databases */
174392 if( p->rc==SQLITE_OK ){
174393 char *pCsr = (char*)&p[1];
174394 int bRetry = 0;
174395 if( zTarget ){
174396 p->zTarget = pCsr;
174397 memcpy(p->zTarget, zTarget, nTarget+1);
174398 pCsr += nTarget+1;
174400 p->zRbu = pCsr;
174401 memcpy(p->zRbu, zRbu, nRbu+1);
174402 pCsr += nRbu+1;
174403 if( zState ){
174404 p->zState = rbuMPrintf(p, "%s", zState);
174407 /* If the first attempt to open the database file fails and the bRetry
174408 ** flag it set, this means that the db was not opened because it seemed
174409 ** to be a wal-mode db. But, this may have happened due to an earlier
174410 ** RBU vacuum operation leaving an old wal file in the directory.
174411 ** If this is the case, it will have been checkpointed and deleted
174412 ** when the handle was closed and a second attempt to open the
174413 ** database may succeed. */
174414 rbuOpenDatabase(p, &bRetry);
174415 if( bRetry ){
174416 rbuOpenDatabase(p, 0);
174420 if( p->rc==SQLITE_OK ){
174421 pState = rbuLoadState(p);
174422 assert( pState || p->rc!=SQLITE_OK );
174423 if( p->rc==SQLITE_OK ){
174425 if( pState->eStage==0 ){
174426 rbuDeleteOalFile(p);
174427 rbuInitPhaseOneSteps(p);
174428 p->eStage = RBU_STAGE_OAL;
174429 }else{
174430 p->eStage = pState->eStage;
174431 p->nPhaseOneStep = pState->nPhaseOneStep;
174433 p->nProgress = pState->nProgress;
174434 p->iOalSz = pState->iOalSz;
174437 assert( p->rc!=SQLITE_OK || p->eStage!=0 );
174439 if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
174440 if( p->eStage==RBU_STAGE_OAL ){
174441 p->rc = SQLITE_ERROR;
174442 p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
174443 }else if( p->eStage==RBU_STAGE_MOVE ){
174444 p->eStage = RBU_STAGE_CKPT;
174445 p->nStep = 0;
174449 if( p->rc==SQLITE_OK
174450 && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
174451 && pState->eStage!=0
174453 rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
174454 if( pFd->iCookie!=pState->iCookie ){
174455 /* At this point (pTargetFd->iCookie) contains the value of the
174456 ** change-counter cookie (the thing that gets incremented when a
174457 ** transaction is committed in rollback mode) currently stored on
174458 ** page 1 of the database file. */
174459 p->rc = SQLITE_BUSY;
174460 p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
174461 (rbuIsVacuum(p) ? "vacuum" : "update")
174466 if( p->rc==SQLITE_OK ){
174467 if( p->eStage==RBU_STAGE_OAL ){
174468 sqlite3 *db = p->dbMain;
174469 p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
174471 /* Point the object iterator at the first object */
174472 if( p->rc==SQLITE_OK ){
174473 p->rc = rbuObjIterFirst(p, &p->objiter);
174476 /* If the RBU database contains no data_xxx tables, declare the RBU
174477 ** update finished. */
174478 if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
174479 p->rc = SQLITE_DONE;
174480 p->eStage = RBU_STAGE_DONE;
174481 }else{
174482 if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
174483 rbuCopyPragma(p, "page_size");
174484 rbuCopyPragma(p, "auto_vacuum");
174487 /* Open transactions both databases. The *-oal file is opened or
174488 ** created at this point. */
174489 if( p->rc==SQLITE_OK ){
174490 p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
174493 /* Check if the main database is a zipvfs db. If it is, set the upper
174494 ** level pager to use "journal_mode=off". This prevents it from
174495 ** generating a large journal using a temp file. */
174496 if( p->rc==SQLITE_OK ){
174497 int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
174498 if( frc==SQLITE_OK ){
174499 p->rc = sqlite3_exec(
174500 db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
174504 if( p->rc==SQLITE_OK ){
174505 rbuSetupOal(p, pState);
174508 }else if( p->eStage==RBU_STAGE_MOVE ){
174509 /* no-op */
174510 }else if( p->eStage==RBU_STAGE_CKPT ){
174511 rbuSetupCheckpoint(p, pState);
174512 }else if( p->eStage==RBU_STAGE_DONE ){
174513 p->rc = SQLITE_DONE;
174514 }else{
174515 p->rc = SQLITE_CORRUPT;
174519 rbuFreeState(pState);
174522 return p;
174526 ** Allocate and return an RBU handle with all fields zeroed except for the
174527 ** error code, which is set to SQLITE_MISUSE.
174529 static sqlite3rbu *rbuMisuseError(void){
174530 sqlite3rbu *pRet;
174531 pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
174532 if( pRet ){
174533 memset(pRet, 0, sizeof(sqlite3rbu));
174534 pRet->rc = SQLITE_MISUSE;
174536 return pRet;
174540 ** Open and return a new RBU handle.
174542 SQLITE_API sqlite3rbu *sqlite3rbu_open(
174543 const char *zTarget,
174544 const char *zRbu,
174545 const char *zState
174547 if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
174548 /* TODO: Check that zTarget and zRbu are non-NULL */
174549 return openRbuHandle(zTarget, zRbu, zState);
174553 ** Open a handle to begin or resume an RBU VACUUM operation.
174555 SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
174556 const char *zTarget,
174557 const char *zState
174559 if( zTarget==0 ){ return rbuMisuseError(); }
174560 /* TODO: Check that both arguments are non-NULL */
174561 return openRbuHandle(0, zTarget, zState);
174565 ** Return the database handle used by pRbu.
174567 SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
174568 sqlite3 *db = 0;
174569 if( pRbu ){
174570 db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
174572 return db;
174577 ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
174578 ** then edit any error message string so as to remove all occurrences of
174579 ** the pattern "rbu_imp_[0-9]*".
174581 static void rbuEditErrmsg(sqlite3rbu *p){
174582 if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
174583 unsigned int i;
174584 size_t nErrmsg = strlen(p->zErrmsg);
174585 for(i=0; i<(nErrmsg-8); i++){
174586 if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
174587 int nDel = 8;
174588 while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
174589 memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
174590 nErrmsg -= nDel;
174597 ** Close the RBU handle.
174599 SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
174600 int rc;
174601 if( p ){
174603 /* Commit the transaction to the *-oal file. */
174604 if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
174605 p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
174608 /* Sync the db file if currently doing an incremental checkpoint */
174609 if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
174610 sqlite3_file *pDb = p->pTargetFd->pReal;
174611 p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
174614 rbuSaveState(p, p->eStage);
174616 if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
174617 p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
174620 /* Close any open statement handles. */
174621 rbuObjIterFinalize(&p->objiter);
174623 /* If this is an RBU vacuum handle and the vacuum has either finished
174624 ** successfully or encountered an error, delete the contents of the
174625 ** state table. This causes the next call to sqlite3rbu_vacuum()
174626 ** specifying the current target and state databases to start a new
174627 ** vacuum from scratch. */
174628 if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
174629 int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
174630 if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
174633 /* Close the open database handle and VFS object. */
174634 sqlite3_close(p->dbRbu);
174635 sqlite3_close(p->dbMain);
174636 assert( p->szTemp==0 );
174637 rbuDeleteVfs(p);
174638 sqlite3_free(p->aBuf);
174639 sqlite3_free(p->aFrame);
174641 rbuEditErrmsg(p);
174642 rc = p->rc;
174643 if( pzErrmsg ){
174644 *pzErrmsg = p->zErrmsg;
174645 }else{
174646 sqlite3_free(p->zErrmsg);
174648 sqlite3_free(p->zState);
174649 sqlite3_free(p);
174650 }else{
174651 rc = SQLITE_NOMEM;
174652 *pzErrmsg = 0;
174654 return rc;
174658 ** Return the total number of key-value operations (inserts, deletes or
174659 ** updates) that have been performed on the target database since the
174660 ** current RBU update was started.
174662 SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
174663 return pRbu->nProgress;
174667 ** Return permyriadage progress indications for the two main stages of
174668 ** an RBU update.
174670 SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
174671 const int MAX_PROGRESS = 10000;
174672 switch( p->eStage ){
174673 case RBU_STAGE_OAL:
174674 if( p->nPhaseOneStep>0 ){
174675 *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
174676 }else{
174677 *pnOne = -1;
174679 *pnTwo = 0;
174680 break;
174682 case RBU_STAGE_MOVE:
174683 *pnOne = MAX_PROGRESS;
174684 *pnTwo = 0;
174685 break;
174687 case RBU_STAGE_CKPT:
174688 *pnOne = MAX_PROGRESS;
174689 *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
174690 break;
174692 case RBU_STAGE_DONE:
174693 *pnOne = MAX_PROGRESS;
174694 *pnTwo = MAX_PROGRESS;
174695 break;
174697 default:
174698 assert( 0 );
174703 ** Return the current state of the RBU vacuum or update operation.
174705 SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
174706 int aRes[] = {
174707 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
174708 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
174711 assert( RBU_STAGE_OAL==1 );
174712 assert( RBU_STAGE_MOVE==2 );
174713 assert( RBU_STAGE_CKPT==4 );
174714 assert( RBU_STAGE_DONE==5 );
174715 assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
174716 assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
174717 assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
174718 assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
174720 if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
174721 return SQLITE_RBU_STATE_ERROR;
174722 }else{
174723 assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
174724 assert( p->eStage==RBU_STAGE_OAL
174725 || p->eStage==RBU_STAGE_MOVE
174726 || p->eStage==RBU_STAGE_CKPT
174727 || p->eStage==RBU_STAGE_DONE
174729 return aRes[p->eStage];
174733 SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
174734 int rc = p->rc;
174735 if( rc==SQLITE_DONE ) return SQLITE_OK;
174737 assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
174738 if( p->eStage==RBU_STAGE_OAL ){
174739 assert( rc!=SQLITE_DONE );
174740 if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
174743 /* Sync the db file */
174744 if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
174745 sqlite3_file *pDb = p->pTargetFd->pReal;
174746 rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
174749 p->rc = rc;
174750 rbuSaveState(p, p->eStage);
174751 rc = p->rc;
174753 if( p->eStage==RBU_STAGE_OAL ){
174754 assert( rc!=SQLITE_DONE );
174755 if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
174756 if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
174757 if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
174760 p->rc = rc;
174761 return rc;
174764 /**************************************************************************
174765 ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
174766 ** of a standard VFS in the following ways:
174768 ** 1. Whenever the first page of a main database file is read or
174769 ** written, the value of the change-counter cookie is stored in
174770 ** rbu_file.iCookie. Similarly, the value of the "write-version"
174771 ** database header field is stored in rbu_file.iWriteVer. This ensures
174772 ** that the values are always trustworthy within an open transaction.
174774 ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
174775 ** member variable of the associated database file descriptor is set
174776 ** to point to the new file. A mutex protected linked list of all main
174777 ** db fds opened using a particular RBU VFS is maintained at
174778 ** rbu_vfs.pMain to facilitate this.
174780 ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
174781 ** object can be marked as the target database of an RBU update. This
174782 ** turns on the following extra special behaviour:
174784 ** 3a. If xAccess() is called to check if there exists a *-wal file
174785 ** associated with an RBU target database currently in RBU_STAGE_OAL
174786 ** stage (preparing the *-oal file), the following special handling
174787 ** applies:
174789 ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
174790 ** target database may not be in wal mode already.
174792 ** * if the *-wal file does not exist, set the output parameter to
174793 ** non-zero (to tell SQLite that it does exist) anyway.
174795 ** Then, when xOpen() is called to open the *-wal file associated with
174796 ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
174797 ** file, the rbu vfs opens the corresponding *-oal file instead.
174799 ** 3b. The *-shm pages returned by xShmMap() for a target db file in
174800 ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
174801 ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
174802 ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
174803 ** because assert() statements in some VFS implementations fail if
174804 ** xShmLock() is called before xShmMap().
174806 ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
174807 ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
174808 ** fails with an SQLITE_BUSY error. This is to stop RBU connections
174809 ** from automatically checkpointing a *-wal (or *-oal) file from within
174810 ** sqlite3_close().
174812 ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
174813 ** all xWrite() calls on the target database file perform no IO.
174814 ** Instead the frame and page numbers that would be read and written
174815 ** are recorded. Additionally, successful attempts to obtain exclusive
174816 ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
174817 ** database file are recorded. xShmLock() calls to unlock the same
174818 ** locks are no-ops (so that once obtained, these locks are never
174819 ** relinquished). Finally, calls to xSync() on the target database
174820 ** file fail with SQLITE_INTERNAL errors.
174823 static void rbuUnlockShm(rbu_file *p){
174824 assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
174825 if( p->pRbu ){
174826 int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
174827 int i;
174828 for(i=0; i<SQLITE_SHM_NLOCK;i++){
174829 if( (1<<i) & p->pRbu->mLock ){
174830 xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
174833 p->pRbu->mLock = 0;
174839 static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
174840 sqlite3rbu *pRbu = pFd->pRbu;
174841 i64 nDiff = nNew - pFd->sz;
174842 pRbu->szTemp += nDiff;
174843 pFd->sz = nNew;
174844 assert( pRbu->szTemp>=0 );
174845 if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
174846 return SQLITE_OK;
174850 ** Close an rbu file.
174852 static int rbuVfsClose(sqlite3_file *pFile){
174853 rbu_file *p = (rbu_file*)pFile;
174854 int rc;
174855 int i;
174857 /* Free the contents of the apShm[] array. And the array itself. */
174858 for(i=0; i<p->nShm; i++){
174859 sqlite3_free(p->apShm[i]);
174861 sqlite3_free(p->apShm);
174862 p->apShm = 0;
174863 sqlite3_free(p->zDel);
174865 if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
174866 rbu_file **pp;
174867 sqlite3_mutex_enter(p->pRbuVfs->mutex);
174868 for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
174869 *pp = p->pMainNext;
174870 sqlite3_mutex_leave(p->pRbuVfs->mutex);
174871 rbuUnlockShm(p);
174872 p->pReal->pMethods->xShmUnmap(p->pReal, 0);
174874 else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
174875 rbuUpdateTempSize(p, 0);
174878 /* Close the underlying file handle */
174879 rc = p->pReal->pMethods->xClose(p->pReal);
174880 return rc;
174885 ** Read and return an unsigned 32-bit big-endian integer from the buffer
174886 ** passed as the only argument.
174888 static u32 rbuGetU32(u8 *aBuf){
174889 return ((u32)aBuf[0] << 24)
174890 + ((u32)aBuf[1] << 16)
174891 + ((u32)aBuf[2] << 8)
174892 + ((u32)aBuf[3]);
174896 ** Write an unsigned 32-bit value in big-endian format to the supplied
174897 ** buffer.
174899 static void rbuPutU32(u8 *aBuf, u32 iVal){
174900 aBuf[0] = (iVal >> 24) & 0xFF;
174901 aBuf[1] = (iVal >> 16) & 0xFF;
174902 aBuf[2] = (iVal >> 8) & 0xFF;
174903 aBuf[3] = (iVal >> 0) & 0xFF;
174906 static void rbuPutU16(u8 *aBuf, u16 iVal){
174907 aBuf[0] = (iVal >> 8) & 0xFF;
174908 aBuf[1] = (iVal >> 0) & 0xFF;
174912 ** Read data from an rbuVfs-file.
174914 static int rbuVfsRead(
174915 sqlite3_file *pFile,
174916 void *zBuf,
174917 int iAmt,
174918 sqlite_int64 iOfst
174920 rbu_file *p = (rbu_file*)pFile;
174921 sqlite3rbu *pRbu = p->pRbu;
174922 int rc;
174924 if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
174925 assert( p->openFlags & SQLITE_OPEN_WAL );
174926 rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
174927 }else{
174928 if( pRbu && pRbu->eStage==RBU_STAGE_OAL
174929 && (p->openFlags & SQLITE_OPEN_WAL)
174930 && iOfst>=pRbu->iOalSz
174932 rc = SQLITE_OK;
174933 memset(zBuf, 0, iAmt);
174934 }else{
174935 rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
174936 #if 1
174937 /* If this is being called to read the first page of the target
174938 ** database as part of an rbu vacuum operation, synthesize the
174939 ** contents of the first page if it does not yet exist. Otherwise,
174940 ** SQLite will not check for a *-wal file. */
174941 if( pRbu && rbuIsVacuum(pRbu)
174942 && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
174943 && (p->openFlags & SQLITE_OPEN_MAIN_DB)
174944 && pRbu->rc==SQLITE_OK
174946 sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
174947 rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
174948 if( rc==SQLITE_OK ){
174949 u8 *aBuf = (u8*)zBuf;
174950 u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
174951 rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
174952 rbuPutU32(&aBuf[36], 0); /* number of free pages */
174953 rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
174954 rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
174955 rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
174957 if( iAmt>100 ){
174958 memset(&aBuf[100], 0, iAmt-100);
174959 rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
174960 aBuf[100] = 0x0D;
174964 #endif
174966 if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
174967 /* These look like magic numbers. But they are stable, as they are part
174968 ** of the definition of the SQLite file format, which may not change. */
174969 u8 *pBuf = (u8*)zBuf;
174970 p->iCookie = rbuGetU32(&pBuf[24]);
174971 p->iWriteVer = pBuf[19];
174974 return rc;
174978 ** Write data to an rbuVfs-file.
174980 static int rbuVfsWrite(
174981 sqlite3_file *pFile,
174982 const void *zBuf,
174983 int iAmt,
174984 sqlite_int64 iOfst
174986 rbu_file *p = (rbu_file*)pFile;
174987 sqlite3rbu *pRbu = p->pRbu;
174988 int rc;
174990 if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
174991 assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
174992 rc = rbuCaptureDbWrite(p->pRbu, iOfst);
174993 }else{
174994 if( pRbu ){
174995 if( pRbu->eStage==RBU_STAGE_OAL
174996 && (p->openFlags & SQLITE_OPEN_WAL)
174997 && iOfst>=pRbu->iOalSz
174999 pRbu->iOalSz = iAmt + iOfst;
175000 }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
175001 i64 szNew = iAmt+iOfst;
175002 if( szNew>p->sz ){
175003 rc = rbuUpdateTempSize(p, szNew);
175004 if( rc!=SQLITE_OK ) return rc;
175008 rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
175009 if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
175010 /* These look like magic numbers. But they are stable, as they are part
175011 ** of the definition of the SQLite file format, which may not change. */
175012 u8 *pBuf = (u8*)zBuf;
175013 p->iCookie = rbuGetU32(&pBuf[24]);
175014 p->iWriteVer = pBuf[19];
175017 return rc;
175021 ** Truncate an rbuVfs-file.
175023 static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
175024 rbu_file *p = (rbu_file*)pFile;
175025 if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
175026 int rc = rbuUpdateTempSize(p, size);
175027 if( rc!=SQLITE_OK ) return rc;
175029 return p->pReal->pMethods->xTruncate(p->pReal, size);
175033 ** Sync an rbuVfs-file.
175035 static int rbuVfsSync(sqlite3_file *pFile, int flags){
175036 rbu_file *p = (rbu_file *)pFile;
175037 if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
175038 if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
175039 return SQLITE_INTERNAL;
175041 return SQLITE_OK;
175043 return p->pReal->pMethods->xSync(p->pReal, flags);
175047 ** Return the current file-size of an rbuVfs-file.
175049 static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
175050 rbu_file *p = (rbu_file *)pFile;
175051 int rc;
175052 rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
175054 /* If this is an RBU vacuum operation and this is the target database,
175055 ** pretend that it has at least one page. Otherwise, SQLite will not
175056 ** check for the existance of a *-wal file. rbuVfsRead() contains
175057 ** similar logic. */
175058 if( rc==SQLITE_OK && *pSize==0
175059 && p->pRbu && rbuIsVacuum(p->pRbu)
175060 && (p->openFlags & SQLITE_OPEN_MAIN_DB)
175062 *pSize = 1024;
175064 return rc;
175068 ** Lock an rbuVfs-file.
175070 static int rbuVfsLock(sqlite3_file *pFile, int eLock){
175071 rbu_file *p = (rbu_file*)pFile;
175072 sqlite3rbu *pRbu = p->pRbu;
175073 int rc = SQLITE_OK;
175075 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
175076 if( eLock==SQLITE_LOCK_EXCLUSIVE
175077 && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
175079 /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
175080 ** prevents it from checkpointing the database from sqlite3_close(). */
175081 rc = SQLITE_BUSY;
175082 }else{
175083 rc = p->pReal->pMethods->xLock(p->pReal, eLock);
175086 return rc;
175090 ** Unlock an rbuVfs-file.
175092 static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
175093 rbu_file *p = (rbu_file *)pFile;
175094 return p->pReal->pMethods->xUnlock(p->pReal, eLock);
175098 ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
175100 static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
175101 rbu_file *p = (rbu_file *)pFile;
175102 return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
175106 ** File control method. For custom operations on an rbuVfs-file.
175108 static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
175109 rbu_file *p = (rbu_file *)pFile;
175110 int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
175111 int rc;
175113 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
175114 || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
175116 if( op==SQLITE_FCNTL_RBU ){
175117 sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
175119 /* First try to find another RBU vfs lower down in the vfs stack. If
175120 ** one is found, this vfs will operate in pass-through mode. The lower
175121 ** level vfs will do the special RBU handling. */
175122 rc = xControl(p->pReal, op, pArg);
175124 if( rc==SQLITE_NOTFOUND ){
175125 /* Now search for a zipvfs instance lower down in the VFS stack. If
175126 ** one is found, this is an error. */
175127 void *dummy = 0;
175128 rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
175129 if( rc==SQLITE_OK ){
175130 rc = SQLITE_ERROR;
175131 pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
175132 }else if( rc==SQLITE_NOTFOUND ){
175133 pRbu->pTargetFd = p;
175134 p->pRbu = pRbu;
175135 if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
175136 rc = SQLITE_OK;
175139 return rc;
175141 else if( op==SQLITE_FCNTL_RBUCNT ){
175142 sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
175143 pRbu->nRbu++;
175144 pRbu->pRbuFd = p;
175145 p->bNolock = 1;
175148 rc = xControl(p->pReal, op, pArg);
175149 if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
175150 rbu_vfs *pRbuVfs = p->pRbuVfs;
175151 char *zIn = *(char**)pArg;
175152 char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
175153 *(char**)pArg = zOut;
175154 if( zOut==0 ) rc = SQLITE_NOMEM;
175157 return rc;
175161 ** Return the sector-size in bytes for an rbuVfs-file.
175163 static int rbuVfsSectorSize(sqlite3_file *pFile){
175164 rbu_file *p = (rbu_file *)pFile;
175165 return p->pReal->pMethods->xSectorSize(p->pReal);
175169 ** Return the device characteristic flags supported by an rbuVfs-file.
175171 static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
175172 rbu_file *p = (rbu_file *)pFile;
175173 return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
175177 ** Take or release a shared-memory lock.
175179 static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
175180 rbu_file *p = (rbu_file*)pFile;
175181 sqlite3rbu *pRbu = p->pRbu;
175182 int rc = SQLITE_OK;
175184 #ifdef SQLITE_AMALGAMATION
175185 assert( WAL_CKPT_LOCK==1 );
175186 #endif
175188 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
175189 if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
175190 /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
175191 ** taking this lock also prevents any checkpoints from occurring.
175192 ** todo: really, it's not clear why this might occur, as
175193 ** wal_autocheckpoint ought to be turned off. */
175194 if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
175195 }else{
175196 int bCapture = 0;
175197 if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
175198 && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
175199 && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
175201 bCapture = 1;
175204 if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
175205 rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
175206 if( bCapture && rc==SQLITE_OK ){
175207 pRbu->mLock |= (1 << ofst);
175212 return rc;
175216 ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
175218 static int rbuVfsShmMap(
175219 sqlite3_file *pFile,
175220 int iRegion,
175221 int szRegion,
175222 int isWrite,
175223 void volatile **pp
175225 rbu_file *p = (rbu_file*)pFile;
175226 int rc = SQLITE_OK;
175227 int eStage = (p->pRbu ? p->pRbu->eStage : 0);
175229 /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
175230 ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
175231 ** instead of a file on disk. */
175232 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
175233 if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
175234 if( iRegion<=p->nShm ){
175235 int nByte = (iRegion+1) * sizeof(char*);
175236 char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
175237 if( apNew==0 ){
175238 rc = SQLITE_NOMEM;
175239 }else{
175240 memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
175241 p->apShm = apNew;
175242 p->nShm = iRegion+1;
175246 if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
175247 char *pNew = (char*)sqlite3_malloc64(szRegion);
175248 if( pNew==0 ){
175249 rc = SQLITE_NOMEM;
175250 }else{
175251 memset(pNew, 0, szRegion);
175252 p->apShm[iRegion] = pNew;
175256 if( rc==SQLITE_OK ){
175257 *pp = p->apShm[iRegion];
175258 }else{
175259 *pp = 0;
175261 }else{
175262 assert( p->apShm==0 );
175263 rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
175266 return rc;
175270 ** Memory barrier.
175272 static void rbuVfsShmBarrier(sqlite3_file *pFile){
175273 rbu_file *p = (rbu_file *)pFile;
175274 p->pReal->pMethods->xShmBarrier(p->pReal);
175278 ** The xShmUnmap method.
175280 static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
175281 rbu_file *p = (rbu_file*)pFile;
175282 int rc = SQLITE_OK;
175283 int eStage = (p->pRbu ? p->pRbu->eStage : 0);
175285 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
175286 if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
175287 /* no-op */
175288 }else{
175289 /* Release the checkpointer and writer locks */
175290 rbuUnlockShm(p);
175291 rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
175293 return rc;
175297 ** Given that zWal points to a buffer containing a wal file name passed to
175298 ** either the xOpen() or xAccess() VFS method, return a pointer to the
175299 ** file-handle opened by the same database connection on the corresponding
175300 ** database file.
175302 static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
175303 rbu_file *pDb;
175304 sqlite3_mutex_enter(pRbuVfs->mutex);
175305 for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
175306 sqlite3_mutex_leave(pRbuVfs->mutex);
175307 return pDb;
175311 ** A main database named zName has just been opened. The following
175312 ** function returns a pointer to a buffer owned by SQLite that contains
175313 ** the name of the *-wal file this db connection will use. SQLite
175314 ** happens to pass a pointer to this buffer when using xAccess()
175315 ** or xOpen() to operate on the *-wal file.
175317 static const char *rbuMainToWal(const char *zName, int flags){
175318 int n = (int)strlen(zName);
175319 const char *z = &zName[n];
175320 if( flags & SQLITE_OPEN_URI ){
175321 int odd = 0;
175322 while( 1 ){
175323 if( z[0]==0 ){
175324 odd = 1 - odd;
175325 if( odd && z[1]==0 ) break;
175329 z += 2;
175330 }else{
175331 while( *z==0 ) z++;
175333 z += (n + 8 + 1);
175334 return z;
175338 ** Open an rbu file handle.
175340 static int rbuVfsOpen(
175341 sqlite3_vfs *pVfs,
175342 const char *zName,
175343 sqlite3_file *pFile,
175344 int flags,
175345 int *pOutFlags
175347 static sqlite3_io_methods rbuvfs_io_methods = {
175348 2, /* iVersion */
175349 rbuVfsClose, /* xClose */
175350 rbuVfsRead, /* xRead */
175351 rbuVfsWrite, /* xWrite */
175352 rbuVfsTruncate, /* xTruncate */
175353 rbuVfsSync, /* xSync */
175354 rbuVfsFileSize, /* xFileSize */
175355 rbuVfsLock, /* xLock */
175356 rbuVfsUnlock, /* xUnlock */
175357 rbuVfsCheckReservedLock, /* xCheckReservedLock */
175358 rbuVfsFileControl, /* xFileControl */
175359 rbuVfsSectorSize, /* xSectorSize */
175360 rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
175361 rbuVfsShmMap, /* xShmMap */
175362 rbuVfsShmLock, /* xShmLock */
175363 rbuVfsShmBarrier, /* xShmBarrier */
175364 rbuVfsShmUnmap, /* xShmUnmap */
175365 0, 0 /* xFetch, xUnfetch */
175367 rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
175368 sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
175369 rbu_file *pFd = (rbu_file *)pFile;
175370 int rc = SQLITE_OK;
175371 const char *zOpen = zName;
175372 int oflags = flags;
175374 memset(pFd, 0, sizeof(rbu_file));
175375 pFd->pReal = (sqlite3_file*)&pFd[1];
175376 pFd->pRbuVfs = pRbuVfs;
175377 pFd->openFlags = flags;
175378 if( zName ){
175379 if( flags & SQLITE_OPEN_MAIN_DB ){
175380 /* A main database has just been opened. The following block sets
175381 ** (pFd->zWal) to point to a buffer owned by SQLite that contains
175382 ** the name of the *-wal file this db connection will use. SQLite
175383 ** happens to pass a pointer to this buffer when using xAccess()
175384 ** or xOpen() to operate on the *-wal file. */
175385 pFd->zWal = rbuMainToWal(zName, flags);
175387 else if( flags & SQLITE_OPEN_WAL ){
175388 rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
175389 if( pDb ){
175390 if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
175391 /* This call is to open a *-wal file. Intead, open the *-oal. This
175392 ** code ensures that the string passed to xOpen() is terminated by a
175393 ** pair of '\0' bytes in case the VFS attempts to extract a URI
175394 ** parameter from it. */
175395 const char *zBase = zName;
175396 size_t nCopy;
175397 char *zCopy;
175398 if( rbuIsVacuum(pDb->pRbu) ){
175399 zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
175400 zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
175402 nCopy = strlen(zBase);
175403 zCopy = sqlite3_malloc64(nCopy+2);
175404 if( zCopy ){
175405 memcpy(zCopy, zBase, nCopy);
175406 zCopy[nCopy-3] = 'o';
175407 zCopy[nCopy] = '\0';
175408 zCopy[nCopy+1] = '\0';
175409 zOpen = (const char*)(pFd->zDel = zCopy);
175410 }else{
175411 rc = SQLITE_NOMEM;
175413 pFd->pRbu = pDb->pRbu;
175415 pDb->pWalFd = pFd;
175418 }else{
175419 pFd->pRbu = pRbuVfs->pRbu;
175422 if( oflags & SQLITE_OPEN_MAIN_DB
175423 && sqlite3_uri_boolean(zName, "rbu_memory", 0)
175425 assert( oflags & SQLITE_OPEN_MAIN_DB );
175426 oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
175427 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
175428 zOpen = 0;
175431 if( rc==SQLITE_OK ){
175432 rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
175434 if( pFd->pReal->pMethods ){
175435 /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
175436 ** pointer and, if the file is a main database file, link it into the
175437 ** mutex protected linked list of all such files. */
175438 pFile->pMethods = &rbuvfs_io_methods;
175439 if( flags & SQLITE_OPEN_MAIN_DB ){
175440 sqlite3_mutex_enter(pRbuVfs->mutex);
175441 pFd->pMainNext = pRbuVfs->pMain;
175442 pRbuVfs->pMain = pFd;
175443 sqlite3_mutex_leave(pRbuVfs->mutex);
175445 }else{
175446 sqlite3_free(pFd->zDel);
175449 return rc;
175453 ** Delete the file located at zPath.
175455 static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
175456 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175457 return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
175461 ** Test for access permissions. Return true if the requested permission
175462 ** is available, or false otherwise.
175464 static int rbuVfsAccess(
175465 sqlite3_vfs *pVfs,
175466 const char *zPath,
175467 int flags,
175468 int *pResOut
175470 rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
175471 sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
175472 int rc;
175474 rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
175476 /* If this call is to check if a *-wal file associated with an RBU target
175477 ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
175478 ** the following special handling is activated:
175480 ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
175481 ** ensures that the RBU extension never tries to update a database
175482 ** in wal mode, even if the first page of the database file has
175483 ** been damaged.
175485 ** b) if the *-wal file does not exist, claim that it does anyway,
175486 ** causing SQLite to call xOpen() to open it. This call will also
175487 ** be intercepted (see the rbuVfsOpen() function) and the *-oal
175488 ** file opened instead.
175490 if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
175491 rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
175492 if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
175493 if( *pResOut ){
175494 rc = SQLITE_CANTOPEN;
175495 }else{
175496 sqlite3_int64 sz = 0;
175497 rc = rbuVfsFileSize(&pDb->base, &sz);
175498 *pResOut = (sz>0);
175503 return rc;
175507 ** Populate buffer zOut with the full canonical pathname corresponding
175508 ** to the pathname in zPath. zOut is guaranteed to point to a buffer
175509 ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
175511 static int rbuVfsFullPathname(
175512 sqlite3_vfs *pVfs,
175513 const char *zPath,
175514 int nOut,
175515 char *zOut
175517 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175518 return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
175521 #ifndef SQLITE_OMIT_LOAD_EXTENSION
175523 ** Open the dynamic library located at zPath and return a handle.
175525 static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
175526 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175527 return pRealVfs->xDlOpen(pRealVfs, zPath);
175531 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
175532 ** utf-8 string describing the most recent error encountered associated
175533 ** with dynamic libraries.
175535 static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
175536 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175537 pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
175541 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
175543 static void (*rbuVfsDlSym(
175544 sqlite3_vfs *pVfs,
175545 void *pArg,
175546 const char *zSym
175547 ))(void){
175548 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175549 return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
175553 ** Close the dynamic library handle pHandle.
175555 static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
175556 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175557 pRealVfs->xDlClose(pRealVfs, pHandle);
175559 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
175562 ** Populate the buffer pointed to by zBufOut with nByte bytes of
175563 ** random data.
175565 static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
175566 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175567 return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
175571 ** Sleep for nMicro microseconds. Return the number of microseconds
175572 ** actually slept.
175574 static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
175575 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175576 return pRealVfs->xSleep(pRealVfs, nMicro);
175580 ** Return the current time as a Julian Day number in *pTimeOut.
175582 static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
175583 sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175584 return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
175588 ** No-op.
175590 static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
175591 return 0;
175595 ** Deregister and destroy an RBU vfs created by an earlier call to
175596 ** sqlite3rbu_create_vfs().
175598 SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
175599 sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
175600 if( pVfs && pVfs->xOpen==rbuVfsOpen ){
175601 sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
175602 sqlite3_vfs_unregister(pVfs);
175603 sqlite3_free(pVfs);
175608 ** Create an RBU VFS named zName that accesses the underlying file-system
175609 ** via existing VFS zParent. The new object is registered as a non-default
175610 ** VFS with SQLite before returning.
175612 SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
175614 /* Template for VFS */
175615 static sqlite3_vfs vfs_template = {
175616 1, /* iVersion */
175617 0, /* szOsFile */
175618 0, /* mxPathname */
175619 0, /* pNext */
175620 0, /* zName */
175621 0, /* pAppData */
175622 rbuVfsOpen, /* xOpen */
175623 rbuVfsDelete, /* xDelete */
175624 rbuVfsAccess, /* xAccess */
175625 rbuVfsFullPathname, /* xFullPathname */
175627 #ifndef SQLITE_OMIT_LOAD_EXTENSION
175628 rbuVfsDlOpen, /* xDlOpen */
175629 rbuVfsDlError, /* xDlError */
175630 rbuVfsDlSym, /* xDlSym */
175631 rbuVfsDlClose, /* xDlClose */
175632 #else
175633 0, 0, 0, 0,
175634 #endif
175636 rbuVfsRandomness, /* xRandomness */
175637 rbuVfsSleep, /* xSleep */
175638 rbuVfsCurrentTime, /* xCurrentTime */
175639 rbuVfsGetLastError, /* xGetLastError */
175640 0, /* xCurrentTimeInt64 (version 2) */
175641 0, 0, 0 /* Unimplemented version 3 methods */
175644 rbu_vfs *pNew = 0; /* Newly allocated VFS */
175645 int rc = SQLITE_OK;
175646 size_t nName;
175647 size_t nByte;
175649 nName = strlen(zName);
175650 nByte = sizeof(rbu_vfs) + nName + 1;
175651 pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
175652 if( pNew==0 ){
175653 rc = SQLITE_NOMEM;
175654 }else{
175655 sqlite3_vfs *pParent; /* Parent VFS */
175656 memset(pNew, 0, nByte);
175657 pParent = sqlite3_vfs_find(zParent);
175658 if( pParent==0 ){
175659 rc = SQLITE_NOTFOUND;
175660 }else{
175661 char *zSpace;
175662 memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
175663 pNew->base.mxPathname = pParent->mxPathname;
175664 pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
175665 pNew->pRealVfs = pParent;
175666 pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
175667 memcpy(zSpace, zName, nName);
175669 /* Allocate the mutex and register the new VFS (not as the default) */
175670 pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
175671 if( pNew->mutex==0 ){
175672 rc = SQLITE_NOMEM;
175673 }else{
175674 rc = sqlite3_vfs_register(&pNew->base, 0);
175678 if( rc!=SQLITE_OK ){
175679 sqlite3_mutex_free(pNew->mutex);
175680 sqlite3_free(pNew);
175684 return rc;
175688 ** Configure the aggregate temp file size limit for this RBU handle.
175690 SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
175691 if( n>=0 ){
175692 pRbu->szTempLimit = n;
175694 return pRbu->szTempLimit;
175697 SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
175698 return pRbu->szTemp;
175702 /**************************************************************************/
175704 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
175706 /************** End of sqlite3rbu.c ******************************************/
175707 /************** Begin file dbstat.c ******************************************/
175709 ** 2010 July 12
175711 ** The author disclaims copyright to this source code. In place of
175712 ** a legal notice, here is a blessing:
175714 ** May you do good and not evil.
175715 ** May you find forgiveness for yourself and forgive others.
175716 ** May you share freely, never taking more than you give.
175718 ******************************************************************************
175720 ** This file contains an implementation of the "dbstat" virtual table.
175722 ** The dbstat virtual table is used to extract low-level formatting
175723 ** information from an SQLite database in order to implement the
175724 ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
175725 ** for an example implementation.
175727 ** Additional information is available on the "dbstat.html" page of the
175728 ** official SQLite documentation.
175731 /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
175732 #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
175733 && !defined(SQLITE_OMIT_VIRTUALTABLE)
175736 ** Page paths:
175738 ** The value of the 'path' column describes the path taken from the
175739 ** root-node of the b-tree structure to each page. The value of the
175740 ** root-node path is '/'.
175742 ** The value of the path for the left-most child page of the root of
175743 ** a b-tree is '/000/'. (Btrees store content ordered from left to right
175744 ** so the pages to the left have smaller keys than the pages to the right.)
175745 ** The next to left-most child of the root page is
175746 ** '/001', and so on, each sibling page identified by a 3-digit hex
175747 ** value. The children of the 451st left-most sibling have paths such
175748 ** as '/1c2/000/, '/1c2/001/' etc.
175750 ** Overflow pages are specified by appending a '+' character and a
175751 ** six-digit hexadecimal value to the path to the cell they are linked
175752 ** from. For example, the three overflow pages in a chain linked from
175753 ** the left-most cell of the 450th child of the root page are identified
175754 ** by the paths:
175756 ** '/1c2/000+000000' // First page in overflow chain
175757 ** '/1c2/000+000001' // Second page in overflow chain
175758 ** '/1c2/000+000002' // Third page in overflow chain
175760 ** If the paths are sorted using the BINARY collation sequence, then
175761 ** the overflow pages associated with a cell will appear earlier in the
175762 ** sort-order than its child page:
175764 ** '/1c2/000/' // Left-most child of 451st child of root
175766 #define VTAB_SCHEMA \
175767 "CREATE TABLE xx( " \
175768 " name TEXT, /* Name of table or index */" \
175769 " path TEXT, /* Path to page from root */" \
175770 " pageno INTEGER, /* Page number */" \
175771 " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \
175772 " ncell INTEGER, /* Cells on page (0 for overflow) */" \
175773 " payload INTEGER, /* Bytes of payload on this page */" \
175774 " unused INTEGER, /* Bytes of unused space on this page */" \
175775 " mx_payload INTEGER, /* Largest payload size of all cells */" \
175776 " pgoffset INTEGER, /* Offset of page in file */" \
175777 " pgsize INTEGER, /* Size of the page */" \
175778 " schema TEXT HIDDEN /* Database schema being analyzed */" \
175782 typedef struct StatTable StatTable;
175783 typedef struct StatCursor StatCursor;
175784 typedef struct StatPage StatPage;
175785 typedef struct StatCell StatCell;
175787 struct StatCell {
175788 int nLocal; /* Bytes of local payload */
175789 u32 iChildPg; /* Child node (or 0 if this is a leaf) */
175790 int nOvfl; /* Entries in aOvfl[] */
175791 u32 *aOvfl; /* Array of overflow page numbers */
175792 int nLastOvfl; /* Bytes of payload on final overflow page */
175793 int iOvfl; /* Iterates through aOvfl[] */
175796 struct StatPage {
175797 u32 iPgno;
175798 DbPage *pPg;
175799 int iCell;
175801 char *zPath; /* Path to this page */
175803 /* Variables populated by statDecodePage(): */
175804 u8 flags; /* Copy of flags byte */
175805 int nCell; /* Number of cells on page */
175806 int nUnused; /* Number of unused bytes on page */
175807 StatCell *aCell; /* Array of parsed cells */
175808 u32 iRightChildPg; /* Right-child page number (or 0) */
175809 int nMxPayload; /* Largest payload of any cell on this page */
175812 struct StatCursor {
175813 sqlite3_vtab_cursor base;
175814 sqlite3_stmt *pStmt; /* Iterates through set of root pages */
175815 int isEof; /* After pStmt has returned SQLITE_DONE */
175816 int iDb; /* Schema used for this query */
175818 StatPage aPage[32];
175819 int iPage; /* Current entry in aPage[] */
175821 /* Values to return. */
175822 char *zName; /* Value of 'name' column */
175823 char *zPath; /* Value of 'path' column */
175824 u32 iPageno; /* Value of 'pageno' column */
175825 char *zPagetype; /* Value of 'pagetype' column */
175826 int nCell; /* Value of 'ncell' column */
175827 int nPayload; /* Value of 'payload' column */
175828 int nUnused; /* Value of 'unused' column */
175829 int nMxPayload; /* Value of 'mx_payload' column */
175830 i64 iOffset; /* Value of 'pgOffset' column */
175831 int szPage; /* Value of 'pgSize' column */
175834 struct StatTable {
175835 sqlite3_vtab base;
175836 sqlite3 *db;
175837 int iDb; /* Index of database to analyze */
175840 #ifndef get2byte
175841 # define get2byte(x) ((x)[0]<<8 | (x)[1])
175842 #endif
175845 ** Connect to or create a statvfs virtual table.
175847 static int statConnect(
175848 sqlite3 *db,
175849 void *pAux,
175850 int argc, const char *const*argv,
175851 sqlite3_vtab **ppVtab,
175852 char **pzErr
175854 StatTable *pTab = 0;
175855 int rc = SQLITE_OK;
175856 int iDb;
175858 if( argc>=4 ){
175859 Token nm;
175860 sqlite3TokenInit(&nm, (char*)argv[3]);
175861 iDb = sqlite3FindDb(db, &nm);
175862 if( iDb<0 ){
175863 *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
175864 return SQLITE_ERROR;
175866 }else{
175867 iDb = 0;
175869 rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
175870 if( rc==SQLITE_OK ){
175871 pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
175872 if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
175875 assert( rc==SQLITE_OK || pTab==0 );
175876 if( rc==SQLITE_OK ){
175877 memset(pTab, 0, sizeof(StatTable));
175878 pTab->db = db;
175879 pTab->iDb = iDb;
175882 *ppVtab = (sqlite3_vtab*)pTab;
175883 return rc;
175887 ** Disconnect from or destroy a statvfs virtual table.
175889 static int statDisconnect(sqlite3_vtab *pVtab){
175890 sqlite3_free(pVtab);
175891 return SQLITE_OK;
175895 ** There is no "best-index". This virtual table always does a linear
175896 ** scan. However, a schema=? constraint should cause this table to
175897 ** operate on a different database schema, so check for it.
175899 ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
175901 static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
175902 int i;
175904 pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
175906 /* Look for a valid schema=? constraint. If found, change the idxNum to
175907 ** 1 and request the value of that constraint be sent to xFilter. And
175908 ** lower the cost estimate to encourage the constrained version to be
175909 ** used.
175911 for(i=0; i<pIdxInfo->nConstraint; i++){
175912 if( pIdxInfo->aConstraint[i].usable==0 ) continue;
175913 if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
175914 if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
175915 pIdxInfo->idxNum = 1;
175916 pIdxInfo->estimatedCost = 1.0;
175917 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
175918 pIdxInfo->aConstraintUsage[i].omit = 1;
175919 break;
175923 /* Records are always returned in ascending order of (name, path).
175924 ** If this will satisfy the client, set the orderByConsumed flag so that
175925 ** SQLite does not do an external sort.
175927 if( ( pIdxInfo->nOrderBy==1
175928 && pIdxInfo->aOrderBy[0].iColumn==0
175929 && pIdxInfo->aOrderBy[0].desc==0
175931 ( pIdxInfo->nOrderBy==2
175932 && pIdxInfo->aOrderBy[0].iColumn==0
175933 && pIdxInfo->aOrderBy[0].desc==0
175934 && pIdxInfo->aOrderBy[1].iColumn==1
175935 && pIdxInfo->aOrderBy[1].desc==0
175938 pIdxInfo->orderByConsumed = 1;
175941 return SQLITE_OK;
175945 ** Open a new statvfs cursor.
175947 static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
175948 StatTable *pTab = (StatTable *)pVTab;
175949 StatCursor *pCsr;
175951 pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
175952 if( pCsr==0 ){
175953 return SQLITE_NOMEM_BKPT;
175954 }else{
175955 memset(pCsr, 0, sizeof(StatCursor));
175956 pCsr->base.pVtab = pVTab;
175957 pCsr->iDb = pTab->iDb;
175960 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
175961 return SQLITE_OK;
175964 static void statClearPage(StatPage *p){
175965 int i;
175966 if( p->aCell ){
175967 for(i=0; i<p->nCell; i++){
175968 sqlite3_free(p->aCell[i].aOvfl);
175970 sqlite3_free(p->aCell);
175972 sqlite3PagerUnref(p->pPg);
175973 sqlite3_free(p->zPath);
175974 memset(p, 0, sizeof(StatPage));
175977 static void statResetCsr(StatCursor *pCsr){
175978 int i;
175979 sqlite3_reset(pCsr->pStmt);
175980 for(i=0; i<ArraySize(pCsr->aPage); i++){
175981 statClearPage(&pCsr->aPage[i]);
175983 pCsr->iPage = 0;
175984 sqlite3_free(pCsr->zPath);
175985 pCsr->zPath = 0;
175986 pCsr->isEof = 0;
175990 ** Close a statvfs cursor.
175992 static int statClose(sqlite3_vtab_cursor *pCursor){
175993 StatCursor *pCsr = (StatCursor *)pCursor;
175994 statResetCsr(pCsr);
175995 sqlite3_finalize(pCsr->pStmt);
175996 sqlite3_free(pCsr);
175997 return SQLITE_OK;
176000 static void getLocalPayload(
176001 int nUsable, /* Usable bytes per page */
176002 u8 flags, /* Page flags */
176003 int nTotal, /* Total record (payload) size */
176004 int *pnLocal /* OUT: Bytes stored locally */
176006 int nLocal;
176007 int nMinLocal;
176008 int nMaxLocal;
176010 if( flags==0x0D ){ /* Table leaf node */
176011 nMinLocal = (nUsable - 12) * 32 / 255 - 23;
176012 nMaxLocal = nUsable - 35;
176013 }else{ /* Index interior and leaf nodes */
176014 nMinLocal = (nUsable - 12) * 32 / 255 - 23;
176015 nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
176018 nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
176019 if( nLocal>nMaxLocal ) nLocal = nMinLocal;
176020 *pnLocal = nLocal;
176023 static int statDecodePage(Btree *pBt, StatPage *p){
176024 int nUnused;
176025 int iOff;
176026 int nHdr;
176027 int isLeaf;
176028 int szPage;
176030 u8 *aData = sqlite3PagerGetData(p->pPg);
176031 u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
176033 p->flags = aHdr[0];
176034 p->nCell = get2byte(&aHdr[3]);
176035 p->nMxPayload = 0;
176037 isLeaf = (p->flags==0x0A || p->flags==0x0D);
176038 nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
176040 nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
176041 nUnused += (int)aHdr[7];
176042 iOff = get2byte(&aHdr[1]);
176043 while( iOff ){
176044 nUnused += get2byte(&aData[iOff+2]);
176045 iOff = get2byte(&aData[iOff]);
176047 p->nUnused = nUnused;
176048 p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
176049 szPage = sqlite3BtreeGetPageSize(pBt);
176051 if( p->nCell ){
176052 int i; /* Used to iterate through cells */
176053 int nUsable; /* Usable bytes per page */
176055 sqlite3BtreeEnter(pBt);
176056 nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
176057 sqlite3BtreeLeave(pBt);
176058 p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
176059 if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
176060 memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
176062 for(i=0; i<p->nCell; i++){
176063 StatCell *pCell = &p->aCell[i];
176065 iOff = get2byte(&aData[nHdr+i*2]);
176066 if( !isLeaf ){
176067 pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
176068 iOff += 4;
176070 if( p->flags==0x05 ){
176071 /* A table interior node. nPayload==0. */
176072 }else{
176073 u32 nPayload; /* Bytes of payload total (local+overflow) */
176074 int nLocal; /* Bytes of payload stored locally */
176075 iOff += getVarint32(&aData[iOff], nPayload);
176076 if( p->flags==0x0D ){
176077 u64 dummy;
176078 iOff += sqlite3GetVarint(&aData[iOff], &dummy);
176080 if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
176081 getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
176082 pCell->nLocal = nLocal;
176083 assert( nLocal>=0 );
176084 assert( nPayload>=(u32)nLocal );
176085 assert( nLocal<=(nUsable-35) );
176086 if( nPayload>(u32)nLocal ){
176087 int j;
176088 int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
176089 pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
176090 pCell->nOvfl = nOvfl;
176091 pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
176092 if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
176093 pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
176094 for(j=1; j<nOvfl; j++){
176095 int rc;
176096 u32 iPrev = pCell->aOvfl[j-1];
176097 DbPage *pPg = 0;
176098 rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
176099 if( rc!=SQLITE_OK ){
176100 assert( pPg==0 );
176101 return rc;
176103 pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
176104 sqlite3PagerUnref(pPg);
176111 return SQLITE_OK;
176115 ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
176116 ** the current value of pCsr->iPageno.
176118 static void statSizeAndOffset(StatCursor *pCsr){
176119 StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
176120 Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
176121 Pager *pPager = sqlite3BtreePager(pBt);
176122 sqlite3_file *fd;
176123 sqlite3_int64 x[2];
176125 /* The default page size and offset */
176126 pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
176127 pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
176129 /* If connected to a ZIPVFS backend, override the page size and
176130 ** offset with actual values obtained from ZIPVFS.
176132 fd = sqlite3PagerFile(pPager);
176133 x[0] = pCsr->iPageno;
176134 if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
176135 pCsr->iOffset = x[0];
176136 pCsr->szPage = (int)x[1];
176141 ** Move a statvfs cursor to the next entry in the file.
176143 static int statNext(sqlite3_vtab_cursor *pCursor){
176144 int rc;
176145 int nPayload;
176146 char *z;
176147 StatCursor *pCsr = (StatCursor *)pCursor;
176148 StatTable *pTab = (StatTable *)pCursor->pVtab;
176149 Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
176150 Pager *pPager = sqlite3BtreePager(pBt);
176152 sqlite3_free(pCsr->zPath);
176153 pCsr->zPath = 0;
176155 statNextRestart:
176156 if( pCsr->aPage[0].pPg==0 ){
176157 rc = sqlite3_step(pCsr->pStmt);
176158 if( rc==SQLITE_ROW ){
176159 int nPage;
176160 u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
176161 sqlite3PagerPagecount(pPager, &nPage);
176162 if( nPage==0 ){
176163 pCsr->isEof = 1;
176164 return sqlite3_reset(pCsr->pStmt);
176166 rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
176167 pCsr->aPage[0].iPgno = iRoot;
176168 pCsr->aPage[0].iCell = 0;
176169 pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
176170 pCsr->iPage = 0;
176171 if( z==0 ) rc = SQLITE_NOMEM_BKPT;
176172 }else{
176173 pCsr->isEof = 1;
176174 return sqlite3_reset(pCsr->pStmt);
176176 }else{
176178 /* Page p itself has already been visited. */
176179 StatPage *p = &pCsr->aPage[pCsr->iPage];
176181 while( p->iCell<p->nCell ){
176182 StatCell *pCell = &p->aCell[p->iCell];
176183 if( pCell->iOvfl<pCell->nOvfl ){
176184 int nUsable;
176185 sqlite3BtreeEnter(pBt);
176186 nUsable = sqlite3BtreeGetPageSize(pBt) -
176187 sqlite3BtreeGetReserveNoMutex(pBt);
176188 sqlite3BtreeLeave(pBt);
176189 pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
176190 pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
176191 pCsr->zPagetype = "overflow";
176192 pCsr->nCell = 0;
176193 pCsr->nMxPayload = 0;
176194 pCsr->zPath = z = sqlite3_mprintf(
176195 "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
176197 if( pCell->iOvfl<pCell->nOvfl-1 ){
176198 pCsr->nUnused = 0;
176199 pCsr->nPayload = nUsable - 4;
176200 }else{
176201 pCsr->nPayload = pCell->nLastOvfl;
176202 pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
176204 pCell->iOvfl++;
176205 statSizeAndOffset(pCsr);
176206 return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
176208 if( p->iRightChildPg ) break;
176209 p->iCell++;
176212 if( !p->iRightChildPg || p->iCell>p->nCell ){
176213 statClearPage(p);
176214 if( pCsr->iPage==0 ) return statNext(pCursor);
176215 pCsr->iPage--;
176216 goto statNextRestart; /* Tail recursion */
176218 pCsr->iPage++;
176219 assert( p==&pCsr->aPage[pCsr->iPage-1] );
176221 if( p->iCell==p->nCell ){
176222 p[1].iPgno = p->iRightChildPg;
176223 }else{
176224 p[1].iPgno = p->aCell[p->iCell].iChildPg;
176226 rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
176227 p[1].iCell = 0;
176228 p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
176229 p->iCell++;
176230 if( z==0 ) rc = SQLITE_NOMEM_BKPT;
176234 /* Populate the StatCursor fields with the values to be returned
176235 ** by the xColumn() and xRowid() methods.
176237 if( rc==SQLITE_OK ){
176238 int i;
176239 StatPage *p = &pCsr->aPage[pCsr->iPage];
176240 pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
176241 pCsr->iPageno = p->iPgno;
176243 rc = statDecodePage(pBt, p);
176244 if( rc==SQLITE_OK ){
176245 statSizeAndOffset(pCsr);
176247 switch( p->flags ){
176248 case 0x05: /* table internal */
176249 case 0x02: /* index internal */
176250 pCsr->zPagetype = "internal";
176251 break;
176252 case 0x0D: /* table leaf */
176253 case 0x0A: /* index leaf */
176254 pCsr->zPagetype = "leaf";
176255 break;
176256 default:
176257 pCsr->zPagetype = "corrupted";
176258 break;
176260 pCsr->nCell = p->nCell;
176261 pCsr->nUnused = p->nUnused;
176262 pCsr->nMxPayload = p->nMxPayload;
176263 pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
176264 if( z==0 ) rc = SQLITE_NOMEM_BKPT;
176265 nPayload = 0;
176266 for(i=0; i<p->nCell; i++){
176267 nPayload += p->aCell[i].nLocal;
176269 pCsr->nPayload = nPayload;
176273 return rc;
176276 static int statEof(sqlite3_vtab_cursor *pCursor){
176277 StatCursor *pCsr = (StatCursor *)pCursor;
176278 return pCsr->isEof;
176281 static int statFilter(
176282 sqlite3_vtab_cursor *pCursor,
176283 int idxNum, const char *idxStr,
176284 int argc, sqlite3_value **argv
176286 StatCursor *pCsr = (StatCursor *)pCursor;
176287 StatTable *pTab = (StatTable*)(pCursor->pVtab);
176288 char *zSql;
176289 int rc = SQLITE_OK;
176290 char *zMaster;
176292 if( idxNum==1 ){
176293 const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
176294 pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
176295 if( pCsr->iDb<0 ){
176296 sqlite3_free(pCursor->pVtab->zErrMsg);
176297 pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
176298 return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
176300 }else{
176301 pCsr->iDb = pTab->iDb;
176303 statResetCsr(pCsr);
176304 sqlite3_finalize(pCsr->pStmt);
176305 pCsr->pStmt = 0;
176306 zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
176307 zSql = sqlite3_mprintf(
176308 "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
176309 " UNION ALL "
176310 "SELECT name, rootpage, type"
176311 " FROM \"%w\".%s WHERE rootpage!=0"
176312 " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
176313 if( zSql==0 ){
176314 return SQLITE_NOMEM_BKPT;
176315 }else{
176316 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
176317 sqlite3_free(zSql);
176320 if( rc==SQLITE_OK ){
176321 rc = statNext(pCursor);
176323 return rc;
176326 static int statColumn(
176327 sqlite3_vtab_cursor *pCursor,
176328 sqlite3_context *ctx,
176329 int i
176331 StatCursor *pCsr = (StatCursor *)pCursor;
176332 switch( i ){
176333 case 0: /* name */
176334 sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
176335 break;
176336 case 1: /* path */
176337 sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
176338 break;
176339 case 2: /* pageno */
176340 sqlite3_result_int64(ctx, pCsr->iPageno);
176341 break;
176342 case 3: /* pagetype */
176343 sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
176344 break;
176345 case 4: /* ncell */
176346 sqlite3_result_int(ctx, pCsr->nCell);
176347 break;
176348 case 5: /* payload */
176349 sqlite3_result_int(ctx, pCsr->nPayload);
176350 break;
176351 case 6: /* unused */
176352 sqlite3_result_int(ctx, pCsr->nUnused);
176353 break;
176354 case 7: /* mx_payload */
176355 sqlite3_result_int(ctx, pCsr->nMxPayload);
176356 break;
176357 case 8: /* pgoffset */
176358 sqlite3_result_int64(ctx, pCsr->iOffset);
176359 break;
176360 case 9: /* pgsize */
176361 sqlite3_result_int(ctx, pCsr->szPage);
176362 break;
176363 default: { /* schema */
176364 sqlite3 *db = sqlite3_context_db_handle(ctx);
176365 int iDb = pCsr->iDb;
176366 sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
176367 break;
176370 return SQLITE_OK;
176373 static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
176374 StatCursor *pCsr = (StatCursor *)pCursor;
176375 *pRowid = pCsr->iPageno;
176376 return SQLITE_OK;
176380 ** Invoke this routine to register the "dbstat" virtual table module
176382 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
176383 static sqlite3_module dbstat_module = {
176384 0, /* iVersion */
176385 statConnect, /* xCreate */
176386 statConnect, /* xConnect */
176387 statBestIndex, /* xBestIndex */
176388 statDisconnect, /* xDisconnect */
176389 statDisconnect, /* xDestroy */
176390 statOpen, /* xOpen - open a cursor */
176391 statClose, /* xClose - close a cursor */
176392 statFilter, /* xFilter - configure scan constraints */
176393 statNext, /* xNext - advance a cursor */
176394 statEof, /* xEof - check for end of scan */
176395 statColumn, /* xColumn - read data */
176396 statRowid, /* xRowid - read data */
176397 0, /* xUpdate */
176398 0, /* xBegin */
176399 0, /* xSync */
176400 0, /* xCommit */
176401 0, /* xRollback */
176402 0, /* xFindMethod */
176403 0, /* xRename */
176404 0, /* xSavepoint */
176405 0, /* xRelease */
176406 0, /* xRollbackTo */
176408 return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
176410 #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
176411 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
176412 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
176414 /************** End of dbstat.c **********************************************/
176415 /************** Begin file dbpage.c ******************************************/
176417 ** 2017-10-11
176419 ** The author disclaims copyright to this source code. In place of
176420 ** a legal notice, here is a blessing:
176422 ** May you do good and not evil.
176423 ** May you find forgiveness for yourself and forgive others.
176424 ** May you share freely, never taking more than you give.
176426 ******************************************************************************
176428 ** This file contains an implementation of the "sqlite_dbpage" virtual table.
176430 ** The sqlite_dbpage virtual table is used to read or write whole raw
176431 ** pages of the database file. The pager interface is used so that
176432 ** uncommitted changes and changes recorded in the WAL file are correctly
176433 ** retrieved.
176435 ** Usage example:
176437 ** SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
176439 ** This is an eponymous virtual table so it does not need to be created before
176440 ** use. The optional argument to the sqlite_dbpage() table name is the
176441 ** schema for the database file that is to be read. The default schema is
176442 ** "main".
176444 ** The data field of sqlite_dbpage table can be updated. The new
176445 ** value must be a BLOB which is the correct page size, otherwise the
176446 ** update fails. Rows may not be deleted or inserted.
176449 /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
176450 #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
176451 && !defined(SQLITE_OMIT_VIRTUALTABLE)
176453 typedef struct DbpageTable DbpageTable;
176454 typedef struct DbpageCursor DbpageCursor;
176456 struct DbpageCursor {
176457 sqlite3_vtab_cursor base; /* Base class. Must be first */
176458 int pgno; /* Current page number */
176459 int mxPgno; /* Last page to visit on this scan */
176462 struct DbpageTable {
176463 sqlite3_vtab base; /* Base class. Must be first */
176464 sqlite3 *db; /* The database */
176465 Pager *pPager; /* Pager being read/written */
176466 int iDb; /* Index of database to analyze */
176467 int szPage; /* Size of each page in bytes */
176468 int nPage; /* Number of pages in the file */
176472 ** Connect to or create a dbpagevfs virtual table.
176474 static int dbpageConnect(
176475 sqlite3 *db,
176476 void *pAux,
176477 int argc, const char *const*argv,
176478 sqlite3_vtab **ppVtab,
176479 char **pzErr
176481 DbpageTable *pTab = 0;
176482 int rc = SQLITE_OK;
176483 int iDb;
176485 if( argc>=4 ){
176486 Token nm;
176487 sqlite3TokenInit(&nm, (char*)argv[3]);
176488 iDb = sqlite3FindDb(db, &nm);
176489 if( iDb<0 ){
176490 *pzErr = sqlite3_mprintf("no such schema: %s", argv[3]);
176491 return SQLITE_ERROR;
176493 }else{
176494 iDb = 0;
176496 rc = sqlite3_declare_vtab(db,
176497 "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
176498 if( rc==SQLITE_OK ){
176499 pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
176500 if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
176503 assert( rc==SQLITE_OK || pTab==0 );
176504 if( rc==SQLITE_OK ){
176505 Btree *pBt = db->aDb[iDb].pBt;
176506 memset(pTab, 0, sizeof(DbpageTable));
176507 pTab->db = db;
176508 pTab->iDb = iDb;
176509 pTab->pPager = pBt ? sqlite3BtreePager(pBt) : 0;
176512 *ppVtab = (sqlite3_vtab*)pTab;
176513 return rc;
176517 ** Disconnect from or destroy a dbpagevfs virtual table.
176519 static int dbpageDisconnect(sqlite3_vtab *pVtab){
176520 sqlite3_free(pVtab);
176521 return SQLITE_OK;
176525 ** idxNum:
176527 ** 0 full table scan
176528 ** 1 pgno=?1
176530 static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
176531 int i;
176532 pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
176533 for(i=0; i<pIdxInfo->nConstraint; i++){
176534 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
176535 if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
176536 pIdxInfo->estimatedRows = 1;
176537 pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
176538 pIdxInfo->estimatedCost = 1.0;
176539 pIdxInfo->idxNum = 1;
176540 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
176541 pIdxInfo->aConstraintUsage[i].omit = 1;
176542 break;
176545 if( pIdxInfo->nOrderBy>=1
176546 && pIdxInfo->aOrderBy[0].iColumn<=0
176547 && pIdxInfo->aOrderBy[0].desc==0
176549 pIdxInfo->orderByConsumed = 1;
176551 return SQLITE_OK;
176555 ** Open a new dbpagevfs cursor.
176557 static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
176558 DbpageCursor *pCsr;
176560 pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
176561 if( pCsr==0 ){
176562 return SQLITE_NOMEM_BKPT;
176563 }else{
176564 memset(pCsr, 0, sizeof(DbpageCursor));
176565 pCsr->base.pVtab = pVTab;
176566 pCsr->pgno = -1;
176569 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
176570 return SQLITE_OK;
176574 ** Close a dbpagevfs cursor.
176576 static int dbpageClose(sqlite3_vtab_cursor *pCursor){
176577 DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176578 sqlite3_free(pCsr);
176579 return SQLITE_OK;
176583 ** Move a dbpagevfs cursor to the next entry in the file.
176585 static int dbpageNext(sqlite3_vtab_cursor *pCursor){
176586 int rc = SQLITE_OK;
176587 DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176588 pCsr->pgno++;
176589 return rc;
176592 static int dbpageEof(sqlite3_vtab_cursor *pCursor){
176593 DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176594 return pCsr->pgno > pCsr->mxPgno;
176597 static int dbpageFilter(
176598 sqlite3_vtab_cursor *pCursor,
176599 int idxNum, const char *idxStr,
176600 int argc, sqlite3_value **argv
176602 DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176603 DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
176604 int rc = SQLITE_OK;
176605 Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
176607 pTab->szPage = sqlite3BtreeGetPageSize(pBt);
176608 pTab->nPage = sqlite3BtreeLastPage(pBt);
176609 if( idxNum==1 ){
176610 pCsr->pgno = sqlite3_value_int(argv[0]);
176611 if( pCsr->pgno<1 || pCsr->pgno>pTab->nPage ){
176612 pCsr->pgno = 1;
176613 pCsr->mxPgno = 0;
176614 }else{
176615 pCsr->mxPgno = pCsr->pgno;
176617 }else{
176618 pCsr->pgno = 1;
176619 pCsr->mxPgno = pTab->nPage;
176621 return rc;
176624 static int dbpageColumn(
176625 sqlite3_vtab_cursor *pCursor,
176626 sqlite3_context *ctx,
176627 int i
176629 DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176630 DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
176631 int rc = SQLITE_OK;
176632 switch( i ){
176633 case 0: { /* pgno */
176634 sqlite3_result_int(ctx, pCsr->pgno);
176635 break;
176637 case 1: { /* data */
176638 DbPage *pDbPage = 0;
176639 rc = sqlite3PagerGet(pTab->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
176640 if( rc==SQLITE_OK ){
176641 sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pTab->szPage,
176642 SQLITE_TRANSIENT);
176644 sqlite3PagerUnref(pDbPage);
176645 break;
176647 default: { /* schema */
176648 sqlite3 *db = sqlite3_context_db_handle(ctx);
176649 sqlite3_result_text(ctx, db->aDb[pTab->iDb].zDbSName, -1, SQLITE_STATIC);
176650 break;
176653 return SQLITE_OK;
176656 static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
176657 DbpageCursor *pCsr = (DbpageCursor *)pCursor;
176658 *pRowid = pCsr->pgno;
176659 return SQLITE_OK;
176662 static int dbpageUpdate(
176663 sqlite3_vtab *pVtab,
176664 int argc,
176665 sqlite3_value **argv,
176666 sqlite_int64 *pRowid
176668 DbpageTable *pTab = (DbpageTable *)pVtab;
176669 int pgno;
176670 DbPage *pDbPage = 0;
176671 int rc = SQLITE_OK;
176672 char *zErr = 0;
176674 if( argc==1 ){
176675 zErr = "cannot delete";
176676 goto update_fail;
176678 pgno = sqlite3_value_int(argv[0]);
176679 if( pgno<1 || pgno>pTab->nPage ){
176680 zErr = "bad page number";
176681 goto update_fail;
176683 if( sqlite3_value_int(argv[1])!=pgno ){
176684 zErr = "cannot insert";
176685 goto update_fail;
176687 if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
176688 || sqlite3_value_bytes(argv[3])!=pTab->szPage
176690 zErr = "bad page value";
176691 goto update_fail;
176693 rc = sqlite3PagerGet(pTab->pPager, pgno, (DbPage**)&pDbPage, 0);
176694 if( rc==SQLITE_OK ){
176695 rc = sqlite3PagerWrite(pDbPage);
176696 if( rc==SQLITE_OK ){
176697 memcpy(sqlite3PagerGetData(pDbPage),
176698 sqlite3_value_blob(argv[3]),
176699 pTab->szPage);
176702 sqlite3PagerUnref(pDbPage);
176703 return rc;
176705 update_fail:
176706 sqlite3_free(pVtab->zErrMsg);
176707 pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
176708 return SQLITE_ERROR;
176712 ** Invoke this routine to register the "dbpage" virtual table module
176714 SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
176715 static sqlite3_module dbpage_module = {
176716 0, /* iVersion */
176717 dbpageConnect, /* xCreate */
176718 dbpageConnect, /* xConnect */
176719 dbpageBestIndex, /* xBestIndex */
176720 dbpageDisconnect, /* xDisconnect */
176721 dbpageDisconnect, /* xDestroy */
176722 dbpageOpen, /* xOpen - open a cursor */
176723 dbpageClose, /* xClose - close a cursor */
176724 dbpageFilter, /* xFilter - configure scan constraints */
176725 dbpageNext, /* xNext - advance a cursor */
176726 dbpageEof, /* xEof - check for end of scan */
176727 dbpageColumn, /* xColumn - read data */
176728 dbpageRowid, /* xRowid - read data */
176729 dbpageUpdate, /* xUpdate */
176730 0, /* xBegin */
176731 0, /* xSync */
176732 0, /* xCommit */
176733 0, /* xRollback */
176734 0, /* xFindMethod */
176735 0, /* xRename */
176736 0, /* xSavepoint */
176737 0, /* xRelease */
176738 0, /* xRollbackTo */
176740 return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
176742 #elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
176743 SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
176744 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
176746 /************** End of dbpage.c **********************************************/
176747 /************** Begin file sqlite3session.c **********************************/
176749 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
176750 /* #include "sqlite3session.h" */
176751 /* #include <assert.h> */
176752 /* #include <string.h> */
176754 #ifndef SQLITE_AMALGAMATION
176755 /* # include "sqliteInt.h" */
176756 /* # include "vdbeInt.h" */
176757 #endif
176759 typedef struct SessionTable SessionTable;
176760 typedef struct SessionChange SessionChange;
176761 typedef struct SessionBuffer SessionBuffer;
176762 typedef struct SessionInput SessionInput;
176765 ** Minimum chunk size used by streaming versions of functions.
176767 #ifndef SESSIONS_STRM_CHUNK_SIZE
176768 # ifdef SQLITE_TEST
176769 # define SESSIONS_STRM_CHUNK_SIZE 64
176770 # else
176771 # define SESSIONS_STRM_CHUNK_SIZE 1024
176772 # endif
176773 #endif
176775 typedef struct SessionHook SessionHook;
176776 struct SessionHook {
176777 void *pCtx;
176778 int (*xOld)(void*,int,sqlite3_value**);
176779 int (*xNew)(void*,int,sqlite3_value**);
176780 int (*xCount)(void*);
176781 int (*xDepth)(void*);
176785 ** Session handle structure.
176787 struct sqlite3_session {
176788 sqlite3 *db; /* Database handle session is attached to */
176789 char *zDb; /* Name of database session is attached to */
176790 int bEnable; /* True if currently recording */
176791 int bIndirect; /* True if all changes are indirect */
176792 int bAutoAttach; /* True to auto-attach tables */
176793 int rc; /* Non-zero if an error has occurred */
176794 void *pFilterCtx; /* First argument to pass to xTableFilter */
176795 int (*xTableFilter)(void *pCtx, const char *zTab);
176796 sqlite3_session *pNext; /* Next session object on same db. */
176797 SessionTable *pTable; /* List of attached tables */
176798 SessionHook hook; /* APIs to grab new and old data with */
176802 ** Instances of this structure are used to build strings or binary records.
176804 struct SessionBuffer {
176805 u8 *aBuf; /* Pointer to changeset buffer */
176806 int nBuf; /* Size of buffer aBuf */
176807 int nAlloc; /* Size of allocation containing aBuf */
176811 ** An object of this type is used internally as an abstraction for
176812 ** input data. Input data may be supplied either as a single large buffer
176813 ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
176814 ** sqlite3changeset_start_strm()).
176816 struct SessionInput {
176817 int bNoDiscard; /* If true, discard no data */
176818 int iCurrent; /* Offset in aData[] of current change */
176819 int iNext; /* Offset in aData[] of next change */
176820 u8 *aData; /* Pointer to buffer containing changeset */
176821 int nData; /* Number of bytes in aData */
176823 SessionBuffer buf; /* Current read buffer */
176824 int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
176825 void *pIn; /* First argument to xInput */
176826 int bEof; /* Set to true after xInput finished */
176830 ** Structure for changeset iterators.
176832 struct sqlite3_changeset_iter {
176833 SessionInput in; /* Input buffer or stream */
176834 SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
176835 int bPatchset; /* True if this is a patchset */
176836 int rc; /* Iterator error code */
176837 sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
176838 char *zTab; /* Current table */
176839 int nCol; /* Number of columns in zTab */
176840 int op; /* Current operation */
176841 int bIndirect; /* True if current change was indirect */
176842 u8 *abPK; /* Primary key array */
176843 sqlite3_value **apValue; /* old.* and new.* values */
176847 ** Each session object maintains a set of the following structures, one
176848 ** for each table the session object is monitoring. The structures are
176849 ** stored in a linked list starting at sqlite3_session.pTable.
176851 ** The keys of the SessionTable.aChange[] hash table are all rows that have
176852 ** been modified in any way since the session object was attached to the
176853 ** table.
176855 ** The data associated with each hash-table entry is a structure containing
176856 ** a subset of the initial values that the modified row contained at the
176857 ** start of the session. Or no initial values if the row was inserted.
176859 struct SessionTable {
176860 SessionTable *pNext;
176861 char *zName; /* Local name of table */
176862 int nCol; /* Number of columns in table zName */
176863 const char **azCol; /* Column names */
176864 u8 *abPK; /* Array of primary key flags */
176865 int nEntry; /* Total number of entries in hash table */
176866 int nChange; /* Size of apChange[] array */
176867 SessionChange **apChange; /* Hash table buckets */
176871 ** RECORD FORMAT:
176873 ** The following record format is similar to (but not compatible with) that
176874 ** used in SQLite database files. This format is used as part of the
176875 ** change-set binary format, and so must be architecture independent.
176877 ** Unlike the SQLite database record format, each field is self-contained -
176878 ** there is no separation of header and data. Each field begins with a
176879 ** single byte describing its type, as follows:
176881 ** 0x00: Undefined value.
176882 ** 0x01: Integer value.
176883 ** 0x02: Real value.
176884 ** 0x03: Text value.
176885 ** 0x04: Blob value.
176886 ** 0x05: SQL NULL value.
176888 ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
176889 ** and so on in sqlite3.h. For undefined and NULL values, the field consists
176890 ** only of the single type byte. For other types of values, the type byte
176891 ** is followed by:
176893 ** Text values:
176894 ** A varint containing the number of bytes in the value (encoded using
176895 ** UTF-8). Followed by a buffer containing the UTF-8 representation
176896 ** of the text value. There is no nul terminator.
176898 ** Blob values:
176899 ** A varint containing the number of bytes in the value, followed by
176900 ** a buffer containing the value itself.
176902 ** Integer values:
176903 ** An 8-byte big-endian integer value.
176905 ** Real values:
176906 ** An 8-byte big-endian IEEE 754-2008 real value.
176908 ** Varint values are encoded in the same way as varints in the SQLite
176909 ** record format.
176911 ** CHANGESET FORMAT:
176913 ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
176914 ** one or more tables. Operations on a single table are grouped together,
176915 ** but may occur in any order (i.e. deletes, updates and inserts are all
176916 ** mixed together).
176918 ** Each group of changes begins with a table header:
176920 ** 1 byte: Constant 0x54 (capital 'T')
176921 ** Varint: Number of columns in the table.
176922 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
176923 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
176925 ** Followed by one or more changes to the table.
176927 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
176928 ** 1 byte: The "indirect-change" flag.
176929 ** old.* record: (delete and update only)
176930 ** new.* record: (insert and update only)
176932 ** The "old.*" and "new.*" records, if present, are N field records in the
176933 ** format described above under "RECORD FORMAT", where N is the number of
176934 ** columns in the table. The i'th field of each record is associated with
176935 ** the i'th column of the table, counting from left to right in the order
176936 ** in which columns were declared in the CREATE TABLE statement.
176938 ** The new.* record that is part of each INSERT change contains the values
176939 ** that make up the new row. Similarly, the old.* record that is part of each
176940 ** DELETE change contains the values that made up the row that was deleted
176941 ** from the database. In the changeset format, the records that are part
176942 ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
176943 ** fields.
176945 ** Within the old.* record associated with an UPDATE change, all fields
176946 ** associated with table columns that are not PRIMARY KEY columns and are
176947 ** not modified by the UPDATE change are set to "undefined". Other fields
176948 ** are set to the values that made up the row before the UPDATE that the
176949 ** change records took place. Within the new.* record, fields associated
176950 ** with table columns modified by the UPDATE change contain the new
176951 ** values. Fields associated with table columns that are not modified
176952 ** are set to "undefined".
176954 ** PATCHSET FORMAT:
176956 ** A patchset is also a collection of changes. It is similar to a changeset,
176957 ** but leaves undefined those fields that are not useful if no conflict
176958 ** resolution is required when applying the changeset.
176960 ** Each group of changes begins with a table header:
176962 ** 1 byte: Constant 0x50 (capital 'P')
176963 ** Varint: Number of columns in the table.
176964 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
176965 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
176967 ** Followed by one or more changes to the table.
176969 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
176970 ** 1 byte: The "indirect-change" flag.
176971 ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
176972 ** full record for INSERT).
176974 ** As in the changeset format, each field of the single record that is part
176975 ** of a patchset change is associated with the correspondingly positioned
176976 ** table column, counting from left to right within the CREATE TABLE
176977 ** statement.
176979 ** For a DELETE change, all fields within the record except those associated
176980 ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
176981 ** contain the values identifying the row to delete.
176983 ** For an UPDATE change, all fields except those associated with PRIMARY KEY
176984 ** columns and columns that are modified by the UPDATE are set to "undefined".
176985 ** PRIMARY KEY fields contain the values identifying the table row to update,
176986 ** and fields associated with modified columns contain the new column values.
176988 ** The records associated with INSERT changes are in the same format as for
176989 ** changesets. It is not possible for a record associated with an INSERT
176990 ** change to contain a field set to "undefined".
176994 ** For each row modified during a session, there exists a single instance of
176995 ** this structure stored in a SessionTable.aChange[] hash table.
176997 struct SessionChange {
176998 int op; /* One of UPDATE, DELETE, INSERT */
176999 int bIndirect; /* True if this change is "indirect" */
177000 int nRecord; /* Number of bytes in buffer aRecord[] */
177001 u8 *aRecord; /* Buffer containing old.* record */
177002 SessionChange *pNext; /* For hash-table collisions */
177006 ** Write a varint with value iVal into the buffer at aBuf. Return the
177007 ** number of bytes written.
177009 static int sessionVarintPut(u8 *aBuf, int iVal){
177010 return putVarint32(aBuf, iVal);
177014 ** Return the number of bytes required to store value iVal as a varint.
177016 static int sessionVarintLen(int iVal){
177017 return sqlite3VarintLen(iVal);
177021 ** Read a varint value from aBuf[] into *piVal. Return the number of
177022 ** bytes read.
177024 static int sessionVarintGet(u8 *aBuf, int *piVal){
177025 return getVarint32(aBuf, *piVal);
177028 /* Load an unaligned and unsigned 32-bit integer */
177029 #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
177032 ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
177033 ** the value read.
177035 static sqlite3_int64 sessionGetI64(u8 *aRec){
177036 u64 x = SESSION_UINT32(aRec);
177037 u32 y = SESSION_UINT32(aRec+4);
177038 x = (x<<32) + y;
177039 return (sqlite3_int64)x;
177043 ** Write a 64-bit big-endian integer value to the buffer aBuf[].
177045 static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
177046 aBuf[0] = (i>>56) & 0xFF;
177047 aBuf[1] = (i>>48) & 0xFF;
177048 aBuf[2] = (i>>40) & 0xFF;
177049 aBuf[3] = (i>>32) & 0xFF;
177050 aBuf[4] = (i>>24) & 0xFF;
177051 aBuf[5] = (i>>16) & 0xFF;
177052 aBuf[6] = (i>> 8) & 0xFF;
177053 aBuf[7] = (i>> 0) & 0xFF;
177057 ** This function is used to serialize the contents of value pValue (see
177058 ** comment titled "RECORD FORMAT" above).
177060 ** If it is non-NULL, the serialized form of the value is written to
177061 ** buffer aBuf. *pnWrite is set to the number of bytes written before
177062 ** returning. Or, if aBuf is NULL, the only thing this function does is
177063 ** set *pnWrite.
177065 ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
177066 ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
177067 ** SQLITE_NOMEM is returned.
177069 static int sessionSerializeValue(
177070 u8 *aBuf, /* If non-NULL, write serialized value here */
177071 sqlite3_value *pValue, /* Value to serialize */
177072 int *pnWrite /* IN/OUT: Increment by bytes written */
177074 int nByte; /* Size of serialized value in bytes */
177076 if( pValue ){
177077 int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
177079 eType = sqlite3_value_type(pValue);
177080 if( aBuf ) aBuf[0] = eType;
177082 switch( eType ){
177083 case SQLITE_NULL:
177084 nByte = 1;
177085 break;
177087 case SQLITE_INTEGER:
177088 case SQLITE_FLOAT:
177089 if( aBuf ){
177090 /* TODO: SQLite does something special to deal with mixed-endian
177091 ** floating point values (e.g. ARM7). This code probably should
177092 ** too. */
177093 u64 i;
177094 if( eType==SQLITE_INTEGER ){
177095 i = (u64)sqlite3_value_int64(pValue);
177096 }else{
177097 double r;
177098 assert( sizeof(double)==8 && sizeof(u64)==8 );
177099 r = sqlite3_value_double(pValue);
177100 memcpy(&i, &r, 8);
177102 sessionPutI64(&aBuf[1], i);
177104 nByte = 9;
177105 break;
177107 default: {
177108 u8 *z;
177109 int n;
177110 int nVarint;
177112 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
177113 if( eType==SQLITE_TEXT ){
177114 z = (u8 *)sqlite3_value_text(pValue);
177115 }else{
177116 z = (u8 *)sqlite3_value_blob(pValue);
177118 n = sqlite3_value_bytes(pValue);
177119 if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
177120 nVarint = sessionVarintLen(n);
177122 if( aBuf ){
177123 sessionVarintPut(&aBuf[1], n);
177124 if( n ) memcpy(&aBuf[nVarint + 1], z, n);
177127 nByte = 1 + nVarint + n;
177128 break;
177131 }else{
177132 nByte = 1;
177133 if( aBuf ) aBuf[0] = '\0';
177136 if( pnWrite ) *pnWrite += nByte;
177137 return SQLITE_OK;
177142 ** This macro is used to calculate hash key values for data structures. In
177143 ** order to use this macro, the entire data structure must be represented
177144 ** as a series of unsigned integers. In order to calculate a hash-key value
177145 ** for a data structure represented as three such integers, the macro may
177146 ** then be used as follows:
177148 ** int hash_key_value;
177149 ** hash_key_value = HASH_APPEND(0, <value 1>);
177150 ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
177151 ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
177153 ** In practice, the data structures this macro is used for are the primary
177154 ** key values of modified rows.
177156 #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
177159 ** Append the hash of the 64-bit integer passed as the second argument to the
177160 ** hash-key value passed as the first. Return the new hash-key value.
177162 static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
177163 h = HASH_APPEND(h, i & 0xFFFFFFFF);
177164 return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
177168 ** Append the hash of the blob passed via the second and third arguments to
177169 ** the hash-key value passed as the first. Return the new hash-key value.
177171 static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
177172 int i;
177173 for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
177174 return h;
177178 ** Append the hash of the data type passed as the second argument to the
177179 ** hash-key value passed as the first. Return the new hash-key value.
177181 static unsigned int sessionHashAppendType(unsigned int h, int eType){
177182 return HASH_APPEND(h, eType);
177186 ** This function may only be called from within a pre-update callback.
177187 ** It calculates a hash based on the primary key values of the old.* or
177188 ** new.* row currently available and, assuming no error occurs, writes it to
177189 ** *piHash before returning. If the primary key contains one or more NULL
177190 ** values, *pbNullPK is set to true before returning.
177192 ** If an error occurs, an SQLite error code is returned and the final values
177193 ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
177194 ** and the output variables are set as described above.
177196 static int sessionPreupdateHash(
177197 sqlite3_session *pSession, /* Session object that owns pTab */
177198 SessionTable *pTab, /* Session table handle */
177199 int bNew, /* True to hash the new.* PK */
177200 int *piHash, /* OUT: Hash value */
177201 int *pbNullPK /* OUT: True if there are NULL values in PK */
177203 unsigned int h = 0; /* Hash value to return */
177204 int i; /* Used to iterate through columns */
177206 assert( *pbNullPK==0 );
177207 assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
177208 for(i=0; i<pTab->nCol; i++){
177209 if( pTab->abPK[i] ){
177210 int rc;
177211 int eType;
177212 sqlite3_value *pVal;
177214 if( bNew ){
177215 rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
177216 }else{
177217 rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
177219 if( rc!=SQLITE_OK ) return rc;
177221 eType = sqlite3_value_type(pVal);
177222 h = sessionHashAppendType(h, eType);
177223 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
177224 i64 iVal;
177225 if( eType==SQLITE_INTEGER ){
177226 iVal = sqlite3_value_int64(pVal);
177227 }else{
177228 double rVal = sqlite3_value_double(pVal);
177229 assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
177230 memcpy(&iVal, &rVal, 8);
177232 h = sessionHashAppendI64(h, iVal);
177233 }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
177234 const u8 *z;
177235 int n;
177236 if( eType==SQLITE_TEXT ){
177237 z = (const u8 *)sqlite3_value_text(pVal);
177238 }else{
177239 z = (const u8 *)sqlite3_value_blob(pVal);
177241 n = sqlite3_value_bytes(pVal);
177242 if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
177243 h = sessionHashAppendBlob(h, n, z);
177244 }else{
177245 assert( eType==SQLITE_NULL );
177246 *pbNullPK = 1;
177251 *piHash = (h % pTab->nChange);
177252 return SQLITE_OK;
177256 ** The buffer that the argument points to contains a serialized SQL value.
177257 ** Return the number of bytes of space occupied by the value (including
177258 ** the type byte).
177260 static int sessionSerialLen(u8 *a){
177261 int e = *a;
177262 int n;
177263 if( e==0 ) return 1;
177264 if( e==SQLITE_NULL ) return 1;
177265 if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
177266 return sessionVarintGet(&a[1], &n) + 1 + n;
177270 ** Based on the primary key values stored in change aRecord, calculate a
177271 ** hash key. Assume the has table has nBucket buckets. The hash keys
177272 ** calculated by this function are compatible with those calculated by
177273 ** sessionPreupdateHash().
177275 ** The bPkOnly argument is non-zero if the record at aRecord[] is from
177276 ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
177278 static unsigned int sessionChangeHash(
177279 SessionTable *pTab, /* Table handle */
177280 int bPkOnly, /* Record consists of PK fields only */
177281 u8 *aRecord, /* Change record */
177282 int nBucket /* Assume this many buckets in hash table */
177284 unsigned int h = 0; /* Value to return */
177285 int i; /* Used to iterate through columns */
177286 u8 *a = aRecord; /* Used to iterate through change record */
177288 for(i=0; i<pTab->nCol; i++){
177289 int eType = *a;
177290 int isPK = pTab->abPK[i];
177291 if( bPkOnly && isPK==0 ) continue;
177293 /* It is not possible for eType to be SQLITE_NULL here. The session
177294 ** module does not record changes for rows with NULL values stored in
177295 ** primary key columns. */
177296 assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
177297 || eType==SQLITE_TEXT || eType==SQLITE_BLOB
177298 || eType==SQLITE_NULL || eType==0
177300 assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
177302 if( isPK ){
177304 h = sessionHashAppendType(h, eType);
177305 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
177306 h = sessionHashAppendI64(h, sessionGetI64(a));
177307 a += 8;
177308 }else{
177309 int n;
177310 a += sessionVarintGet(a, &n);
177311 h = sessionHashAppendBlob(h, n, a);
177312 a += n;
177314 }else{
177315 a += sessionSerialLen(a);
177318 return (h % nBucket);
177322 ** Arguments aLeft and aRight are pointers to change records for table pTab.
177323 ** This function returns true if the two records apply to the same row (i.e.
177324 ** have the same values stored in the primary key columns), or false
177325 ** otherwise.
177327 static int sessionChangeEqual(
177328 SessionTable *pTab, /* Table used for PK definition */
177329 int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
177330 u8 *aLeft, /* Change record */
177331 int bRightPkOnly, /* True if aRight[] contains PK fields only */
177332 u8 *aRight /* Change record */
177334 u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
177335 u8 *a2 = aRight; /* Cursor to iterate through aRight */
177336 int iCol; /* Used to iterate through table columns */
177338 for(iCol=0; iCol<pTab->nCol; iCol++){
177339 if( pTab->abPK[iCol] ){
177340 int n1 = sessionSerialLen(a1);
177341 int n2 = sessionSerialLen(a2);
177343 if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
177344 return 0;
177346 a1 += n1;
177347 a2 += n2;
177348 }else{
177349 if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
177350 if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
177354 return 1;
177358 ** Arguments aLeft and aRight both point to buffers containing change
177359 ** records with nCol columns. This function "merges" the two records into
177360 ** a single records which is written to the buffer at *paOut. *paOut is
177361 ** then set to point to one byte after the last byte written before
177362 ** returning.
177364 ** The merging of records is done as follows: For each column, if the
177365 ** aRight record contains a value for the column, copy the value from
177366 ** their. Otherwise, if aLeft contains a value, copy it. If neither
177367 ** record contains a value for a given column, then neither does the
177368 ** output record.
177370 static void sessionMergeRecord(
177371 u8 **paOut,
177372 int nCol,
177373 u8 *aLeft,
177374 u8 *aRight
177376 u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
177377 u8 *a2 = aRight; /* Cursor used to iterate through aRight */
177378 u8 *aOut = *paOut; /* Output cursor */
177379 int iCol; /* Used to iterate from 0 to nCol */
177381 for(iCol=0; iCol<nCol; iCol++){
177382 int n1 = sessionSerialLen(a1);
177383 int n2 = sessionSerialLen(a2);
177384 if( *a2 ){
177385 memcpy(aOut, a2, n2);
177386 aOut += n2;
177387 }else{
177388 memcpy(aOut, a1, n1);
177389 aOut += n1;
177391 a1 += n1;
177392 a2 += n2;
177395 *paOut = aOut;
177399 ** This is a helper function used by sessionMergeUpdate().
177401 ** When this function is called, both *paOne and *paTwo point to a value
177402 ** within a change record. Before it returns, both have been advanced so
177403 ** as to point to the next value in the record.
177405 ** If, when this function is called, *paTwo points to a valid value (i.e.
177406 ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
177407 ** pointer is returned and *pnVal is set to the number of bytes in the
177408 ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
177409 ** set to the number of bytes in the value at *paOne. If *paOne points
177410 ** to the "no value" placeholder, *pnVal is set to 1. In other words:
177412 ** if( *paTwo is valid ) return *paTwo;
177413 ** return *paOne;
177416 static u8 *sessionMergeValue(
177417 u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
177418 u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
177419 int *pnVal /* OUT: Bytes in returned value */
177421 u8 *a1 = *paOne;
177422 u8 *a2 = *paTwo;
177423 u8 *pRet = 0;
177424 int n1;
177426 assert( a1 );
177427 if( a2 ){
177428 int n2 = sessionSerialLen(a2);
177429 if( *a2 ){
177430 *pnVal = n2;
177431 pRet = a2;
177433 *paTwo = &a2[n2];
177436 n1 = sessionSerialLen(a1);
177437 if( pRet==0 ){
177438 *pnVal = n1;
177439 pRet = a1;
177441 *paOne = &a1[n1];
177443 return pRet;
177447 ** This function is used by changeset_concat() to merge two UPDATE changes
177448 ** on the same row.
177450 static int sessionMergeUpdate(
177451 u8 **paOut, /* IN/OUT: Pointer to output buffer */
177452 SessionTable *pTab, /* Table change pertains to */
177453 int bPatchset, /* True if records are patchset records */
177454 u8 *aOldRecord1, /* old.* record for first change */
177455 u8 *aOldRecord2, /* old.* record for second change */
177456 u8 *aNewRecord1, /* new.* record for first change */
177457 u8 *aNewRecord2 /* new.* record for second change */
177459 u8 *aOld1 = aOldRecord1;
177460 u8 *aOld2 = aOldRecord2;
177461 u8 *aNew1 = aNewRecord1;
177462 u8 *aNew2 = aNewRecord2;
177464 u8 *aOut = *paOut;
177465 int i;
177467 if( bPatchset==0 ){
177468 int bRequired = 0;
177470 assert( aOldRecord1 && aNewRecord1 );
177472 /* Write the old.* vector first. */
177473 for(i=0; i<pTab->nCol; i++){
177474 int nOld;
177475 u8 *aOld;
177476 int nNew;
177477 u8 *aNew;
177479 aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
177480 aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
177481 if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
177482 if( pTab->abPK[i]==0 ) bRequired = 1;
177483 memcpy(aOut, aOld, nOld);
177484 aOut += nOld;
177485 }else{
177486 *(aOut++) = '\0';
177490 if( !bRequired ) return 0;
177493 /* Write the new.* vector */
177494 aOld1 = aOldRecord1;
177495 aOld2 = aOldRecord2;
177496 aNew1 = aNewRecord1;
177497 aNew2 = aNewRecord2;
177498 for(i=0; i<pTab->nCol; i++){
177499 int nOld;
177500 u8 *aOld;
177501 int nNew;
177502 u8 *aNew;
177504 aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
177505 aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
177506 if( bPatchset==0
177507 && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
177509 *(aOut++) = '\0';
177510 }else{
177511 memcpy(aOut, aNew, nNew);
177512 aOut += nNew;
177516 *paOut = aOut;
177517 return 1;
177521 ** This function is only called from within a pre-update-hook callback.
177522 ** It determines if the current pre-update-hook change affects the same row
177523 ** as the change stored in argument pChange. If so, it returns true. Otherwise
177524 ** if the pre-update-hook does not affect the same row as pChange, it returns
177525 ** false.
177527 static int sessionPreupdateEqual(
177528 sqlite3_session *pSession, /* Session object that owns SessionTable */
177529 SessionTable *pTab, /* Table associated with change */
177530 SessionChange *pChange, /* Change to compare to */
177531 int op /* Current pre-update operation */
177533 int iCol; /* Used to iterate through columns */
177534 u8 *a = pChange->aRecord; /* Cursor used to scan change record */
177536 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
177537 for(iCol=0; iCol<pTab->nCol; iCol++){
177538 if( !pTab->abPK[iCol] ){
177539 a += sessionSerialLen(a);
177540 }else{
177541 sqlite3_value *pVal; /* Value returned by preupdate_new/old */
177542 int rc; /* Error code from preupdate_new/old */
177543 int eType = *a++; /* Type of value from change record */
177545 /* The following calls to preupdate_new() and preupdate_old() can not
177546 ** fail. This is because they cache their return values, and by the
177547 ** time control flows to here they have already been called once from
177548 ** within sessionPreupdateHash(). The first two asserts below verify
177549 ** this (that the method has already been called). */
177550 if( op==SQLITE_INSERT ){
177551 /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
177552 rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
177553 }else{
177554 /* assert( db->pPreUpdate->pUnpacked ); */
177555 rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
177557 assert( rc==SQLITE_OK );
177558 if( sqlite3_value_type(pVal)!=eType ) return 0;
177560 /* A SessionChange object never has a NULL value in a PK column */
177561 assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
177562 || eType==SQLITE_BLOB || eType==SQLITE_TEXT
177565 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
177566 i64 iVal = sessionGetI64(a);
177567 a += 8;
177568 if( eType==SQLITE_INTEGER ){
177569 if( sqlite3_value_int64(pVal)!=iVal ) return 0;
177570 }else{
177571 double rVal;
177572 assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
177573 memcpy(&rVal, &iVal, 8);
177574 if( sqlite3_value_double(pVal)!=rVal ) return 0;
177576 }else{
177577 int n;
177578 const u8 *z;
177579 a += sessionVarintGet(a, &n);
177580 if( sqlite3_value_bytes(pVal)!=n ) return 0;
177581 if( eType==SQLITE_TEXT ){
177582 z = sqlite3_value_text(pVal);
177583 }else{
177584 z = sqlite3_value_blob(pVal);
177586 if( memcmp(a, z, n) ) return 0;
177587 a += n;
177588 break;
177593 return 1;
177597 ** If required, grow the hash table used to store changes on table pTab
177598 ** (part of the session pSession). If a fatal OOM error occurs, set the
177599 ** session object to failed and return SQLITE_ERROR. Otherwise, return
177600 ** SQLITE_OK.
177602 ** It is possible that a non-fatal OOM error occurs in this function. In
177603 ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
177604 ** Growing the hash table in this case is a performance optimization only,
177605 ** it is not required for correct operation.
177607 static int sessionGrowHash(int bPatchset, SessionTable *pTab){
177608 if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
177609 int i;
177610 SessionChange **apNew;
177611 int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
177613 apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
177614 if( apNew==0 ){
177615 if( pTab->nChange==0 ){
177616 return SQLITE_ERROR;
177618 return SQLITE_OK;
177620 memset(apNew, 0, sizeof(SessionChange *) * nNew);
177622 for(i=0; i<pTab->nChange; i++){
177623 SessionChange *p;
177624 SessionChange *pNext;
177625 for(p=pTab->apChange[i]; p; p=pNext){
177626 int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
177627 int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
177628 pNext = p->pNext;
177629 p->pNext = apNew[iHash];
177630 apNew[iHash] = p;
177634 sqlite3_free(pTab->apChange);
177635 pTab->nChange = nNew;
177636 pTab->apChange = apNew;
177639 return SQLITE_OK;
177643 ** This function queries the database for the names of the columns of table
177644 ** zThis, in schema zDb. It is expected that the table has nCol columns. If
177645 ** not, SQLITE_SCHEMA is returned and none of the output variables are
177646 ** populated.
177648 ** Otherwise, if they are not NULL, variable *pnCol is set to the number
177649 ** of columns in the database table and variable *pzTab is set to point to a
177650 ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
177651 ** point to an array of pointers to column names. And *pabPK (again, if not
177652 ** NULL) is set to point to an array of booleans - true if the corresponding
177653 ** column is part of the primary key.
177655 ** For example, if the table is declared as:
177657 ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
177659 ** Then the four output variables are populated as follows:
177661 ** *pnCol = 4
177662 ** *pzTab = "tbl1"
177663 ** *pazCol = {"w", "x", "y", "z"}
177664 ** *pabPK = {1, 0, 0, 1}
177666 ** All returned buffers are part of the same single allocation, which must
177667 ** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
177668 ** pointer *pazCol should be freed to release all memory. Otherwise, pointer
177669 ** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
177671 static int sessionTableInfo(
177672 sqlite3 *db, /* Database connection */
177673 const char *zDb, /* Name of attached database (e.g. "main") */
177674 const char *zThis, /* Table name */
177675 int *pnCol, /* OUT: number of columns */
177676 const char **pzTab, /* OUT: Copy of zThis */
177677 const char ***pazCol, /* OUT: Array of column names for table */
177678 u8 **pabPK /* OUT: Array of booleans - true for PK col */
177680 char *zPragma;
177681 sqlite3_stmt *pStmt;
177682 int rc;
177683 int nByte;
177684 int nDbCol = 0;
177685 int nThis;
177686 int i;
177687 u8 *pAlloc = 0;
177688 char **azCol = 0;
177689 u8 *abPK = 0;
177691 assert( pazCol && pabPK );
177693 nThis = sqlite3Strlen30(zThis);
177694 zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
177695 if( !zPragma ) return SQLITE_NOMEM;
177697 rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
177698 sqlite3_free(zPragma);
177699 if( rc!=SQLITE_OK ) return rc;
177701 nByte = nThis + 1;
177702 while( SQLITE_ROW==sqlite3_step(pStmt) ){
177703 nByte += sqlite3_column_bytes(pStmt, 1);
177704 nDbCol++;
177706 rc = sqlite3_reset(pStmt);
177708 if( rc==SQLITE_OK ){
177709 nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
177710 pAlloc = sqlite3_malloc(nByte);
177711 if( pAlloc==0 ){
177712 rc = SQLITE_NOMEM;
177715 if( rc==SQLITE_OK ){
177716 azCol = (char **)pAlloc;
177717 pAlloc = (u8 *)&azCol[nDbCol];
177718 abPK = (u8 *)pAlloc;
177719 pAlloc = &abPK[nDbCol];
177720 if( pzTab ){
177721 memcpy(pAlloc, zThis, nThis+1);
177722 *pzTab = (char *)pAlloc;
177723 pAlloc += nThis+1;
177726 i = 0;
177727 while( SQLITE_ROW==sqlite3_step(pStmt) ){
177728 int nName = sqlite3_column_bytes(pStmt, 1);
177729 const unsigned char *zName = sqlite3_column_text(pStmt, 1);
177730 if( zName==0 ) break;
177731 memcpy(pAlloc, zName, nName+1);
177732 azCol[i] = (char *)pAlloc;
177733 pAlloc += nName+1;
177734 abPK[i] = sqlite3_column_int(pStmt, 5);
177737 rc = sqlite3_reset(pStmt);
177741 /* If successful, populate the output variables. Otherwise, zero them and
177742 ** free any allocation made. An error code will be returned in this case.
177744 if( rc==SQLITE_OK ){
177745 *pazCol = (const char **)azCol;
177746 *pabPK = abPK;
177747 *pnCol = nDbCol;
177748 }else{
177749 *pazCol = 0;
177750 *pabPK = 0;
177751 *pnCol = 0;
177752 if( pzTab ) *pzTab = 0;
177753 sqlite3_free(azCol);
177755 sqlite3_finalize(pStmt);
177756 return rc;
177760 ** This function is only called from within a pre-update handler for a
177761 ** write to table pTab, part of session pSession. If this is the first
177762 ** write to this table, initalize the SessionTable.nCol, azCol[] and
177763 ** abPK[] arrays accordingly.
177765 ** If an error occurs, an error code is stored in sqlite3_session.rc and
177766 ** non-zero returned. Or, if no error occurs but the table has no primary
177767 ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
177768 ** indicate that updates on this table should be ignored. SessionTable.abPK
177769 ** is set to NULL in this case.
177771 static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
177772 if( pTab->nCol==0 ){
177773 u8 *abPK;
177774 assert( pTab->azCol==0 || pTab->abPK==0 );
177775 pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
177776 pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
177778 if( pSession->rc==SQLITE_OK ){
177779 int i;
177780 for(i=0; i<pTab->nCol; i++){
177781 if( abPK[i] ){
177782 pTab->abPK = abPK;
177783 break;
177788 return (pSession->rc || pTab->abPK==0);
177792 ** This function is only called from with a pre-update-hook reporting a
177793 ** change on table pTab (attached to session pSession). The type of change
177794 ** (UPDATE, INSERT, DELETE) is specified by the first argument.
177796 ** Unless one is already present or an error occurs, an entry is added
177797 ** to the changed-rows hash table associated with table pTab.
177799 static void sessionPreupdateOneChange(
177800 int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
177801 sqlite3_session *pSession, /* Session object pTab is attached to */
177802 SessionTable *pTab /* Table that change applies to */
177804 int iHash;
177805 int bNull = 0;
177806 int rc = SQLITE_OK;
177808 if( pSession->rc ) return;
177810 /* Load table details if required */
177811 if( sessionInitTable(pSession, pTab) ) return;
177813 /* Check the number of columns in this xPreUpdate call matches the
177814 ** number of columns in the table. */
177815 if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
177816 pSession->rc = SQLITE_SCHEMA;
177817 return;
177820 /* Grow the hash table if required */
177821 if( sessionGrowHash(0, pTab) ){
177822 pSession->rc = SQLITE_NOMEM;
177823 return;
177826 /* Calculate the hash-key for this change. If the primary key of the row
177827 ** includes a NULL value, exit early. Such changes are ignored by the
177828 ** session module. */
177829 rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
177830 if( rc!=SQLITE_OK ) goto error_out;
177832 if( bNull==0 ){
177833 /* Search the hash table for an existing record for this row. */
177834 SessionChange *pC;
177835 for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
177836 if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
177839 if( pC==0 ){
177840 /* Create a new change object containing all the old values (if
177841 ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
177842 ** values (if this is an INSERT). */
177843 SessionChange *pChange; /* New change object */
177844 int nByte; /* Number of bytes to allocate */
177845 int i; /* Used to iterate through columns */
177847 assert( rc==SQLITE_OK );
177848 pTab->nEntry++;
177850 /* Figure out how large an allocation is required */
177851 nByte = sizeof(SessionChange);
177852 for(i=0; i<pTab->nCol; i++){
177853 sqlite3_value *p = 0;
177854 if( op!=SQLITE_INSERT ){
177855 TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
177856 assert( trc==SQLITE_OK );
177857 }else if( pTab->abPK[i] ){
177858 TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
177859 assert( trc==SQLITE_OK );
177862 /* This may fail if SQLite value p contains a utf-16 string that must
177863 ** be converted to utf-8 and an OOM error occurs while doing so. */
177864 rc = sessionSerializeValue(0, p, &nByte);
177865 if( rc!=SQLITE_OK ) goto error_out;
177868 /* Allocate the change object */
177869 pChange = (SessionChange *)sqlite3_malloc(nByte);
177870 if( !pChange ){
177871 rc = SQLITE_NOMEM;
177872 goto error_out;
177873 }else{
177874 memset(pChange, 0, sizeof(SessionChange));
177875 pChange->aRecord = (u8 *)&pChange[1];
177878 /* Populate the change object. None of the preupdate_old(),
177879 ** preupdate_new() or SerializeValue() calls below may fail as all
177880 ** required values and encodings have already been cached in memory.
177881 ** It is not possible for an OOM to occur in this block. */
177882 nByte = 0;
177883 for(i=0; i<pTab->nCol; i++){
177884 sqlite3_value *p = 0;
177885 if( op!=SQLITE_INSERT ){
177886 pSession->hook.xOld(pSession->hook.pCtx, i, &p);
177887 }else if( pTab->abPK[i] ){
177888 pSession->hook.xNew(pSession->hook.pCtx, i, &p);
177890 sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
177893 /* Add the change to the hash-table */
177894 if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
177895 pChange->bIndirect = 1;
177897 pChange->nRecord = nByte;
177898 pChange->op = op;
177899 pChange->pNext = pTab->apChange[iHash];
177900 pTab->apChange[iHash] = pChange;
177902 }else if( pC->bIndirect ){
177903 /* If the existing change is considered "indirect", but this current
177904 ** change is "direct", mark the change object as direct. */
177905 if( pSession->hook.xDepth(pSession->hook.pCtx)==0
177906 && pSession->bIndirect==0
177908 pC->bIndirect = 0;
177913 /* If an error has occurred, mark the session object as failed. */
177914 error_out:
177915 if( rc!=SQLITE_OK ){
177916 pSession->rc = rc;
177920 static int sessionFindTable(
177921 sqlite3_session *pSession,
177922 const char *zName,
177923 SessionTable **ppTab
177925 int rc = SQLITE_OK;
177926 int nName = sqlite3Strlen30(zName);
177927 SessionTable *pRet;
177929 /* Search for an existing table */
177930 for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
177931 if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
177934 if( pRet==0 && pSession->bAutoAttach ){
177935 /* If there is a table-filter configured, invoke it. If it returns 0,
177936 ** do not automatically add the new table. */
177937 if( pSession->xTableFilter==0
177938 || pSession->xTableFilter(pSession->pFilterCtx, zName)
177940 rc = sqlite3session_attach(pSession, zName);
177941 if( rc==SQLITE_OK ){
177942 for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
177943 assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
177948 assert( rc==SQLITE_OK || pRet==0 );
177949 *ppTab = pRet;
177950 return rc;
177954 ** The 'pre-update' hook registered by this module with SQLite databases.
177956 static void xPreUpdate(
177957 void *pCtx, /* Copy of third arg to preupdate_hook() */
177958 sqlite3 *db, /* Database handle */
177959 int op, /* SQLITE_UPDATE, DELETE or INSERT */
177960 char const *zDb, /* Database name */
177961 char const *zName, /* Table name */
177962 sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
177963 sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
177965 sqlite3_session *pSession;
177966 int nDb = sqlite3Strlen30(zDb);
177968 assert( sqlite3_mutex_held(db->mutex) );
177970 for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
177971 SessionTable *pTab;
177973 /* If this session is attached to a different database ("main", "temp"
177974 ** etc.), or if it is not currently enabled, there is nothing to do. Skip
177975 ** to the next session object attached to this database. */
177976 if( pSession->bEnable==0 ) continue;
177977 if( pSession->rc ) continue;
177978 if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
177980 pSession->rc = sessionFindTable(pSession, zName, &pTab);
177981 if( pTab ){
177982 assert( pSession->rc==SQLITE_OK );
177983 sessionPreupdateOneChange(op, pSession, pTab);
177984 if( op==SQLITE_UPDATE ){
177985 sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
177992 ** The pre-update hook implementations.
177994 static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
177995 return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
177997 static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
177998 return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
178000 static int sessionPreupdateCount(void *pCtx){
178001 return sqlite3_preupdate_count((sqlite3*)pCtx);
178003 static int sessionPreupdateDepth(void *pCtx){
178004 return sqlite3_preupdate_depth((sqlite3*)pCtx);
178008 ** Install the pre-update hooks on the session object passed as the only
178009 ** argument.
178011 static void sessionPreupdateHooks(
178012 sqlite3_session *pSession
178014 pSession->hook.pCtx = (void*)pSession->db;
178015 pSession->hook.xOld = sessionPreupdateOld;
178016 pSession->hook.xNew = sessionPreupdateNew;
178017 pSession->hook.xCount = sessionPreupdateCount;
178018 pSession->hook.xDepth = sessionPreupdateDepth;
178021 typedef struct SessionDiffCtx SessionDiffCtx;
178022 struct SessionDiffCtx {
178023 sqlite3_stmt *pStmt;
178024 int nOldOff;
178028 ** The diff hook implementations.
178030 static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
178031 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
178032 *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
178033 return SQLITE_OK;
178035 static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
178036 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
178037 *ppVal = sqlite3_column_value(p->pStmt, iVal);
178038 return SQLITE_OK;
178040 static int sessionDiffCount(void *pCtx){
178041 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
178042 return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
178044 static int sessionDiffDepth(void *pCtx){
178045 return 0;
178049 ** Install the diff hooks on the session object passed as the only
178050 ** argument.
178052 static void sessionDiffHooks(
178053 sqlite3_session *pSession,
178054 SessionDiffCtx *pDiffCtx
178056 pSession->hook.pCtx = (void*)pDiffCtx;
178057 pSession->hook.xOld = sessionDiffOld;
178058 pSession->hook.xNew = sessionDiffNew;
178059 pSession->hook.xCount = sessionDiffCount;
178060 pSession->hook.xDepth = sessionDiffDepth;
178063 static char *sessionExprComparePK(
178064 int nCol,
178065 const char *zDb1, const char *zDb2,
178066 const char *zTab,
178067 const char **azCol, u8 *abPK
178069 int i;
178070 const char *zSep = "";
178071 char *zRet = 0;
178073 for(i=0; i<nCol; i++){
178074 if( abPK[i] ){
178075 zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
178076 zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
178078 zSep = " AND ";
178079 if( zRet==0 ) break;
178083 return zRet;
178086 static char *sessionExprCompareOther(
178087 int nCol,
178088 const char *zDb1, const char *zDb2,
178089 const char *zTab,
178090 const char **azCol, u8 *abPK
178092 int i;
178093 const char *zSep = "";
178094 char *zRet = 0;
178095 int bHave = 0;
178097 for(i=0; i<nCol; i++){
178098 if( abPK[i]==0 ){
178099 bHave = 1;
178100 zRet = sqlite3_mprintf(
178101 "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
178102 zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
178104 zSep = " OR ";
178105 if( zRet==0 ) break;
178109 if( bHave==0 ){
178110 assert( zRet==0 );
178111 zRet = sqlite3_mprintf("0");
178114 return zRet;
178117 static char *sessionSelectFindNew(
178118 int nCol,
178119 const char *zDb1, /* Pick rows in this db only */
178120 const char *zDb2, /* But not in this one */
178121 const char *zTbl, /* Table name */
178122 const char *zExpr
178124 char *zRet = sqlite3_mprintf(
178125 "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
178126 " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
178128 zDb1, zTbl, zDb2, zTbl, zExpr
178130 return zRet;
178133 static int sessionDiffFindNew(
178134 int op,
178135 sqlite3_session *pSession,
178136 SessionTable *pTab,
178137 const char *zDb1,
178138 const char *zDb2,
178139 char *zExpr
178141 int rc = SQLITE_OK;
178142 char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
178144 if( zStmt==0 ){
178145 rc = SQLITE_NOMEM;
178146 }else{
178147 sqlite3_stmt *pStmt;
178148 rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
178149 if( rc==SQLITE_OK ){
178150 SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
178151 pDiffCtx->pStmt = pStmt;
178152 pDiffCtx->nOldOff = 0;
178153 while( SQLITE_ROW==sqlite3_step(pStmt) ){
178154 sessionPreupdateOneChange(op, pSession, pTab);
178156 rc = sqlite3_finalize(pStmt);
178158 sqlite3_free(zStmt);
178161 return rc;
178164 static int sessionDiffFindModified(
178165 sqlite3_session *pSession,
178166 SessionTable *pTab,
178167 const char *zFrom,
178168 const char *zExpr
178170 int rc = SQLITE_OK;
178172 char *zExpr2 = sessionExprCompareOther(pTab->nCol,
178173 pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
178175 if( zExpr2==0 ){
178176 rc = SQLITE_NOMEM;
178177 }else{
178178 char *zStmt = sqlite3_mprintf(
178179 "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
178180 pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
178182 if( zStmt==0 ){
178183 rc = SQLITE_NOMEM;
178184 }else{
178185 sqlite3_stmt *pStmt;
178186 rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
178188 if( rc==SQLITE_OK ){
178189 SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
178190 pDiffCtx->pStmt = pStmt;
178191 pDiffCtx->nOldOff = pTab->nCol;
178192 while( SQLITE_ROW==sqlite3_step(pStmt) ){
178193 sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
178195 rc = sqlite3_finalize(pStmt);
178197 sqlite3_free(zStmt);
178201 return rc;
178204 SQLITE_API int sqlite3session_diff(
178205 sqlite3_session *pSession,
178206 const char *zFrom,
178207 const char *zTbl,
178208 char **pzErrMsg
178210 const char *zDb = pSession->zDb;
178211 int rc = pSession->rc;
178212 SessionDiffCtx d;
178214 memset(&d, 0, sizeof(d));
178215 sessionDiffHooks(pSession, &d);
178217 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
178218 if( pzErrMsg ) *pzErrMsg = 0;
178219 if( rc==SQLITE_OK ){
178220 char *zExpr = 0;
178221 sqlite3 *db = pSession->db;
178222 SessionTable *pTo; /* Table zTbl */
178224 /* Locate and if necessary initialize the target table object */
178225 rc = sessionFindTable(pSession, zTbl, &pTo);
178226 if( pTo==0 ) goto diff_out;
178227 if( sessionInitTable(pSession, pTo) ){
178228 rc = pSession->rc;
178229 goto diff_out;
178232 /* Check the table schemas match */
178233 if( rc==SQLITE_OK ){
178234 int bHasPk = 0;
178235 int bMismatch = 0;
178236 int nCol; /* Columns in zFrom.zTbl */
178237 u8 *abPK;
178238 const char **azCol = 0;
178239 rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
178240 if( rc==SQLITE_OK ){
178241 if( pTo->nCol!=nCol ){
178242 bMismatch = 1;
178243 }else{
178244 int i;
178245 for(i=0; i<nCol; i++){
178246 if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
178247 if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
178248 if( abPK[i] ) bHasPk = 1;
178253 sqlite3_free((char*)azCol);
178254 if( bMismatch ){
178255 *pzErrMsg = sqlite3_mprintf("table schemas do not match");
178256 rc = SQLITE_SCHEMA;
178258 if( bHasPk==0 ){
178259 /* Ignore tables with no primary keys */
178260 goto diff_out;
178264 if( rc==SQLITE_OK ){
178265 zExpr = sessionExprComparePK(pTo->nCol,
178266 zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
178270 /* Find new rows */
178271 if( rc==SQLITE_OK ){
178272 rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
178275 /* Find old rows */
178276 if( rc==SQLITE_OK ){
178277 rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
178280 /* Find modified rows */
178281 if( rc==SQLITE_OK ){
178282 rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
178285 sqlite3_free(zExpr);
178288 diff_out:
178289 sessionPreupdateHooks(pSession);
178290 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
178291 return rc;
178295 ** Create a session object. This session object will record changes to
178296 ** database zDb attached to connection db.
178298 SQLITE_API int sqlite3session_create(
178299 sqlite3 *db, /* Database handle */
178300 const char *zDb, /* Name of db (e.g. "main") */
178301 sqlite3_session **ppSession /* OUT: New session object */
178303 sqlite3_session *pNew; /* Newly allocated session object */
178304 sqlite3_session *pOld; /* Session object already attached to db */
178305 int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
178307 /* Zero the output value in case an error occurs. */
178308 *ppSession = 0;
178310 /* Allocate and populate the new session object. */
178311 pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
178312 if( !pNew ) return SQLITE_NOMEM;
178313 memset(pNew, 0, sizeof(sqlite3_session));
178314 pNew->db = db;
178315 pNew->zDb = (char *)&pNew[1];
178316 pNew->bEnable = 1;
178317 memcpy(pNew->zDb, zDb, nDb+1);
178318 sessionPreupdateHooks(pNew);
178320 /* Add the new session object to the linked list of session objects
178321 ** attached to database handle $db. Do this under the cover of the db
178322 ** handle mutex. */
178323 sqlite3_mutex_enter(sqlite3_db_mutex(db));
178324 pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
178325 pNew->pNext = pOld;
178326 sqlite3_mutex_leave(sqlite3_db_mutex(db));
178328 *ppSession = pNew;
178329 return SQLITE_OK;
178333 ** Free the list of table objects passed as the first argument. The contents
178334 ** of the changed-rows hash tables are also deleted.
178336 static void sessionDeleteTable(SessionTable *pList){
178337 SessionTable *pNext;
178338 SessionTable *pTab;
178340 for(pTab=pList; pTab; pTab=pNext){
178341 int i;
178342 pNext = pTab->pNext;
178343 for(i=0; i<pTab->nChange; i++){
178344 SessionChange *p;
178345 SessionChange *pNextChange;
178346 for(p=pTab->apChange[i]; p; p=pNextChange){
178347 pNextChange = p->pNext;
178348 sqlite3_free(p);
178351 sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
178352 sqlite3_free(pTab->apChange);
178353 sqlite3_free(pTab);
178358 ** Delete a session object previously allocated using sqlite3session_create().
178360 SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
178361 sqlite3 *db = pSession->db;
178362 sqlite3_session *pHead;
178363 sqlite3_session **pp;
178365 /* Unlink the session from the linked list of sessions attached to the
178366 ** database handle. Hold the db mutex while doing so. */
178367 sqlite3_mutex_enter(sqlite3_db_mutex(db));
178368 pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
178369 for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
178370 if( (*pp)==pSession ){
178371 *pp = (*pp)->pNext;
178372 if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
178373 break;
178376 sqlite3_mutex_leave(sqlite3_db_mutex(db));
178378 /* Delete all attached table objects. And the contents of their
178379 ** associated hash-tables. */
178380 sessionDeleteTable(pSession->pTable);
178382 /* Free the session object itself. */
178383 sqlite3_free(pSession);
178387 ** Set a table filter on a Session Object.
178389 SQLITE_API void sqlite3session_table_filter(
178390 sqlite3_session *pSession,
178391 int(*xFilter)(void*, const char*),
178392 void *pCtx /* First argument passed to xFilter */
178394 pSession->bAutoAttach = 1;
178395 pSession->pFilterCtx = pCtx;
178396 pSession->xTableFilter = xFilter;
178400 ** Attach a table to a session. All subsequent changes made to the table
178401 ** while the session object is enabled will be recorded.
178403 ** Only tables that have a PRIMARY KEY defined may be attached. It does
178404 ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
178405 ** or not.
178407 SQLITE_API int sqlite3session_attach(
178408 sqlite3_session *pSession, /* Session object */
178409 const char *zName /* Table name */
178411 int rc = SQLITE_OK;
178412 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
178414 if( !zName ){
178415 pSession->bAutoAttach = 1;
178416 }else{
178417 SessionTable *pTab; /* New table object (if required) */
178418 int nName; /* Number of bytes in string zName */
178420 /* First search for an existing entry. If one is found, this call is
178421 ** a no-op. Return early. */
178422 nName = sqlite3Strlen30(zName);
178423 for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
178424 if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
178427 if( !pTab ){
178428 /* Allocate new SessionTable object. */
178429 pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
178430 if( !pTab ){
178431 rc = SQLITE_NOMEM;
178432 }else{
178433 /* Populate the new SessionTable object and link it into the list.
178434 ** The new object must be linked onto the end of the list, not
178435 ** simply added to the start of it in order to ensure that tables
178436 ** appear in the correct order when a changeset or patchset is
178437 ** eventually generated. */
178438 SessionTable **ppTab;
178439 memset(pTab, 0, sizeof(SessionTable));
178440 pTab->zName = (char *)&pTab[1];
178441 memcpy(pTab->zName, zName, nName+1);
178442 for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
178443 *ppTab = pTab;
178448 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
178449 return rc;
178453 ** Ensure that there is room in the buffer to append nByte bytes of data.
178454 ** If not, use sqlite3_realloc() to grow the buffer so that there is.
178456 ** If successful, return zero. Otherwise, if an OOM condition is encountered,
178457 ** set *pRc to SQLITE_NOMEM and return non-zero.
178459 static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
178460 if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
178461 u8 *aNew;
178462 int nNew = p->nAlloc ? p->nAlloc : 128;
178464 nNew = nNew*2;
178465 }while( nNew<(p->nBuf+nByte) );
178467 aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
178468 if( 0==aNew ){
178469 *pRc = SQLITE_NOMEM;
178470 }else{
178471 p->aBuf = aNew;
178472 p->nAlloc = nNew;
178475 return (*pRc!=SQLITE_OK);
178479 ** Append the value passed as the second argument to the buffer passed
178480 ** as the first.
178482 ** This function is a no-op if *pRc is non-zero when it is called.
178483 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
178484 ** before returning.
178486 static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
178487 int rc = *pRc;
178488 if( rc==SQLITE_OK ){
178489 int nByte = 0;
178490 rc = sessionSerializeValue(0, pVal, &nByte);
178491 sessionBufferGrow(p, nByte, &rc);
178492 if( rc==SQLITE_OK ){
178493 rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
178494 p->nBuf += nByte;
178495 }else{
178496 *pRc = rc;
178502 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
178503 ** called. Otherwise, append a single byte to the buffer.
178505 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178506 ** returning.
178508 static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
178509 if( 0==sessionBufferGrow(p, 1, pRc) ){
178510 p->aBuf[p->nBuf++] = v;
178515 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
178516 ** called. Otherwise, append a single varint to the buffer.
178518 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178519 ** returning.
178521 static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
178522 if( 0==sessionBufferGrow(p, 9, pRc) ){
178523 p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
178528 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
178529 ** called. Otherwise, append a blob of data to the buffer.
178531 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178532 ** returning.
178534 static void sessionAppendBlob(
178535 SessionBuffer *p,
178536 const u8 *aBlob,
178537 int nBlob,
178538 int *pRc
178540 if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
178541 memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
178542 p->nBuf += nBlob;
178547 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
178548 ** called. Otherwise, append a string to the buffer. All bytes in the string
178549 ** up to (but not including) the nul-terminator are written to the buffer.
178551 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178552 ** returning.
178554 static void sessionAppendStr(
178555 SessionBuffer *p,
178556 const char *zStr,
178557 int *pRc
178559 int nStr = sqlite3Strlen30(zStr);
178560 if( 0==sessionBufferGrow(p, nStr, pRc) ){
178561 memcpy(&p->aBuf[p->nBuf], zStr, nStr);
178562 p->nBuf += nStr;
178567 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
178568 ** called. Otherwise, append the string representation of integer iVal
178569 ** to the buffer. No nul-terminator is written.
178571 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178572 ** returning.
178574 static void sessionAppendInteger(
178575 SessionBuffer *p, /* Buffer to append to */
178576 int iVal, /* Value to write the string rep. of */
178577 int *pRc /* IN/OUT: Error code */
178579 char aBuf[24];
178580 sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
178581 sessionAppendStr(p, aBuf, pRc);
178585 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
178586 ** called. Otherwise, append the string zStr enclosed in quotes (") and
178587 ** with any embedded quote characters escaped to the buffer. No
178588 ** nul-terminator byte is written.
178590 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
178591 ** returning.
178593 static void sessionAppendIdent(
178594 SessionBuffer *p, /* Buffer to a append to */
178595 const char *zStr, /* String to quote, escape and append */
178596 int *pRc /* IN/OUT: Error code */
178598 int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
178599 if( 0==sessionBufferGrow(p, nStr, pRc) ){
178600 char *zOut = (char *)&p->aBuf[p->nBuf];
178601 const char *zIn = zStr;
178602 *zOut++ = '"';
178603 while( *zIn ){
178604 if( *zIn=='"' ) *zOut++ = '"';
178605 *zOut++ = *(zIn++);
178607 *zOut++ = '"';
178608 p->nBuf = (int)((u8 *)zOut - p->aBuf);
178613 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
178614 ** called. Otherwse, it appends the serialized version of the value stored
178615 ** in column iCol of the row that SQL statement pStmt currently points
178616 ** to to the buffer.
178618 static void sessionAppendCol(
178619 SessionBuffer *p, /* Buffer to append to */
178620 sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
178621 int iCol, /* Column to read value from */
178622 int *pRc /* IN/OUT: Error code */
178624 if( *pRc==SQLITE_OK ){
178625 int eType = sqlite3_column_type(pStmt, iCol);
178626 sessionAppendByte(p, (u8)eType, pRc);
178627 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
178628 sqlite3_int64 i;
178629 u8 aBuf[8];
178630 if( eType==SQLITE_INTEGER ){
178631 i = sqlite3_column_int64(pStmt, iCol);
178632 }else{
178633 double r = sqlite3_column_double(pStmt, iCol);
178634 memcpy(&i, &r, 8);
178636 sessionPutI64(aBuf, i);
178637 sessionAppendBlob(p, aBuf, 8, pRc);
178639 if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
178640 u8 *z;
178641 int nByte;
178642 if( eType==SQLITE_BLOB ){
178643 z = (u8 *)sqlite3_column_blob(pStmt, iCol);
178644 }else{
178645 z = (u8 *)sqlite3_column_text(pStmt, iCol);
178647 nByte = sqlite3_column_bytes(pStmt, iCol);
178648 if( z || (eType==SQLITE_BLOB && nByte==0) ){
178649 sessionAppendVarint(p, nByte, pRc);
178650 sessionAppendBlob(p, z, nByte, pRc);
178651 }else{
178652 *pRc = SQLITE_NOMEM;
178660 ** This function appends an update change to the buffer (see the comments
178661 ** under "CHANGESET FORMAT" at the top of the file). An update change
178662 ** consists of:
178664 ** 1 byte: SQLITE_UPDATE (0x17)
178665 ** n bytes: old.* record (see RECORD FORMAT)
178666 ** m bytes: new.* record (see RECORD FORMAT)
178668 ** The SessionChange object passed as the third argument contains the
178669 ** values that were stored in the row when the session began (the old.*
178670 ** values). The statement handle passed as the second argument points
178671 ** at the current version of the row (the new.* values).
178673 ** If all of the old.* values are equal to their corresponding new.* value
178674 ** (i.e. nothing has changed), then no data at all is appended to the buffer.
178676 ** Otherwise, the old.* record contains all primary key values and the
178677 ** original values of any fields that have been modified. The new.* record
178678 ** contains the new values of only those fields that have been modified.
178680 static int sessionAppendUpdate(
178681 SessionBuffer *pBuf, /* Buffer to append to */
178682 int bPatchset, /* True for "patchset", 0 for "changeset" */
178683 sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
178684 SessionChange *p, /* Object containing old values */
178685 u8 *abPK /* Boolean array - true for PK columns */
178687 int rc = SQLITE_OK;
178688 SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
178689 int bNoop = 1; /* Set to zero if any values are modified */
178690 int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
178691 int i; /* Used to iterate through columns */
178692 u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
178694 sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
178695 sessionAppendByte(pBuf, p->bIndirect, &rc);
178696 for(i=0; i<sqlite3_column_count(pStmt); i++){
178697 int bChanged = 0;
178698 int nAdvance;
178699 int eType = *pCsr;
178700 switch( eType ){
178701 case SQLITE_NULL:
178702 nAdvance = 1;
178703 if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
178704 bChanged = 1;
178706 break;
178708 case SQLITE_FLOAT:
178709 case SQLITE_INTEGER: {
178710 nAdvance = 9;
178711 if( eType==sqlite3_column_type(pStmt, i) ){
178712 sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
178713 if( eType==SQLITE_INTEGER ){
178714 if( iVal==sqlite3_column_int64(pStmt, i) ) break;
178715 }else{
178716 double dVal;
178717 memcpy(&dVal, &iVal, 8);
178718 if( dVal==sqlite3_column_double(pStmt, i) ) break;
178721 bChanged = 1;
178722 break;
178725 default: {
178726 int n;
178727 int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
178728 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
178729 nAdvance = nHdr + n;
178730 if( eType==sqlite3_column_type(pStmt, i)
178731 && n==sqlite3_column_bytes(pStmt, i)
178732 && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
178734 break;
178736 bChanged = 1;
178740 /* If at least one field has been modified, this is not a no-op. */
178741 if( bChanged ) bNoop = 0;
178743 /* Add a field to the old.* record. This is omitted if this modules is
178744 ** currently generating a patchset. */
178745 if( bPatchset==0 ){
178746 if( bChanged || abPK[i] ){
178747 sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
178748 }else{
178749 sessionAppendByte(pBuf, 0, &rc);
178753 /* Add a field to the new.* record. Or the only record if currently
178754 ** generating a patchset. */
178755 if( bChanged || (bPatchset && abPK[i]) ){
178756 sessionAppendCol(&buf2, pStmt, i, &rc);
178757 }else{
178758 sessionAppendByte(&buf2, 0, &rc);
178761 pCsr += nAdvance;
178764 if( bNoop ){
178765 pBuf->nBuf = nRewind;
178766 }else{
178767 sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
178769 sqlite3_free(buf2.aBuf);
178771 return rc;
178775 ** Append a DELETE change to the buffer passed as the first argument. Use
178776 ** the changeset format if argument bPatchset is zero, or the patchset
178777 ** format otherwise.
178779 static int sessionAppendDelete(
178780 SessionBuffer *pBuf, /* Buffer to append to */
178781 int bPatchset, /* True for "patchset", 0 for "changeset" */
178782 SessionChange *p, /* Object containing old values */
178783 int nCol, /* Number of columns in table */
178784 u8 *abPK /* Boolean array - true for PK columns */
178786 int rc = SQLITE_OK;
178788 sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
178789 sessionAppendByte(pBuf, p->bIndirect, &rc);
178791 if( bPatchset==0 ){
178792 sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
178793 }else{
178794 int i;
178795 u8 *a = p->aRecord;
178796 for(i=0; i<nCol; i++){
178797 u8 *pStart = a;
178798 int eType = *a++;
178800 switch( eType ){
178801 case 0:
178802 case SQLITE_NULL:
178803 assert( abPK[i]==0 );
178804 break;
178806 case SQLITE_FLOAT:
178807 case SQLITE_INTEGER:
178808 a += 8;
178809 break;
178811 default: {
178812 int n;
178813 a += sessionVarintGet(a, &n);
178814 a += n;
178815 break;
178818 if( abPK[i] ){
178819 sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
178822 assert( (a - p->aRecord)==p->nRecord );
178825 return rc;
178829 ** Formulate and prepare a SELECT statement to retrieve a row from table
178830 ** zTab in database zDb based on its primary key. i.e.
178832 ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
178834 static int sessionSelectStmt(
178835 sqlite3 *db, /* Database handle */
178836 const char *zDb, /* Database name */
178837 const char *zTab, /* Table name */
178838 int nCol, /* Number of columns in table */
178839 const char **azCol, /* Names of table columns */
178840 u8 *abPK, /* PRIMARY KEY array */
178841 sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
178843 int rc = SQLITE_OK;
178844 int i;
178845 const char *zSep = "";
178846 SessionBuffer buf = {0, 0, 0};
178848 sessionAppendStr(&buf, "SELECT * FROM ", &rc);
178849 sessionAppendIdent(&buf, zDb, &rc);
178850 sessionAppendStr(&buf, ".", &rc);
178851 sessionAppendIdent(&buf, zTab, &rc);
178852 sessionAppendStr(&buf, " WHERE ", &rc);
178853 for(i=0; i<nCol; i++){
178854 if( abPK[i] ){
178855 sessionAppendStr(&buf, zSep, &rc);
178856 sessionAppendIdent(&buf, azCol[i], &rc);
178857 sessionAppendStr(&buf, " = ?", &rc);
178858 sessionAppendInteger(&buf, i+1, &rc);
178859 zSep = " AND ";
178862 if( rc==SQLITE_OK ){
178863 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
178865 sqlite3_free(buf.aBuf);
178866 return rc;
178870 ** Bind the PRIMARY KEY values from the change passed in argument pChange
178871 ** to the SELECT statement passed as the first argument. The SELECT statement
178872 ** is as prepared by function sessionSelectStmt().
178874 ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
178875 ** error code (e.g. SQLITE_NOMEM) otherwise.
178877 static int sessionSelectBind(
178878 sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
178879 int nCol, /* Number of columns in table */
178880 u8 *abPK, /* PRIMARY KEY array */
178881 SessionChange *pChange /* Change structure */
178883 int i;
178884 int rc = SQLITE_OK;
178885 u8 *a = pChange->aRecord;
178887 for(i=0; i<nCol && rc==SQLITE_OK; i++){
178888 int eType = *a++;
178890 switch( eType ){
178891 case 0:
178892 case SQLITE_NULL:
178893 assert( abPK[i]==0 );
178894 break;
178896 case SQLITE_INTEGER: {
178897 if( abPK[i] ){
178898 i64 iVal = sessionGetI64(a);
178899 rc = sqlite3_bind_int64(pSelect, i+1, iVal);
178901 a += 8;
178902 break;
178905 case SQLITE_FLOAT: {
178906 if( abPK[i] ){
178907 double rVal;
178908 i64 iVal = sessionGetI64(a);
178909 memcpy(&rVal, &iVal, 8);
178910 rc = sqlite3_bind_double(pSelect, i+1, rVal);
178912 a += 8;
178913 break;
178916 case SQLITE_TEXT: {
178917 int n;
178918 a += sessionVarintGet(a, &n);
178919 if( abPK[i] ){
178920 rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
178922 a += n;
178923 break;
178926 default: {
178927 int n;
178928 assert( eType==SQLITE_BLOB );
178929 a += sessionVarintGet(a, &n);
178930 if( abPK[i] ){
178931 rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
178933 a += n;
178934 break;
178939 return rc;
178943 ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
178944 ** is called. Otherwise, append a serialized table header (part of the binary
178945 ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
178946 ** SQLite error code before returning.
178948 static void sessionAppendTableHdr(
178949 SessionBuffer *pBuf, /* Append header to this buffer */
178950 int bPatchset, /* Use the patchset format if true */
178951 SessionTable *pTab, /* Table object to append header for */
178952 int *pRc /* IN/OUT: Error code */
178954 /* Write a table header */
178955 sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
178956 sessionAppendVarint(pBuf, pTab->nCol, pRc);
178957 sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
178958 sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
178962 ** Generate either a changeset (if argument bPatchset is zero) or a patchset
178963 ** (if it is non-zero) based on the current contents of the session object
178964 ** passed as the first argument.
178966 ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
178967 ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
178968 ** occurs, an SQLite error code is returned and both output variables set
178969 ** to 0.
178971 static int sessionGenerateChangeset(
178972 sqlite3_session *pSession, /* Session object */
178973 int bPatchset, /* True for patchset, false for changeset */
178974 int (*xOutput)(void *pOut, const void *pData, int nData),
178975 void *pOut, /* First argument for xOutput */
178976 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
178977 void **ppChangeset /* OUT: Buffer containing changeset */
178979 sqlite3 *db = pSession->db; /* Source database handle */
178980 SessionTable *pTab; /* Used to iterate through attached tables */
178981 SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
178982 int rc; /* Return code */
178984 assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
178986 /* Zero the output variables in case an error occurs. If this session
178987 ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
178988 ** this call will be a no-op. */
178989 if( xOutput==0 ){
178990 *pnChangeset = 0;
178991 *ppChangeset = 0;
178994 if( pSession->rc ) return pSession->rc;
178995 rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
178996 if( rc!=SQLITE_OK ) return rc;
178998 sqlite3_mutex_enter(sqlite3_db_mutex(db));
179000 for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
179001 if( pTab->nEntry ){
179002 const char *zName = pTab->zName;
179003 int nCol; /* Number of columns in table */
179004 u8 *abPK; /* Primary key array */
179005 const char **azCol = 0; /* Table columns */
179006 int i; /* Used to iterate through hash buckets */
179007 sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
179008 int nRewind = buf.nBuf; /* Initial size of write buffer */
179009 int nNoop; /* Size of buffer after writing tbl header */
179011 /* Check the table schema is still Ok. */
179012 rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
179013 if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
179014 rc = SQLITE_SCHEMA;
179017 /* Write a table header */
179018 sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
179020 /* Build and compile a statement to execute: */
179021 if( rc==SQLITE_OK ){
179022 rc = sessionSelectStmt(
179023 db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
179026 nNoop = buf.nBuf;
179027 for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
179028 SessionChange *p; /* Used to iterate through changes */
179030 for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
179031 rc = sessionSelectBind(pSel, nCol, abPK, p);
179032 if( rc!=SQLITE_OK ) continue;
179033 if( sqlite3_step(pSel)==SQLITE_ROW ){
179034 if( p->op==SQLITE_INSERT ){
179035 int iCol;
179036 sessionAppendByte(&buf, SQLITE_INSERT, &rc);
179037 sessionAppendByte(&buf, p->bIndirect, &rc);
179038 for(iCol=0; iCol<nCol; iCol++){
179039 sessionAppendCol(&buf, pSel, iCol, &rc);
179041 }else{
179042 rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
179044 }else if( p->op!=SQLITE_INSERT ){
179045 rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
179047 if( rc==SQLITE_OK ){
179048 rc = sqlite3_reset(pSel);
179051 /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
179052 ** its contents to the xOutput() callback. */
179053 if( xOutput
179054 && rc==SQLITE_OK
179055 && buf.nBuf>nNoop
179056 && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
179058 rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
179059 nNoop = -1;
179060 buf.nBuf = 0;
179066 sqlite3_finalize(pSel);
179067 if( buf.nBuf==nNoop ){
179068 buf.nBuf = nRewind;
179070 sqlite3_free((char*)azCol); /* cast works around VC++ bug */
179074 if( rc==SQLITE_OK ){
179075 if( xOutput==0 ){
179076 *pnChangeset = buf.nBuf;
179077 *ppChangeset = buf.aBuf;
179078 buf.aBuf = 0;
179079 }else if( buf.nBuf>0 ){
179080 rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
179084 sqlite3_free(buf.aBuf);
179085 sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
179086 sqlite3_mutex_leave(sqlite3_db_mutex(db));
179087 return rc;
179091 ** Obtain a changeset object containing all changes recorded by the
179092 ** session object passed as the first argument.
179094 ** It is the responsibility of the caller to eventually free the buffer
179095 ** using sqlite3_free().
179097 SQLITE_API int sqlite3session_changeset(
179098 sqlite3_session *pSession, /* Session object */
179099 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
179100 void **ppChangeset /* OUT: Buffer containing changeset */
179102 return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
179106 ** Streaming version of sqlite3session_changeset().
179108 SQLITE_API int sqlite3session_changeset_strm(
179109 sqlite3_session *pSession,
179110 int (*xOutput)(void *pOut, const void *pData, int nData),
179111 void *pOut
179113 return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
179117 ** Streaming version of sqlite3session_patchset().
179119 SQLITE_API int sqlite3session_patchset_strm(
179120 sqlite3_session *pSession,
179121 int (*xOutput)(void *pOut, const void *pData, int nData),
179122 void *pOut
179124 return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
179128 ** Obtain a patchset object containing all changes recorded by the
179129 ** session object passed as the first argument.
179131 ** It is the responsibility of the caller to eventually free the buffer
179132 ** using sqlite3_free().
179134 SQLITE_API int sqlite3session_patchset(
179135 sqlite3_session *pSession, /* Session object */
179136 int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
179137 void **ppPatchset /* OUT: Buffer containing changeset */
179139 return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
179143 ** Enable or disable the session object passed as the first argument.
179145 SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
179146 int ret;
179147 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
179148 if( bEnable>=0 ){
179149 pSession->bEnable = bEnable;
179151 ret = pSession->bEnable;
179152 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
179153 return ret;
179157 ** Enable or disable the session object passed as the first argument.
179159 SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
179160 int ret;
179161 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
179162 if( bIndirect>=0 ){
179163 pSession->bIndirect = bIndirect;
179165 ret = pSession->bIndirect;
179166 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
179167 return ret;
179171 ** Return true if there have been no changes to monitored tables recorded
179172 ** by the session object passed as the only argument.
179174 SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
179175 int ret = 0;
179176 SessionTable *pTab;
179178 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
179179 for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
179180 ret = (pTab->nEntry>0);
179182 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
179184 return (ret==0);
179188 ** Do the work for either sqlite3changeset_start() or start_strm().
179190 static int sessionChangesetStart(
179191 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
179192 int (*xInput)(void *pIn, void *pData, int *pnData),
179193 void *pIn,
179194 int nChangeset, /* Size of buffer pChangeset in bytes */
179195 void *pChangeset /* Pointer to buffer containing changeset */
179197 sqlite3_changeset_iter *pRet; /* Iterator to return */
179198 int nByte; /* Number of bytes to allocate for iterator */
179200 assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
179202 /* Zero the output variable in case an error occurs. */
179203 *pp = 0;
179205 /* Allocate and initialize the iterator structure. */
179206 nByte = sizeof(sqlite3_changeset_iter);
179207 pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
179208 if( !pRet ) return SQLITE_NOMEM;
179209 memset(pRet, 0, sizeof(sqlite3_changeset_iter));
179210 pRet->in.aData = (u8 *)pChangeset;
179211 pRet->in.nData = nChangeset;
179212 pRet->in.xInput = xInput;
179213 pRet->in.pIn = pIn;
179214 pRet->in.bEof = (xInput ? 0 : 1);
179216 /* Populate the output variable and return success. */
179217 *pp = pRet;
179218 return SQLITE_OK;
179222 ** Create an iterator used to iterate through the contents of a changeset.
179224 SQLITE_API int sqlite3changeset_start(
179225 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
179226 int nChangeset, /* Size of buffer pChangeset in bytes */
179227 void *pChangeset /* Pointer to buffer containing changeset */
179229 return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
179233 ** Streaming version of sqlite3changeset_start().
179235 SQLITE_API int sqlite3changeset_start_strm(
179236 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
179237 int (*xInput)(void *pIn, void *pData, int *pnData),
179238 void *pIn
179240 return sessionChangesetStart(pp, xInput, pIn, 0, 0);
179244 ** If the SessionInput object passed as the only argument is a streaming
179245 ** object and the buffer is full, discard some data to free up space.
179247 static void sessionDiscardData(SessionInput *pIn){
179248 if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
179249 int nMove = pIn->buf.nBuf - pIn->iNext;
179250 assert( nMove>=0 );
179251 if( nMove>0 ){
179252 memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
179254 pIn->buf.nBuf -= pIn->iNext;
179255 pIn->iNext = 0;
179256 pIn->nData = pIn->buf.nBuf;
179261 ** Ensure that there are at least nByte bytes available in the buffer. Or,
179262 ** if there are not nByte bytes remaining in the input, that all available
179263 ** data is in the buffer.
179265 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
179267 static int sessionInputBuffer(SessionInput *pIn, int nByte){
179268 int rc = SQLITE_OK;
179269 if( pIn->xInput ){
179270 while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
179271 int nNew = SESSIONS_STRM_CHUNK_SIZE;
179273 if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
179274 if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
179275 rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
179276 if( nNew==0 ){
179277 pIn->bEof = 1;
179278 }else{
179279 pIn->buf.nBuf += nNew;
179283 pIn->aData = pIn->buf.aBuf;
179284 pIn->nData = pIn->buf.nBuf;
179287 return rc;
179291 ** When this function is called, *ppRec points to the start of a record
179292 ** that contains nCol values. This function advances the pointer *ppRec
179293 ** until it points to the byte immediately following that record.
179295 static void sessionSkipRecord(
179296 u8 **ppRec, /* IN/OUT: Record pointer */
179297 int nCol /* Number of values in record */
179299 u8 *aRec = *ppRec;
179300 int i;
179301 for(i=0; i<nCol; i++){
179302 int eType = *aRec++;
179303 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
179304 int nByte;
179305 aRec += sessionVarintGet((u8*)aRec, &nByte);
179306 aRec += nByte;
179307 }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
179308 aRec += 8;
179312 *ppRec = aRec;
179316 ** This function sets the value of the sqlite3_value object passed as the
179317 ** first argument to a copy of the string or blob held in the aData[]
179318 ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
179319 ** error occurs.
179321 static int sessionValueSetStr(
179322 sqlite3_value *pVal, /* Set the value of this object */
179323 u8 *aData, /* Buffer containing string or blob data */
179324 int nData, /* Size of buffer aData[] in bytes */
179325 u8 enc /* String encoding (0 for blobs) */
179327 /* In theory this code could just pass SQLITE_TRANSIENT as the final
179328 ** argument to sqlite3ValueSetStr() and have the copy created
179329 ** automatically. But doing so makes it difficult to detect any OOM
179330 ** error. Hence the code to create the copy externally. */
179331 u8 *aCopy = sqlite3_malloc(nData+1);
179332 if( aCopy==0 ) return SQLITE_NOMEM;
179333 memcpy(aCopy, aData, nData);
179334 sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
179335 return SQLITE_OK;
179339 ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
179340 ** for details.
179342 ** When this function is called, *paChange points to the start of the record
179343 ** to deserialize. Assuming no error occurs, *paChange is set to point to
179344 ** one byte after the end of the same record before this function returns.
179345 ** If the argument abPK is NULL, then the record contains nCol values. Or,
179346 ** if abPK is other than NULL, then the record contains only the PK fields
179347 ** (in other words, it is a patchset DELETE record).
179349 ** If successful, each element of the apOut[] array (allocated by the caller)
179350 ** is set to point to an sqlite3_value object containing the value read
179351 ** from the corresponding position in the record. If that value is not
179352 ** included in the record (i.e. because the record is part of an UPDATE change
179353 ** and the field was not modified), the corresponding element of apOut[] is
179354 ** set to NULL.
179356 ** It is the responsibility of the caller to free all sqlite_value structures
179357 ** using sqlite3_free().
179359 ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
179360 ** The apOut[] array may have been partially populated in this case.
179362 static int sessionReadRecord(
179363 SessionInput *pIn, /* Input data */
179364 int nCol, /* Number of values in record */
179365 u8 *abPK, /* Array of primary key flags, or NULL */
179366 sqlite3_value **apOut /* Write values to this array */
179368 int i; /* Used to iterate through columns */
179369 int rc = SQLITE_OK;
179371 for(i=0; i<nCol && rc==SQLITE_OK; i++){
179372 int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
179373 if( abPK && abPK[i]==0 ) continue;
179374 rc = sessionInputBuffer(pIn, 9);
179375 if( rc==SQLITE_OK ){
179376 eType = pIn->aData[pIn->iNext++];
179379 assert( apOut[i]==0 );
179380 if( eType ){
179381 apOut[i] = sqlite3ValueNew(0);
179382 if( !apOut[i] ) rc = SQLITE_NOMEM;
179385 if( rc==SQLITE_OK ){
179386 u8 *aVal = &pIn->aData[pIn->iNext];
179387 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
179388 int nByte;
179389 pIn->iNext += sessionVarintGet(aVal, &nByte);
179390 rc = sessionInputBuffer(pIn, nByte);
179391 if( rc==SQLITE_OK ){
179392 u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
179393 rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
179395 pIn->iNext += nByte;
179397 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
179398 sqlite3_int64 v = sessionGetI64(aVal);
179399 if( eType==SQLITE_INTEGER ){
179400 sqlite3VdbeMemSetInt64(apOut[i], v);
179401 }else{
179402 double d;
179403 memcpy(&d, &v, 8);
179404 sqlite3VdbeMemSetDouble(apOut[i], d);
179406 pIn->iNext += 8;
179411 return rc;
179415 ** The input pointer currently points to the second byte of a table-header.
179416 ** Specifically, to the following:
179418 ** + number of columns in table (varint)
179419 ** + array of PK flags (1 byte per column),
179420 ** + table name (nul terminated).
179422 ** This function ensures that all of the above is present in the input
179423 ** buffer (i.e. that it can be accessed without any calls to xInput()).
179424 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
179425 ** The input pointer is not moved.
179427 static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
179428 int rc = SQLITE_OK;
179429 int nCol = 0;
179430 int nRead = 0;
179432 rc = sessionInputBuffer(pIn, 9);
179433 if( rc==SQLITE_OK ){
179434 nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
179435 rc = sessionInputBuffer(pIn, nRead+nCol+100);
179436 nRead += nCol;
179439 while( rc==SQLITE_OK ){
179440 while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
179441 nRead++;
179443 if( (pIn->iNext + nRead)<pIn->nData ) break;
179444 rc = sessionInputBuffer(pIn, nRead + 100);
179446 *pnByte = nRead+1;
179447 return rc;
179451 ** The input pointer currently points to the first byte of the first field
179452 ** of a record consisting of nCol columns. This function ensures the entire
179453 ** record is buffered. It does not move the input pointer.
179455 ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
179456 ** the record in bytes. Otherwise, an SQLite error code is returned. The
179457 ** final value of *pnByte is undefined in this case.
179459 static int sessionChangesetBufferRecord(
179460 SessionInput *pIn, /* Input data */
179461 int nCol, /* Number of columns in record */
179462 int *pnByte /* OUT: Size of record in bytes */
179464 int rc = SQLITE_OK;
179465 int nByte = 0;
179466 int i;
179467 for(i=0; rc==SQLITE_OK && i<nCol; i++){
179468 int eType;
179469 rc = sessionInputBuffer(pIn, nByte + 10);
179470 if( rc==SQLITE_OK ){
179471 eType = pIn->aData[pIn->iNext + nByte++];
179472 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
179473 int n;
179474 nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
179475 nByte += n;
179476 rc = sessionInputBuffer(pIn, nByte);
179477 }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
179478 nByte += 8;
179482 *pnByte = nByte;
179483 return rc;
179487 ** The input pointer currently points to the second byte of a table-header.
179488 ** Specifically, to the following:
179490 ** + number of columns in table (varint)
179491 ** + array of PK flags (1 byte per column),
179492 ** + table name (nul terminated).
179494 ** This function decodes the table-header and populates the p->nCol,
179495 ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
179496 ** also allocated or resized according to the new value of p->nCol. The
179497 ** input pointer is left pointing to the byte following the table header.
179499 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
179500 ** is returned and the final values of the various fields enumerated above
179501 ** are undefined.
179503 static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
179504 int rc;
179505 int nCopy;
179506 assert( p->rc==SQLITE_OK );
179508 rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
179509 if( rc==SQLITE_OK ){
179510 int nByte;
179511 int nVarint;
179512 nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
179513 nCopy -= nVarint;
179514 p->in.iNext += nVarint;
179515 nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
179516 p->tblhdr.nBuf = 0;
179517 sessionBufferGrow(&p->tblhdr, nByte, &rc);
179520 if( rc==SQLITE_OK ){
179521 int iPK = sizeof(sqlite3_value*)*p->nCol*2;
179522 memset(p->tblhdr.aBuf, 0, iPK);
179523 memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
179524 p->in.iNext += nCopy;
179527 p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
179528 p->abPK = (u8*)&p->apValue[p->nCol*2];
179529 p->zTab = (char*)&p->abPK[p->nCol];
179530 return (p->rc = rc);
179534 ** Advance the changeset iterator to the next change.
179536 ** If both paRec and pnRec are NULL, then this function works like the public
179537 ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
179538 ** sqlite3changeset_new() and old() APIs may be used to query for values.
179540 ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
179541 ** record is written to *paRec before returning and the number of bytes in
179542 ** the record to *pnRec.
179544 ** Either way, this function returns SQLITE_ROW if the iterator is
179545 ** successfully advanced to the next change in the changeset, an SQLite
179546 ** error code if an error occurs, or SQLITE_DONE if there are no further
179547 ** changes in the changeset.
179549 static int sessionChangesetNext(
179550 sqlite3_changeset_iter *p, /* Changeset iterator */
179551 u8 **paRec, /* If non-NULL, store record pointer here */
179552 int *pnRec /* If non-NULL, store size of record here */
179554 int i;
179555 u8 op;
179557 assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
179559 /* If the iterator is in the error-state, return immediately. */
179560 if( p->rc!=SQLITE_OK ) return p->rc;
179562 /* Free the current contents of p->apValue[], if any. */
179563 if( p->apValue ){
179564 for(i=0; i<p->nCol*2; i++){
179565 sqlite3ValueFree(p->apValue[i]);
179567 memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
179570 /* Make sure the buffer contains at least 10 bytes of input data, or all
179571 ** remaining data if there are less than 10 bytes available. This is
179572 ** sufficient either for the 'T' or 'P' byte and the varint that follows
179573 ** it, or for the two single byte values otherwise. */
179574 p->rc = sessionInputBuffer(&p->in, 2);
179575 if( p->rc!=SQLITE_OK ) return p->rc;
179577 /* If the iterator is already at the end of the changeset, return DONE. */
179578 if( p->in.iNext>=p->in.nData ){
179579 return SQLITE_DONE;
179582 sessionDiscardData(&p->in);
179583 p->in.iCurrent = p->in.iNext;
179585 op = p->in.aData[p->in.iNext++];
179586 while( op=='T' || op=='P' ){
179587 p->bPatchset = (op=='P');
179588 if( sessionChangesetReadTblhdr(p) ) return p->rc;
179589 if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
179590 p->in.iCurrent = p->in.iNext;
179591 if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
179592 op = p->in.aData[p->in.iNext++];
179595 p->op = op;
179596 p->bIndirect = p->in.aData[p->in.iNext++];
179597 if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
179598 return (p->rc = SQLITE_CORRUPT_BKPT);
179601 if( paRec ){
179602 int nVal; /* Number of values to buffer */
179603 if( p->bPatchset==0 && op==SQLITE_UPDATE ){
179604 nVal = p->nCol * 2;
179605 }else if( p->bPatchset && op==SQLITE_DELETE ){
179606 nVal = 0;
179607 for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
179608 }else{
179609 nVal = p->nCol;
179611 p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
179612 if( p->rc!=SQLITE_OK ) return p->rc;
179613 *paRec = &p->in.aData[p->in.iNext];
179614 p->in.iNext += *pnRec;
179615 }else{
179617 /* If this is an UPDATE or DELETE, read the old.* record. */
179618 if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
179619 u8 *abPK = p->bPatchset ? p->abPK : 0;
179620 p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
179621 if( p->rc!=SQLITE_OK ) return p->rc;
179624 /* If this is an INSERT or UPDATE, read the new.* record. */
179625 if( p->op!=SQLITE_DELETE ){
179626 p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
179627 if( p->rc!=SQLITE_OK ) return p->rc;
179630 if( p->bPatchset && p->op==SQLITE_UPDATE ){
179631 /* If this is an UPDATE that is part of a patchset, then all PK and
179632 ** modified fields are present in the new.* record. The old.* record
179633 ** is currently completely empty. This block shifts the PK fields from
179634 ** new.* to old.*, to accommodate the code that reads these arrays. */
179635 for(i=0; i<p->nCol; i++){
179636 assert( p->apValue[i]==0 );
179637 assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
179638 if( p->abPK[i] ){
179639 p->apValue[i] = p->apValue[i+p->nCol];
179640 p->apValue[i+p->nCol] = 0;
179646 return SQLITE_ROW;
179650 ** Advance an iterator created by sqlite3changeset_start() to the next
179651 ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
179652 ** or SQLITE_CORRUPT.
179654 ** This function may not be called on iterators passed to a conflict handler
179655 ** callback by changeset_apply().
179657 SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
179658 return sessionChangesetNext(p, 0, 0);
179662 ** The following function extracts information on the current change
179663 ** from a changeset iterator. It may only be called after changeset_next()
179664 ** has returned SQLITE_ROW.
179666 SQLITE_API int sqlite3changeset_op(
179667 sqlite3_changeset_iter *pIter, /* Iterator handle */
179668 const char **pzTab, /* OUT: Pointer to table name */
179669 int *pnCol, /* OUT: Number of columns in table */
179670 int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
179671 int *pbIndirect /* OUT: True if change is indirect */
179673 *pOp = pIter->op;
179674 *pnCol = pIter->nCol;
179675 *pzTab = pIter->zTab;
179676 if( pbIndirect ) *pbIndirect = pIter->bIndirect;
179677 return SQLITE_OK;
179681 ** Return information regarding the PRIMARY KEY and number of columns in
179682 ** the database table affected by the change that pIter currently points
179683 ** to. This function may only be called after changeset_next() returns
179684 ** SQLITE_ROW.
179686 SQLITE_API int sqlite3changeset_pk(
179687 sqlite3_changeset_iter *pIter, /* Iterator object */
179688 unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
179689 int *pnCol /* OUT: Number of entries in output array */
179691 *pabPK = pIter->abPK;
179692 if( pnCol ) *pnCol = pIter->nCol;
179693 return SQLITE_OK;
179697 ** This function may only be called while the iterator is pointing to an
179698 ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
179699 ** Otherwise, SQLITE_MISUSE is returned.
179701 ** It sets *ppValue to point to an sqlite3_value structure containing the
179702 ** iVal'th value in the old.* record. Or, if that particular value is not
179703 ** included in the record (because the change is an UPDATE and the field
179704 ** was not modified and is not a PK column), set *ppValue to NULL.
179706 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
179707 ** not modified. Otherwise, SQLITE_OK.
179709 SQLITE_API int sqlite3changeset_old(
179710 sqlite3_changeset_iter *pIter, /* Changeset iterator */
179711 int iVal, /* Index of old.* value to retrieve */
179712 sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
179714 if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
179715 return SQLITE_MISUSE;
179717 if( iVal<0 || iVal>=pIter->nCol ){
179718 return SQLITE_RANGE;
179720 *ppValue = pIter->apValue[iVal];
179721 return SQLITE_OK;
179725 ** This function may only be called while the iterator is pointing to an
179726 ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
179727 ** Otherwise, SQLITE_MISUSE is returned.
179729 ** It sets *ppValue to point to an sqlite3_value structure containing the
179730 ** iVal'th value in the new.* record. Or, if that particular value is not
179731 ** included in the record (because the change is an UPDATE and the field
179732 ** was not modified), set *ppValue to NULL.
179734 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
179735 ** not modified. Otherwise, SQLITE_OK.
179737 SQLITE_API int sqlite3changeset_new(
179738 sqlite3_changeset_iter *pIter, /* Changeset iterator */
179739 int iVal, /* Index of new.* value to retrieve */
179740 sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
179742 if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
179743 return SQLITE_MISUSE;
179745 if( iVal<0 || iVal>=pIter->nCol ){
179746 return SQLITE_RANGE;
179748 *ppValue = pIter->apValue[pIter->nCol+iVal];
179749 return SQLITE_OK;
179753 ** The following two macros are used internally. They are similar to the
179754 ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
179755 ** they omit all error checking and return a pointer to the requested value.
179757 #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
179758 #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
179761 ** This function may only be called with a changeset iterator that has been
179762 ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
179763 ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
179765 ** If successful, *ppValue is set to point to an sqlite3_value structure
179766 ** containing the iVal'th value of the conflicting record.
179768 ** If value iVal is out-of-range or some other error occurs, an SQLite error
179769 ** code is returned. Otherwise, SQLITE_OK.
179771 SQLITE_API int sqlite3changeset_conflict(
179772 sqlite3_changeset_iter *pIter, /* Changeset iterator */
179773 int iVal, /* Index of conflict record value to fetch */
179774 sqlite3_value **ppValue /* OUT: Value from conflicting row */
179776 if( !pIter->pConflict ){
179777 return SQLITE_MISUSE;
179779 if( iVal<0 || iVal>=pIter->nCol ){
179780 return SQLITE_RANGE;
179782 *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
179783 return SQLITE_OK;
179787 ** This function may only be called with an iterator passed to an
179788 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
179789 ** it sets the output variable to the total number of known foreign key
179790 ** violations in the destination database and returns SQLITE_OK.
179792 ** In all other cases this function returns SQLITE_MISUSE.
179794 SQLITE_API int sqlite3changeset_fk_conflicts(
179795 sqlite3_changeset_iter *pIter, /* Changeset iterator */
179796 int *pnOut /* OUT: Number of FK violations */
179798 if( pIter->pConflict || pIter->apValue ){
179799 return SQLITE_MISUSE;
179801 *pnOut = pIter->nCol;
179802 return SQLITE_OK;
179807 ** Finalize an iterator allocated with sqlite3changeset_start().
179809 ** This function may not be called on iterators passed to a conflict handler
179810 ** callback by changeset_apply().
179812 SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
179813 int rc = SQLITE_OK;
179814 if( p ){
179815 int i; /* Used to iterate through p->apValue[] */
179816 rc = p->rc;
179817 if( p->apValue ){
179818 for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
179820 sqlite3_free(p->tblhdr.aBuf);
179821 sqlite3_free(p->in.buf.aBuf);
179822 sqlite3_free(p);
179824 return rc;
179827 static int sessionChangesetInvert(
179828 SessionInput *pInput, /* Input changeset */
179829 int (*xOutput)(void *pOut, const void *pData, int nData),
179830 void *pOut,
179831 int *pnInverted, /* OUT: Number of bytes in output changeset */
179832 void **ppInverted /* OUT: Inverse of pChangeset */
179834 int rc = SQLITE_OK; /* Return value */
179835 SessionBuffer sOut; /* Output buffer */
179836 int nCol = 0; /* Number of cols in current table */
179837 u8 *abPK = 0; /* PK array for current table */
179838 sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
179839 SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
179841 /* Initialize the output buffer */
179842 memset(&sOut, 0, sizeof(SessionBuffer));
179844 /* Zero the output variables in case an error occurs. */
179845 if( ppInverted ){
179846 *ppInverted = 0;
179847 *pnInverted = 0;
179850 while( 1 ){
179851 u8 eType;
179853 /* Test for EOF. */
179854 if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
179855 if( pInput->iNext>=pInput->nData ) break;
179856 eType = pInput->aData[pInput->iNext];
179858 switch( eType ){
179859 case 'T': {
179860 /* A 'table' record consists of:
179862 ** * A constant 'T' character,
179863 ** * Number of columns in said table (a varint),
179864 ** * An array of nCol bytes (sPK),
179865 ** * A nul-terminated table name.
179867 int nByte;
179868 int nVar;
179869 pInput->iNext++;
179870 if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
179871 goto finished_invert;
179873 nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
179874 sPK.nBuf = 0;
179875 sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
179876 sessionAppendByte(&sOut, eType, &rc);
179877 sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
179878 if( rc ) goto finished_invert;
179880 pInput->iNext += nByte;
179881 sqlite3_free(apVal);
179882 apVal = 0;
179883 abPK = sPK.aBuf;
179884 break;
179887 case SQLITE_INSERT:
179888 case SQLITE_DELETE: {
179889 int nByte;
179890 int bIndirect = pInput->aData[pInput->iNext+1];
179891 int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
179892 pInput->iNext += 2;
179893 assert( rc==SQLITE_OK );
179894 rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
179895 sessionAppendByte(&sOut, eType2, &rc);
179896 sessionAppendByte(&sOut, bIndirect, &rc);
179897 sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
179898 pInput->iNext += nByte;
179899 if( rc ) goto finished_invert;
179900 break;
179903 case SQLITE_UPDATE: {
179904 int iCol;
179906 if( 0==apVal ){
179907 apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
179908 if( 0==apVal ){
179909 rc = SQLITE_NOMEM;
179910 goto finished_invert;
179912 memset(apVal, 0, sizeof(apVal[0])*nCol*2);
179915 /* Write the header for the new UPDATE change. Same as the original. */
179916 sessionAppendByte(&sOut, eType, &rc);
179917 sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
179919 /* Read the old.* and new.* records for the update change. */
179920 pInput->iNext += 2;
179921 rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
179922 if( rc==SQLITE_OK ){
179923 rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
179926 /* Write the new old.* record. Consists of the PK columns from the
179927 ** original old.* record, and the other values from the original
179928 ** new.* record. */
179929 for(iCol=0; iCol<nCol; iCol++){
179930 sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
179931 sessionAppendValue(&sOut, pVal, &rc);
179934 /* Write the new new.* record. Consists of a copy of all values
179935 ** from the original old.* record, except for the PK columns, which
179936 ** are set to "undefined". */
179937 for(iCol=0; iCol<nCol; iCol++){
179938 sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
179939 sessionAppendValue(&sOut, pVal, &rc);
179942 for(iCol=0; iCol<nCol*2; iCol++){
179943 sqlite3ValueFree(apVal[iCol]);
179945 memset(apVal, 0, sizeof(apVal[0])*nCol*2);
179946 if( rc!=SQLITE_OK ){
179947 goto finished_invert;
179950 break;
179953 default:
179954 rc = SQLITE_CORRUPT_BKPT;
179955 goto finished_invert;
179958 assert( rc==SQLITE_OK );
179959 if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
179960 rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
179961 sOut.nBuf = 0;
179962 if( rc!=SQLITE_OK ) goto finished_invert;
179966 assert( rc==SQLITE_OK );
179967 if( pnInverted ){
179968 *pnInverted = sOut.nBuf;
179969 *ppInverted = sOut.aBuf;
179970 sOut.aBuf = 0;
179971 }else if( sOut.nBuf>0 ){
179972 rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
179975 finished_invert:
179976 sqlite3_free(sOut.aBuf);
179977 sqlite3_free(apVal);
179978 sqlite3_free(sPK.aBuf);
179979 return rc;
179984 ** Invert a changeset object.
179986 SQLITE_API int sqlite3changeset_invert(
179987 int nChangeset, /* Number of bytes in input */
179988 const void *pChangeset, /* Input changeset */
179989 int *pnInverted, /* OUT: Number of bytes in output changeset */
179990 void **ppInverted /* OUT: Inverse of pChangeset */
179992 SessionInput sInput;
179994 /* Set up the input stream */
179995 memset(&sInput, 0, sizeof(SessionInput));
179996 sInput.nData = nChangeset;
179997 sInput.aData = (u8*)pChangeset;
179999 return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
180003 ** Streaming version of sqlite3changeset_invert().
180005 SQLITE_API int sqlite3changeset_invert_strm(
180006 int (*xInput)(void *pIn, void *pData, int *pnData),
180007 void *pIn,
180008 int (*xOutput)(void *pOut, const void *pData, int nData),
180009 void *pOut
180011 SessionInput sInput;
180012 int rc;
180014 /* Set up the input stream */
180015 memset(&sInput, 0, sizeof(SessionInput));
180016 sInput.xInput = xInput;
180017 sInput.pIn = pIn;
180019 rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
180020 sqlite3_free(sInput.buf.aBuf);
180021 return rc;
180024 typedef struct SessionApplyCtx SessionApplyCtx;
180025 struct SessionApplyCtx {
180026 sqlite3 *db;
180027 sqlite3_stmt *pDelete; /* DELETE statement */
180028 sqlite3_stmt *pUpdate; /* UPDATE statement */
180029 sqlite3_stmt *pInsert; /* INSERT statement */
180030 sqlite3_stmt *pSelect; /* SELECT statement */
180031 int nCol; /* Size of azCol[] and abPK[] arrays */
180032 const char **azCol; /* Array of column names */
180033 u8 *abPK; /* Boolean array - true if column is in PK */
180035 int bDeferConstraints; /* True to defer constraints */
180036 SessionBuffer constraints; /* Deferred constraints are stored here */
180040 ** Formulate a statement to DELETE a row from database db. Assuming a table
180041 ** structure like this:
180043 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
180045 ** The DELETE statement looks like this:
180047 ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
180049 ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
180050 ** matching b and d values, or 1 otherwise. The second case comes up if the
180051 ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
180053 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
180054 ** pointing to the prepared version of the SQL statement.
180056 static int sessionDeleteRow(
180057 sqlite3 *db, /* Database handle */
180058 const char *zTab, /* Table name */
180059 SessionApplyCtx *p /* Session changeset-apply context */
180061 int i;
180062 const char *zSep = "";
180063 int rc = SQLITE_OK;
180064 SessionBuffer buf = {0, 0, 0};
180065 int nPk = 0;
180067 sessionAppendStr(&buf, "DELETE FROM ", &rc);
180068 sessionAppendIdent(&buf, zTab, &rc);
180069 sessionAppendStr(&buf, " WHERE ", &rc);
180071 for(i=0; i<p->nCol; i++){
180072 if( p->abPK[i] ){
180073 nPk++;
180074 sessionAppendStr(&buf, zSep, &rc);
180075 sessionAppendIdent(&buf, p->azCol[i], &rc);
180076 sessionAppendStr(&buf, " = ?", &rc);
180077 sessionAppendInteger(&buf, i+1, &rc);
180078 zSep = " AND ";
180082 if( nPk<p->nCol ){
180083 sessionAppendStr(&buf, " AND (?", &rc);
180084 sessionAppendInteger(&buf, p->nCol+1, &rc);
180085 sessionAppendStr(&buf, " OR ", &rc);
180087 zSep = "";
180088 for(i=0; i<p->nCol; i++){
180089 if( !p->abPK[i] ){
180090 sessionAppendStr(&buf, zSep, &rc);
180091 sessionAppendIdent(&buf, p->azCol[i], &rc);
180092 sessionAppendStr(&buf, " IS ?", &rc);
180093 sessionAppendInteger(&buf, i+1, &rc);
180094 zSep = "AND ";
180097 sessionAppendStr(&buf, ")", &rc);
180100 if( rc==SQLITE_OK ){
180101 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
180103 sqlite3_free(buf.aBuf);
180105 return rc;
180109 ** Formulate and prepare a statement to UPDATE a row from database db.
180110 ** Assuming a table structure like this:
180112 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
180114 ** The UPDATE statement looks like this:
180116 ** UPDATE x SET
180117 ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
180118 ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
180119 ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
180120 ** d = CASE WHEN ?11 THEN ?12 ELSE d END
180121 ** WHERE a = ?1 AND c = ?7 AND (?13 OR
180122 ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
180125 ** For each column in the table, there are three variables to bind:
180127 ** ?(i*3+1) The old.* value of the column, if any.
180128 ** ?(i*3+2) A boolean flag indicating that the value is being modified.
180129 ** ?(i*3+3) The new.* value of the column, if any.
180131 ** Also, a boolean flag that, if set to true, causes the statement to update
180132 ** a row even if the non-PK values do not match. This is required if the
180133 ** conflict-handler is invoked with CHANGESET_DATA and returns
180134 ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
180136 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
180137 ** pointing to the prepared version of the SQL statement.
180139 static int sessionUpdateRow(
180140 sqlite3 *db, /* Database handle */
180141 const char *zTab, /* Table name */
180142 SessionApplyCtx *p /* Session changeset-apply context */
180144 int rc = SQLITE_OK;
180145 int i;
180146 const char *zSep = "";
180147 SessionBuffer buf = {0, 0, 0};
180149 /* Append "UPDATE tbl SET " */
180150 sessionAppendStr(&buf, "UPDATE ", &rc);
180151 sessionAppendIdent(&buf, zTab, &rc);
180152 sessionAppendStr(&buf, " SET ", &rc);
180154 /* Append the assignments */
180155 for(i=0; i<p->nCol; i++){
180156 sessionAppendStr(&buf, zSep, &rc);
180157 sessionAppendIdent(&buf, p->azCol[i], &rc);
180158 sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
180159 sessionAppendInteger(&buf, i*3+2, &rc);
180160 sessionAppendStr(&buf, " THEN ?", &rc);
180161 sessionAppendInteger(&buf, i*3+3, &rc);
180162 sessionAppendStr(&buf, " ELSE ", &rc);
180163 sessionAppendIdent(&buf, p->azCol[i], &rc);
180164 sessionAppendStr(&buf, " END", &rc);
180165 zSep = ", ";
180168 /* Append the PK part of the WHERE clause */
180169 sessionAppendStr(&buf, " WHERE ", &rc);
180170 for(i=0; i<p->nCol; i++){
180171 if( p->abPK[i] ){
180172 sessionAppendIdent(&buf, p->azCol[i], &rc);
180173 sessionAppendStr(&buf, " = ?", &rc);
180174 sessionAppendInteger(&buf, i*3+1, &rc);
180175 sessionAppendStr(&buf, " AND ", &rc);
180179 /* Append the non-PK part of the WHERE clause */
180180 sessionAppendStr(&buf, " (?", &rc);
180181 sessionAppendInteger(&buf, p->nCol*3+1, &rc);
180182 sessionAppendStr(&buf, " OR 1", &rc);
180183 for(i=0; i<p->nCol; i++){
180184 if( !p->abPK[i] ){
180185 sessionAppendStr(&buf, " AND (?", &rc);
180186 sessionAppendInteger(&buf, i*3+2, &rc);
180187 sessionAppendStr(&buf, "=0 OR ", &rc);
180188 sessionAppendIdent(&buf, p->azCol[i], &rc);
180189 sessionAppendStr(&buf, " IS ?", &rc);
180190 sessionAppendInteger(&buf, i*3+1, &rc);
180191 sessionAppendStr(&buf, ")", &rc);
180194 sessionAppendStr(&buf, ")", &rc);
180196 if( rc==SQLITE_OK ){
180197 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
180199 sqlite3_free(buf.aBuf);
180201 return rc;
180205 ** Formulate and prepare an SQL statement to query table zTab by primary
180206 ** key. Assuming the following table structure:
180208 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
180210 ** The SELECT statement looks like this:
180212 ** SELECT * FROM x WHERE a = ?1 AND c = ?3
180214 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
180215 ** pointing to the prepared version of the SQL statement.
180217 static int sessionSelectRow(
180218 sqlite3 *db, /* Database handle */
180219 const char *zTab, /* Table name */
180220 SessionApplyCtx *p /* Session changeset-apply context */
180222 return sessionSelectStmt(
180223 db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
180227 ** Formulate and prepare an INSERT statement to add a record to table zTab.
180228 ** For example:
180230 ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
180232 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
180233 ** pointing to the prepared version of the SQL statement.
180235 static int sessionInsertRow(
180236 sqlite3 *db, /* Database handle */
180237 const char *zTab, /* Table name */
180238 SessionApplyCtx *p /* Session changeset-apply context */
180240 int rc = SQLITE_OK;
180241 int i;
180242 SessionBuffer buf = {0, 0, 0};
180244 sessionAppendStr(&buf, "INSERT INTO main.", &rc);
180245 sessionAppendIdent(&buf, zTab, &rc);
180246 sessionAppendStr(&buf, "(", &rc);
180247 for(i=0; i<p->nCol; i++){
180248 if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
180249 sessionAppendIdent(&buf, p->azCol[i], &rc);
180252 sessionAppendStr(&buf, ") VALUES(?", &rc);
180253 for(i=1; i<p->nCol; i++){
180254 sessionAppendStr(&buf, ", ?", &rc);
180256 sessionAppendStr(&buf, ")", &rc);
180258 if( rc==SQLITE_OK ){
180259 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
180261 sqlite3_free(buf.aBuf);
180262 return rc;
180266 ** A wrapper around sqlite3_bind_value() that detects an extra problem.
180267 ** See comments in the body of this function for details.
180269 static int sessionBindValue(
180270 sqlite3_stmt *pStmt, /* Statement to bind value to */
180271 int i, /* Parameter number to bind to */
180272 sqlite3_value *pVal /* Value to bind */
180274 int eType = sqlite3_value_type(pVal);
180275 /* COVERAGE: The (pVal->z==0) branch is never true using current versions
180276 ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
180277 ** the (pVal->z) variable remains as it was or the type of the value is
180278 ** set to SQLITE_NULL. */
180279 if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
180280 /* This condition occurs when an earlier OOM in a call to
180281 ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
180282 ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
180283 return SQLITE_NOMEM;
180285 return sqlite3_bind_value(pStmt, i, pVal);
180289 ** Iterator pIter must point to an SQLITE_INSERT entry. This function
180290 ** transfers new.* values from the current iterator entry to statement
180291 ** pStmt. The table being inserted into has nCol columns.
180293 ** New.* value $i from the iterator is bound to variable ($i+1) of
180294 ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
180295 ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
180296 ** to an array nCol elements in size. In this case only those values for
180297 ** which abPK[$i] is true are read from the iterator and bound to the
180298 ** statement.
180300 ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
180302 static int sessionBindRow(
180303 sqlite3_changeset_iter *pIter, /* Iterator to read values from */
180304 int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
180305 int nCol, /* Number of columns */
180306 u8 *abPK, /* If not NULL, bind only if true */
180307 sqlite3_stmt *pStmt /* Bind values to this statement */
180309 int i;
180310 int rc = SQLITE_OK;
180312 /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
180313 ** argument iterator points to a suitable entry. Make sure that xValue
180314 ** is one of these to guarantee that it is safe to ignore the return
180315 ** in the code below. */
180316 assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
180318 for(i=0; rc==SQLITE_OK && i<nCol; i++){
180319 if( !abPK || abPK[i] ){
180320 sqlite3_value *pVal;
180321 (void)xValue(pIter, i, &pVal);
180322 rc = sessionBindValue(pStmt, i+1, pVal);
180325 return rc;
180329 ** SQL statement pSelect is as generated by the sessionSelectRow() function.
180330 ** This function binds the primary key values from the change that changeset
180331 ** iterator pIter points to to the SELECT and attempts to seek to the table
180332 ** entry. If a row is found, the SELECT statement left pointing at the row
180333 ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
180334 ** has occured, the statement is reset and SQLITE_OK is returned. If an
180335 ** error occurs, the statement is reset and an SQLite error code is returned.
180337 ** If this function returns SQLITE_ROW, the caller must eventually reset()
180338 ** statement pSelect. If any other value is returned, the statement does
180339 ** not require a reset().
180341 ** If the iterator currently points to an INSERT record, bind values from the
180342 ** new.* record to the SELECT statement. Or, if it points to a DELETE or
180343 ** UPDATE, bind values from the old.* record.
180345 static int sessionSeekToRow(
180346 sqlite3 *db, /* Database handle */
180347 sqlite3_changeset_iter *pIter, /* Changeset iterator */
180348 u8 *abPK, /* Primary key flags array */
180349 sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
180351 int rc; /* Return code */
180352 int nCol; /* Number of columns in table */
180353 int op; /* Changset operation (SQLITE_UPDATE etc.) */
180354 const char *zDummy; /* Unused */
180356 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
180357 rc = sessionBindRow(pIter,
180358 op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
180359 nCol, abPK, pSelect
180362 if( rc==SQLITE_OK ){
180363 rc = sqlite3_step(pSelect);
180364 if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
180367 return rc;
180371 ** Invoke the conflict handler for the change that the changeset iterator
180372 ** currently points to.
180374 ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
180375 ** If argument pbReplace is NULL, then the type of conflict handler invoked
180376 ** depends solely on eType, as follows:
180378 ** eType value Value passed to xConflict
180379 ** -------------------------------------------------
180380 ** CHANGESET_DATA CHANGESET_NOTFOUND
180381 ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
180383 ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
180384 ** record with the same primary key as the record about to be deleted, updated
180385 ** or inserted. If such a record can be found, it is available to the conflict
180386 ** handler as the "conflicting" record. In this case the type of conflict
180387 ** handler invoked is as follows:
180389 ** eType value PK Record found? Value passed to xConflict
180390 ** ----------------------------------------------------------------
180391 ** CHANGESET_DATA Yes CHANGESET_DATA
180392 ** CHANGESET_DATA No CHANGESET_NOTFOUND
180393 ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
180394 ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
180396 ** If pbReplace is not NULL, and a record with a matching PK is found, and
180397 ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
180398 ** is set to non-zero before returning SQLITE_OK.
180400 ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
180401 ** returned. Or, if the conflict handler returns an invalid value,
180402 ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
180403 ** this function returns SQLITE_OK.
180405 static int sessionConflictHandler(
180406 int eType, /* Either CHANGESET_DATA or CONFLICT */
180407 SessionApplyCtx *p, /* changeset_apply() context */
180408 sqlite3_changeset_iter *pIter, /* Changeset iterator */
180409 int(*xConflict)(void *, int, sqlite3_changeset_iter*),
180410 void *pCtx, /* First argument for conflict handler */
180411 int *pbReplace /* OUT: Set to true if PK row is found */
180413 int res = 0; /* Value returned by conflict handler */
180414 int rc;
180415 int nCol;
180416 int op;
180417 const char *zDummy;
180419 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
180421 assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
180422 assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
180423 assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
180425 /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
180426 if( pbReplace ){
180427 rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
180428 }else{
180429 rc = SQLITE_OK;
180432 if( rc==SQLITE_ROW ){
180433 /* There exists another row with the new.* primary key. */
180434 pIter->pConflict = p->pSelect;
180435 res = xConflict(pCtx, eType, pIter);
180436 pIter->pConflict = 0;
180437 rc = sqlite3_reset(p->pSelect);
180438 }else if( rc==SQLITE_OK ){
180439 if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
180440 /* Instead of invoking the conflict handler, append the change blob
180441 ** to the SessionApplyCtx.constraints buffer. */
180442 u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
180443 int nBlob = pIter->in.iNext - pIter->in.iCurrent;
180444 sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
180445 res = SQLITE_CHANGESET_OMIT;
180446 }else{
180447 /* No other row with the new.* primary key. */
180448 res = xConflict(pCtx, eType+1, pIter);
180449 if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
180453 if( rc==SQLITE_OK ){
180454 switch( res ){
180455 case SQLITE_CHANGESET_REPLACE:
180456 assert( pbReplace );
180457 *pbReplace = 1;
180458 break;
180460 case SQLITE_CHANGESET_OMIT:
180461 break;
180463 case SQLITE_CHANGESET_ABORT:
180464 rc = SQLITE_ABORT;
180465 break;
180467 default:
180468 rc = SQLITE_MISUSE;
180469 break;
180473 return rc;
180477 ** Attempt to apply the change that the iterator passed as the first argument
180478 ** currently points to to the database. If a conflict is encountered, invoke
180479 ** the conflict handler callback.
180481 ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
180482 ** one is encountered, update or delete the row with the matching primary key
180483 ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
180484 ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
180485 ** to true before returning. In this case the caller will invoke this function
180486 ** again, this time with pbRetry set to NULL.
180488 ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
180489 ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
180490 ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
180491 ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
180492 ** before retrying. In this case the caller attempts to remove the conflicting
180493 ** row before invoking this function again, this time with pbReplace set
180494 ** to NULL.
180496 ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
180497 ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
180498 ** returned.
180500 static int sessionApplyOneOp(
180501 sqlite3_changeset_iter *pIter, /* Changeset iterator */
180502 SessionApplyCtx *p, /* changeset_apply() context */
180503 int(*xConflict)(void *, int, sqlite3_changeset_iter *),
180504 void *pCtx, /* First argument for the conflict handler */
180505 int *pbReplace, /* OUT: True to remove PK row and retry */
180506 int *pbRetry /* OUT: True to retry. */
180508 const char *zDummy;
180509 int op;
180510 int nCol;
180511 int rc = SQLITE_OK;
180513 assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
180514 assert( p->azCol && p->abPK );
180515 assert( !pbReplace || *pbReplace==0 );
180517 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
180519 if( op==SQLITE_DELETE ){
180521 /* Bind values to the DELETE statement. If conflict handling is required,
180522 ** bind values for all columns and set bound variable (nCol+1) to true.
180523 ** Or, if conflict handling is not required, bind just the PK column
180524 ** values and, if it exists, set (nCol+1) to false. Conflict handling
180525 ** is not required if:
180527 ** * this is a patchset, or
180528 ** * (pbRetry==0), or
180529 ** * all columns of the table are PK columns (in this case there is
180530 ** no (nCol+1) variable to bind to).
180532 u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
180533 rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
180534 if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
180535 rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
180537 if( rc!=SQLITE_OK ) return rc;
180539 sqlite3_step(p->pDelete);
180540 rc = sqlite3_reset(p->pDelete);
180541 if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
180542 rc = sessionConflictHandler(
180543 SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
180545 }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
180546 rc = sessionConflictHandler(
180547 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
180551 }else if( op==SQLITE_UPDATE ){
180552 int i;
180554 /* Bind values to the UPDATE statement. */
180555 for(i=0; rc==SQLITE_OK && i<nCol; i++){
180556 sqlite3_value *pOld = sessionChangesetOld(pIter, i);
180557 sqlite3_value *pNew = sessionChangesetNew(pIter, i);
180559 sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
180560 if( pOld ){
180561 rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
180563 if( rc==SQLITE_OK && pNew ){
180564 rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
180567 if( rc==SQLITE_OK ){
180568 sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
180570 if( rc!=SQLITE_OK ) return rc;
180572 /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
180573 ** the result will be SQLITE_OK with 0 rows modified. */
180574 sqlite3_step(p->pUpdate);
180575 rc = sqlite3_reset(p->pUpdate);
180577 if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
180578 /* A NOTFOUND or DATA error. Search the table to see if it contains
180579 ** a row with a matching primary key. If so, this is a DATA conflict.
180580 ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
180582 rc = sessionConflictHandler(
180583 SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
180586 }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
180587 /* This is always a CONSTRAINT conflict. */
180588 rc = sessionConflictHandler(
180589 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
180593 }else{
180594 assert( op==SQLITE_INSERT );
180595 rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
180596 if( rc!=SQLITE_OK ) return rc;
180598 sqlite3_step(p->pInsert);
180599 rc = sqlite3_reset(p->pInsert);
180600 if( (rc&0xff)==SQLITE_CONSTRAINT ){
180601 rc = sessionConflictHandler(
180602 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
180607 return rc;
180611 ** Attempt to apply the change that the iterator passed as the first argument
180612 ** currently points to to the database. If a conflict is encountered, invoke
180613 ** the conflict handler callback.
180615 ** The difference between this function and sessionApplyOne() is that this
180616 ** function handles the case where the conflict-handler is invoked and
180617 ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
180618 ** retried in some manner.
180620 static int sessionApplyOneWithRetry(
180621 sqlite3 *db, /* Apply change to "main" db of this handle */
180622 sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
180623 SessionApplyCtx *pApply, /* Apply context */
180624 int(*xConflict)(void*, int, sqlite3_changeset_iter*),
180625 void *pCtx /* First argument passed to xConflict */
180627 int bReplace = 0;
180628 int bRetry = 0;
180629 int rc;
180631 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
180632 assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
180634 /* If the bRetry flag is set, the change has not been applied due to an
180635 ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
180636 ** a row with the correct PK is present in the db, but one or more other
180637 ** fields do not contain the expected values) and the conflict handler
180638 ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
180639 ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
180640 ** the SQLITE_CHANGESET_DATA problem. */
180641 if( bRetry ){
180642 assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
180643 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
180646 /* If the bReplace flag is set, the change is an INSERT that has not
180647 ** been performed because the database already contains a row with the
180648 ** specified primary key and the conflict handler returned
180649 ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
180650 ** before reattempting the INSERT. */
180651 else if( bReplace ){
180652 assert( pIter->op==SQLITE_INSERT );
180653 rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
180654 if( rc==SQLITE_OK ){
180655 rc = sessionBindRow(pIter,
180656 sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
180657 sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
180659 if( rc==SQLITE_OK ){
180660 sqlite3_step(pApply->pDelete);
180661 rc = sqlite3_reset(pApply->pDelete);
180663 if( rc==SQLITE_OK ){
180664 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
180666 if( rc==SQLITE_OK ){
180667 rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
180671 return rc;
180675 ** Retry the changes accumulated in the pApply->constraints buffer.
180677 static int sessionRetryConstraints(
180678 sqlite3 *db,
180679 int bPatchset,
180680 const char *zTab,
180681 SessionApplyCtx *pApply,
180682 int(*xConflict)(void*, int, sqlite3_changeset_iter*),
180683 void *pCtx /* First argument passed to xConflict */
180685 int rc = SQLITE_OK;
180687 while( pApply->constraints.nBuf ){
180688 sqlite3_changeset_iter *pIter2 = 0;
180689 SessionBuffer cons = pApply->constraints;
180690 memset(&pApply->constraints, 0, sizeof(SessionBuffer));
180692 rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
180693 if( rc==SQLITE_OK ){
180694 int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
180695 int rc2;
180696 pIter2->bPatchset = bPatchset;
180697 pIter2->zTab = (char*)zTab;
180698 pIter2->nCol = pApply->nCol;
180699 pIter2->abPK = pApply->abPK;
180700 sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
180701 pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
180702 if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
180704 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
180705 rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
180708 rc2 = sqlite3changeset_finalize(pIter2);
180709 if( rc==SQLITE_OK ) rc = rc2;
180711 assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
180713 sqlite3_free(cons.aBuf);
180714 if( rc!=SQLITE_OK ) break;
180715 if( pApply->constraints.nBuf>=cons.nBuf ){
180716 /* No progress was made on the last round. */
180717 pApply->bDeferConstraints = 0;
180721 return rc;
180725 ** Argument pIter is a changeset iterator that has been initialized, but
180726 ** not yet passed to sqlite3changeset_next(). This function applies the
180727 ** changeset to the main database attached to handle "db". The supplied
180728 ** conflict handler callback is invoked to resolve any conflicts encountered
180729 ** while applying the change.
180731 static int sessionChangesetApply(
180732 sqlite3 *db, /* Apply change to "main" db of this handle */
180733 sqlite3_changeset_iter *pIter, /* Changeset to apply */
180734 int(*xFilter)(
180735 void *pCtx, /* Copy of sixth arg to _apply() */
180736 const char *zTab /* Table name */
180738 int(*xConflict)(
180739 void *pCtx, /* Copy of fifth arg to _apply() */
180740 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
180741 sqlite3_changeset_iter *p /* Handle describing change and conflict */
180743 void *pCtx /* First argument passed to xConflict */
180745 int schemaMismatch = 0;
180746 int rc; /* Return code */
180747 const char *zTab = 0; /* Name of current table */
180748 int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
180749 SessionApplyCtx sApply; /* changeset_apply() context object */
180750 int bPatchset;
180752 assert( xConflict!=0 );
180754 pIter->in.bNoDiscard = 1;
180755 memset(&sApply, 0, sizeof(sApply));
180756 sqlite3_mutex_enter(sqlite3_db_mutex(db));
180757 rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
180758 if( rc==SQLITE_OK ){
180759 rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
180761 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
180762 int nCol;
180763 int op;
180764 const char *zNew;
180766 sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
180768 if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
180769 u8 *abPK;
180771 rc = sessionRetryConstraints(
180772 db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
180774 if( rc!=SQLITE_OK ) break;
180776 sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
180777 sqlite3_finalize(sApply.pDelete);
180778 sqlite3_finalize(sApply.pUpdate);
180779 sqlite3_finalize(sApply.pInsert);
180780 sqlite3_finalize(sApply.pSelect);
180781 memset(&sApply, 0, sizeof(sApply));
180782 sApply.db = db;
180783 sApply.bDeferConstraints = 1;
180785 /* If an xFilter() callback was specified, invoke it now. If the
180786 ** xFilter callback returns zero, skip this table. If it returns
180787 ** non-zero, proceed. */
180788 schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
180789 if( schemaMismatch ){
180790 zTab = sqlite3_mprintf("%s", zNew);
180791 if( zTab==0 ){
180792 rc = SQLITE_NOMEM;
180793 break;
180795 nTab = (int)strlen(zTab);
180796 sApply.azCol = (const char **)zTab;
180797 }else{
180798 int nMinCol = 0;
180799 int i;
180801 sqlite3changeset_pk(pIter, &abPK, 0);
180802 rc = sessionTableInfo(
180803 db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
180805 if( rc!=SQLITE_OK ) break;
180806 for(i=0; i<sApply.nCol; i++){
180807 if( sApply.abPK[i] ) nMinCol = i+1;
180810 if( sApply.nCol==0 ){
180811 schemaMismatch = 1;
180812 sqlite3_log(SQLITE_SCHEMA,
180813 "sqlite3changeset_apply(): no such table: %s", zTab
180816 else if( sApply.nCol<nCol ){
180817 schemaMismatch = 1;
180818 sqlite3_log(SQLITE_SCHEMA,
180819 "sqlite3changeset_apply(): table %s has %d columns, "
180820 "expected %d or more",
180821 zTab, sApply.nCol, nCol
180824 else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
180825 schemaMismatch = 1;
180826 sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
180827 "primary key mismatch for table %s", zTab
180830 else{
180831 sApply.nCol = nCol;
180832 if((rc = sessionSelectRow(db, zTab, &sApply))
180833 || (rc = sessionUpdateRow(db, zTab, &sApply))
180834 || (rc = sessionDeleteRow(db, zTab, &sApply))
180835 || (rc = sessionInsertRow(db, zTab, &sApply))
180837 break;
180840 nTab = sqlite3Strlen30(zTab);
180844 /* If there is a schema mismatch on the current table, proceed to the
180845 ** next change. A log message has already been issued. */
180846 if( schemaMismatch ) continue;
180848 rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
180851 bPatchset = pIter->bPatchset;
180852 if( rc==SQLITE_OK ){
180853 rc = sqlite3changeset_finalize(pIter);
180854 }else{
180855 sqlite3changeset_finalize(pIter);
180858 if( rc==SQLITE_OK ){
180859 rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
180862 if( rc==SQLITE_OK ){
180863 int nFk, notUsed;
180864 sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
180865 if( nFk!=0 ){
180866 int res = SQLITE_CHANGESET_ABORT;
180867 sqlite3_changeset_iter sIter;
180868 memset(&sIter, 0, sizeof(sIter));
180869 sIter.nCol = nFk;
180870 res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
180871 if( res!=SQLITE_CHANGESET_OMIT ){
180872 rc = SQLITE_CONSTRAINT;
180876 sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
180878 if( rc==SQLITE_OK ){
180879 rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
180880 }else{
180881 sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
180882 sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
180885 sqlite3_finalize(sApply.pInsert);
180886 sqlite3_finalize(sApply.pDelete);
180887 sqlite3_finalize(sApply.pUpdate);
180888 sqlite3_finalize(sApply.pSelect);
180889 sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
180890 sqlite3_free((char*)sApply.constraints.aBuf);
180891 sqlite3_mutex_leave(sqlite3_db_mutex(db));
180892 return rc;
180896 ** Apply the changeset passed via pChangeset/nChangeset to the main database
180897 ** attached to handle "db". Invoke the supplied conflict handler callback
180898 ** to resolve any conflicts encountered while applying the change.
180900 SQLITE_API int sqlite3changeset_apply(
180901 sqlite3 *db, /* Apply change to "main" db of this handle */
180902 int nChangeset, /* Size of changeset in bytes */
180903 void *pChangeset, /* Changeset blob */
180904 int(*xFilter)(
180905 void *pCtx, /* Copy of sixth arg to _apply() */
180906 const char *zTab /* Table name */
180908 int(*xConflict)(
180909 void *pCtx, /* Copy of fifth arg to _apply() */
180910 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
180911 sqlite3_changeset_iter *p /* Handle describing change and conflict */
180913 void *pCtx /* First argument passed to xConflict */
180915 sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
180916 int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
180917 if( rc==SQLITE_OK ){
180918 rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
180920 return rc;
180924 ** Apply the changeset passed via xInput/pIn to the main database
180925 ** attached to handle "db". Invoke the supplied conflict handler callback
180926 ** to resolve any conflicts encountered while applying the change.
180928 SQLITE_API int sqlite3changeset_apply_strm(
180929 sqlite3 *db, /* Apply change to "main" db of this handle */
180930 int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
180931 void *pIn, /* First arg for xInput */
180932 int(*xFilter)(
180933 void *pCtx, /* Copy of sixth arg to _apply() */
180934 const char *zTab /* Table name */
180936 int(*xConflict)(
180937 void *pCtx, /* Copy of sixth arg to _apply() */
180938 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
180939 sqlite3_changeset_iter *p /* Handle describing change and conflict */
180941 void *pCtx /* First argument passed to xConflict */
180943 sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
180944 int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
180945 if( rc==SQLITE_OK ){
180946 rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
180948 return rc;
180952 ** sqlite3_changegroup handle.
180954 struct sqlite3_changegroup {
180955 int rc; /* Error code */
180956 int bPatch; /* True to accumulate patchsets */
180957 SessionTable *pList; /* List of tables in current patch */
180961 ** This function is called to merge two changes to the same row together as
180962 ** part of an sqlite3changeset_concat() operation. A new change object is
180963 ** allocated and a pointer to it stored in *ppNew.
180965 static int sessionChangeMerge(
180966 SessionTable *pTab, /* Table structure */
180967 int bPatchset, /* True for patchsets */
180968 SessionChange *pExist, /* Existing change */
180969 int op2, /* Second change operation */
180970 int bIndirect, /* True if second change is indirect */
180971 u8 *aRec, /* Second change record */
180972 int nRec, /* Number of bytes in aRec */
180973 SessionChange **ppNew /* OUT: Merged change */
180975 SessionChange *pNew = 0;
180977 if( !pExist ){
180978 pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
180979 if( !pNew ){
180980 return SQLITE_NOMEM;
180982 memset(pNew, 0, sizeof(SessionChange));
180983 pNew->op = op2;
180984 pNew->bIndirect = bIndirect;
180985 pNew->nRecord = nRec;
180986 pNew->aRecord = (u8*)&pNew[1];
180987 memcpy(pNew->aRecord, aRec, nRec);
180988 }else{
180989 int op1 = pExist->op;
180992 ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
180993 ** op1=INSERT, op2=UPDATE -> INSERT.
180994 ** op1=INSERT, op2=DELETE -> (none)
180996 ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
180997 ** op1=UPDATE, op2=UPDATE -> UPDATE.
180998 ** op1=UPDATE, op2=DELETE -> DELETE.
181000 ** op1=DELETE, op2=INSERT -> UPDATE.
181001 ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
181002 ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
181004 if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
181005 || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
181006 || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
181007 || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
181009 pNew = pExist;
181010 }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
181011 sqlite3_free(pExist);
181012 assert( pNew==0 );
181013 }else{
181014 u8 *aExist = pExist->aRecord;
181015 int nByte;
181016 u8 *aCsr;
181018 /* Allocate a new SessionChange object. Ensure that the aRecord[]
181019 ** buffer of the new object is large enough to hold any record that
181020 ** may be generated by combining the input records. */
181021 nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
181022 pNew = (SessionChange *)sqlite3_malloc(nByte);
181023 if( !pNew ){
181024 sqlite3_free(pExist);
181025 return SQLITE_NOMEM;
181027 memset(pNew, 0, sizeof(SessionChange));
181028 pNew->bIndirect = (bIndirect && pExist->bIndirect);
181029 aCsr = pNew->aRecord = (u8 *)&pNew[1];
181031 if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
181032 u8 *a1 = aRec;
181033 assert( op2==SQLITE_UPDATE );
181034 pNew->op = SQLITE_INSERT;
181035 if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
181036 sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
181037 }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
181038 assert( op2==SQLITE_INSERT );
181039 pNew->op = SQLITE_UPDATE;
181040 if( bPatchset ){
181041 memcpy(aCsr, aRec, nRec);
181042 aCsr += nRec;
181043 }else{
181044 if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
181045 sqlite3_free(pNew);
181046 pNew = 0;
181049 }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
181050 u8 *a1 = aExist;
181051 u8 *a2 = aRec;
181052 assert( op1==SQLITE_UPDATE );
181053 if( bPatchset==0 ){
181054 sessionSkipRecord(&a1, pTab->nCol);
181055 sessionSkipRecord(&a2, pTab->nCol);
181057 pNew->op = SQLITE_UPDATE;
181058 if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
181059 sqlite3_free(pNew);
181060 pNew = 0;
181062 }else{ /* UPDATE + DELETE */
181063 assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
181064 pNew->op = SQLITE_DELETE;
181065 if( bPatchset ){
181066 memcpy(aCsr, aRec, nRec);
181067 aCsr += nRec;
181068 }else{
181069 sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
181073 if( pNew ){
181074 pNew->nRecord = (int)(aCsr - pNew->aRecord);
181076 sqlite3_free(pExist);
181080 *ppNew = pNew;
181081 return SQLITE_OK;
181085 ** Add all changes in the changeset traversed by the iterator passed as
181086 ** the first argument to the changegroup hash tables.
181088 static int sessionChangesetToHash(
181089 sqlite3_changeset_iter *pIter, /* Iterator to read from */
181090 sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */
181092 u8 *aRec;
181093 int nRec;
181094 int rc = SQLITE_OK;
181095 SessionTable *pTab = 0;
181098 while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
181099 const char *zNew;
181100 int nCol;
181101 int op;
181102 int iHash;
181103 int bIndirect;
181104 SessionChange *pChange;
181105 SessionChange *pExist = 0;
181106 SessionChange **pp;
181108 if( pGrp->pList==0 ){
181109 pGrp->bPatch = pIter->bPatchset;
181110 }else if( pIter->bPatchset!=pGrp->bPatch ){
181111 rc = SQLITE_ERROR;
181112 break;
181115 sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
181116 if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
181117 /* Search the list for a matching table */
181118 int nNew = (int)strlen(zNew);
181119 u8 *abPK;
181121 sqlite3changeset_pk(pIter, &abPK, 0);
181122 for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
181123 if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
181125 if( !pTab ){
181126 SessionTable **ppTab;
181128 pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
181129 if( !pTab ){
181130 rc = SQLITE_NOMEM;
181131 break;
181133 memset(pTab, 0, sizeof(SessionTable));
181134 pTab->nCol = nCol;
181135 pTab->abPK = (u8*)&pTab[1];
181136 memcpy(pTab->abPK, abPK, nCol);
181137 pTab->zName = (char*)&pTab->abPK[nCol];
181138 memcpy(pTab->zName, zNew, nNew+1);
181140 /* The new object must be linked on to the end of the list, not
181141 ** simply added to the start of it. This is to ensure that the
181142 ** tables within the output of sqlite3changegroup_output() are in
181143 ** the right order. */
181144 for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
181145 *ppTab = pTab;
181146 }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
181147 rc = SQLITE_SCHEMA;
181148 break;
181152 if( sessionGrowHash(pIter->bPatchset, pTab) ){
181153 rc = SQLITE_NOMEM;
181154 break;
181156 iHash = sessionChangeHash(
181157 pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
181160 /* Search for existing entry. If found, remove it from the hash table.
181161 ** Code below may link it back in.
181163 for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
181164 int bPkOnly1 = 0;
181165 int bPkOnly2 = 0;
181166 if( pIter->bPatchset ){
181167 bPkOnly1 = (*pp)->op==SQLITE_DELETE;
181168 bPkOnly2 = op==SQLITE_DELETE;
181170 if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
181171 pExist = *pp;
181172 *pp = (*pp)->pNext;
181173 pTab->nEntry--;
181174 break;
181178 rc = sessionChangeMerge(pTab,
181179 pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
181181 if( rc ) break;
181182 if( pChange ){
181183 pChange->pNext = pTab->apChange[iHash];
181184 pTab->apChange[iHash] = pChange;
181185 pTab->nEntry++;
181189 if( rc==SQLITE_OK ) rc = pIter->rc;
181190 return rc;
181194 ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
181195 ** added to the changegroup object passed as the first argument.
181197 ** If xOutput is not NULL, then the changeset/patchset is returned to the
181198 ** user via one or more calls to xOutput, as with the other streaming
181199 ** interfaces.
181201 ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
181202 ** buffer containing the output changeset before this function returns. In
181203 ** this case (*pnOut) is set to the size of the output buffer in bytes. It
181204 ** is the responsibility of the caller to free the output buffer using
181205 ** sqlite3_free() when it is no longer required.
181207 ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
181208 ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
181209 ** are both set to 0 before returning.
181211 static int sessionChangegroupOutput(
181212 sqlite3_changegroup *pGrp,
181213 int (*xOutput)(void *pOut, const void *pData, int nData),
181214 void *pOut,
181215 int *pnOut,
181216 void **ppOut
181218 int rc = SQLITE_OK;
181219 SessionBuffer buf = {0, 0, 0};
181220 SessionTable *pTab;
181221 assert( xOutput==0 || (ppOut==0 && pnOut==0) );
181223 /* Create the serialized output changeset based on the contents of the
181224 ** hash tables attached to the SessionTable objects in list p->pList.
181226 for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
181227 int i;
181228 if( pTab->nEntry==0 ) continue;
181230 sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
181231 for(i=0; i<pTab->nChange; i++){
181232 SessionChange *p;
181233 for(p=pTab->apChange[i]; p; p=p->pNext){
181234 sessionAppendByte(&buf, p->op, &rc);
181235 sessionAppendByte(&buf, p->bIndirect, &rc);
181236 sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
181240 if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
181241 rc = xOutput(pOut, buf.aBuf, buf.nBuf);
181242 buf.nBuf = 0;
181246 if( rc==SQLITE_OK ){
181247 if( xOutput ){
181248 if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
181249 }else{
181250 *ppOut = buf.aBuf;
181251 *pnOut = buf.nBuf;
181252 buf.aBuf = 0;
181255 sqlite3_free(buf.aBuf);
181257 return rc;
181261 ** Allocate a new, empty, sqlite3_changegroup.
181263 SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
181264 int rc = SQLITE_OK; /* Return code */
181265 sqlite3_changegroup *p; /* New object */
181266 p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
181267 if( p==0 ){
181268 rc = SQLITE_NOMEM;
181269 }else{
181270 memset(p, 0, sizeof(sqlite3_changegroup));
181272 *pp = p;
181273 return rc;
181277 ** Add the changeset currently stored in buffer pData, size nData bytes,
181278 ** to changeset-group p.
181280 SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
181281 sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
181282 int rc; /* Return code */
181284 rc = sqlite3changeset_start(&pIter, nData, pData);
181285 if( rc==SQLITE_OK ){
181286 rc = sessionChangesetToHash(pIter, pGrp);
181288 sqlite3changeset_finalize(pIter);
181289 return rc;
181293 ** Obtain a buffer containing a changeset representing the concatenation
181294 ** of all changesets added to the group so far.
181296 SQLITE_API int sqlite3changegroup_output(
181297 sqlite3_changegroup *pGrp,
181298 int *pnData,
181299 void **ppData
181301 return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
181305 ** Streaming versions of changegroup_add().
181307 SQLITE_API int sqlite3changegroup_add_strm(
181308 sqlite3_changegroup *pGrp,
181309 int (*xInput)(void *pIn, void *pData, int *pnData),
181310 void *pIn
181312 sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
181313 int rc; /* Return code */
181315 rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
181316 if( rc==SQLITE_OK ){
181317 rc = sessionChangesetToHash(pIter, pGrp);
181319 sqlite3changeset_finalize(pIter);
181320 return rc;
181324 ** Streaming versions of changegroup_output().
181326 SQLITE_API int sqlite3changegroup_output_strm(
181327 sqlite3_changegroup *pGrp,
181328 int (*xOutput)(void *pOut, const void *pData, int nData),
181329 void *pOut
181331 return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
181335 ** Delete a changegroup object.
181337 SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
181338 if( pGrp ){
181339 sessionDeleteTable(pGrp->pList);
181340 sqlite3_free(pGrp);
181345 ** Combine two changesets together.
181347 SQLITE_API int sqlite3changeset_concat(
181348 int nLeft, /* Number of bytes in lhs input */
181349 void *pLeft, /* Lhs input changeset */
181350 int nRight /* Number of bytes in rhs input */,
181351 void *pRight, /* Rhs input changeset */
181352 int *pnOut, /* OUT: Number of bytes in output changeset */
181353 void **ppOut /* OUT: changeset (left <concat> right) */
181355 sqlite3_changegroup *pGrp;
181356 int rc;
181358 rc = sqlite3changegroup_new(&pGrp);
181359 if( rc==SQLITE_OK ){
181360 rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
181362 if( rc==SQLITE_OK ){
181363 rc = sqlite3changegroup_add(pGrp, nRight, pRight);
181365 if( rc==SQLITE_OK ){
181366 rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
181368 sqlite3changegroup_delete(pGrp);
181370 return rc;
181374 ** Streaming version of sqlite3changeset_concat().
181376 SQLITE_API int sqlite3changeset_concat_strm(
181377 int (*xInputA)(void *pIn, void *pData, int *pnData),
181378 void *pInA,
181379 int (*xInputB)(void *pIn, void *pData, int *pnData),
181380 void *pInB,
181381 int (*xOutput)(void *pOut, const void *pData, int nData),
181382 void *pOut
181384 sqlite3_changegroup *pGrp;
181385 int rc;
181387 rc = sqlite3changegroup_new(&pGrp);
181388 if( rc==SQLITE_OK ){
181389 rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
181391 if( rc==SQLITE_OK ){
181392 rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
181394 if( rc==SQLITE_OK ){
181395 rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
181397 sqlite3changegroup_delete(pGrp);
181399 return rc;
181402 #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
181404 /************** End of sqlite3session.c **************************************/
181405 /************** Begin file json1.c *******************************************/
181407 ** 2015-08-12
181409 ** The author disclaims copyright to this source code. In place of
181410 ** a legal notice, here is a blessing:
181412 ** May you do good and not evil.
181413 ** May you find forgiveness for yourself and forgive others.
181414 ** May you share freely, never taking more than you give.
181416 ******************************************************************************
181418 ** This SQLite extension implements JSON functions. The interface is
181419 ** modeled after MySQL JSON functions:
181421 ** https://dev.mysql.com/doc/refman/5.7/en/json.html
181423 ** For the time being, all JSON is stored as pure text. (We might add
181424 ** a JSONB type in the future which stores a binary encoding of JSON in
181425 ** a BLOB, but there is no support for JSONB in the current implementation.
181426 ** This implementation parses JSON text at 250 MB/s, so it is hard to see
181427 ** how JSONB might improve on that.)
181429 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
181430 #if !defined(SQLITEINT_H)
181431 /* #include "sqlite3ext.h" */
181432 #endif
181433 SQLITE_EXTENSION_INIT1
181434 /* #include <assert.h> */
181435 /* #include <string.h> */
181436 /* #include <stdlib.h> */
181437 /* #include <stdarg.h> */
181439 /* Mark a function parameter as unused, to suppress nuisance compiler
181440 ** warnings. */
181441 #ifndef UNUSED_PARAM
181442 # define UNUSED_PARAM(X) (void)(X)
181443 #endif
181445 #ifndef LARGEST_INT64
181446 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
181447 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
181448 #endif
181451 ** Versions of isspace(), isalnum() and isdigit() to which it is safe
181452 ** to pass signed char values.
181454 #ifdef sqlite3Isdigit
181455 /* Use the SQLite core versions if this routine is part of the
181456 ** SQLite amalgamation */
181457 # define safe_isdigit(x) sqlite3Isdigit(x)
181458 # define safe_isalnum(x) sqlite3Isalnum(x)
181459 # define safe_isxdigit(x) sqlite3Isxdigit(x)
181460 #else
181461 /* Use the standard library for separate compilation */
181462 #include <ctype.h> /* amalgamator: keep */
181463 # define safe_isdigit(x) isdigit((unsigned char)(x))
181464 # define safe_isalnum(x) isalnum((unsigned char)(x))
181465 # define safe_isxdigit(x) isxdigit((unsigned char)(x))
181466 #endif
181469 ** Growing our own isspace() routine this way is twice as fast as
181470 ** the library isspace() function, resulting in a 7% overall performance
181471 ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
181473 static const char jsonIsSpace[] = {
181474 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
181475 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181476 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181477 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181478 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181479 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181480 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181481 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181482 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181483 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181484 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181485 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181486 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181487 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181488 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181489 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
181491 #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
181493 #ifndef SQLITE_AMALGAMATION
181494 /* Unsigned integer types. These are already defined in the sqliteInt.h,
181495 ** but the definitions need to be repeated for separate compilation. */
181496 typedef sqlite3_uint64 u64;
181497 typedef unsigned int u32;
181498 typedef unsigned short int u16;
181499 typedef unsigned char u8;
181500 #endif
181502 /* Objects */
181503 typedef struct JsonString JsonString;
181504 typedef struct JsonNode JsonNode;
181505 typedef struct JsonParse JsonParse;
181507 /* An instance of this object represents a JSON string
181508 ** under construction. Really, this is a generic string accumulator
181509 ** that can be and is used to create strings other than JSON.
181511 struct JsonString {
181512 sqlite3_context *pCtx; /* Function context - put error messages here */
181513 char *zBuf; /* Append JSON content here */
181514 u64 nAlloc; /* Bytes of storage available in zBuf[] */
181515 u64 nUsed; /* Bytes of zBuf[] currently used */
181516 u8 bStatic; /* True if zBuf is static space */
181517 u8 bErr; /* True if an error has been encountered */
181518 char zSpace[100]; /* Initial static space */
181521 /* JSON type values
181523 #define JSON_NULL 0
181524 #define JSON_TRUE 1
181525 #define JSON_FALSE 2
181526 #define JSON_INT 3
181527 #define JSON_REAL 4
181528 #define JSON_STRING 5
181529 #define JSON_ARRAY 6
181530 #define JSON_OBJECT 7
181532 /* The "subtype" set for JSON values */
181533 #define JSON_SUBTYPE 74 /* Ascii for "J" */
181536 ** Names of the various JSON types:
181538 static const char * const jsonType[] = {
181539 "null", "true", "false", "integer", "real", "text", "array", "object"
181542 /* Bit values for the JsonNode.jnFlag field
181544 #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
181545 #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
181546 #define JNODE_REMOVE 0x04 /* Do not output */
181547 #define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
181548 #define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
181549 #define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
181550 #define JNODE_LABEL 0x40 /* Is a label of an object */
181553 /* A single node of parsed JSON
181555 struct JsonNode {
181556 u8 eType; /* One of the JSON_ type values */
181557 u8 jnFlags; /* JNODE flags */
181558 u32 n; /* Bytes of content, or number of sub-nodes */
181559 union {
181560 const char *zJContent; /* Content for INT, REAL, and STRING */
181561 u32 iAppend; /* More terms for ARRAY and OBJECT */
181562 u32 iKey; /* Key for ARRAY objects in json_tree() */
181563 u32 iReplace; /* Replacement content for JNODE_REPLACE */
181564 JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
181568 /* A completely parsed JSON string
181570 struct JsonParse {
181571 u32 nNode; /* Number of slots of aNode[] used */
181572 u32 nAlloc; /* Number of slots of aNode[] allocated */
181573 JsonNode *aNode; /* Array of nodes containing the parse */
181574 const char *zJson; /* Original JSON string */
181575 u32 *aUp; /* Index of parent of each node */
181576 u8 oom; /* Set to true if out of memory */
181577 u8 nErr; /* Number of errors seen */
181578 u16 iDepth; /* Nesting depth */
181579 int nJson; /* Length of the zJson string in bytes */
181583 ** Maximum nesting depth of JSON for this implementation.
181585 ** This limit is needed to avoid a stack overflow in the recursive
181586 ** descent parser. A depth of 2000 is far deeper than any sane JSON
181587 ** should go.
181589 #define JSON_MAX_DEPTH 2000
181591 /**************************************************************************
181592 ** Utility routines for dealing with JsonString objects
181593 **************************************************************************/
181595 /* Set the JsonString object to an empty string
181597 static void jsonZero(JsonString *p){
181598 p->zBuf = p->zSpace;
181599 p->nAlloc = sizeof(p->zSpace);
181600 p->nUsed = 0;
181601 p->bStatic = 1;
181604 /* Initialize the JsonString object
181606 static void jsonInit(JsonString *p, sqlite3_context *pCtx){
181607 p->pCtx = pCtx;
181608 p->bErr = 0;
181609 jsonZero(p);
181613 /* Free all allocated memory and reset the JsonString object back to its
181614 ** initial state.
181616 static void jsonReset(JsonString *p){
181617 if( !p->bStatic ) sqlite3_free(p->zBuf);
181618 jsonZero(p);
181622 /* Report an out-of-memory (OOM) condition
181624 static void jsonOom(JsonString *p){
181625 p->bErr = 1;
181626 sqlite3_result_error_nomem(p->pCtx);
181627 jsonReset(p);
181630 /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
181631 ** Return zero on success. Return non-zero on an OOM error
181633 static int jsonGrow(JsonString *p, u32 N){
181634 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
181635 char *zNew;
181636 if( p->bStatic ){
181637 if( p->bErr ) return 1;
181638 zNew = sqlite3_malloc64(nTotal);
181639 if( zNew==0 ){
181640 jsonOom(p);
181641 return SQLITE_NOMEM;
181643 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
181644 p->zBuf = zNew;
181645 p->bStatic = 0;
181646 }else{
181647 zNew = sqlite3_realloc64(p->zBuf, nTotal);
181648 if( zNew==0 ){
181649 jsonOom(p);
181650 return SQLITE_NOMEM;
181652 p->zBuf = zNew;
181654 p->nAlloc = nTotal;
181655 return SQLITE_OK;
181658 /* Append N bytes from zIn onto the end of the JsonString string.
181660 static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
181661 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
181662 memcpy(p->zBuf+p->nUsed, zIn, N);
181663 p->nUsed += N;
181666 /* Append formatted text (not to exceed N bytes) to the JsonString.
181668 static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
181669 va_list ap;
181670 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
181671 va_start(ap, zFormat);
181672 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
181673 va_end(ap);
181674 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
181677 /* Append a single character
181679 static void jsonAppendChar(JsonString *p, char c){
181680 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
181681 p->zBuf[p->nUsed++] = c;
181684 /* Append a comma separator to the output buffer, if the previous
181685 ** character is not '[' or '{'.
181687 static void jsonAppendSeparator(JsonString *p){
181688 char c;
181689 if( p->nUsed==0 ) return;
181690 c = p->zBuf[p->nUsed-1];
181691 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
181694 /* Append the N-byte string in zIn to the end of the JsonString string
181695 ** under construction. Enclose the string in "..." and escape
181696 ** any double-quotes or backslash characters contained within the
181697 ** string.
181699 static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
181700 u32 i;
181701 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
181702 p->zBuf[p->nUsed++] = '"';
181703 for(i=0; i<N; i++){
181704 unsigned char c = ((unsigned const char*)zIn)[i];
181705 if( c=='"' || c=='\\' ){
181706 json_simple_escape:
181707 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
181708 p->zBuf[p->nUsed++] = '\\';
181709 }else if( c<=0x1f ){
181710 static const char aSpecial[] = {
181711 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
181712 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
181714 assert( sizeof(aSpecial)==32 );
181715 assert( aSpecial['\b']=='b' );
181716 assert( aSpecial['\f']=='f' );
181717 assert( aSpecial['\n']=='n' );
181718 assert( aSpecial['\r']=='r' );
181719 assert( aSpecial['\t']=='t' );
181720 if( aSpecial[c] ){
181721 c = aSpecial[c];
181722 goto json_simple_escape;
181724 if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
181725 p->zBuf[p->nUsed++] = '\\';
181726 p->zBuf[p->nUsed++] = 'u';
181727 p->zBuf[p->nUsed++] = '0';
181728 p->zBuf[p->nUsed++] = '0';
181729 p->zBuf[p->nUsed++] = '0' + (c>>4);
181730 c = "0123456789abcdef"[c&0xf];
181732 p->zBuf[p->nUsed++] = c;
181734 p->zBuf[p->nUsed++] = '"';
181735 assert( p->nUsed<p->nAlloc );
181739 ** Append a function parameter value to the JSON string under
181740 ** construction.
181742 static void jsonAppendValue(
181743 JsonString *p, /* Append to this JSON string */
181744 sqlite3_value *pValue /* Value to append */
181746 switch( sqlite3_value_type(pValue) ){
181747 case SQLITE_NULL: {
181748 jsonAppendRaw(p, "null", 4);
181749 break;
181751 case SQLITE_INTEGER:
181752 case SQLITE_FLOAT: {
181753 const char *z = (const char*)sqlite3_value_text(pValue);
181754 u32 n = (u32)sqlite3_value_bytes(pValue);
181755 jsonAppendRaw(p, z, n);
181756 break;
181758 case SQLITE_TEXT: {
181759 const char *z = (const char*)sqlite3_value_text(pValue);
181760 u32 n = (u32)sqlite3_value_bytes(pValue);
181761 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
181762 jsonAppendRaw(p, z, n);
181763 }else{
181764 jsonAppendString(p, z, n);
181766 break;
181768 default: {
181769 if( p->bErr==0 ){
181770 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
181771 p->bErr = 2;
181772 jsonReset(p);
181774 break;
181780 /* Make the JSON in p the result of the SQL function.
181782 static void jsonResult(JsonString *p){
181783 if( p->bErr==0 ){
181784 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
181785 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
181786 SQLITE_UTF8);
181787 jsonZero(p);
181789 assert( p->bStatic );
181792 /**************************************************************************
181793 ** Utility routines for dealing with JsonNode and JsonParse objects
181794 **************************************************************************/
181797 ** Return the number of consecutive JsonNode slots need to represent
181798 ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
181799 ** OBJECT types, the number might be larger.
181801 ** Appended elements are not counted. The value returned is the number
181802 ** by which the JsonNode counter should increment in order to go to the
181803 ** next peer value.
181805 static u32 jsonNodeSize(JsonNode *pNode){
181806 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
181810 ** Reclaim all memory allocated by a JsonParse object. But do not
181811 ** delete the JsonParse object itself.
181813 static void jsonParseReset(JsonParse *pParse){
181814 sqlite3_free(pParse->aNode);
181815 pParse->aNode = 0;
181816 pParse->nNode = 0;
181817 pParse->nAlloc = 0;
181818 sqlite3_free(pParse->aUp);
181819 pParse->aUp = 0;
181823 ** Free a JsonParse object that was obtained from sqlite3_malloc().
181825 static void jsonParseFree(JsonParse *pParse){
181826 jsonParseReset(pParse);
181827 sqlite3_free(pParse);
181831 ** Convert the JsonNode pNode into a pure JSON string and
181832 ** append to pOut. Subsubstructure is also included. Return
181833 ** the number of JsonNode objects that are encoded.
181835 static void jsonRenderNode(
181836 JsonNode *pNode, /* The node to render */
181837 JsonString *pOut, /* Write JSON here */
181838 sqlite3_value **aReplace /* Replacement values */
181840 if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
181841 if( pNode->jnFlags & JNODE_REPLACE ){
181842 jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
181843 return;
181845 pNode = pNode->u.pPatch;
181847 switch( pNode->eType ){
181848 default: {
181849 assert( pNode->eType==JSON_NULL );
181850 jsonAppendRaw(pOut, "null", 4);
181851 break;
181853 case JSON_TRUE: {
181854 jsonAppendRaw(pOut, "true", 4);
181855 break;
181857 case JSON_FALSE: {
181858 jsonAppendRaw(pOut, "false", 5);
181859 break;
181861 case JSON_STRING: {
181862 if( pNode->jnFlags & JNODE_RAW ){
181863 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
181864 break;
181866 /* Fall through into the next case */
181868 case JSON_REAL:
181869 case JSON_INT: {
181870 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
181871 break;
181873 case JSON_ARRAY: {
181874 u32 j = 1;
181875 jsonAppendChar(pOut, '[');
181876 for(;;){
181877 while( j<=pNode->n ){
181878 if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
181879 jsonAppendSeparator(pOut);
181880 jsonRenderNode(&pNode[j], pOut, aReplace);
181882 j += jsonNodeSize(&pNode[j]);
181884 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
181885 pNode = &pNode[pNode->u.iAppend];
181886 j = 1;
181888 jsonAppendChar(pOut, ']');
181889 break;
181891 case JSON_OBJECT: {
181892 u32 j = 1;
181893 jsonAppendChar(pOut, '{');
181894 for(;;){
181895 while( j<=pNode->n ){
181896 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
181897 jsonAppendSeparator(pOut);
181898 jsonRenderNode(&pNode[j], pOut, aReplace);
181899 jsonAppendChar(pOut, ':');
181900 jsonRenderNode(&pNode[j+1], pOut, aReplace);
181902 j += 1 + jsonNodeSize(&pNode[j+1]);
181904 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
181905 pNode = &pNode[pNode->u.iAppend];
181906 j = 1;
181908 jsonAppendChar(pOut, '}');
181909 break;
181915 ** Return a JsonNode and all its descendents as a JSON string.
181917 static void jsonReturnJson(
181918 JsonNode *pNode, /* Node to return */
181919 sqlite3_context *pCtx, /* Return value for this function */
181920 sqlite3_value **aReplace /* Array of replacement values */
181922 JsonString s;
181923 jsonInit(&s, pCtx);
181924 jsonRenderNode(pNode, &s, aReplace);
181925 jsonResult(&s);
181926 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
181930 ** Make the JsonNode the return value of the function.
181932 static void jsonReturn(
181933 JsonNode *pNode, /* Node to return */
181934 sqlite3_context *pCtx, /* Return value for this function */
181935 sqlite3_value **aReplace /* Array of replacement values */
181937 switch( pNode->eType ){
181938 default: {
181939 assert( pNode->eType==JSON_NULL );
181940 sqlite3_result_null(pCtx);
181941 break;
181943 case JSON_TRUE: {
181944 sqlite3_result_int(pCtx, 1);
181945 break;
181947 case JSON_FALSE: {
181948 sqlite3_result_int(pCtx, 0);
181949 break;
181951 case JSON_INT: {
181952 sqlite3_int64 i = 0;
181953 const char *z = pNode->u.zJContent;
181954 if( z[0]=='-' ){ z++; }
181955 while( z[0]>='0' && z[0]<='9' ){
181956 unsigned v = *(z++) - '0';
181957 if( i>=LARGEST_INT64/10 ){
181958 if( i>LARGEST_INT64/10 ) goto int_as_real;
181959 if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
181960 if( v==9 ) goto int_as_real;
181961 if( v==8 ){
181962 if( pNode->u.zJContent[0]=='-' ){
181963 sqlite3_result_int64(pCtx, SMALLEST_INT64);
181964 goto int_done;
181965 }else{
181966 goto int_as_real;
181970 i = i*10 + v;
181972 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
181973 sqlite3_result_int64(pCtx, i);
181974 int_done:
181975 break;
181976 int_as_real: /* fall through to real */;
181978 case JSON_REAL: {
181979 double r;
181980 #ifdef SQLITE_AMALGAMATION
181981 const char *z = pNode->u.zJContent;
181982 sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
181983 #else
181984 r = strtod(pNode->u.zJContent, 0);
181985 #endif
181986 sqlite3_result_double(pCtx, r);
181987 break;
181989 case JSON_STRING: {
181990 #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
181991 ** json_insert() and json_replace() and those routines do not
181992 ** call jsonReturn() */
181993 if( pNode->jnFlags & JNODE_RAW ){
181994 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
181995 SQLITE_TRANSIENT);
181996 }else
181997 #endif
181998 assert( (pNode->jnFlags & JNODE_RAW)==0 );
181999 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
182000 /* JSON formatted without any backslash-escapes */
182001 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
182002 SQLITE_TRANSIENT);
182003 }else{
182004 /* Translate JSON formatted string into raw text */
182005 u32 i;
182006 u32 n = pNode->n;
182007 const char *z = pNode->u.zJContent;
182008 char *zOut;
182009 u32 j;
182010 zOut = sqlite3_malloc( n+1 );
182011 if( zOut==0 ){
182012 sqlite3_result_error_nomem(pCtx);
182013 break;
182015 for(i=1, j=0; i<n-1; i++){
182016 char c = z[i];
182017 if( c!='\\' ){
182018 zOut[j++] = c;
182019 }else{
182020 c = z[++i];
182021 if( c=='u' ){
182022 u32 v = 0, k;
182023 for(k=0; k<4; i++, k++){
182024 assert( i<n-2 );
182025 c = z[i+1];
182026 assert( safe_isxdigit(c) );
182027 if( c<='9' ) v = v*16 + c - '0';
182028 else if( c<='F' ) v = v*16 + c - 'A' + 10;
182029 else v = v*16 + c - 'a' + 10;
182031 if( v==0 ) break;
182032 if( v<=0x7f ){
182033 zOut[j++] = (char)v;
182034 }else if( v<=0x7ff ){
182035 zOut[j++] = (char)(0xc0 | (v>>6));
182036 zOut[j++] = 0x80 | (v&0x3f);
182037 }else{
182038 zOut[j++] = (char)(0xe0 | (v>>12));
182039 zOut[j++] = 0x80 | ((v>>6)&0x3f);
182040 zOut[j++] = 0x80 | (v&0x3f);
182042 }else{
182043 if( c=='b' ){
182044 c = '\b';
182045 }else if( c=='f' ){
182046 c = '\f';
182047 }else if( c=='n' ){
182048 c = '\n';
182049 }else if( c=='r' ){
182050 c = '\r';
182051 }else if( c=='t' ){
182052 c = '\t';
182054 zOut[j++] = c;
182058 zOut[j] = 0;
182059 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
182061 break;
182063 case JSON_ARRAY:
182064 case JSON_OBJECT: {
182065 jsonReturnJson(pNode, pCtx, aReplace);
182066 break;
182071 /* Forward reference */
182072 static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
182075 ** A macro to hint to the compiler that a function should not be
182076 ** inlined.
182078 #if defined(__GNUC__)
182079 # define JSON_NOINLINE __attribute__((noinline))
182080 #elif defined(_MSC_VER) && _MSC_VER>=1310
182081 # define JSON_NOINLINE __declspec(noinline)
182082 #else
182083 # define JSON_NOINLINE
182084 #endif
182087 static JSON_NOINLINE int jsonParseAddNodeExpand(
182088 JsonParse *pParse, /* Append the node to this object */
182089 u32 eType, /* Node type */
182090 u32 n, /* Content size or sub-node count */
182091 const char *zContent /* Content */
182093 u32 nNew;
182094 JsonNode *pNew;
182095 assert( pParse->nNode>=pParse->nAlloc );
182096 if( pParse->oom ) return -1;
182097 nNew = pParse->nAlloc*2 + 10;
182098 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
182099 if( pNew==0 ){
182100 pParse->oom = 1;
182101 return -1;
182103 pParse->nAlloc = nNew;
182104 pParse->aNode = pNew;
182105 assert( pParse->nNode<pParse->nAlloc );
182106 return jsonParseAddNode(pParse, eType, n, zContent);
182110 ** Create a new JsonNode instance based on the arguments and append that
182111 ** instance to the JsonParse. Return the index in pParse->aNode[] of the
182112 ** new node, or -1 if a memory allocation fails.
182114 static int jsonParseAddNode(
182115 JsonParse *pParse, /* Append the node to this object */
182116 u32 eType, /* Node type */
182117 u32 n, /* Content size or sub-node count */
182118 const char *zContent /* Content */
182120 JsonNode *p;
182121 if( pParse->nNode>=pParse->nAlloc ){
182122 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
182124 p = &pParse->aNode[pParse->nNode];
182125 p->eType = (u8)eType;
182126 p->jnFlags = 0;
182127 p->n = n;
182128 p->u.zJContent = zContent;
182129 return pParse->nNode++;
182133 ** Return true if z[] begins with 4 (or more) hexadecimal digits
182135 static int jsonIs4Hex(const char *z){
182136 int i;
182137 for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
182138 return 1;
182142 ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
182143 ** index of the first character past the end of the value parsed.
182145 ** Return negative for a syntax error. Special cases: return -2 if the
182146 ** first non-whitespace character is '}' and return -3 if the first
182147 ** non-whitespace character is ']'.
182149 static int jsonParseValue(JsonParse *pParse, u32 i){
182150 char c;
182151 u32 j;
182152 int iThis;
182153 int x;
182154 JsonNode *pNode;
182155 const char *z = pParse->zJson;
182156 while( safe_isspace(z[i]) ){ i++; }
182157 if( (c = z[i])=='{' ){
182158 /* Parse object */
182159 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
182160 if( iThis<0 ) return -1;
182161 for(j=i+1;;j++){
182162 while( safe_isspace(z[j]) ){ j++; }
182163 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
182164 x = jsonParseValue(pParse, j);
182165 if( x<0 ){
182166 pParse->iDepth--;
182167 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
182168 return -1;
182170 if( pParse->oom ) return -1;
182171 pNode = &pParse->aNode[pParse->nNode-1];
182172 if( pNode->eType!=JSON_STRING ) return -1;
182173 pNode->jnFlags |= JNODE_LABEL;
182174 j = x;
182175 while( safe_isspace(z[j]) ){ j++; }
182176 if( z[j]!=':' ) return -1;
182178 x = jsonParseValue(pParse, j);
182179 pParse->iDepth--;
182180 if( x<0 ) return -1;
182181 j = x;
182182 while( safe_isspace(z[j]) ){ j++; }
182183 c = z[j];
182184 if( c==',' ) continue;
182185 if( c!='}' ) return -1;
182186 break;
182188 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
182189 return j+1;
182190 }else if( c=='[' ){
182191 /* Parse array */
182192 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
182193 if( iThis<0 ) return -1;
182194 for(j=i+1;;j++){
182195 while( safe_isspace(z[j]) ){ j++; }
182196 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
182197 x = jsonParseValue(pParse, j);
182198 pParse->iDepth--;
182199 if( x<0 ){
182200 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
182201 return -1;
182203 j = x;
182204 while( safe_isspace(z[j]) ){ j++; }
182205 c = z[j];
182206 if( c==',' ) continue;
182207 if( c!=']' ) return -1;
182208 break;
182210 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
182211 return j+1;
182212 }else if( c=='"' ){
182213 /* Parse string */
182214 u8 jnFlags = 0;
182215 j = i+1;
182216 for(;;){
182217 c = z[j];
182218 if( (c & ~0x1f)==0 ){
182219 /* Control characters are not allowed in strings */
182220 return -1;
182222 if( c=='\\' ){
182223 c = z[++j];
182224 if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
182225 || c=='n' || c=='r' || c=='t'
182226 || (c=='u' && jsonIs4Hex(z+j+1)) ){
182227 jnFlags = JNODE_ESCAPE;
182228 }else{
182229 return -1;
182231 }else if( c=='"' ){
182232 break;
182236 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
182237 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
182238 return j+1;
182239 }else if( c=='n'
182240 && strncmp(z+i,"null",4)==0
182241 && !safe_isalnum(z[i+4]) ){
182242 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
182243 return i+4;
182244 }else if( c=='t'
182245 && strncmp(z+i,"true",4)==0
182246 && !safe_isalnum(z[i+4]) ){
182247 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
182248 return i+4;
182249 }else if( c=='f'
182250 && strncmp(z+i,"false",5)==0
182251 && !safe_isalnum(z[i+5]) ){
182252 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
182253 return i+5;
182254 }else if( c=='-' || (c>='0' && c<='9') ){
182255 /* Parse number */
182256 u8 seenDP = 0;
182257 u8 seenE = 0;
182258 assert( '-' < '0' );
182259 if( c<='0' ){
182260 j = c=='-' ? i+1 : i;
182261 if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
182263 j = i+1;
182264 for(;; j++){
182265 c = z[j];
182266 if( c>='0' && c<='9' ) continue;
182267 if( c=='.' ){
182268 if( z[j-1]=='-' ) return -1;
182269 if( seenDP ) return -1;
182270 seenDP = 1;
182271 continue;
182273 if( c=='e' || c=='E' ){
182274 if( z[j-1]<'0' ) return -1;
182275 if( seenE ) return -1;
182276 seenDP = seenE = 1;
182277 c = z[j+1];
182278 if( c=='+' || c=='-' ){
182280 c = z[j+1];
182282 if( c<'0' || c>'9' ) return -1;
182283 continue;
182285 break;
182287 if( z[j-1]<'0' ) return -1;
182288 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
182289 j - i, &z[i]);
182290 return j;
182291 }else if( c=='}' ){
182292 return -2; /* End of {...} */
182293 }else if( c==']' ){
182294 return -3; /* End of [...] */
182295 }else if( c==0 ){
182296 return 0; /* End of file */
182297 }else{
182298 return -1; /* Syntax error */
182303 ** Parse a complete JSON string. Return 0 on success or non-zero if there
182304 ** are any errors. If an error occurs, free all memory associated with
182305 ** pParse.
182307 ** pParse is uninitialized when this routine is called.
182309 static int jsonParse(
182310 JsonParse *pParse, /* Initialize and fill this JsonParse object */
182311 sqlite3_context *pCtx, /* Report errors here */
182312 const char *zJson /* Input JSON text to be parsed */
182314 int i;
182315 memset(pParse, 0, sizeof(*pParse));
182316 if( zJson==0 ) return 1;
182317 pParse->zJson = zJson;
182318 i = jsonParseValue(pParse, 0);
182319 if( pParse->oom ) i = -1;
182320 if( i>0 ){
182321 assert( pParse->iDepth==0 );
182322 while( safe_isspace(zJson[i]) ) i++;
182323 if( zJson[i] ) i = -1;
182325 if( i<=0 ){
182326 if( pCtx!=0 ){
182327 if( pParse->oom ){
182328 sqlite3_result_error_nomem(pCtx);
182329 }else{
182330 sqlite3_result_error(pCtx, "malformed JSON", -1);
182333 jsonParseReset(pParse);
182334 return 1;
182336 return 0;
182339 /* Mark node i of pParse as being a child of iParent. Call recursively
182340 ** to fill in all the descendants of node i.
182342 static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
182343 JsonNode *pNode = &pParse->aNode[i];
182344 u32 j;
182345 pParse->aUp[i] = iParent;
182346 switch( pNode->eType ){
182347 case JSON_ARRAY: {
182348 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
182349 jsonParseFillInParentage(pParse, i+j, i);
182351 break;
182353 case JSON_OBJECT: {
182354 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
182355 pParse->aUp[i+j] = i;
182356 jsonParseFillInParentage(pParse, i+j+1, i);
182358 break;
182360 default: {
182361 break;
182367 ** Compute the parentage of all nodes in a completed parse.
182369 static int jsonParseFindParents(JsonParse *pParse){
182370 u32 *aUp;
182371 assert( pParse->aUp==0 );
182372 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
182373 if( aUp==0 ){
182374 pParse->oom = 1;
182375 return SQLITE_NOMEM;
182377 jsonParseFillInParentage(pParse, 0, 0);
182378 return SQLITE_OK;
182382 ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
182384 #define JSON_CACHE_ID (-429938)
182387 ** Obtain a complete parse of the JSON found in the first argument
182388 ** of the argv array. Use the sqlite3_get_auxdata() cache for this
182389 ** parse if it is available. If the cache is not available or if it
182390 ** is no longer valid, parse the JSON again and return the new parse,
182391 ** and also register the new parse so that it will be available for
182392 ** future sqlite3_get_auxdata() calls.
182394 static JsonParse *jsonParseCached(
182395 sqlite3_context *pCtx,
182396 sqlite3_value **argv
182398 const char *zJson = (const char*)sqlite3_value_text(argv[0]);
182399 int nJson = sqlite3_value_bytes(argv[0]);
182400 JsonParse *p;
182401 if( zJson==0 ) return 0;
182402 p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
182403 if( p && p->nJson==nJson && memcmp(p->zJson,zJson,nJson)==0 ){
182404 p->nErr = 0;
182405 return p; /* The cached entry matches, so return it */
182407 p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
182408 if( p==0 ){
182409 sqlite3_result_error_nomem(pCtx);
182410 return 0;
182412 memset(p, 0, sizeof(*p));
182413 p->zJson = (char*)&p[1];
182414 memcpy((char*)p->zJson, zJson, nJson+1);
182415 if( jsonParse(p, pCtx, p->zJson) ){
182416 sqlite3_free(p);
182417 return 0;
182419 p->nJson = nJson;
182420 sqlite3_set_auxdata(pCtx, JSON_CACHE_ID, p, (void(*)(void*))jsonParseFree);
182421 return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
182425 ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
182426 ** a match.
182428 static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
182429 if( pNode->jnFlags & JNODE_RAW ){
182430 if( pNode->n!=nKey ) return 0;
182431 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
182432 }else{
182433 if( pNode->n!=nKey+2 ) return 0;
182434 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
182438 /* forward declaration */
182439 static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
182442 ** Search along zPath to find the node specified. Return a pointer
182443 ** to that node, or NULL if zPath is malformed or if there is no such
182444 ** node.
182446 ** If pApnd!=0, then try to append new nodes to complete zPath if it is
182447 ** possible to do so and if no existing node corresponds to zPath. If
182448 ** new nodes are appended *pApnd is set to 1.
182450 static JsonNode *jsonLookupStep(
182451 JsonParse *pParse, /* The JSON to search */
182452 u32 iRoot, /* Begin the search at this node */
182453 const char *zPath, /* The path to search */
182454 int *pApnd, /* Append nodes to complete path if not NULL */
182455 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
182457 u32 i, j, nKey;
182458 const char *zKey;
182459 JsonNode *pRoot = &pParse->aNode[iRoot];
182460 if( zPath[0]==0 ) return pRoot;
182461 if( zPath[0]=='.' ){
182462 if( pRoot->eType!=JSON_OBJECT ) return 0;
182463 zPath++;
182464 if( zPath[0]=='"' ){
182465 zKey = zPath + 1;
182466 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
182467 nKey = i-1;
182468 if( zPath[i] ){
182470 }else{
182471 *pzErr = zPath;
182472 return 0;
182474 }else{
182475 zKey = zPath;
182476 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
182477 nKey = i;
182479 if( nKey==0 ){
182480 *pzErr = zPath;
182481 return 0;
182483 j = 1;
182484 for(;;){
182485 while( j<=pRoot->n ){
182486 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
182487 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
182490 j += jsonNodeSize(&pRoot[j]);
182492 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
182493 iRoot += pRoot->u.iAppend;
182494 pRoot = &pParse->aNode[iRoot];
182495 j = 1;
182497 if( pApnd ){
182498 u32 iStart, iLabel;
182499 JsonNode *pNode;
182500 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
182501 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
182502 zPath += i;
182503 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
182504 if( pParse->oom ) return 0;
182505 if( pNode ){
182506 pRoot = &pParse->aNode[iRoot];
182507 pRoot->u.iAppend = iStart - iRoot;
182508 pRoot->jnFlags |= JNODE_APPEND;
182509 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
182511 return pNode;
182513 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
182514 if( pRoot->eType!=JSON_ARRAY ) return 0;
182515 i = 0;
182516 j = 1;
182517 while( safe_isdigit(zPath[j]) ){
182518 i = i*10 + zPath[j] - '0';
182521 if( zPath[j]!=']' ){
182522 *pzErr = zPath;
182523 return 0;
182525 zPath += j + 1;
182526 j = 1;
182527 for(;;){
182528 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
182529 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
182530 j += jsonNodeSize(&pRoot[j]);
182532 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
182533 iRoot += pRoot->u.iAppend;
182534 pRoot = &pParse->aNode[iRoot];
182535 j = 1;
182537 if( j<=pRoot->n ){
182538 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
182540 if( i==0 && pApnd ){
182541 u32 iStart;
182542 JsonNode *pNode;
182543 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
182544 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
182545 if( pParse->oom ) return 0;
182546 if( pNode ){
182547 pRoot = &pParse->aNode[iRoot];
182548 pRoot->u.iAppend = iStart - iRoot;
182549 pRoot->jnFlags |= JNODE_APPEND;
182551 return pNode;
182553 }else{
182554 *pzErr = zPath;
182556 return 0;
182560 ** Append content to pParse that will complete zPath. Return a pointer
182561 ** to the inserted node, or return NULL if the append fails.
182563 static JsonNode *jsonLookupAppend(
182564 JsonParse *pParse, /* Append content to the JSON parse */
182565 const char *zPath, /* Description of content to append */
182566 int *pApnd, /* Set this flag to 1 */
182567 const char **pzErr /* Make this point to any syntax error */
182569 *pApnd = 1;
182570 if( zPath[0]==0 ){
182571 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
182572 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
182574 if( zPath[0]=='.' ){
182575 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
182576 }else if( strncmp(zPath,"[0]",3)==0 ){
182577 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
182578 }else{
182579 return 0;
182581 if( pParse->oom ) return 0;
182582 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
182586 ** Return the text of a syntax error message on a JSON path. Space is
182587 ** obtained from sqlite3_malloc().
182589 static char *jsonPathSyntaxError(const char *zErr){
182590 return sqlite3_mprintf("JSON path error near '%q'", zErr);
182594 ** Do a node lookup using zPath. Return a pointer to the node on success.
182595 ** Return NULL if not found or if there is an error.
182597 ** On an error, write an error message into pCtx and increment the
182598 ** pParse->nErr counter.
182600 ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
182601 ** nodes are appended.
182603 static JsonNode *jsonLookup(
182604 JsonParse *pParse, /* The JSON to search */
182605 const char *zPath, /* The path to search */
182606 int *pApnd, /* Append nodes to complete path if not NULL */
182607 sqlite3_context *pCtx /* Report errors here, if not NULL */
182609 const char *zErr = 0;
182610 JsonNode *pNode = 0;
182611 char *zMsg;
182613 if( zPath==0 ) return 0;
182614 if( zPath[0]!='$' ){
182615 zErr = zPath;
182616 goto lookup_err;
182618 zPath++;
182619 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
182620 if( zErr==0 ) return pNode;
182622 lookup_err:
182623 pParse->nErr++;
182624 assert( zErr!=0 && pCtx!=0 );
182625 zMsg = jsonPathSyntaxError(zErr);
182626 if( zMsg ){
182627 sqlite3_result_error(pCtx, zMsg, -1);
182628 sqlite3_free(zMsg);
182629 }else{
182630 sqlite3_result_error_nomem(pCtx);
182632 return 0;
182637 ** Report the wrong number of arguments for json_insert(), json_replace()
182638 ** or json_set().
182640 static void jsonWrongNumArgs(
182641 sqlite3_context *pCtx,
182642 const char *zFuncName
182644 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
182645 zFuncName);
182646 sqlite3_result_error(pCtx, zMsg, -1);
182647 sqlite3_free(zMsg);
182651 ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
182653 static void jsonRemoveAllNulls(JsonNode *pNode){
182654 int i, n;
182655 assert( pNode->eType==JSON_OBJECT );
182656 n = pNode->n;
182657 for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
182658 switch( pNode[i].eType ){
182659 case JSON_NULL:
182660 pNode[i].jnFlags |= JNODE_REMOVE;
182661 break;
182662 case JSON_OBJECT:
182663 jsonRemoveAllNulls(&pNode[i]);
182664 break;
182670 /****************************************************************************
182671 ** SQL functions used for testing and debugging
182672 ****************************************************************************/
182674 #ifdef SQLITE_DEBUG
182676 ** The json_parse(JSON) function returns a string which describes
182677 ** a parse of the JSON provided. Or it returns NULL if JSON is not
182678 ** well-formed.
182680 static void jsonParseFunc(
182681 sqlite3_context *ctx,
182682 int argc,
182683 sqlite3_value **argv
182685 JsonString s; /* Output string - not real JSON */
182686 JsonParse x; /* The parse */
182687 u32 i;
182689 assert( argc==1 );
182690 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
182691 jsonParseFindParents(&x);
182692 jsonInit(&s, ctx);
182693 for(i=0; i<x.nNode; i++){
182694 const char *zType;
182695 if( x.aNode[i].jnFlags & JNODE_LABEL ){
182696 assert( x.aNode[i].eType==JSON_STRING );
182697 zType = "label";
182698 }else{
182699 zType = jsonType[x.aNode[i].eType];
182701 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
182702 i, zType, x.aNode[i].n, x.aUp[i]);
182703 if( x.aNode[i].u.zJContent!=0 ){
182704 jsonAppendRaw(&s, " ", 1);
182705 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
182707 jsonAppendRaw(&s, "\n", 1);
182709 jsonParseReset(&x);
182710 jsonResult(&s);
182714 ** The json_test1(JSON) function return true (1) if the input is JSON
182715 ** text generated by another json function. It returns (0) if the input
182716 ** is not known to be JSON.
182718 static void jsonTest1Func(
182719 sqlite3_context *ctx,
182720 int argc,
182721 sqlite3_value **argv
182723 UNUSED_PARAM(argc);
182724 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
182726 #endif /* SQLITE_DEBUG */
182728 /****************************************************************************
182729 ** Scalar SQL function implementations
182730 ****************************************************************************/
182733 ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
182734 ** corresponding to the SQL value input. Mostly this means putting
182735 ** double-quotes around strings and returning the unquoted string "null"
182736 ** when given a NULL input.
182738 static void jsonQuoteFunc(
182739 sqlite3_context *ctx,
182740 int argc,
182741 sqlite3_value **argv
182743 JsonString jx;
182744 UNUSED_PARAM(argc);
182746 jsonInit(&jx, ctx);
182747 jsonAppendValue(&jx, argv[0]);
182748 jsonResult(&jx);
182749 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
182753 ** Implementation of the json_array(VALUE,...) function. Return a JSON
182754 ** array that contains all values given in arguments. Or if any argument
182755 ** is a BLOB, throw an error.
182757 static void jsonArrayFunc(
182758 sqlite3_context *ctx,
182759 int argc,
182760 sqlite3_value **argv
182762 int i;
182763 JsonString jx;
182765 jsonInit(&jx, ctx);
182766 jsonAppendChar(&jx, '[');
182767 for(i=0; i<argc; i++){
182768 jsonAppendSeparator(&jx);
182769 jsonAppendValue(&jx, argv[i]);
182771 jsonAppendChar(&jx, ']');
182772 jsonResult(&jx);
182773 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
182778 ** json_array_length(JSON)
182779 ** json_array_length(JSON, PATH)
182781 ** Return the number of elements in the top-level JSON array.
182782 ** Return 0 if the input is not a well-formed JSON array.
182784 static void jsonArrayLengthFunc(
182785 sqlite3_context *ctx,
182786 int argc,
182787 sqlite3_value **argv
182789 JsonParse *p; /* The parse */
182790 sqlite3_int64 n = 0;
182791 u32 i;
182792 JsonNode *pNode;
182794 p = jsonParseCached(ctx, argv);
182795 if( p==0 ) return;
182796 assert( p->nNode );
182797 if( argc==2 ){
182798 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
182799 pNode = jsonLookup(p, zPath, 0, ctx);
182800 }else{
182801 pNode = p->aNode;
182803 if( pNode==0 ){
182804 return;
182806 if( pNode->eType==JSON_ARRAY ){
182807 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
182808 for(i=1; i<=pNode->n; n++){
182809 i += jsonNodeSize(&pNode[i]);
182812 sqlite3_result_int64(ctx, n);
182816 ** json_extract(JSON, PATH, ...)
182818 ** Return the element described by PATH. Return NULL if there is no
182819 ** PATH element. If there are multiple PATHs, then return a JSON array
182820 ** with the result from each path. Throw an error if the JSON or any PATH
182821 ** is malformed.
182823 static void jsonExtractFunc(
182824 sqlite3_context *ctx,
182825 int argc,
182826 sqlite3_value **argv
182828 JsonParse *p; /* The parse */
182829 JsonNode *pNode;
182830 const char *zPath;
182831 JsonString jx;
182832 int i;
182834 if( argc<2 ) return;
182835 p = jsonParseCached(ctx, argv);
182836 if( p==0 ) return;
182837 jsonInit(&jx, ctx);
182838 jsonAppendChar(&jx, '[');
182839 for(i=1; i<argc; i++){
182840 zPath = (const char*)sqlite3_value_text(argv[i]);
182841 pNode = jsonLookup(p, zPath, 0, ctx);
182842 if( p->nErr ) break;
182843 if( argc>2 ){
182844 jsonAppendSeparator(&jx);
182845 if( pNode ){
182846 jsonRenderNode(pNode, &jx, 0);
182847 }else{
182848 jsonAppendRaw(&jx, "null", 4);
182850 }else if( pNode ){
182851 jsonReturn(pNode, ctx, 0);
182854 if( argc>2 && i==argc ){
182855 jsonAppendChar(&jx, ']');
182856 jsonResult(&jx);
182857 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
182859 jsonReset(&jx);
182862 /* This is the RFC 7396 MergePatch algorithm.
182864 static JsonNode *jsonMergePatch(
182865 JsonParse *pParse, /* The JSON parser that contains the TARGET */
182866 u32 iTarget, /* Node of the TARGET in pParse */
182867 JsonNode *pPatch /* The PATCH */
182869 u32 i, j;
182870 u32 iRoot;
182871 JsonNode *pTarget;
182872 if( pPatch->eType!=JSON_OBJECT ){
182873 return pPatch;
182875 assert( iTarget>=0 && iTarget<pParse->nNode );
182876 pTarget = &pParse->aNode[iTarget];
182877 assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
182878 if( pTarget->eType!=JSON_OBJECT ){
182879 jsonRemoveAllNulls(pPatch);
182880 return pPatch;
182882 iRoot = iTarget;
182883 for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
182884 u32 nKey;
182885 const char *zKey;
182886 assert( pPatch[i].eType==JSON_STRING );
182887 assert( pPatch[i].jnFlags & JNODE_LABEL );
182888 nKey = pPatch[i].n;
182889 zKey = pPatch[i].u.zJContent;
182890 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
182891 for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
182892 assert( pTarget[j].eType==JSON_STRING );
182893 assert( pTarget[j].jnFlags & JNODE_LABEL );
182894 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
182895 if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
182896 if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
182897 if( pPatch[i+1].eType==JSON_NULL ){
182898 pTarget[j+1].jnFlags |= JNODE_REMOVE;
182899 }else{
182900 JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
182901 if( pNew==0 ) return 0;
182902 pTarget = &pParse->aNode[iTarget];
182903 if( pNew!=&pTarget[j+1] ){
182904 pTarget[j+1].u.pPatch = pNew;
182905 pTarget[j+1].jnFlags |= JNODE_PATCH;
182908 break;
182911 if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
182912 int iStart, iPatch;
182913 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
182914 jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
182915 iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
182916 if( pParse->oom ) return 0;
182917 jsonRemoveAllNulls(pPatch);
182918 pTarget = &pParse->aNode[iTarget];
182919 pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
182920 pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
182921 iRoot = iStart;
182922 pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
182923 pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
182926 return pTarget;
182930 ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
182931 ** object that is the result of running the RFC 7396 MergePatch() algorithm
182932 ** on the two arguments.
182934 static void jsonPatchFunc(
182935 sqlite3_context *ctx,
182936 int argc,
182937 sqlite3_value **argv
182939 JsonParse x; /* The JSON that is being patched */
182940 JsonParse y; /* The patch */
182941 JsonNode *pResult; /* The result of the merge */
182943 UNUSED_PARAM(argc);
182944 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
182945 if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
182946 jsonParseReset(&x);
182947 return;
182949 pResult = jsonMergePatch(&x, 0, y.aNode);
182950 assert( pResult!=0 || x.oom );
182951 if( pResult ){
182952 jsonReturnJson(pResult, ctx, 0);
182953 }else{
182954 sqlite3_result_error_nomem(ctx);
182956 jsonParseReset(&x);
182957 jsonParseReset(&y);
182962 ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
182963 ** object that contains all name/value given in arguments. Or if any name
182964 ** is not a string or if any value is a BLOB, throw an error.
182966 static void jsonObjectFunc(
182967 sqlite3_context *ctx,
182968 int argc,
182969 sqlite3_value **argv
182971 int i;
182972 JsonString jx;
182973 const char *z;
182974 u32 n;
182976 if( argc&1 ){
182977 sqlite3_result_error(ctx, "json_object() requires an even number "
182978 "of arguments", -1);
182979 return;
182981 jsonInit(&jx, ctx);
182982 jsonAppendChar(&jx, '{');
182983 for(i=0; i<argc; i+=2){
182984 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
182985 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
182986 jsonReset(&jx);
182987 return;
182989 jsonAppendSeparator(&jx);
182990 z = (const char*)sqlite3_value_text(argv[i]);
182991 n = (u32)sqlite3_value_bytes(argv[i]);
182992 jsonAppendString(&jx, z, n);
182993 jsonAppendChar(&jx, ':');
182994 jsonAppendValue(&jx, argv[i+1]);
182996 jsonAppendChar(&jx, '}');
182997 jsonResult(&jx);
182998 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
183003 ** json_remove(JSON, PATH, ...)
183005 ** Remove the named elements from JSON and return the result. malformed
183006 ** JSON or PATH arguments result in an error.
183008 static void jsonRemoveFunc(
183009 sqlite3_context *ctx,
183010 int argc,
183011 sqlite3_value **argv
183013 JsonParse x; /* The parse */
183014 JsonNode *pNode;
183015 const char *zPath;
183016 u32 i;
183018 if( argc<1 ) return;
183019 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
183020 assert( x.nNode );
183021 for(i=1; i<(u32)argc; i++){
183022 zPath = (const char*)sqlite3_value_text(argv[i]);
183023 if( zPath==0 ) goto remove_done;
183024 pNode = jsonLookup(&x, zPath, 0, ctx);
183025 if( x.nErr ) goto remove_done;
183026 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
183028 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
183029 jsonReturnJson(x.aNode, ctx, 0);
183031 remove_done:
183032 jsonParseReset(&x);
183036 ** json_replace(JSON, PATH, VALUE, ...)
183038 ** Replace the value at PATH with VALUE. If PATH does not already exist,
183039 ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
183041 static void jsonReplaceFunc(
183042 sqlite3_context *ctx,
183043 int argc,
183044 sqlite3_value **argv
183046 JsonParse x; /* The parse */
183047 JsonNode *pNode;
183048 const char *zPath;
183049 u32 i;
183051 if( argc<1 ) return;
183052 if( (argc&1)==0 ) {
183053 jsonWrongNumArgs(ctx, "replace");
183054 return;
183056 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
183057 assert( x.nNode );
183058 for(i=1; i<(u32)argc; i+=2){
183059 zPath = (const char*)sqlite3_value_text(argv[i]);
183060 pNode = jsonLookup(&x, zPath, 0, ctx);
183061 if( x.nErr ) goto replace_err;
183062 if( pNode ){
183063 pNode->jnFlags |= (u8)JNODE_REPLACE;
183064 pNode->u.iReplace = i + 1;
183067 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
183068 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
183069 }else{
183070 jsonReturnJson(x.aNode, ctx, argv);
183072 replace_err:
183073 jsonParseReset(&x);
183077 ** json_set(JSON, PATH, VALUE, ...)
183079 ** Set the value at PATH to VALUE. Create the PATH if it does not already
183080 ** exist. Overwrite existing values that do exist.
183081 ** If JSON or PATH is malformed, throw an error.
183083 ** json_insert(JSON, PATH, VALUE, ...)
183085 ** Create PATH and initialize it to VALUE. If PATH already exists, this
183086 ** routine is a no-op. If JSON or PATH is malformed, throw an error.
183088 static void jsonSetFunc(
183089 sqlite3_context *ctx,
183090 int argc,
183091 sqlite3_value **argv
183093 JsonParse x; /* The parse */
183094 JsonNode *pNode;
183095 const char *zPath;
183096 u32 i;
183097 int bApnd;
183098 int bIsSet = *(int*)sqlite3_user_data(ctx);
183100 if( argc<1 ) return;
183101 if( (argc&1)==0 ) {
183102 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
183103 return;
183105 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
183106 assert( x.nNode );
183107 for(i=1; i<(u32)argc; i+=2){
183108 zPath = (const char*)sqlite3_value_text(argv[i]);
183109 bApnd = 0;
183110 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
183111 if( x.oom ){
183112 sqlite3_result_error_nomem(ctx);
183113 goto jsonSetDone;
183114 }else if( x.nErr ){
183115 goto jsonSetDone;
183116 }else if( pNode && (bApnd || bIsSet) ){
183117 pNode->jnFlags |= (u8)JNODE_REPLACE;
183118 pNode->u.iReplace = i + 1;
183121 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
183122 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
183123 }else{
183124 jsonReturnJson(x.aNode, ctx, argv);
183126 jsonSetDone:
183127 jsonParseReset(&x);
183131 ** json_type(JSON)
183132 ** json_type(JSON, PATH)
183134 ** Return the top-level "type" of a JSON string. Throw an error if
183135 ** either the JSON or PATH inputs are not well-formed.
183137 static void jsonTypeFunc(
183138 sqlite3_context *ctx,
183139 int argc,
183140 sqlite3_value **argv
183142 JsonParse x; /* The parse */
183143 const char *zPath;
183144 JsonNode *pNode;
183146 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
183147 assert( x.nNode );
183148 if( argc==2 ){
183149 zPath = (const char*)sqlite3_value_text(argv[1]);
183150 pNode = jsonLookup(&x, zPath, 0, ctx);
183151 }else{
183152 pNode = x.aNode;
183154 if( pNode ){
183155 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
183157 jsonParseReset(&x);
183161 ** json_valid(JSON)
183163 ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
183164 ** Return 0 otherwise.
183166 static void jsonValidFunc(
183167 sqlite3_context *ctx,
183168 int argc,
183169 sqlite3_value **argv
183171 JsonParse x; /* The parse */
183172 int rc = 0;
183174 UNUSED_PARAM(argc);
183175 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
183176 rc = 1;
183178 jsonParseReset(&x);
183179 sqlite3_result_int(ctx, rc);
183183 /****************************************************************************
183184 ** Aggregate SQL function implementations
183185 ****************************************************************************/
183187 ** json_group_array(VALUE)
183189 ** Return a JSON array composed of all values in the aggregate.
183191 static void jsonArrayStep(
183192 sqlite3_context *ctx,
183193 int argc,
183194 sqlite3_value **argv
183196 JsonString *pStr;
183197 UNUSED_PARAM(argc);
183198 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
183199 if( pStr ){
183200 if( pStr->zBuf==0 ){
183201 jsonInit(pStr, ctx);
183202 jsonAppendChar(pStr, '[');
183203 }else{
183204 jsonAppendChar(pStr, ',');
183205 pStr->pCtx = ctx;
183207 jsonAppendValue(pStr, argv[0]);
183210 static void jsonArrayFinal(sqlite3_context *ctx){
183211 JsonString *pStr;
183212 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
183213 if( pStr ){
183214 pStr->pCtx = ctx;
183215 jsonAppendChar(pStr, ']');
183216 if( pStr->bErr ){
183217 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
183218 assert( pStr->bStatic );
183219 }else{
183220 sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
183221 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
183222 pStr->bStatic = 1;
183224 }else{
183225 sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
183227 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
183231 ** json_group_obj(NAME,VALUE)
183233 ** Return a JSON object composed of all names and values in the aggregate.
183235 static void jsonObjectStep(
183236 sqlite3_context *ctx,
183237 int argc,
183238 sqlite3_value **argv
183240 JsonString *pStr;
183241 const char *z;
183242 u32 n;
183243 UNUSED_PARAM(argc);
183244 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
183245 if( pStr ){
183246 if( pStr->zBuf==0 ){
183247 jsonInit(pStr, ctx);
183248 jsonAppendChar(pStr, '{');
183249 }else{
183250 jsonAppendChar(pStr, ',');
183251 pStr->pCtx = ctx;
183253 z = (const char*)sqlite3_value_text(argv[0]);
183254 n = (u32)sqlite3_value_bytes(argv[0]);
183255 jsonAppendString(pStr, z, n);
183256 jsonAppendChar(pStr, ':');
183257 jsonAppendValue(pStr, argv[1]);
183260 static void jsonObjectFinal(sqlite3_context *ctx){
183261 JsonString *pStr;
183262 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
183263 if( pStr ){
183264 jsonAppendChar(pStr, '}');
183265 if( pStr->bErr ){
183266 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
183267 assert( pStr->bStatic );
183268 }else{
183269 sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
183270 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
183271 pStr->bStatic = 1;
183273 }else{
183274 sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
183276 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
183280 #ifndef SQLITE_OMIT_VIRTUALTABLE
183281 /****************************************************************************
183282 ** The json_each virtual table
183283 ****************************************************************************/
183284 typedef struct JsonEachCursor JsonEachCursor;
183285 struct JsonEachCursor {
183286 sqlite3_vtab_cursor base; /* Base class - must be first */
183287 u32 iRowid; /* The rowid */
183288 u32 iBegin; /* The first node of the scan */
183289 u32 i; /* Index in sParse.aNode[] of current row */
183290 u32 iEnd; /* EOF when i equals or exceeds this value */
183291 u8 eType; /* Type of top-level element */
183292 u8 bRecursive; /* True for json_tree(). False for json_each() */
183293 char *zJson; /* Input JSON */
183294 char *zRoot; /* Path by which to filter zJson */
183295 JsonParse sParse; /* Parse of the input JSON */
183298 /* Constructor for the json_each virtual table */
183299 static int jsonEachConnect(
183300 sqlite3 *db,
183301 void *pAux,
183302 int argc, const char *const*argv,
183303 sqlite3_vtab **ppVtab,
183304 char **pzErr
183306 sqlite3_vtab *pNew;
183307 int rc;
183309 /* Column numbers */
183310 #define JEACH_KEY 0
183311 #define JEACH_VALUE 1
183312 #define JEACH_TYPE 2
183313 #define JEACH_ATOM 3
183314 #define JEACH_ID 4
183315 #define JEACH_PARENT 5
183316 #define JEACH_FULLKEY 6
183317 #define JEACH_PATH 7
183318 #define JEACH_JSON 8
183319 #define JEACH_ROOT 9
183321 UNUSED_PARAM(pzErr);
183322 UNUSED_PARAM(argv);
183323 UNUSED_PARAM(argc);
183324 UNUSED_PARAM(pAux);
183325 rc = sqlite3_declare_vtab(db,
183326 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
183327 "json HIDDEN,root HIDDEN)");
183328 if( rc==SQLITE_OK ){
183329 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
183330 if( pNew==0 ) return SQLITE_NOMEM;
183331 memset(pNew, 0, sizeof(*pNew));
183333 return rc;
183336 /* destructor for json_each virtual table */
183337 static int jsonEachDisconnect(sqlite3_vtab *pVtab){
183338 sqlite3_free(pVtab);
183339 return SQLITE_OK;
183342 /* constructor for a JsonEachCursor object for json_each(). */
183343 static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
183344 JsonEachCursor *pCur;
183346 UNUSED_PARAM(p);
183347 pCur = sqlite3_malloc( sizeof(*pCur) );
183348 if( pCur==0 ) return SQLITE_NOMEM;
183349 memset(pCur, 0, sizeof(*pCur));
183350 *ppCursor = &pCur->base;
183351 return SQLITE_OK;
183354 /* constructor for a JsonEachCursor object for json_tree(). */
183355 static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
183356 int rc = jsonEachOpenEach(p, ppCursor);
183357 if( rc==SQLITE_OK ){
183358 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
183359 pCur->bRecursive = 1;
183361 return rc;
183364 /* Reset a JsonEachCursor back to its original state. Free any memory
183365 ** held. */
183366 static void jsonEachCursorReset(JsonEachCursor *p){
183367 sqlite3_free(p->zJson);
183368 sqlite3_free(p->zRoot);
183369 jsonParseReset(&p->sParse);
183370 p->iRowid = 0;
183371 p->i = 0;
183372 p->iEnd = 0;
183373 p->eType = 0;
183374 p->zJson = 0;
183375 p->zRoot = 0;
183378 /* Destructor for a jsonEachCursor object */
183379 static int jsonEachClose(sqlite3_vtab_cursor *cur){
183380 JsonEachCursor *p = (JsonEachCursor*)cur;
183381 jsonEachCursorReset(p);
183382 sqlite3_free(cur);
183383 return SQLITE_OK;
183386 /* Return TRUE if the jsonEachCursor object has been advanced off the end
183387 ** of the JSON object */
183388 static int jsonEachEof(sqlite3_vtab_cursor *cur){
183389 JsonEachCursor *p = (JsonEachCursor*)cur;
183390 return p->i >= p->iEnd;
183393 /* Advance the cursor to the next element for json_tree() */
183394 static int jsonEachNext(sqlite3_vtab_cursor *cur){
183395 JsonEachCursor *p = (JsonEachCursor*)cur;
183396 if( p->bRecursive ){
183397 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
183398 p->i++;
183399 p->iRowid++;
183400 if( p->i<p->iEnd ){
183401 u32 iUp = p->sParse.aUp[p->i];
183402 JsonNode *pUp = &p->sParse.aNode[iUp];
183403 p->eType = pUp->eType;
183404 if( pUp->eType==JSON_ARRAY ){
183405 if( iUp==p->i-1 ){
183406 pUp->u.iKey = 0;
183407 }else{
183408 pUp->u.iKey++;
183412 }else{
183413 switch( p->eType ){
183414 case JSON_ARRAY: {
183415 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
183416 p->iRowid++;
183417 break;
183419 case JSON_OBJECT: {
183420 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
183421 p->iRowid++;
183422 break;
183424 default: {
183425 p->i = p->iEnd;
183426 break;
183430 return SQLITE_OK;
183433 /* Append the name of the path for element i to pStr
183435 static void jsonEachComputePath(
183436 JsonEachCursor *p, /* The cursor */
183437 JsonString *pStr, /* Write the path here */
183438 u32 i /* Path to this element */
183440 JsonNode *pNode, *pUp;
183441 u32 iUp;
183442 if( i==0 ){
183443 jsonAppendChar(pStr, '$');
183444 return;
183446 iUp = p->sParse.aUp[i];
183447 jsonEachComputePath(p, pStr, iUp);
183448 pNode = &p->sParse.aNode[i];
183449 pUp = &p->sParse.aNode[iUp];
183450 if( pUp->eType==JSON_ARRAY ){
183451 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
183452 }else{
183453 assert( pUp->eType==JSON_OBJECT );
183454 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
183455 assert( pNode->eType==JSON_STRING );
183456 assert( pNode->jnFlags & JNODE_LABEL );
183457 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
183461 /* Return the value of a column */
183462 static int jsonEachColumn(
183463 sqlite3_vtab_cursor *cur, /* The cursor */
183464 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
183465 int i /* Which column to return */
183467 JsonEachCursor *p = (JsonEachCursor*)cur;
183468 JsonNode *pThis = &p->sParse.aNode[p->i];
183469 switch( i ){
183470 case JEACH_KEY: {
183471 if( p->i==0 ) break;
183472 if( p->eType==JSON_OBJECT ){
183473 jsonReturn(pThis, ctx, 0);
183474 }else if( p->eType==JSON_ARRAY ){
183475 u32 iKey;
183476 if( p->bRecursive ){
183477 if( p->iRowid==0 ) break;
183478 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
183479 }else{
183480 iKey = p->iRowid;
183482 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
183484 break;
183486 case JEACH_VALUE: {
183487 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
183488 jsonReturn(pThis, ctx, 0);
183489 break;
183491 case JEACH_TYPE: {
183492 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
183493 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
183494 break;
183496 case JEACH_ATOM: {
183497 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
183498 if( pThis->eType>=JSON_ARRAY ) break;
183499 jsonReturn(pThis, ctx, 0);
183500 break;
183502 case JEACH_ID: {
183503 sqlite3_result_int64(ctx,
183504 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
183505 break;
183507 case JEACH_PARENT: {
183508 if( p->i>p->iBegin && p->bRecursive ){
183509 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
183511 break;
183513 case JEACH_FULLKEY: {
183514 JsonString x;
183515 jsonInit(&x, ctx);
183516 if( p->bRecursive ){
183517 jsonEachComputePath(p, &x, p->i);
183518 }else{
183519 if( p->zRoot ){
183520 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
183521 }else{
183522 jsonAppendChar(&x, '$');
183524 if( p->eType==JSON_ARRAY ){
183525 jsonPrintf(30, &x, "[%d]", p->iRowid);
183526 }else{
183527 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
183530 jsonResult(&x);
183531 break;
183533 case JEACH_PATH: {
183534 if( p->bRecursive ){
183535 JsonString x;
183536 jsonInit(&x, ctx);
183537 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
183538 jsonResult(&x);
183539 break;
183541 /* For json_each() path and root are the same so fall through
183542 ** into the root case */
183544 default: {
183545 const char *zRoot = p->zRoot;
183546 if( zRoot==0 ) zRoot = "$";
183547 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
183548 break;
183550 case JEACH_JSON: {
183551 assert( i==JEACH_JSON );
183552 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
183553 break;
183556 return SQLITE_OK;
183559 /* Return the current rowid value */
183560 static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
183561 JsonEachCursor *p = (JsonEachCursor*)cur;
183562 *pRowid = p->iRowid;
183563 return SQLITE_OK;
183566 /* The query strategy is to look for an equality constraint on the json
183567 ** column. Without such a constraint, the table cannot operate. idxNum is
183568 ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
183569 ** and 0 otherwise.
183571 static int jsonEachBestIndex(
183572 sqlite3_vtab *tab,
183573 sqlite3_index_info *pIdxInfo
183575 int i;
183576 int jsonIdx = -1;
183577 int rootIdx = -1;
183578 const struct sqlite3_index_constraint *pConstraint;
183580 UNUSED_PARAM(tab);
183581 pConstraint = pIdxInfo->aConstraint;
183582 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
183583 if( pConstraint->usable==0 ) continue;
183584 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
183585 switch( pConstraint->iColumn ){
183586 case JEACH_JSON: jsonIdx = i; break;
183587 case JEACH_ROOT: rootIdx = i; break;
183588 default: /* no-op */ break;
183591 if( jsonIdx<0 ){
183592 pIdxInfo->idxNum = 0;
183593 pIdxInfo->estimatedCost = 1e99;
183594 }else{
183595 pIdxInfo->estimatedCost = 1.0;
183596 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
183597 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
183598 if( rootIdx<0 ){
183599 pIdxInfo->idxNum = 1;
183600 }else{
183601 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
183602 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
183603 pIdxInfo->idxNum = 3;
183606 return SQLITE_OK;
183609 /* Start a search on a new JSON string */
183610 static int jsonEachFilter(
183611 sqlite3_vtab_cursor *cur,
183612 int idxNum, const char *idxStr,
183613 int argc, sqlite3_value **argv
183615 JsonEachCursor *p = (JsonEachCursor*)cur;
183616 const char *z;
183617 const char *zRoot = 0;
183618 sqlite3_int64 n;
183620 UNUSED_PARAM(idxStr);
183621 UNUSED_PARAM(argc);
183622 jsonEachCursorReset(p);
183623 if( idxNum==0 ) return SQLITE_OK;
183624 z = (const char*)sqlite3_value_text(argv[0]);
183625 if( z==0 ) return SQLITE_OK;
183626 n = sqlite3_value_bytes(argv[0]);
183627 p->zJson = sqlite3_malloc64( n+1 );
183628 if( p->zJson==0 ) return SQLITE_NOMEM;
183629 memcpy(p->zJson, z, (size_t)n+1);
183630 if( jsonParse(&p->sParse, 0, p->zJson) ){
183631 int rc = SQLITE_NOMEM;
183632 if( p->sParse.oom==0 ){
183633 sqlite3_free(cur->pVtab->zErrMsg);
183634 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
183635 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
183637 jsonEachCursorReset(p);
183638 return rc;
183639 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
183640 jsonEachCursorReset(p);
183641 return SQLITE_NOMEM;
183642 }else{
183643 JsonNode *pNode = 0;
183644 if( idxNum==3 ){
183645 const char *zErr = 0;
183646 zRoot = (const char*)sqlite3_value_text(argv[1]);
183647 if( zRoot==0 ) return SQLITE_OK;
183648 n = sqlite3_value_bytes(argv[1]);
183649 p->zRoot = sqlite3_malloc64( n+1 );
183650 if( p->zRoot==0 ) return SQLITE_NOMEM;
183651 memcpy(p->zRoot, zRoot, (size_t)n+1);
183652 if( zRoot[0]!='$' ){
183653 zErr = zRoot;
183654 }else{
183655 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
183657 if( zErr ){
183658 sqlite3_free(cur->pVtab->zErrMsg);
183659 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
183660 jsonEachCursorReset(p);
183661 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
183662 }else if( pNode==0 ){
183663 return SQLITE_OK;
183665 }else{
183666 pNode = p->sParse.aNode;
183668 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
183669 p->eType = pNode->eType;
183670 if( p->eType>=JSON_ARRAY ){
183671 pNode->u.iKey = 0;
183672 p->iEnd = p->i + pNode->n + 1;
183673 if( p->bRecursive ){
183674 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
183675 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
183676 p->i--;
183678 }else{
183679 p->i++;
183681 }else{
183682 p->iEnd = p->i+1;
183685 return SQLITE_OK;
183688 /* The methods of the json_each virtual table */
183689 static sqlite3_module jsonEachModule = {
183690 0, /* iVersion */
183691 0, /* xCreate */
183692 jsonEachConnect, /* xConnect */
183693 jsonEachBestIndex, /* xBestIndex */
183694 jsonEachDisconnect, /* xDisconnect */
183695 0, /* xDestroy */
183696 jsonEachOpenEach, /* xOpen - open a cursor */
183697 jsonEachClose, /* xClose - close a cursor */
183698 jsonEachFilter, /* xFilter - configure scan constraints */
183699 jsonEachNext, /* xNext - advance a cursor */
183700 jsonEachEof, /* xEof - check for end of scan */
183701 jsonEachColumn, /* xColumn - read data */
183702 jsonEachRowid, /* xRowid - read data */
183703 0, /* xUpdate */
183704 0, /* xBegin */
183705 0, /* xSync */
183706 0, /* xCommit */
183707 0, /* xRollback */
183708 0, /* xFindMethod */
183709 0, /* xRename */
183710 0, /* xSavepoint */
183711 0, /* xRelease */
183712 0 /* xRollbackTo */
183715 /* The methods of the json_tree virtual table. */
183716 static sqlite3_module jsonTreeModule = {
183717 0, /* iVersion */
183718 0, /* xCreate */
183719 jsonEachConnect, /* xConnect */
183720 jsonEachBestIndex, /* xBestIndex */
183721 jsonEachDisconnect, /* xDisconnect */
183722 0, /* xDestroy */
183723 jsonEachOpenTree, /* xOpen - open a cursor */
183724 jsonEachClose, /* xClose - close a cursor */
183725 jsonEachFilter, /* xFilter - configure scan constraints */
183726 jsonEachNext, /* xNext - advance a cursor */
183727 jsonEachEof, /* xEof - check for end of scan */
183728 jsonEachColumn, /* xColumn - read data */
183729 jsonEachRowid, /* xRowid - read data */
183730 0, /* xUpdate */
183731 0, /* xBegin */
183732 0, /* xSync */
183733 0, /* xCommit */
183734 0, /* xRollback */
183735 0, /* xFindMethod */
183736 0, /* xRename */
183737 0, /* xSavepoint */
183738 0, /* xRelease */
183739 0 /* xRollbackTo */
183741 #endif /* SQLITE_OMIT_VIRTUALTABLE */
183743 /****************************************************************************
183744 ** The following routines are the only publically visible identifiers in this
183745 ** file. Call the following routines in order to register the various SQL
183746 ** functions and the virtual table implemented by this file.
183747 ****************************************************************************/
183749 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
183750 int rc = SQLITE_OK;
183751 unsigned int i;
183752 static const struct {
183753 const char *zName;
183754 int nArg;
183755 int flag;
183756 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
183757 } aFunc[] = {
183758 { "json", 1, 0, jsonRemoveFunc },
183759 { "json_array", -1, 0, jsonArrayFunc },
183760 { "json_array_length", 1, 0, jsonArrayLengthFunc },
183761 { "json_array_length", 2, 0, jsonArrayLengthFunc },
183762 { "json_extract", -1, 0, jsonExtractFunc },
183763 { "json_insert", -1, 0, jsonSetFunc },
183764 { "json_object", -1, 0, jsonObjectFunc },
183765 { "json_patch", 2, 0, jsonPatchFunc },
183766 { "json_quote", 1, 0, jsonQuoteFunc },
183767 { "json_remove", -1, 0, jsonRemoveFunc },
183768 { "json_replace", -1, 0, jsonReplaceFunc },
183769 { "json_set", -1, 1, jsonSetFunc },
183770 { "json_type", 1, 0, jsonTypeFunc },
183771 { "json_type", 2, 0, jsonTypeFunc },
183772 { "json_valid", 1, 0, jsonValidFunc },
183774 #if SQLITE_DEBUG
183775 /* DEBUG and TESTING functions */
183776 { "json_parse", 1, 0, jsonParseFunc },
183777 { "json_test1", 1, 0, jsonTest1Func },
183778 #endif
183780 static const struct {
183781 const char *zName;
183782 int nArg;
183783 void (*xStep)(sqlite3_context*,int,sqlite3_value**);
183784 void (*xFinal)(sqlite3_context*);
183785 } aAgg[] = {
183786 { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
183787 { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
183789 #ifndef SQLITE_OMIT_VIRTUALTABLE
183790 static const struct {
183791 const char *zName;
183792 sqlite3_module *pModule;
183793 } aMod[] = {
183794 { "json_each", &jsonEachModule },
183795 { "json_tree", &jsonTreeModule },
183797 #endif
183798 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
183799 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
183800 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
183801 (void*)&aFunc[i].flag,
183802 aFunc[i].xFunc, 0, 0);
183804 for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
183805 rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
183806 SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
183807 0, aAgg[i].xStep, aAgg[i].xFinal);
183809 #ifndef SQLITE_OMIT_VIRTUALTABLE
183810 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
183811 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
183813 #endif
183814 return rc;
183818 #ifndef SQLITE_CORE
183819 #ifdef _WIN32
183820 __declspec(dllexport)
183821 #endif
183822 SQLITE_API int sqlite3_json_init(
183823 sqlite3 *db,
183824 char **pzErrMsg,
183825 const sqlite3_api_routines *pApi
183827 SQLITE_EXTENSION_INIT2(pApi);
183828 (void)pzErrMsg; /* Unused parameter */
183829 return sqlite3Json1Init(db);
183831 #endif
183832 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
183834 /************** End of json1.c ***********************************************/
183835 /************** Begin file fts5.c ********************************************/
183838 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
183840 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
183841 # define NDEBUG 1
183842 #endif
183843 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
183844 # undef NDEBUG
183845 #endif
183848 ** 2014 May 31
183850 ** The author disclaims copyright to this source code. In place of
183851 ** a legal notice, here is a blessing:
183853 ** May you do good and not evil.
183854 ** May you find forgiveness for yourself and forgive others.
183855 ** May you share freely, never taking more than you give.
183857 ******************************************************************************
183859 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
183860 ** FTS5 may be extended with:
183862 ** * custom tokenizers, and
183863 ** * custom auxiliary functions.
183867 #ifndef _FTS5_H
183868 #define _FTS5_H
183870 /* #include "sqlite3.h" */
183872 #if 0
183873 extern "C" {
183874 #endif
183876 /*************************************************************************
183877 ** CUSTOM AUXILIARY FUNCTIONS
183879 ** Virtual table implementations may overload SQL functions by implementing
183880 ** the sqlite3_module.xFindFunction() method.
183883 typedef struct Fts5ExtensionApi Fts5ExtensionApi;
183884 typedef struct Fts5Context Fts5Context;
183885 typedef struct Fts5PhraseIter Fts5PhraseIter;
183887 typedef void (*fts5_extension_function)(
183888 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
183889 Fts5Context *pFts, /* First arg to pass to pApi functions */
183890 sqlite3_context *pCtx, /* Context for returning result/error */
183891 int nVal, /* Number of values in apVal[] array */
183892 sqlite3_value **apVal /* Array of trailing arguments */
183895 struct Fts5PhraseIter {
183896 const unsigned char *a;
183897 const unsigned char *b;
183901 ** EXTENSION API FUNCTIONS
183903 ** xUserData(pFts):
183904 ** Return a copy of the context pointer the extension function was
183905 ** registered with.
183907 ** xColumnTotalSize(pFts, iCol, pnToken):
183908 ** If parameter iCol is less than zero, set output variable *pnToken
183909 ** to the total number of tokens in the FTS5 table. Or, if iCol is
183910 ** non-negative but less than the number of columns in the table, return
183911 ** the total number of tokens in column iCol, considering all rows in
183912 ** the FTS5 table.
183914 ** If parameter iCol is greater than or equal to the number of columns
183915 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
183916 ** an OOM condition or IO error), an appropriate SQLite error code is
183917 ** returned.
183919 ** xColumnCount(pFts):
183920 ** Return the number of columns in the table.
183922 ** xColumnSize(pFts, iCol, pnToken):
183923 ** If parameter iCol is less than zero, set output variable *pnToken
183924 ** to the total number of tokens in the current row. Or, if iCol is
183925 ** non-negative but less than the number of columns in the table, set
183926 ** *pnToken to the number of tokens in column iCol of the current row.
183928 ** If parameter iCol is greater than or equal to the number of columns
183929 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
183930 ** an OOM condition or IO error), an appropriate SQLite error code is
183931 ** returned.
183933 ** This function may be quite inefficient if used with an FTS5 table
183934 ** created with the "columnsize=0" option.
183936 ** xColumnText:
183937 ** This function attempts to retrieve the text of column iCol of the
183938 ** current document. If successful, (*pz) is set to point to a buffer
183939 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
183940 ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
183941 ** if an error occurs, an SQLite error code is returned and the final values
183942 ** of (*pz) and (*pn) are undefined.
183944 ** xPhraseCount:
183945 ** Returns the number of phrases in the current query expression.
183947 ** xPhraseSize:
183948 ** Returns the number of tokens in phrase iPhrase of the query. Phrases
183949 ** are numbered starting from zero.
183951 ** xInstCount:
183952 ** Set *pnInst to the total number of occurrences of all phrases within
183953 ** the query within the current row. Return SQLITE_OK if successful, or
183954 ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
183956 ** This API can be quite slow if used with an FTS5 table created with the
183957 ** "detail=none" or "detail=column" option. If the FTS5 table is created
183958 ** with either "detail=none" or "detail=column" and "content=" option
183959 ** (i.e. if it is a contentless table), then this API always returns 0.
183961 ** xInst:
183962 ** Query for the details of phrase match iIdx within the current row.
183963 ** Phrase matches are numbered starting from zero, so the iIdx argument
183964 ** should be greater than or equal to zero and smaller than the value
183965 ** output by xInstCount().
183967 ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
183968 ** to the column in which it occurs and *piOff the token offset of the
183969 ** first token of the phrase. The exception is if the table was created
183970 ** with the offsets=0 option specified. In this case *piOff is always
183971 ** set to -1.
183973 ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
183974 ** if an error occurs.
183976 ** This API can be quite slow if used with an FTS5 table created with the
183977 ** "detail=none" or "detail=column" option.
183979 ** xRowid:
183980 ** Returns the rowid of the current row.
183982 ** xTokenize:
183983 ** Tokenize text using the tokenizer belonging to the FTS5 table.
183985 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
183986 ** This API function is used to query the FTS table for phrase iPhrase
183987 ** of the current query. Specifically, a query equivalent to:
183989 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
183991 ** with $p set to a phrase equivalent to the phrase iPhrase of the
183992 ** current query is executed. Any column filter that applies to
183993 ** phrase iPhrase of the current query is included in $p. For each
183994 ** row visited, the callback function passed as the fourth argument
183995 ** is invoked. The context and API objects passed to the callback
183996 ** function may be used to access the properties of each matched row.
183997 ** Invoking Api.xUserData() returns a copy of the pointer passed as
183998 ** the third argument to pUserData.
184000 ** If the callback function returns any value other than SQLITE_OK, the
184001 ** query is abandoned and the xQueryPhrase function returns immediately.
184002 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
184003 ** Otherwise, the error code is propagated upwards.
184005 ** If the query runs to completion without incident, SQLITE_OK is returned.
184006 ** Or, if some error occurs before the query completes or is aborted by
184007 ** the callback, an SQLite error code is returned.
184010 ** xSetAuxdata(pFts5, pAux, xDelete)
184012 ** Save the pointer passed as the second argument as the extension functions
184013 ** "auxiliary data". The pointer may then be retrieved by the current or any
184014 ** future invocation of the same fts5 extension function made as part of
184015 ** of the same MATCH query using the xGetAuxdata() API.
184017 ** Each extension function is allocated a single auxiliary data slot for
184018 ** each FTS query (MATCH expression). If the extension function is invoked
184019 ** more than once for a single FTS query, then all invocations share a
184020 ** single auxiliary data context.
184022 ** If there is already an auxiliary data pointer when this function is
184023 ** invoked, then it is replaced by the new pointer. If an xDelete callback
184024 ** was specified along with the original pointer, it is invoked at this
184025 ** point.
184027 ** The xDelete callback, if one is specified, is also invoked on the
184028 ** auxiliary data pointer after the FTS5 query has finished.
184030 ** If an error (e.g. an OOM condition) occurs within this function, an
184031 ** the auxiliary data is set to NULL and an error code returned. If the
184032 ** xDelete parameter was not NULL, it is invoked on the auxiliary data
184033 ** pointer before returning.
184036 ** xGetAuxdata(pFts5, bClear)
184038 ** Returns the current auxiliary data pointer for the fts5 extension
184039 ** function. See the xSetAuxdata() method for details.
184041 ** If the bClear argument is non-zero, then the auxiliary data is cleared
184042 ** (set to NULL) before this function returns. In this case the xDelete,
184043 ** if any, is not invoked.
184046 ** xRowCount(pFts5, pnRow)
184048 ** This function is used to retrieve the total number of rows in the table.
184049 ** In other words, the same value that would be returned by:
184051 ** SELECT count(*) FROM ftstable;
184053 ** xPhraseFirst()
184054 ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
184055 ** method, to iterate through all instances of a single query phrase within
184056 ** the current row. This is the same information as is accessible via the
184057 ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
184058 ** to use, this API may be faster under some circumstances. To iterate
184059 ** through instances of phrase iPhrase, use the following code:
184061 ** Fts5PhraseIter iter;
184062 ** int iCol, iOff;
184063 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
184064 ** iCol>=0;
184065 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
184066 ** ){
184067 ** // An instance of phrase iPhrase at offset iOff of column iCol
184070 ** The Fts5PhraseIter structure is defined above. Applications should not
184071 ** modify this structure directly - it should only be used as shown above
184072 ** with the xPhraseFirst() and xPhraseNext() API methods (and by
184073 ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
184075 ** This API can be quite slow if used with an FTS5 table created with the
184076 ** "detail=none" or "detail=column" option. If the FTS5 table is created
184077 ** with either "detail=none" or "detail=column" and "content=" option
184078 ** (i.e. if it is a contentless table), then this API always iterates
184079 ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
184081 ** xPhraseNext()
184082 ** See xPhraseFirst above.
184084 ** xPhraseFirstColumn()
184085 ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
184086 ** and xPhraseNext() APIs described above. The difference is that instead
184087 ** of iterating through all instances of a phrase in the current row, these
184088 ** APIs are used to iterate through the set of columns in the current row
184089 ** that contain one or more instances of a specified phrase. For example:
184091 ** Fts5PhraseIter iter;
184092 ** int iCol;
184093 ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
184094 ** iCol>=0;
184095 ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
184096 ** ){
184097 ** // Column iCol contains at least one instance of phrase iPhrase
184100 ** This API can be quite slow if used with an FTS5 table created with the
184101 ** "detail=none" option. If the FTS5 table is created with either
184102 ** "detail=none" "content=" option (i.e. if it is a contentless table),
184103 ** then this API always iterates through an empty set (all calls to
184104 ** xPhraseFirstColumn() set iCol to -1).
184106 ** The information accessed using this API and its companion
184107 ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
184108 ** (or xInst/xInstCount). The chief advantage of this API is that it is
184109 ** significantly more efficient than those alternatives when used with
184110 ** "detail=column" tables.
184112 ** xPhraseNextColumn()
184113 ** See xPhraseFirstColumn above.
184115 struct Fts5ExtensionApi {
184116 int iVersion; /* Currently always set to 3 */
184118 void *(*xUserData)(Fts5Context*);
184120 int (*xColumnCount)(Fts5Context*);
184121 int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
184122 int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
184124 int (*xTokenize)(Fts5Context*,
184125 const char *pText, int nText, /* Text to tokenize */
184126 void *pCtx, /* Context passed to xToken() */
184127 int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
184130 int (*xPhraseCount)(Fts5Context*);
184131 int (*xPhraseSize)(Fts5Context*, int iPhrase);
184133 int (*xInstCount)(Fts5Context*, int *pnInst);
184134 int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
184136 sqlite3_int64 (*xRowid)(Fts5Context*);
184137 int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
184138 int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
184140 int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
184141 int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
184143 int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
184144 void *(*xGetAuxdata)(Fts5Context*, int bClear);
184146 int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
184147 void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
184149 int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
184150 void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
184154 ** CUSTOM AUXILIARY FUNCTIONS
184155 *************************************************************************/
184157 /*************************************************************************
184158 ** CUSTOM TOKENIZERS
184160 ** Applications may also register custom tokenizer types. A tokenizer
184161 ** is registered by providing fts5 with a populated instance of the
184162 ** following structure. All structure methods must be defined, setting
184163 ** any member of the fts5_tokenizer struct to NULL leads to undefined
184164 ** behaviour. The structure methods are expected to function as follows:
184166 ** xCreate:
184167 ** This function is used to allocate and initialize a tokenizer instance.
184168 ** A tokenizer instance is required to actually tokenize text.
184170 ** The first argument passed to this function is a copy of the (void*)
184171 ** pointer provided by the application when the fts5_tokenizer object
184172 ** was registered with FTS5 (the third argument to xCreateTokenizer()).
184173 ** The second and third arguments are an array of nul-terminated strings
184174 ** containing the tokenizer arguments, if any, specified following the
184175 ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
184176 ** to create the FTS5 table.
184178 ** The final argument is an output variable. If successful, (*ppOut)
184179 ** should be set to point to the new tokenizer handle and SQLITE_OK
184180 ** returned. If an error occurs, some value other than SQLITE_OK should
184181 ** be returned. In this case, fts5 assumes that the final value of *ppOut
184182 ** is undefined.
184184 ** xDelete:
184185 ** This function is invoked to delete a tokenizer handle previously
184186 ** allocated using xCreate(). Fts5 guarantees that this function will
184187 ** be invoked exactly once for each successful call to xCreate().
184189 ** xTokenize:
184190 ** This function is expected to tokenize the nText byte string indicated
184191 ** by argument pText. pText may or may not be nul-terminated. The first
184192 ** argument passed to this function is a pointer to an Fts5Tokenizer object
184193 ** returned by an earlier call to xCreate().
184195 ** The second argument indicates the reason that FTS5 is requesting
184196 ** tokenization of the supplied text. This is always one of the following
184197 ** four values:
184199 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
184200 ** or removed from the FTS table. The tokenizer is being invoked to
184201 ** determine the set of tokens to add to (or delete from) the
184202 ** FTS index.
184204 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
184205 ** against the FTS index. The tokenizer is being called to tokenize
184206 ** a bareword or quoted string specified as part of the query.
184208 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
184209 ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
184210 ** followed by a "*" character, indicating that the last token
184211 ** returned by the tokenizer will be treated as a token prefix.
184213 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
184214 ** satisfy an fts5_api.xTokenize() request made by an auxiliary
184215 ** function. Or an fts5_api.xColumnSize() request made by the same
184216 ** on a columnsize=0 database.
184217 ** </ul>
184219 ** For each token in the input string, the supplied callback xToken() must
184220 ** be invoked. The first argument to it should be a copy of the pointer
184221 ** passed as the second argument to xTokenize(). The third and fourth
184222 ** arguments are a pointer to a buffer containing the token text, and the
184223 ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
184224 ** of the first byte of and first byte immediately following the text from
184225 ** which the token is derived within the input.
184227 ** The second argument passed to the xToken() callback ("tflags") should
184228 ** normally be set to 0. The exception is if the tokenizer supports
184229 ** synonyms. In this case see the discussion below for details.
184231 ** FTS5 assumes the xToken() callback is invoked for each token in the
184232 ** order that they occur within the input text.
184234 ** If an xToken() callback returns any value other than SQLITE_OK, then
184235 ** the tokenization should be abandoned and the xTokenize() method should
184236 ** immediately return a copy of the xToken() return value. Or, if the
184237 ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
184238 ** if an error occurs with the xTokenize() implementation itself, it
184239 ** may abandon the tokenization and return any error code other than
184240 ** SQLITE_OK or SQLITE_DONE.
184242 ** SYNONYM SUPPORT
184244 ** Custom tokenizers may also support synonyms. Consider a case in which a
184245 ** user wishes to query for a phrase such as "first place". Using the
184246 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
184247 ** of "first place" within the document set, but not alternative forms
184248 ** such as "1st place". In some applications, it would be better to match
184249 ** all instances of "first place" or "1st place" regardless of which form
184250 ** the user specified in the MATCH query text.
184252 ** There are several ways to approach this in FTS5:
184254 ** <ol><li> By mapping all synonyms to a single token. In this case, the
184255 ** In the above example, this means that the tokenizer returns the
184256 ** same token for inputs "first" and "1st". Say that token is in
184257 ** fact "first", so that when the user inserts the document "I won
184258 ** 1st place" entries are added to the index for tokens "i", "won",
184259 ** "first" and "place". If the user then queries for '1st + place',
184260 ** the tokenizer substitutes "first" for "1st" and the query works
184261 ** as expected.
184263 ** <li> By adding multiple synonyms for a single term to the FTS index.
184264 ** In this case, when tokenizing query text, the tokenizer may
184265 ** provide multiple synonyms for a single term within the document.
184266 ** FTS5 then queries the index for each synonym individually. For
184267 ** example, faced with the query:
184269 ** <codeblock>
184270 ** ... MATCH 'first place'</codeblock>
184272 ** the tokenizer offers both "1st" and "first" as synonyms for the
184273 ** first token in the MATCH query and FTS5 effectively runs a query
184274 ** similar to:
184276 ** <codeblock>
184277 ** ... MATCH '(first OR 1st) place'</codeblock>
184279 ** except that, for the purposes of auxiliary functions, the query
184280 ** still appears to contain just two phrases - "(first OR 1st)"
184281 ** being treated as a single phrase.
184283 ** <li> By adding multiple synonyms for a single term to the FTS index.
184284 ** Using this method, when tokenizing document text, the tokenizer
184285 ** provides multiple synonyms for each token. So that when a
184286 ** document such as "I won first place" is tokenized, entries are
184287 ** added to the FTS index for "i", "won", "first", "1st" and
184288 ** "place".
184290 ** This way, even if the tokenizer does not provide synonyms
184291 ** when tokenizing query text (it should not - to do would be
184292 ** inefficient), it doesn't matter if the user queries for
184293 ** 'first + place' or '1st + place', as there are entires in the
184294 ** FTS index corresponding to both forms of the first token.
184295 ** </ol>
184297 ** Whether it is parsing document or query text, any call to xToken that
184298 ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
184299 ** is considered to supply a synonym for the previous token. For example,
184300 ** when parsing the document "I won first place", a tokenizer that supports
184301 ** synonyms would call xToken() 5 times, as follows:
184303 ** <codeblock>
184304 ** xToken(pCtx, 0, "i", 1, 0, 1);
184305 ** xToken(pCtx, 0, "won", 3, 2, 5);
184306 ** xToken(pCtx, 0, "first", 5, 6, 11);
184307 ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
184308 ** xToken(pCtx, 0, "place", 5, 12, 17);
184309 **</codeblock>
184311 ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
184312 ** xToken() is called. Multiple synonyms may be specified for a single token
184313 ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
184314 ** There is no limit to the number of synonyms that may be provided for a
184315 ** single token.
184317 ** In many cases, method (1) above is the best approach. It does not add
184318 ** extra data to the FTS index or require FTS5 to query for multiple terms,
184319 ** so it is efficient in terms of disk space and query speed. However, it
184320 ** does not support prefix queries very well. If, as suggested above, the
184321 ** token "first" is subsituted for "1st" by the tokenizer, then the query:
184323 ** <codeblock>
184324 ** ... MATCH '1s*'</codeblock>
184326 ** will not match documents that contain the token "1st" (as the tokenizer
184327 ** will probably not map "1s" to any prefix of "first").
184329 ** For full prefix support, method (3) may be preferred. In this case,
184330 ** because the index contains entries for both "first" and "1st", prefix
184331 ** queries such as 'fi*' or '1s*' will match correctly. However, because
184332 ** extra entries are added to the FTS index, this method uses more space
184333 ** within the database.
184335 ** Method (2) offers a midpoint between (1) and (3). Using this method,
184336 ** a query such as '1s*' will match documents that contain the literal
184337 ** token "1st", but not "first" (assuming the tokenizer is not able to
184338 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
184339 ** will match against "1st" and "first". This method does not require
184340 ** extra disk space, as no extra entries are added to the FTS index.
184341 ** On the other hand, it may require more CPU cycles to run MATCH queries,
184342 ** as separate queries of the FTS index are required for each synonym.
184344 ** When using methods (2) or (3), it is important that the tokenizer only
184345 ** provide synonyms when tokenizing document text (method (2)) or query
184346 ** text (method (3)), not both. Doing so will not cause any errors, but is
184347 ** inefficient.
184349 typedef struct Fts5Tokenizer Fts5Tokenizer;
184350 typedef struct fts5_tokenizer fts5_tokenizer;
184351 struct fts5_tokenizer {
184352 int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
184353 void (*xDelete)(Fts5Tokenizer*);
184354 int (*xTokenize)(Fts5Tokenizer*,
184355 void *pCtx,
184356 int flags, /* Mask of FTS5_TOKENIZE_* flags */
184357 const char *pText, int nText,
184358 int (*xToken)(
184359 void *pCtx, /* Copy of 2nd argument to xTokenize() */
184360 int tflags, /* Mask of FTS5_TOKEN_* flags */
184361 const char *pToken, /* Pointer to buffer containing token */
184362 int nToken, /* Size of token in bytes */
184363 int iStart, /* Byte offset of token within input text */
184364 int iEnd /* Byte offset of end of token within input text */
184369 /* Flags that may be passed as the third argument to xTokenize() */
184370 #define FTS5_TOKENIZE_QUERY 0x0001
184371 #define FTS5_TOKENIZE_PREFIX 0x0002
184372 #define FTS5_TOKENIZE_DOCUMENT 0x0004
184373 #define FTS5_TOKENIZE_AUX 0x0008
184375 /* Flags that may be passed by the tokenizer implementation back to FTS5
184376 ** as the third argument to the supplied xToken callback. */
184377 #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
184380 ** END OF CUSTOM TOKENIZERS
184381 *************************************************************************/
184383 /*************************************************************************
184384 ** FTS5 EXTENSION REGISTRATION API
184386 typedef struct fts5_api fts5_api;
184387 struct fts5_api {
184388 int iVersion; /* Currently always set to 2 */
184390 /* Create a new tokenizer */
184391 int (*xCreateTokenizer)(
184392 fts5_api *pApi,
184393 const char *zName,
184394 void *pContext,
184395 fts5_tokenizer *pTokenizer,
184396 void (*xDestroy)(void*)
184399 /* Find an existing tokenizer */
184400 int (*xFindTokenizer)(
184401 fts5_api *pApi,
184402 const char *zName,
184403 void **ppContext,
184404 fts5_tokenizer *pTokenizer
184407 /* Create a new auxiliary function */
184408 int (*xCreateFunction)(
184409 fts5_api *pApi,
184410 const char *zName,
184411 void *pContext,
184412 fts5_extension_function xFunction,
184413 void (*xDestroy)(void*)
184418 ** END OF REGISTRATION API
184419 *************************************************************************/
184421 #if 0
184422 } /* end of the 'extern "C"' block */
184423 #endif
184425 #endif /* _FTS5_H */
184428 ** 2014 May 31
184430 ** The author disclaims copyright to this source code. In place of
184431 ** a legal notice, here is a blessing:
184433 ** May you do good and not evil.
184434 ** May you find forgiveness for yourself and forgive others.
184435 ** May you share freely, never taking more than you give.
184437 ******************************************************************************
184440 #ifndef _FTS5INT_H
184441 #define _FTS5INT_H
184443 /* #include "fts5.h" */
184444 /* #include "sqlite3ext.h" */
184445 SQLITE_EXTENSION_INIT1
184447 /* #include <string.h> */
184448 /* #include <assert.h> */
184450 #ifndef SQLITE_AMALGAMATION
184452 typedef unsigned char u8;
184453 typedef unsigned int u32;
184454 typedef unsigned short u16;
184455 typedef short i16;
184456 typedef sqlite3_int64 i64;
184457 typedef sqlite3_uint64 u64;
184459 #ifndef ArraySize
184460 # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
184461 #endif
184463 #define testcase(x)
184464 #define ALWAYS(x) 1
184465 #define NEVER(x) 0
184467 #define MIN(x,y) (((x) < (y)) ? (x) : (y))
184468 #define MAX(x,y) (((x) > (y)) ? (x) : (y))
184471 ** Constants for the largest and smallest possible 64-bit signed integers.
184473 # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
184474 # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
184476 #endif
184478 /* Truncate very long tokens to this many bytes. Hard limit is
184479 ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
184480 ** field that occurs at the start of each leaf page (see fts5_index.c). */
184481 #define FTS5_MAX_TOKEN_SIZE 32768
184484 ** Maximum number of prefix indexes on single FTS5 table. This must be
184485 ** less than 32. If it is set to anything large than that, an #error
184486 ** directive in fts5_index.c will cause the build to fail.
184488 #define FTS5_MAX_PREFIX_INDEXES 31
184490 #define FTS5_DEFAULT_NEARDIST 10
184491 #define FTS5_DEFAULT_RANK "bm25"
184493 /* Name of rank and rowid columns */
184494 #define FTS5_RANK_NAME "rank"
184495 #define FTS5_ROWID_NAME "rowid"
184497 #ifdef SQLITE_DEBUG
184498 # define FTS5_CORRUPT sqlite3Fts5Corrupt()
184499 static int sqlite3Fts5Corrupt(void);
184500 #else
184501 # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
184502 #endif
184505 ** The assert_nc() macro is similar to the assert() macro, except that it
184506 ** is used for assert() conditions that are true only if it can be
184507 ** guranteed that the database is not corrupt.
184509 #ifdef SQLITE_DEBUG
184510 SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
184511 # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
184512 #else
184513 # define assert_nc(x) assert(x)
184514 #endif
184516 /* Mark a function parameter as unused, to suppress nuisance compiler
184517 ** warnings. */
184518 #ifndef UNUSED_PARAM
184519 # define UNUSED_PARAM(X) (void)(X)
184520 #endif
184522 #ifndef UNUSED_PARAM2
184523 # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
184524 #endif
184526 typedef struct Fts5Global Fts5Global;
184527 typedef struct Fts5Colset Fts5Colset;
184529 /* If a NEAR() clump or phrase may only match a specific set of columns,
184530 ** then an object of the following type is used to record the set of columns.
184531 ** Each entry in the aiCol[] array is a column that may be matched.
184533 ** This object is used by fts5_expr.c and fts5_index.c.
184535 struct Fts5Colset {
184536 int nCol;
184537 int aiCol[1];
184542 /**************************************************************************
184543 ** Interface to code in fts5_config.c. fts5_config.c contains contains code
184544 ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
184547 typedef struct Fts5Config Fts5Config;
184550 ** An instance of the following structure encodes all information that can
184551 ** be gleaned from the CREATE VIRTUAL TABLE statement.
184553 ** And all information loaded from the %_config table.
184555 ** nAutomerge:
184556 ** The minimum number of segments that an auto-merge operation should
184557 ** attempt to merge together. A value of 1 sets the object to use the
184558 ** compile time default. Zero disables auto-merge altogether.
184560 ** zContent:
184562 ** zContentRowid:
184563 ** The value of the content_rowid= option, if one was specified. Or
184564 ** the string "rowid" otherwise. This text is not quoted - if it is
184565 ** used as part of an SQL statement it needs to be quoted appropriately.
184567 ** zContentExprlist:
184569 ** pzErrmsg:
184570 ** This exists in order to allow the fts5_index.c module to return a
184571 ** decent error message if it encounters a file-format version it does
184572 ** not understand.
184574 ** bColumnsize:
184575 ** True if the %_docsize table is created.
184577 ** bPrefixIndex:
184578 ** This is only used for debugging. If set to false, any prefix indexes
184579 ** are ignored. This value is configured using:
184581 ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
184584 struct Fts5Config {
184585 sqlite3 *db; /* Database handle */
184586 char *zDb; /* Database holding FTS index (e.g. "main") */
184587 char *zName; /* Name of FTS index */
184588 int nCol; /* Number of columns */
184589 char **azCol; /* Column names */
184590 u8 *abUnindexed; /* True for unindexed columns */
184591 int nPrefix; /* Number of prefix indexes */
184592 int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
184593 int eContent; /* An FTS5_CONTENT value */
184594 char *zContent; /* content table */
184595 char *zContentRowid; /* "content_rowid=" option value */
184596 int bColumnsize; /* "columnsize=" option value (dflt==1) */
184597 int eDetail; /* FTS5_DETAIL_XXX value */
184598 char *zContentExprlist;
184599 Fts5Tokenizer *pTok;
184600 fts5_tokenizer *pTokApi;
184602 /* Values loaded from the %_config table */
184603 int iCookie; /* Incremented when %_config is modified */
184604 int pgsz; /* Approximate page size used in %_data */
184605 int nAutomerge; /* 'automerge' setting */
184606 int nCrisisMerge; /* Maximum allowed segments per level */
184607 int nUsermerge; /* 'usermerge' setting */
184608 int nHashSize; /* Bytes of memory for in-memory hash */
184609 char *zRank; /* Name of rank function */
184610 char *zRankArgs; /* Arguments to rank function */
184612 /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
184613 char **pzErrmsg;
184615 #ifdef SQLITE_DEBUG
184616 int bPrefixIndex; /* True to use prefix-indexes */
184617 #endif
184620 /* Current expected value of %_config table 'version' field */
184621 #define FTS5_CURRENT_VERSION 4
184623 #define FTS5_CONTENT_NORMAL 0
184624 #define FTS5_CONTENT_NONE 1
184625 #define FTS5_CONTENT_EXTERNAL 2
184627 #define FTS5_DETAIL_FULL 0
184628 #define FTS5_DETAIL_NONE 1
184629 #define FTS5_DETAIL_COLUMNS 2
184633 static int sqlite3Fts5ConfigParse(
184634 Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
184636 static void sqlite3Fts5ConfigFree(Fts5Config*);
184638 static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
184640 static int sqlite3Fts5Tokenize(
184641 Fts5Config *pConfig, /* FTS5 Configuration object */
184642 int flags, /* FTS5_TOKENIZE_* flags */
184643 const char *pText, int nText, /* Text to tokenize */
184644 void *pCtx, /* Context passed to xToken() */
184645 int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
184648 static void sqlite3Fts5Dequote(char *z);
184650 /* Load the contents of the %_config table */
184651 static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
184653 /* Set the value of a single config attribute */
184654 static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
184656 static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
184659 ** End of interface to code in fts5_config.c.
184660 **************************************************************************/
184662 /**************************************************************************
184663 ** Interface to code in fts5_buffer.c.
184667 ** Buffer object for the incremental building of string data.
184669 typedef struct Fts5Buffer Fts5Buffer;
184670 struct Fts5Buffer {
184671 u8 *p;
184672 int n;
184673 int nSpace;
184676 static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
184677 static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
184678 static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
184679 static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
184680 static void sqlite3Fts5BufferFree(Fts5Buffer*);
184681 static void sqlite3Fts5BufferZero(Fts5Buffer*);
184682 static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
184683 static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
184685 static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
184687 #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
184688 #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
184689 #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
184690 #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
184691 #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
184693 #define fts5BufferGrow(pRc,pBuf,nn) ( \
184694 (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
184695 sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
184698 /* Write and decode big-endian 32-bit integer values */
184699 static void sqlite3Fts5Put32(u8*, int);
184700 static int sqlite3Fts5Get32(const u8*);
184702 #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
184703 #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
184705 typedef struct Fts5PoslistReader Fts5PoslistReader;
184706 struct Fts5PoslistReader {
184707 /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
184708 const u8 *a; /* Position list to iterate through */
184709 int n; /* Size of buffer at a[] in bytes */
184710 int i; /* Current offset in a[] */
184712 u8 bFlag; /* For client use (any custom purpose) */
184714 /* Output variables */
184715 u8 bEof; /* Set to true at EOF */
184716 i64 iPos; /* (iCol<<32) + iPos */
184718 static int sqlite3Fts5PoslistReaderInit(
184719 const u8 *a, int n, /* Poslist buffer to iterate through */
184720 Fts5PoslistReader *pIter /* Iterator object to initialize */
184722 static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
184724 typedef struct Fts5PoslistWriter Fts5PoslistWriter;
184725 struct Fts5PoslistWriter {
184726 i64 iPrev;
184728 static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
184729 static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
184731 static int sqlite3Fts5PoslistNext64(
184732 const u8 *a, int n, /* Buffer containing poslist */
184733 int *pi, /* IN/OUT: Offset within a[] */
184734 i64 *piOff /* IN/OUT: Current offset */
184737 /* Malloc utility */
184738 static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
184739 static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
184741 /* Character set tests (like isspace(), isalpha() etc.) */
184742 static int sqlite3Fts5IsBareword(char t);
184745 /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
184746 typedef struct Fts5Termset Fts5Termset;
184747 static int sqlite3Fts5TermsetNew(Fts5Termset**);
184748 static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
184749 static void sqlite3Fts5TermsetFree(Fts5Termset*);
184752 ** End of interface to code in fts5_buffer.c.
184753 **************************************************************************/
184755 /**************************************************************************
184756 ** Interface to code in fts5_index.c. fts5_index.c contains contains code
184757 ** to access the data stored in the %_data table.
184760 typedef struct Fts5Index Fts5Index;
184761 typedef struct Fts5IndexIter Fts5IndexIter;
184763 struct Fts5IndexIter {
184764 i64 iRowid;
184765 const u8 *pData;
184766 int nData;
184767 u8 bEof;
184770 #define sqlite3Fts5IterEof(x) ((x)->bEof)
184773 ** Values used as part of the flags argument passed to IndexQuery().
184775 #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
184776 #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
184777 #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
184778 #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
184780 /* The following are used internally by the fts5_index.c module. They are
184781 ** defined here only to make it easier to avoid clashes with the flags
184782 ** above. */
184783 #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
184784 #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
184787 ** Create/destroy an Fts5Index object.
184789 static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
184790 static int sqlite3Fts5IndexClose(Fts5Index *p);
184793 ** Return a simple checksum value based on the arguments.
184795 static u64 sqlite3Fts5IndexEntryCksum(
184796 i64 iRowid,
184797 int iCol,
184798 int iPos,
184799 int iIdx,
184800 const char *pTerm,
184801 int nTerm
184805 ** Argument p points to a buffer containing utf-8 text that is n bytes in
184806 ** size. Return the number of bytes in the nChar character prefix of the
184807 ** buffer, or 0 if there are less than nChar characters in total.
184809 static int sqlite3Fts5IndexCharlenToBytelen(
184810 const char *p,
184811 int nByte,
184812 int nChar
184816 ** Open a new iterator to iterate though all rowids that match the
184817 ** specified token or token prefix.
184819 static int sqlite3Fts5IndexQuery(
184820 Fts5Index *p, /* FTS index to query */
184821 const char *pToken, int nToken, /* Token (or prefix) to query for */
184822 int flags, /* Mask of FTS5INDEX_QUERY_X flags */
184823 Fts5Colset *pColset, /* Match these columns only */
184824 Fts5IndexIter **ppIter /* OUT: New iterator object */
184828 ** The various operations on open token or token prefix iterators opened
184829 ** using sqlite3Fts5IndexQuery().
184831 static int sqlite3Fts5IterNext(Fts5IndexIter*);
184832 static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
184835 ** Close an iterator opened by sqlite3Fts5IndexQuery().
184837 static void sqlite3Fts5IterClose(Fts5IndexIter*);
184840 ** This interface is used by the fts5vocab module.
184842 static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
184843 static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
184847 ** Insert or remove data to or from the index. Each time a document is
184848 ** added to or removed from the index, this function is called one or more
184849 ** times.
184851 ** For an insert, it must be called once for each token in the new document.
184852 ** If the operation is a delete, it must be called (at least) once for each
184853 ** unique token in the document with an iCol value less than zero. The iPos
184854 ** argument is ignored for a delete.
184856 static int sqlite3Fts5IndexWrite(
184857 Fts5Index *p, /* Index to write to */
184858 int iCol, /* Column token appears in (-ve -> delete) */
184859 int iPos, /* Position of token within column */
184860 const char *pToken, int nToken /* Token to add or remove to or from index */
184864 ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
184865 ** document iDocid.
184867 static int sqlite3Fts5IndexBeginWrite(
184868 Fts5Index *p, /* Index to write to */
184869 int bDelete, /* True if current operation is a delete */
184870 i64 iDocid /* Docid to add or remove data from */
184874 ** Flush any data stored in the in-memory hash tables to the database.
184875 ** Also close any open blob handles.
184877 static int sqlite3Fts5IndexSync(Fts5Index *p);
184880 ** Discard any data stored in the in-memory hash tables. Do not write it
184881 ** to the database. Additionally, assume that the contents of the %_data
184882 ** table may have changed on disk. So any in-memory caches of %_data
184883 ** records must be invalidated.
184885 static int sqlite3Fts5IndexRollback(Fts5Index *p);
184888 ** Get or set the "averages" values.
184890 static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
184891 static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
184894 ** Functions called by the storage module as part of integrity-check.
184896 static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
184899 ** Called during virtual module initialization to register UDF
184900 ** fts5_decode() with SQLite
184902 static int sqlite3Fts5IndexInit(sqlite3*);
184904 static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
184907 ** Return the total number of entries read from the %_data table by
184908 ** this connection since it was created.
184910 static int sqlite3Fts5IndexReads(Fts5Index *p);
184912 static int sqlite3Fts5IndexReinit(Fts5Index *p);
184913 static int sqlite3Fts5IndexOptimize(Fts5Index *p);
184914 static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
184915 static int sqlite3Fts5IndexReset(Fts5Index *p);
184917 static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
184920 ** End of interface to code in fts5_index.c.
184921 **************************************************************************/
184923 /**************************************************************************
184924 ** Interface to code in fts5_varint.c.
184926 static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
184927 static int sqlite3Fts5GetVarintLen(u32 iVal);
184928 static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
184929 static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
184931 #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
184932 #define fts5GetVarint sqlite3Fts5GetVarint
184934 #define fts5FastGetVarint32(a, iOff, nVal) { \
184935 nVal = (a)[iOff++]; \
184936 if( nVal & 0x80 ){ \
184937 iOff--; \
184938 iOff += fts5GetVarint32(&(a)[iOff], nVal); \
184944 ** End of interface to code in fts5_varint.c.
184945 **************************************************************************/
184948 /**************************************************************************
184949 ** Interface to code in fts5.c.
184952 static int sqlite3Fts5GetTokenizer(
184953 Fts5Global*,
184954 const char **azArg,
184955 int nArg,
184956 Fts5Tokenizer**,
184957 fts5_tokenizer**,
184958 char **pzErr
184961 static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
184964 ** End of interface to code in fts5.c.
184965 **************************************************************************/
184967 /**************************************************************************
184968 ** Interface to code in fts5_hash.c.
184970 typedef struct Fts5Hash Fts5Hash;
184973 ** Create a hash table, free a hash table.
184975 static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
184976 static void sqlite3Fts5HashFree(Fts5Hash*);
184978 static int sqlite3Fts5HashWrite(
184979 Fts5Hash*,
184980 i64 iRowid, /* Rowid for this entry */
184981 int iCol, /* Column token appears in (-ve -> delete) */
184982 int iPos, /* Position of token within column */
184983 char bByte,
184984 const char *pToken, int nToken /* Token to add or remove to or from index */
184988 ** Empty (but do not delete) a hash table.
184990 static void sqlite3Fts5HashClear(Fts5Hash*);
184992 static int sqlite3Fts5HashQuery(
184993 Fts5Hash*, /* Hash table to query */
184994 const char *pTerm, int nTerm, /* Query term */
184995 const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
184996 int *pnDoclist /* OUT: Size of doclist in bytes */
184999 static int sqlite3Fts5HashScanInit(
185000 Fts5Hash*, /* Hash table to query */
185001 const char *pTerm, int nTerm /* Query prefix */
185003 static void sqlite3Fts5HashScanNext(Fts5Hash*);
185004 static int sqlite3Fts5HashScanEof(Fts5Hash*);
185005 static void sqlite3Fts5HashScanEntry(Fts5Hash *,
185006 const char **pzTerm, /* OUT: term (nul-terminated) */
185007 const u8 **ppDoclist, /* OUT: pointer to doclist */
185008 int *pnDoclist /* OUT: size of doclist in bytes */
185013 ** End of interface to code in fts5_hash.c.
185014 **************************************************************************/
185016 /**************************************************************************
185017 ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
185018 ** code to access the data stored in the %_content and %_docsize tables.
185021 #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
185022 #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
185023 #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
185025 typedef struct Fts5Storage Fts5Storage;
185027 static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
185028 static int sqlite3Fts5StorageClose(Fts5Storage *p);
185029 static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
185031 static int sqlite3Fts5DropAll(Fts5Config*);
185032 static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
185034 static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
185035 static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
185036 static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
185038 static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
185040 static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
185041 static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
185043 static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
185044 static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
185045 static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
185047 static int sqlite3Fts5StorageSync(Fts5Storage *p);
185048 static int sqlite3Fts5StorageRollback(Fts5Storage *p);
185050 static int sqlite3Fts5StorageConfigValue(
185051 Fts5Storage *p, const char*, sqlite3_value*, int
185054 static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
185055 static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
185056 static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
185057 static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
185058 static int sqlite3Fts5StorageReset(Fts5Storage *p);
185061 ** End of interface to code in fts5_storage.c.
185062 **************************************************************************/
185065 /**************************************************************************
185066 ** Interface to code in fts5_expr.c.
185068 typedef struct Fts5Expr Fts5Expr;
185069 typedef struct Fts5ExprNode Fts5ExprNode;
185070 typedef struct Fts5Parse Fts5Parse;
185071 typedef struct Fts5Token Fts5Token;
185072 typedef struct Fts5ExprPhrase Fts5ExprPhrase;
185073 typedef struct Fts5ExprNearset Fts5ExprNearset;
185075 struct Fts5Token {
185076 const char *p; /* Token text (not NULL terminated) */
185077 int n; /* Size of buffer p in bytes */
185080 /* Parse a MATCH expression. */
185081 static int sqlite3Fts5ExprNew(
185082 Fts5Config *pConfig,
185083 int iCol, /* Column on LHS of MATCH operator */
185084 const char *zExpr,
185085 Fts5Expr **ppNew,
185086 char **pzErr
185090 ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
185091 ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
185092 ** rc = sqlite3Fts5ExprNext(pExpr)
185093 ** ){
185094 ** // The document with rowid iRowid matches the expression!
185095 ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
185098 static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
185099 static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
185100 static int sqlite3Fts5ExprEof(Fts5Expr*);
185101 static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
185103 static void sqlite3Fts5ExprFree(Fts5Expr*);
185105 /* Called during startup to register a UDF with SQLite */
185106 static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
185108 static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
185109 static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
185110 static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
185112 typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
185113 static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
185114 static int sqlite3Fts5ExprPopulatePoslists(
185115 Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
185117 static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
185119 static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
185121 static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
185123 /*******************************************
185124 ** The fts5_expr.c API above this point is used by the other hand-written
185125 ** C code in this module. The interfaces below this point are called by
185126 ** the parser code in fts5parse.y. */
185128 static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
185130 static Fts5ExprNode *sqlite3Fts5ParseNode(
185131 Fts5Parse *pParse,
185132 int eType,
185133 Fts5ExprNode *pLeft,
185134 Fts5ExprNode *pRight,
185135 Fts5ExprNearset *pNear
185138 static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
185139 Fts5Parse *pParse,
185140 Fts5ExprNode *pLeft,
185141 Fts5ExprNode *pRight
185144 static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
185145 Fts5Parse *pParse,
185146 Fts5ExprPhrase *pPhrase,
185147 Fts5Token *pToken,
185148 int bPrefix
185151 static Fts5ExprNearset *sqlite3Fts5ParseNearset(
185152 Fts5Parse*,
185153 Fts5ExprNearset*,
185154 Fts5ExprPhrase*
185157 static Fts5Colset *sqlite3Fts5ParseColset(
185158 Fts5Parse*,
185159 Fts5Colset*,
185160 Fts5Token *
185163 static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
185164 static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
185165 static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
185167 static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
185168 static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
185169 static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
185170 static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
185171 static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
185174 ** End of interface to code in fts5_expr.c.
185175 **************************************************************************/
185179 /**************************************************************************
185180 ** Interface to code in fts5_aux.c.
185183 static int sqlite3Fts5AuxInit(fts5_api*);
185185 ** End of interface to code in fts5_aux.c.
185186 **************************************************************************/
185188 /**************************************************************************
185189 ** Interface to code in fts5_tokenizer.c.
185192 static int sqlite3Fts5TokenizerInit(fts5_api*);
185194 ** End of interface to code in fts5_tokenizer.c.
185195 **************************************************************************/
185197 /**************************************************************************
185198 ** Interface to code in fts5_vocab.c.
185201 static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
185204 ** End of interface to code in fts5_vocab.c.
185205 **************************************************************************/
185208 /**************************************************************************
185209 ** Interface to automatically generated code in fts5_unicode2.c.
185211 static int sqlite3Fts5UnicodeIsalnum(int c);
185212 static int sqlite3Fts5UnicodeIsdiacritic(int c);
185213 static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
185215 ** End of interface to code in fts5_unicode2.c.
185216 **************************************************************************/
185218 #endif
185220 #define FTS5_OR 1
185221 #define FTS5_AND 2
185222 #define FTS5_NOT 3
185223 #define FTS5_TERM 4
185224 #define FTS5_COLON 5
185225 #define FTS5_MINUS 6
185226 #define FTS5_LCP 7
185227 #define FTS5_RCP 8
185228 #define FTS5_STRING 9
185229 #define FTS5_LP 10
185230 #define FTS5_RP 11
185231 #define FTS5_COMMA 12
185232 #define FTS5_PLUS 13
185233 #define FTS5_STAR 14
185236 ** 2000-05-29
185238 ** The author disclaims copyright to this source code. In place of
185239 ** a legal notice, here is a blessing:
185241 ** May you do good and not evil.
185242 ** May you find forgiveness for yourself and forgive others.
185243 ** May you share freely, never taking more than you give.
185245 *************************************************************************
185246 ** Driver template for the LEMON parser generator.
185248 ** The "lemon" program processes an LALR(1) input grammar file, then uses
185249 ** this template to construct a parser. The "lemon" program inserts text
185250 ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
185251 ** interstitial "-" characters) contained in this template is changed into
185252 ** the value of the %name directive from the grammar. Otherwise, the content
185253 ** of this template is copied straight through into the generate parser
185254 ** source file.
185256 ** The following is the concatenation of all %include directives from the
185257 ** input grammar file:
185259 /* #include <stdio.h> */
185260 /************ Begin %include sections from the grammar ************************/
185262 /* #include "fts5Int.h" */
185263 /* #include "fts5parse.h" */
185266 ** Disable all error recovery processing in the parser push-down
185267 ** automaton.
185269 #define fts5YYNOERRORRECOVERY 1
185272 ** Make fts5yytestcase() the same as testcase()
185274 #define fts5yytestcase(X) testcase(X)
185277 ** Indicate that sqlite3ParserFree() will never be called with a null
185278 ** pointer.
185280 #define fts5YYPARSEFREENOTNULL 1
185283 ** Alternative datatype for the argument to the malloc() routine passed
185284 ** into sqlite3ParserAlloc(). The default is size_t.
185286 #define fts5YYMALLOCARGTYPE u64
185288 /**************** End of %include directives **********************************/
185289 /* These constants specify the various numeric values for terminal symbols
185290 ** in a format understandable to "makeheaders". This section is blank unless
185291 ** "lemon" is run with the "-m" command-line option.
185292 ***************** Begin makeheaders token definitions *************************/
185293 /**************** End makeheaders token definitions ***************************/
185295 /* The next sections is a series of control #defines.
185296 ** various aspects of the generated parser.
185297 ** fts5YYCODETYPE is the data type used to store the integer codes
185298 ** that represent terminal and non-terminal symbols.
185299 ** "unsigned char" is used if there are fewer than
185300 ** 256 symbols. Larger types otherwise.
185301 ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
185302 ** any terminal or nonterminal symbol.
185303 ** fts5YYFALLBACK If defined, this indicates that one or more tokens
185304 ** (also known as: "terminal symbols") have fall-back
185305 ** values which should be used if the original symbol
185306 ** would not parse. This permits keywords to sometimes
185307 ** be used as identifiers, for example.
185308 ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
185309 ** that indicate what to do in response to the next
185310 ** token.
185311 ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
185312 ** symbols. Background: A "minor type" is a semantic
185313 ** value associated with a terminal or non-terminal
185314 ** symbols. For example, for an "ID" terminal symbol,
185315 ** the minor type might be the name of the identifier.
185316 ** Each non-terminal can have a different minor type.
185317 ** Terminal symbols all have the same minor type, though.
185318 ** This macros defines the minor type for terminal
185319 ** symbols.
185320 ** fts5YYMINORTYPE is the data type used for all minor types.
185321 ** This is typically a union of many types, one of
185322 ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
185323 ** for terminal symbols is called "fts5yy0".
185324 ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
185325 ** zero the stack is dynamically sized using realloc()
185326 ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
185327 ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
185328 ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
185329 ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
185330 ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
185331 ** defined, then do no error processing.
185332 ** fts5YYNSTATE the combined number of states.
185333 ** fts5YYNRULE the number of rules in the grammar
185334 ** fts5YY_MAX_SHIFT Maximum value for shift actions
185335 ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
185336 ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
185337 ** fts5YY_MIN_REDUCE Minimum value for reduce actions
185338 ** fts5YY_MAX_REDUCE Maximum value for reduce actions
185339 ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
185340 ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
185341 ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
185343 #ifndef INTERFACE
185344 # define INTERFACE 1
185345 #endif
185346 /************* Begin control #defines *****************************************/
185347 #define fts5YYCODETYPE unsigned char
185348 #define fts5YYNOCODE 28
185349 #define fts5YYACTIONTYPE unsigned char
185350 #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
185351 typedef union {
185352 int fts5yyinit;
185353 sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
185354 int fts5yy4;
185355 Fts5Colset* fts5yy11;
185356 Fts5ExprNode* fts5yy24;
185357 Fts5ExprNearset* fts5yy46;
185358 Fts5ExprPhrase* fts5yy53;
185359 } fts5YYMINORTYPE;
185360 #ifndef fts5YYSTACKDEPTH
185361 #define fts5YYSTACKDEPTH 100
185362 #endif
185363 #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
185364 #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
185365 #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
185366 #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
185367 #define fts5YYNSTATE 33
185368 #define fts5YYNRULE 27
185369 #define fts5YY_MAX_SHIFT 32
185370 #define fts5YY_MIN_SHIFTREDUCE 50
185371 #define fts5YY_MAX_SHIFTREDUCE 76
185372 #define fts5YY_MIN_REDUCE 77
185373 #define fts5YY_MAX_REDUCE 103
185374 #define fts5YY_ERROR_ACTION 104
185375 #define fts5YY_ACCEPT_ACTION 105
185376 #define fts5YY_NO_ACTION 106
185377 /************* End control #defines *******************************************/
185379 /* Define the fts5yytestcase() macro to be a no-op if is not already defined
185380 ** otherwise.
185382 ** Applications can choose to define fts5yytestcase() in the %include section
185383 ** to a macro that can assist in verifying code coverage. For production
185384 ** code the fts5yytestcase() macro should be turned off. But it is useful
185385 ** for testing.
185387 #ifndef fts5yytestcase
185388 # define fts5yytestcase(X)
185389 #endif
185392 /* Next are the tables used to determine what action to take based on the
185393 ** current state and lookahead token. These tables are used to implement
185394 ** functions that take a state number and lookahead value and return an
185395 ** action integer.
185397 ** Suppose the action integer is N. Then the action is determined as
185398 ** follows
185400 ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
185401 ** token onto the stack and goto state N.
185403 ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
185404 ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
185406 ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
185407 ** and fts5YY_MAX_REDUCE
185409 ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
185411 ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
185413 ** N == fts5YY_NO_ACTION No such action. Denotes unused
185414 ** slots in the fts5yy_action[] table.
185416 ** The action table is constructed as a single large table named fts5yy_action[].
185417 ** Given state S and lookahead X, the action is computed as either:
185419 ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
185420 ** (B) N = fts5yy_default[S]
185422 ** The (A) formula is preferred. The B formula is used instead if:
185423 ** (1) The fts5yy_shift_ofst[S]+X value is out of range, or
185424 ** (2) fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X, or
185425 ** (3) fts5yy_shift_ofst[S] equal fts5YY_SHIFT_USE_DFLT.
185426 ** (Implementation note: fts5YY_SHIFT_USE_DFLT is chosen so that
185427 ** fts5YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
185428 ** Hence only tests (1) and (2) need to be evaluated.)
185430 ** The formulas above are for computing the action when the lookahead is
185431 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
185432 ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
185433 ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
185434 ** fts5YY_SHIFT_USE_DFLT.
185436 ** The following are the tables generated in this section:
185438 ** fts5yy_action[] A single table containing all actions.
185439 ** fts5yy_lookahead[] A table containing the lookahead for each entry in
185440 ** fts5yy_action. Used to detect hash collisions.
185441 ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
185442 ** shifting terminals.
185443 ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
185444 ** shifting non-terminals after a reduce.
185445 ** fts5yy_default[] Default action for each state.
185447 *********** Begin parsing tables **********************************************/
185448 #define fts5YY_ACTTAB_COUNT (98)
185449 static const fts5YYACTIONTYPE fts5yy_action[] = {
185450 /* 0 */ 105, 19, 90, 6, 26, 93, 92, 24, 24, 17,
185451 /* 10 */ 90, 6, 26, 16, 92, 54, 24, 18, 90, 6,
185452 /* 20 */ 26, 10, 92, 12, 24, 75, 86, 90, 6, 26,
185453 /* 30 */ 13, 92, 75, 24, 20, 90, 6, 26, 101, 92,
185454 /* 40 */ 56, 24, 27, 90, 6, 26, 100, 92, 21, 24,
185455 /* 50 */ 23, 15, 30, 11, 1, 91, 22, 25, 9, 92,
185456 /* 60 */ 7, 24, 3, 4, 5, 3, 4, 5, 3, 77,
185457 /* 70 */ 4, 5, 3, 61, 23, 15, 60, 11, 80, 12,
185458 /* 80 */ 2, 13, 68, 10, 29, 52, 55, 75, 31, 32,
185459 /* 90 */ 8, 28, 5, 3, 51, 55, 72, 14,
185461 static const fts5YYCODETYPE fts5yy_lookahead[] = {
185462 /* 0 */ 16, 17, 18, 19, 20, 22, 22, 24, 24, 17,
185463 /* 10 */ 18, 19, 20, 7, 22, 9, 24, 17, 18, 19,
185464 /* 20 */ 20, 10, 22, 9, 24, 14, 17, 18, 19, 20,
185465 /* 30 */ 9, 22, 14, 24, 17, 18, 19, 20, 26, 22,
185466 /* 40 */ 9, 24, 17, 18, 19, 20, 26, 22, 21, 24,
185467 /* 50 */ 6, 7, 13, 9, 10, 18, 21, 20, 5, 22,
185468 /* 60 */ 5, 24, 3, 1, 2, 3, 1, 2, 3, 0,
185469 /* 70 */ 1, 2, 3, 11, 6, 7, 11, 9, 5, 9,
185470 /* 80 */ 10, 9, 11, 10, 12, 8, 9, 14, 24, 25,
185471 /* 90 */ 23, 24, 2, 3, 8, 9, 9, 9,
185473 #define fts5YY_SHIFT_USE_DFLT (98)
185474 #define fts5YY_SHIFT_COUNT (32)
185475 #define fts5YY_SHIFT_MIN (0)
185476 #define fts5YY_SHIFT_MAX (90)
185477 static const unsigned char fts5yy_shift_ofst[] = {
185478 /* 0 */ 44, 44, 44, 44, 44, 44, 68, 70, 72, 14,
185479 /* 10 */ 21, 73, 11, 18, 18, 31, 31, 62, 65, 69,
185480 /* 20 */ 90, 77, 86, 6, 39, 53, 55, 59, 39, 87,
185481 /* 30 */ 88, 39, 71,
185483 #define fts5YY_REDUCE_USE_DFLT (-18)
185484 #define fts5YY_REDUCE_COUNT (16)
185485 #define fts5YY_REDUCE_MIN (-17)
185486 #define fts5YY_REDUCE_MAX (67)
185487 static const signed char fts5yy_reduce_ofst[] = {
185488 /* 0 */ -16, -8, 0, 9, 17, 25, 37, -17, 64, -17,
185489 /* 10 */ 67, 12, 12, 12, 20, 27, 35,
185491 static const fts5YYACTIONTYPE fts5yy_default[] = {
185492 /* 0 */ 104, 104, 104, 104, 104, 104, 89, 104, 98, 104,
185493 /* 10 */ 104, 103, 103, 103, 103, 104, 104, 104, 104, 104,
185494 /* 20 */ 85, 104, 104, 104, 94, 104, 104, 84, 96, 104,
185495 /* 30 */ 104, 97, 104,
185497 /********** End of lemon-generated parsing tables *****************************/
185499 /* The next table maps tokens (terminal symbols) into fallback tokens.
185500 ** If a construct like the following:
185502 ** %fallback ID X Y Z.
185504 ** appears in the grammar, then ID becomes a fallback token for X, Y,
185505 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
185506 ** but it does not parse, the type of the token is changed to ID and
185507 ** the parse is retried before an error is thrown.
185509 ** This feature can be used, for example, to cause some keywords in a language
185510 ** to revert to identifiers if they keyword does not apply in the context where
185511 ** it appears.
185513 #ifdef fts5YYFALLBACK
185514 static const fts5YYCODETYPE fts5yyFallback[] = {
185516 #endif /* fts5YYFALLBACK */
185518 /* The following structure represents a single element of the
185519 ** parser's stack. Information stored includes:
185521 ** + The state number for the parser at this level of the stack.
185523 ** + The value of the token stored at this level of the stack.
185524 ** (In other words, the "major" token.)
185526 ** + The semantic value stored at this level of the stack. This is
185527 ** the information used by the action routines in the grammar.
185528 ** It is sometimes called the "minor" token.
185530 ** After the "shift" half of a SHIFTREDUCE action, the stateno field
185531 ** actually contains the reduce action for the second half of the
185532 ** SHIFTREDUCE.
185534 struct fts5yyStackEntry {
185535 fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
185536 fts5YYCODETYPE major; /* The major token value. This is the code
185537 ** number for the token at this stack level */
185538 fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
185539 ** is the value of the token */
185541 typedef struct fts5yyStackEntry fts5yyStackEntry;
185543 /* The state of the parser is completely contained in an instance of
185544 ** the following structure */
185545 struct fts5yyParser {
185546 fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
185547 #ifdef fts5YYTRACKMAXSTACKDEPTH
185548 int fts5yyhwm; /* High-water mark of the stack */
185549 #endif
185550 #ifndef fts5YYNOERRORRECOVERY
185551 int fts5yyerrcnt; /* Shifts left before out of the error */
185552 #endif
185553 sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
185554 #if fts5YYSTACKDEPTH<=0
185555 int fts5yystksz; /* Current side of the stack */
185556 fts5yyStackEntry *fts5yystack; /* The parser's stack */
185557 fts5yyStackEntry fts5yystk0; /* First stack entry */
185558 #else
185559 fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
185560 fts5yyStackEntry *fts5yystackEnd; /* Last entry in the stack */
185561 #endif
185563 typedef struct fts5yyParser fts5yyParser;
185565 #ifndef NDEBUG
185566 /* #include <stdio.h> */
185567 static FILE *fts5yyTraceFILE = 0;
185568 static char *fts5yyTracePrompt = 0;
185569 #endif /* NDEBUG */
185571 #ifndef NDEBUG
185573 ** Turn parser tracing on by giving a stream to which to write the trace
185574 ** and a prompt to preface each trace message. Tracing is turned off
185575 ** by making either argument NULL
185577 ** Inputs:
185578 ** <ul>
185579 ** <li> A FILE* to which trace output should be written.
185580 ** If NULL, then tracing is turned off.
185581 ** <li> A prefix string written at the beginning of every
185582 ** line of trace output. If NULL, then tracing is
185583 ** turned off.
185584 ** </ul>
185586 ** Outputs:
185587 ** None.
185589 static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
185590 fts5yyTraceFILE = TraceFILE;
185591 fts5yyTracePrompt = zTracePrompt;
185592 if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
185593 else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
185595 #endif /* NDEBUG */
185597 #ifndef NDEBUG
185598 /* For tracing shifts, the names of all terminals and nonterminals
185599 ** are required. The following table supplies these names */
185600 static const char *const fts5yyTokenName[] = {
185601 "$", "OR", "AND", "NOT",
185602 "TERM", "COLON", "MINUS", "LCP",
185603 "RCP", "STRING", "LP", "RP",
185604 "COMMA", "PLUS", "STAR", "error",
185605 "input", "expr", "cnearset", "exprlist",
185606 "colset", "colsetlist", "nearset", "nearphrases",
185607 "phrase", "neardist_opt", "star_opt",
185609 #endif /* NDEBUG */
185611 #ifndef NDEBUG
185612 /* For tracing reduce actions, the names of all rules are required.
185614 static const char *const fts5yyRuleName[] = {
185615 /* 0 */ "input ::= expr",
185616 /* 1 */ "colset ::= MINUS LCP colsetlist RCP",
185617 /* 2 */ "colset ::= LCP colsetlist RCP",
185618 /* 3 */ "colset ::= STRING",
185619 /* 4 */ "colset ::= MINUS STRING",
185620 /* 5 */ "colsetlist ::= colsetlist STRING",
185621 /* 6 */ "colsetlist ::= STRING",
185622 /* 7 */ "expr ::= expr AND expr",
185623 /* 8 */ "expr ::= expr OR expr",
185624 /* 9 */ "expr ::= expr NOT expr",
185625 /* 10 */ "expr ::= colset COLON LP expr RP",
185626 /* 11 */ "expr ::= LP expr RP",
185627 /* 12 */ "expr ::= exprlist",
185628 /* 13 */ "exprlist ::= cnearset",
185629 /* 14 */ "exprlist ::= exprlist cnearset",
185630 /* 15 */ "cnearset ::= nearset",
185631 /* 16 */ "cnearset ::= colset COLON nearset",
185632 /* 17 */ "nearset ::= phrase",
185633 /* 18 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
185634 /* 19 */ "nearphrases ::= phrase",
185635 /* 20 */ "nearphrases ::= nearphrases phrase",
185636 /* 21 */ "neardist_opt ::=",
185637 /* 22 */ "neardist_opt ::= COMMA STRING",
185638 /* 23 */ "phrase ::= phrase PLUS STRING star_opt",
185639 /* 24 */ "phrase ::= STRING star_opt",
185640 /* 25 */ "star_opt ::= STAR",
185641 /* 26 */ "star_opt ::=",
185643 #endif /* NDEBUG */
185646 #if fts5YYSTACKDEPTH<=0
185648 ** Try to increase the size of the parser stack. Return the number
185649 ** of errors. Return 0 on success.
185651 static int fts5yyGrowStack(fts5yyParser *p){
185652 int newSize;
185653 int idx;
185654 fts5yyStackEntry *pNew;
185656 newSize = p->fts5yystksz*2 + 100;
185657 idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
185658 if( p->fts5yystack==&p->fts5yystk0 ){
185659 pNew = malloc(newSize*sizeof(pNew[0]));
185660 if( pNew ) pNew[0] = p->fts5yystk0;
185661 }else{
185662 pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
185664 if( pNew ){
185665 p->fts5yystack = pNew;
185666 p->fts5yytos = &p->fts5yystack[idx];
185667 #ifndef NDEBUG
185668 if( fts5yyTraceFILE ){
185669 fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
185670 fts5yyTracePrompt, p->fts5yystksz, newSize);
185672 #endif
185673 p->fts5yystksz = newSize;
185675 return pNew==0;
185677 #endif
185679 /* Datatype of the argument to the memory allocated passed as the
185680 ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
185681 ** putting an appropriate #define in the %include section of the input
185682 ** grammar.
185684 #ifndef fts5YYMALLOCARGTYPE
185685 # define fts5YYMALLOCARGTYPE size_t
185686 #endif
185688 /* Initialize a new parser that has already been allocated.
185690 static void sqlite3Fts5ParserInit(void *fts5yypParser){
185691 fts5yyParser *pParser = (fts5yyParser*)fts5yypParser;
185692 #ifdef fts5YYTRACKMAXSTACKDEPTH
185693 pParser->fts5yyhwm = 0;
185694 #endif
185695 #if fts5YYSTACKDEPTH<=0
185696 pParser->fts5yytos = NULL;
185697 pParser->fts5yystack = NULL;
185698 pParser->fts5yystksz = 0;
185699 if( fts5yyGrowStack(pParser) ){
185700 pParser->fts5yystack = &pParser->fts5yystk0;
185701 pParser->fts5yystksz = 1;
185703 #endif
185704 #ifndef fts5YYNOERRORRECOVERY
185705 pParser->fts5yyerrcnt = -1;
185706 #endif
185707 pParser->fts5yytos = pParser->fts5yystack;
185708 pParser->fts5yystack[0].stateno = 0;
185709 pParser->fts5yystack[0].major = 0;
185710 #if fts5YYSTACKDEPTH>0
185711 pParser->fts5yystackEnd = &pParser->fts5yystack[fts5YYSTACKDEPTH-1];
185712 #endif
185715 #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
185717 ** This function allocates a new parser.
185718 ** The only argument is a pointer to a function which works like
185719 ** malloc.
185721 ** Inputs:
185722 ** A pointer to the function used to allocate memory.
185724 ** Outputs:
185725 ** A pointer to a parser. This pointer is used in subsequent calls
185726 ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
185728 static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
185729 fts5yyParser *pParser;
185730 pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
185731 if( pParser ) sqlite3Fts5ParserInit(pParser);
185732 return pParser;
185734 #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
185737 /* The following function deletes the "minor type" or semantic value
185738 ** associated with a symbol. The symbol can be either a terminal
185739 ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
185740 ** a pointer to the value to be deleted. The code used to do the
185741 ** deletions is derived from the %destructor and/or %token_destructor
185742 ** directives of the input grammar.
185744 static void fts5yy_destructor(
185745 fts5yyParser *fts5yypParser, /* The parser */
185746 fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
185747 fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
185749 sqlite3Fts5ParserARG_FETCH;
185750 switch( fts5yymajor ){
185751 /* Here is inserted the actions which take place when a
185752 ** terminal or non-terminal is destroyed. This can happen
185753 ** when the symbol is popped from the stack during a
185754 ** reduce or during error processing or when a parser is
185755 ** being destroyed before it is finished parsing.
185757 ** Note: during a reduce, the only symbols destroyed are those
185758 ** which appear on the RHS of the rule, but which are *not* used
185759 ** inside the C code.
185761 /********* Begin destructor definitions ***************************************/
185762 case 16: /* input */
185764 (void)pParse;
185766 break;
185767 case 17: /* expr */
185768 case 18: /* cnearset */
185769 case 19: /* exprlist */
185771 sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
185773 break;
185774 case 20: /* colset */
185775 case 21: /* colsetlist */
185777 sqlite3_free((fts5yypminor->fts5yy11));
185779 break;
185780 case 22: /* nearset */
185781 case 23: /* nearphrases */
185783 sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
185785 break;
185786 case 24: /* phrase */
185788 sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
185790 break;
185791 /********* End destructor definitions *****************************************/
185792 default: break; /* If no destructor action specified: do nothing */
185797 ** Pop the parser's stack once.
185799 ** If there is a destructor routine associated with the token which
185800 ** is popped from the stack, then call it.
185802 static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
185803 fts5yyStackEntry *fts5yytos;
185804 assert( pParser->fts5yytos!=0 );
185805 assert( pParser->fts5yytos > pParser->fts5yystack );
185806 fts5yytos = pParser->fts5yytos--;
185807 #ifndef NDEBUG
185808 if( fts5yyTraceFILE ){
185809 fprintf(fts5yyTraceFILE,"%sPopping %s\n",
185810 fts5yyTracePrompt,
185811 fts5yyTokenName[fts5yytos->major]);
185813 #endif
185814 fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
185818 ** Clear all secondary memory allocations from the parser
185820 static void sqlite3Fts5ParserFinalize(void *p){
185821 fts5yyParser *pParser = (fts5yyParser*)p;
185822 while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
185823 #if fts5YYSTACKDEPTH<=0
185824 if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
185825 #endif
185828 #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
185830 ** Deallocate and destroy a parser. Destructors are called for
185831 ** all stack elements before shutting the parser down.
185833 ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
185834 ** is defined in a %include section of the input grammar) then it is
185835 ** assumed that the input pointer is never NULL.
185837 static void sqlite3Fts5ParserFree(
185838 void *p, /* The parser to be deleted */
185839 void (*freeProc)(void*) /* Function used to reclaim memory */
185841 #ifndef fts5YYPARSEFREENEVERNULL
185842 if( p==0 ) return;
185843 #endif
185844 sqlite3Fts5ParserFinalize(p);
185845 (*freeProc)(p);
185847 #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
185850 ** Return the peak depth of the stack for a parser.
185852 #ifdef fts5YYTRACKMAXSTACKDEPTH
185853 static int sqlite3Fts5ParserStackPeak(void *p){
185854 fts5yyParser *pParser = (fts5yyParser*)p;
185855 return pParser->fts5yyhwm;
185857 #endif
185860 ** Find the appropriate action for a parser given the terminal
185861 ** look-ahead token iLookAhead.
185863 static unsigned int fts5yy_find_shift_action(
185864 fts5yyParser *pParser, /* The parser */
185865 fts5YYCODETYPE iLookAhead /* The look-ahead token */
185867 int i;
185868 int stateno = pParser->fts5yytos->stateno;
185870 if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
185871 assert( stateno <= fts5YY_SHIFT_COUNT );
185873 i = fts5yy_shift_ofst[stateno];
185874 assert( iLookAhead!=fts5YYNOCODE );
185875 i += iLookAhead;
185876 if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
185877 #ifdef fts5YYFALLBACK
185878 fts5YYCODETYPE iFallback; /* Fallback token */
185879 if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
185880 && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
185881 #ifndef NDEBUG
185882 if( fts5yyTraceFILE ){
185883 fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
185884 fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
185886 #endif
185887 assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
185888 iLookAhead = iFallback;
185889 continue;
185891 #endif
185892 #ifdef fts5YYWILDCARD
185894 int j = i - iLookAhead + fts5YYWILDCARD;
185896 #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
185897 j>=0 &&
185898 #endif
185899 #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
185900 j<fts5YY_ACTTAB_COUNT &&
185901 #endif
185902 fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
185904 #ifndef NDEBUG
185905 if( fts5yyTraceFILE ){
185906 fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
185907 fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
185908 fts5yyTokenName[fts5YYWILDCARD]);
185910 #endif /* NDEBUG */
185911 return fts5yy_action[j];
185914 #endif /* fts5YYWILDCARD */
185915 return fts5yy_default[stateno];
185916 }else{
185917 return fts5yy_action[i];
185919 }while(1);
185923 ** Find the appropriate action for a parser given the non-terminal
185924 ** look-ahead token iLookAhead.
185926 static int fts5yy_find_reduce_action(
185927 int stateno, /* Current state number */
185928 fts5YYCODETYPE iLookAhead /* The look-ahead token */
185930 int i;
185931 #ifdef fts5YYERRORSYMBOL
185932 if( stateno>fts5YY_REDUCE_COUNT ){
185933 return fts5yy_default[stateno];
185935 #else
185936 assert( stateno<=fts5YY_REDUCE_COUNT );
185937 #endif
185938 i = fts5yy_reduce_ofst[stateno];
185939 assert( i!=fts5YY_REDUCE_USE_DFLT );
185940 assert( iLookAhead!=fts5YYNOCODE );
185941 i += iLookAhead;
185942 #ifdef fts5YYERRORSYMBOL
185943 if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
185944 return fts5yy_default[stateno];
185946 #else
185947 assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
185948 assert( fts5yy_lookahead[i]==iLookAhead );
185949 #endif
185950 return fts5yy_action[i];
185954 ** The following routine is called if the stack overflows.
185956 static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
185957 sqlite3Fts5ParserARG_FETCH;
185958 #ifndef NDEBUG
185959 if( fts5yyTraceFILE ){
185960 fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
185962 #endif
185963 while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
185964 /* Here code is inserted which will execute if the parser
185965 ** stack every overflows */
185966 /******** Begin %stack_overflow code ******************************************/
185968 sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
185969 /******** End %stack_overflow code ********************************************/
185970 sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
185974 ** Print tracing information for a SHIFT action
185976 #ifndef NDEBUG
185977 static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
185978 if( fts5yyTraceFILE ){
185979 if( fts5yyNewState<fts5YYNSTATE ){
185980 fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
185981 fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
185982 fts5yyNewState);
185983 }else{
185984 fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
185985 fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
185989 #else
185990 # define fts5yyTraceShift(X,Y)
185991 #endif
185994 ** Perform a shift action.
185996 static void fts5yy_shift(
185997 fts5yyParser *fts5yypParser, /* The parser to be shifted */
185998 int fts5yyNewState, /* The new state to shift in */
185999 int fts5yyMajor, /* The major token to shift in */
186000 sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
186002 fts5yyStackEntry *fts5yytos;
186003 fts5yypParser->fts5yytos++;
186004 #ifdef fts5YYTRACKMAXSTACKDEPTH
186005 if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
186006 fts5yypParser->fts5yyhwm++;
186007 assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
186009 #endif
186010 #if fts5YYSTACKDEPTH>0
186011 if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
186012 fts5yypParser->fts5yytos--;
186013 fts5yyStackOverflow(fts5yypParser);
186014 return;
186016 #else
186017 if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
186018 if( fts5yyGrowStack(fts5yypParser) ){
186019 fts5yypParser->fts5yytos--;
186020 fts5yyStackOverflow(fts5yypParser);
186021 return;
186024 #endif
186025 if( fts5yyNewState > fts5YY_MAX_SHIFT ){
186026 fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
186028 fts5yytos = fts5yypParser->fts5yytos;
186029 fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
186030 fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
186031 fts5yytos->minor.fts5yy0 = fts5yyMinor;
186032 fts5yyTraceShift(fts5yypParser, fts5yyNewState);
186035 /* The following table contains information about every rule that
186036 ** is used during the reduce.
186038 static const struct {
186039 fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
186040 signed char nrhs; /* Negative of the number of RHS symbols in the rule */
186041 } fts5yyRuleInfo[] = {
186042 { 16, -1 },
186043 { 20, -4 },
186044 { 20, -3 },
186045 { 20, -1 },
186046 { 20, -2 },
186047 { 21, -2 },
186048 { 21, -1 },
186049 { 17, -3 },
186050 { 17, -3 },
186051 { 17, -3 },
186052 { 17, -5 },
186053 { 17, -3 },
186054 { 17, -1 },
186055 { 19, -1 },
186056 { 19, -2 },
186057 { 18, -1 },
186058 { 18, -3 },
186059 { 22, -1 },
186060 { 22, -5 },
186061 { 23, -1 },
186062 { 23, -2 },
186063 { 25, 0 },
186064 { 25, -2 },
186065 { 24, -4 },
186066 { 24, -2 },
186067 { 26, -1 },
186068 { 26, 0 },
186071 static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
186074 ** Perform a reduce action and the shift that must immediately
186075 ** follow the reduce.
186077 static void fts5yy_reduce(
186078 fts5yyParser *fts5yypParser, /* The parser */
186079 unsigned int fts5yyruleno /* Number of the rule by which to reduce */
186081 int fts5yygoto; /* The next state */
186082 int fts5yyact; /* The next action */
186083 fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
186084 int fts5yysize; /* Amount to pop the stack */
186085 sqlite3Fts5ParserARG_FETCH;
186086 fts5yymsp = fts5yypParser->fts5yytos;
186087 #ifndef NDEBUG
186088 if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
186089 fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
186090 fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
186091 fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
186093 #endif /* NDEBUG */
186095 /* Check that the stack is large enough to grow by a single entry
186096 ** if the RHS of the rule is empty. This ensures that there is room
186097 ** enough on the stack to push the LHS value */
186098 if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
186099 #ifdef fts5YYTRACKMAXSTACKDEPTH
186100 if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
186101 fts5yypParser->fts5yyhwm++;
186102 assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
186104 #endif
186105 #if fts5YYSTACKDEPTH>0
186106 if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
186107 fts5yyStackOverflow(fts5yypParser);
186108 return;
186110 #else
186111 if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
186112 if( fts5yyGrowStack(fts5yypParser) ){
186113 fts5yyStackOverflow(fts5yypParser);
186114 return;
186116 fts5yymsp = fts5yypParser->fts5yytos;
186118 #endif
186121 switch( fts5yyruleno ){
186122 /* Beginning here are the reduction cases. A typical example
186123 ** follows:
186124 ** case 0:
186125 ** #line <lineno> <grammarfile>
186126 ** { ... } // User supplied code
186127 ** #line <lineno> <thisfile>
186128 ** break;
186130 /********** Begin reduce actions **********************************************/
186131 fts5YYMINORTYPE fts5yylhsminor;
186132 case 0: /* input ::= expr */
186133 { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
186134 break;
186135 case 1: /* colset ::= MINUS LCP colsetlist RCP */
186137 fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
186139 break;
186140 case 2: /* colset ::= LCP colsetlist RCP */
186141 { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
186142 break;
186143 case 3: /* colset ::= STRING */
186145 fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
186147 fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
186148 break;
186149 case 4: /* colset ::= MINUS STRING */
186151 fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
186152 fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
186154 break;
186155 case 5: /* colsetlist ::= colsetlist STRING */
186157 fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
186158 fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
186159 break;
186160 case 6: /* colsetlist ::= STRING */
186162 fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
186164 fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
186165 break;
186166 case 7: /* expr ::= expr AND expr */
186168 fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
186170 fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186171 break;
186172 case 8: /* expr ::= expr OR expr */
186174 fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
186176 fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186177 break;
186178 case 9: /* expr ::= expr NOT expr */
186180 fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
186182 fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186183 break;
186184 case 10: /* expr ::= colset COLON LP expr RP */
186186 sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
186187 fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
186189 fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186190 break;
186191 case 11: /* expr ::= LP expr RP */
186192 {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
186193 break;
186194 case 12: /* expr ::= exprlist */
186195 case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
186196 {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
186197 fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186198 break;
186199 case 14: /* exprlist ::= exprlist cnearset */
186201 fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
186203 fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186204 break;
186205 case 15: /* cnearset ::= nearset */
186207 fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
186209 fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186210 break;
186211 case 16: /* cnearset ::= colset COLON nearset */
186213 fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
186214 sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
186216 fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
186217 break;
186218 case 17: /* nearset ::= phrase */
186219 { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
186220 fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
186221 break;
186222 case 18: /* nearset ::= STRING LP nearphrases neardist_opt RP */
186224 sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
186225 sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
186226 fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
186228 fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
186229 break;
186230 case 19: /* nearphrases ::= phrase */
186232 fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
186234 fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
186235 break;
186236 case 20: /* nearphrases ::= nearphrases phrase */
186238 fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
186240 fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
186241 break;
186242 case 21: /* neardist_opt ::= */
186243 { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
186244 break;
186245 case 22: /* neardist_opt ::= COMMA STRING */
186246 { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
186247 break;
186248 case 23: /* phrase ::= phrase PLUS STRING star_opt */
186250 fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
186252 fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
186253 break;
186254 case 24: /* phrase ::= STRING star_opt */
186256 fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
186258 fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
186259 break;
186260 case 25: /* star_opt ::= STAR */
186261 { fts5yymsp[0].minor.fts5yy4 = 1; }
186262 break;
186263 case 26: /* star_opt ::= */
186264 { fts5yymsp[1].minor.fts5yy4 = 0; }
186265 break;
186266 default:
186267 break;
186268 /********** End reduce actions ************************************************/
186270 assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
186271 fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
186272 fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
186273 fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
186275 /* There are no SHIFTREDUCE actions on nonterminals because the table
186276 ** generator has simplified them to pure REDUCE actions. */
186277 assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
186279 /* It is not possible for a REDUCE to be followed by an error */
186280 assert( fts5yyact!=fts5YY_ERROR_ACTION );
186282 if( fts5yyact==fts5YY_ACCEPT_ACTION ){
186283 fts5yypParser->fts5yytos += fts5yysize;
186284 fts5yy_accept(fts5yypParser);
186285 }else{
186286 fts5yymsp += fts5yysize+1;
186287 fts5yypParser->fts5yytos = fts5yymsp;
186288 fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
186289 fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
186290 fts5yyTraceShift(fts5yypParser, fts5yyact);
186295 ** The following code executes when the parse fails
186297 #ifndef fts5YYNOERRORRECOVERY
186298 static void fts5yy_parse_failed(
186299 fts5yyParser *fts5yypParser /* The parser */
186301 sqlite3Fts5ParserARG_FETCH;
186302 #ifndef NDEBUG
186303 if( fts5yyTraceFILE ){
186304 fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
186306 #endif
186307 while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
186308 /* Here code is inserted which will be executed whenever the
186309 ** parser fails */
186310 /************ Begin %parse_failure code ***************************************/
186311 /************ End %parse_failure code *****************************************/
186312 sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
186314 #endif /* fts5YYNOERRORRECOVERY */
186317 ** The following code executes when a syntax error first occurs.
186319 static void fts5yy_syntax_error(
186320 fts5yyParser *fts5yypParser, /* The parser */
186321 int fts5yymajor, /* The major type of the error token */
186322 sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
186324 sqlite3Fts5ParserARG_FETCH;
186325 #define FTS5TOKEN fts5yyminor
186326 /************ Begin %syntax_error code ****************************************/
186328 UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
186329 sqlite3Fts5ParseError(
186330 pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
186332 /************ End %syntax_error code ******************************************/
186333 sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
186337 ** The following is executed when the parser accepts
186339 static void fts5yy_accept(
186340 fts5yyParser *fts5yypParser /* The parser */
186342 sqlite3Fts5ParserARG_FETCH;
186343 #ifndef NDEBUG
186344 if( fts5yyTraceFILE ){
186345 fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
186347 #endif
186348 #ifndef fts5YYNOERRORRECOVERY
186349 fts5yypParser->fts5yyerrcnt = -1;
186350 #endif
186351 assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
186352 /* Here code is inserted which will be executed whenever the
186353 ** parser accepts */
186354 /*********** Begin %parse_accept code *****************************************/
186355 /*********** End %parse_accept code *******************************************/
186356 sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
186359 /* The main parser program.
186360 ** The first argument is a pointer to a structure obtained from
186361 ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
186362 ** The second argument is the major token number. The third is
186363 ** the minor token. The fourth optional argument is whatever the
186364 ** user wants (and specified in the grammar) and is available for
186365 ** use by the action routines.
186367 ** Inputs:
186368 ** <ul>
186369 ** <li> A pointer to the parser (an opaque structure.)
186370 ** <li> The major token number.
186371 ** <li> The minor token number.
186372 ** <li> An option argument of a grammar-specified type.
186373 ** </ul>
186375 ** Outputs:
186376 ** None.
186378 static void sqlite3Fts5Parser(
186379 void *fts5yyp, /* The parser */
186380 int fts5yymajor, /* The major token code number */
186381 sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
186382 sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
186384 fts5YYMINORTYPE fts5yyminorunion;
186385 unsigned int fts5yyact; /* The parser action. */
186386 #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
186387 int fts5yyendofinput; /* True if we are at the end of input */
186388 #endif
186389 #ifdef fts5YYERRORSYMBOL
186390 int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
186391 #endif
186392 fts5yyParser *fts5yypParser; /* The parser */
186394 fts5yypParser = (fts5yyParser*)fts5yyp;
186395 assert( fts5yypParser->fts5yytos!=0 );
186396 #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
186397 fts5yyendofinput = (fts5yymajor==0);
186398 #endif
186399 sqlite3Fts5ParserARG_STORE;
186401 #ifndef NDEBUG
186402 if( fts5yyTraceFILE ){
186403 fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
186405 #endif
186408 fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
186409 if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
186410 fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
186411 #ifndef fts5YYNOERRORRECOVERY
186412 fts5yypParser->fts5yyerrcnt--;
186413 #endif
186414 fts5yymajor = fts5YYNOCODE;
186415 }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
186416 fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
186417 }else{
186418 assert( fts5yyact == fts5YY_ERROR_ACTION );
186419 fts5yyminorunion.fts5yy0 = fts5yyminor;
186420 #ifdef fts5YYERRORSYMBOL
186421 int fts5yymx;
186422 #endif
186423 #ifndef NDEBUG
186424 if( fts5yyTraceFILE ){
186425 fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
186427 #endif
186428 #ifdef fts5YYERRORSYMBOL
186429 /* A syntax error has occurred.
186430 ** The response to an error depends upon whether or not the
186431 ** grammar defines an error token "ERROR".
186433 ** This is what we do if the grammar does define ERROR:
186435 ** * Call the %syntax_error function.
186437 ** * Begin popping the stack until we enter a state where
186438 ** it is legal to shift the error symbol, then shift
186439 ** the error symbol.
186441 ** * Set the error count to three.
186443 ** * Begin accepting and shifting new tokens. No new error
186444 ** processing will occur until three tokens have been
186445 ** shifted successfully.
186448 if( fts5yypParser->fts5yyerrcnt<0 ){
186449 fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
186451 fts5yymx = fts5yypParser->fts5yytos->major;
186452 if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
186453 #ifndef NDEBUG
186454 if( fts5yyTraceFILE ){
186455 fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
186456 fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
186458 #endif
186459 fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
186460 fts5yymajor = fts5YYNOCODE;
186461 }else{
186462 while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
186463 && fts5yymx != fts5YYERRORSYMBOL
186464 && (fts5yyact = fts5yy_find_reduce_action(
186465 fts5yypParser->fts5yytos->stateno,
186466 fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
186468 fts5yy_pop_parser_stack(fts5yypParser);
186470 if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
186471 fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
186472 fts5yy_parse_failed(fts5yypParser);
186473 #ifndef fts5YYNOERRORRECOVERY
186474 fts5yypParser->fts5yyerrcnt = -1;
186475 #endif
186476 fts5yymajor = fts5YYNOCODE;
186477 }else if( fts5yymx!=fts5YYERRORSYMBOL ){
186478 fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
186481 fts5yypParser->fts5yyerrcnt = 3;
186482 fts5yyerrorhit = 1;
186483 #elif defined(fts5YYNOERRORRECOVERY)
186484 /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
186485 ** do any kind of error recovery. Instead, simply invoke the syntax
186486 ** error routine and continue going as if nothing had happened.
186488 ** Applications can set this macro (for example inside %include) if
186489 ** they intend to abandon the parse upon the first syntax error seen.
186491 fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
186492 fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
186493 fts5yymajor = fts5YYNOCODE;
186495 #else /* fts5YYERRORSYMBOL is not defined */
186496 /* This is what we do if the grammar does not define ERROR:
186498 ** * Report an error message, and throw away the input token.
186500 ** * If the input token is $, then fail the parse.
186502 ** As before, subsequent error messages are suppressed until
186503 ** three input tokens have been successfully shifted.
186505 if( fts5yypParser->fts5yyerrcnt<=0 ){
186506 fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
186508 fts5yypParser->fts5yyerrcnt = 3;
186509 fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
186510 if( fts5yyendofinput ){
186511 fts5yy_parse_failed(fts5yypParser);
186512 #ifndef fts5YYNOERRORRECOVERY
186513 fts5yypParser->fts5yyerrcnt = -1;
186514 #endif
186516 fts5yymajor = fts5YYNOCODE;
186517 #endif
186519 }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
186520 #ifndef NDEBUG
186521 if( fts5yyTraceFILE ){
186522 fts5yyStackEntry *i;
186523 char cDiv = '[';
186524 fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
186525 for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
186526 fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
186527 cDiv = ' ';
186529 fprintf(fts5yyTraceFILE,"]\n");
186531 #endif
186532 return;
186536 ** 2014 May 31
186538 ** The author disclaims copyright to this source code. In place of
186539 ** a legal notice, here is a blessing:
186541 ** May you do good and not evil.
186542 ** May you find forgiveness for yourself and forgive others.
186543 ** May you share freely, never taking more than you give.
186545 ******************************************************************************
186549 /* #include "fts5Int.h" */
186550 #include <math.h> /* amalgamator: keep */
186553 ** Object used to iterate through all "coalesced phrase instances" in
186554 ** a single column of the current row. If the phrase instances in the
186555 ** column being considered do not overlap, this object simply iterates
186556 ** through them. Or, if they do overlap (share one or more tokens in
186557 ** common), each set of overlapping instances is treated as a single
186558 ** match. See documentation for the highlight() auxiliary function for
186559 ** details.
186561 ** Usage is:
186563 ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
186564 ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
186565 ** rc = fts5CInstIterNext(&iter)
186566 ** ){
186567 ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
186571 typedef struct CInstIter CInstIter;
186572 struct CInstIter {
186573 const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
186574 Fts5Context *pFts; /* First arg to pass to pApi functions */
186575 int iCol; /* Column to search */
186576 int iInst; /* Next phrase instance index */
186577 int nInst; /* Total number of phrase instances */
186579 /* Output variables */
186580 int iStart; /* First token in coalesced phrase instance */
186581 int iEnd; /* Last token in coalesced phrase instance */
186585 ** Advance the iterator to the next coalesced phrase instance. Return
186586 ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
186588 static int fts5CInstIterNext(CInstIter *pIter){
186589 int rc = SQLITE_OK;
186590 pIter->iStart = -1;
186591 pIter->iEnd = -1;
186593 while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
186594 int ip; int ic; int io;
186595 rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
186596 if( rc==SQLITE_OK ){
186597 if( ic==pIter->iCol ){
186598 int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
186599 if( pIter->iStart<0 ){
186600 pIter->iStart = io;
186601 pIter->iEnd = iEnd;
186602 }else if( io<=pIter->iEnd ){
186603 if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
186604 }else{
186605 break;
186608 pIter->iInst++;
186612 return rc;
186616 ** Initialize the iterator object indicated by the final parameter to
186617 ** iterate through coalesced phrase instances in column iCol.
186619 static int fts5CInstIterInit(
186620 const Fts5ExtensionApi *pApi,
186621 Fts5Context *pFts,
186622 int iCol,
186623 CInstIter *pIter
186625 int rc;
186627 memset(pIter, 0, sizeof(CInstIter));
186628 pIter->pApi = pApi;
186629 pIter->pFts = pFts;
186630 pIter->iCol = iCol;
186631 rc = pApi->xInstCount(pFts, &pIter->nInst);
186633 if( rc==SQLITE_OK ){
186634 rc = fts5CInstIterNext(pIter);
186637 return rc;
186642 /*************************************************************************
186643 ** Start of highlight() implementation.
186645 typedef struct HighlightContext HighlightContext;
186646 struct HighlightContext {
186647 CInstIter iter; /* Coalesced Instance Iterator */
186648 int iPos; /* Current token offset in zIn[] */
186649 int iRangeStart; /* First token to include */
186650 int iRangeEnd; /* If non-zero, last token to include */
186651 const char *zOpen; /* Opening highlight */
186652 const char *zClose; /* Closing highlight */
186653 const char *zIn; /* Input text */
186654 int nIn; /* Size of input text in bytes */
186655 int iOff; /* Current offset within zIn[] */
186656 char *zOut; /* Output value */
186660 ** Append text to the HighlightContext output string - p->zOut. Argument
186661 ** z points to a buffer containing n bytes of text to append. If n is
186662 ** negative, everything up until the first '\0' is appended to the output.
186664 ** If *pRc is set to any value other than SQLITE_OK when this function is
186665 ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
186666 ** *pRc is set to an error code before returning.
186668 static void fts5HighlightAppend(
186669 int *pRc,
186670 HighlightContext *p,
186671 const char *z, int n
186673 if( *pRc==SQLITE_OK ){
186674 if( n<0 ) n = (int)strlen(z);
186675 p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
186676 if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
186681 ** Tokenizer callback used by implementation of highlight() function.
186683 static int fts5HighlightCb(
186684 void *pContext, /* Pointer to HighlightContext object */
186685 int tflags, /* Mask of FTS5_TOKEN_* flags */
186686 const char *pToken, /* Buffer containing token */
186687 int nToken, /* Size of token in bytes */
186688 int iStartOff, /* Start offset of token */
186689 int iEndOff /* End offset of token */
186691 HighlightContext *p = (HighlightContext*)pContext;
186692 int rc = SQLITE_OK;
186693 int iPos;
186695 UNUSED_PARAM2(pToken, nToken);
186697 if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
186698 iPos = p->iPos++;
186700 if( p->iRangeEnd>0 ){
186701 if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
186702 if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
186705 if( iPos==p->iter.iStart ){
186706 fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
186707 fts5HighlightAppend(&rc, p, p->zOpen, -1);
186708 p->iOff = iStartOff;
186711 if( iPos==p->iter.iEnd ){
186712 if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
186713 fts5HighlightAppend(&rc, p, p->zOpen, -1);
186715 fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
186716 fts5HighlightAppend(&rc, p, p->zClose, -1);
186717 p->iOff = iEndOff;
186718 if( rc==SQLITE_OK ){
186719 rc = fts5CInstIterNext(&p->iter);
186723 if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
186724 fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
186725 p->iOff = iEndOff;
186726 if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
186727 fts5HighlightAppend(&rc, p, p->zClose, -1);
186731 return rc;
186735 ** Implementation of highlight() function.
186737 static void fts5HighlightFunction(
186738 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
186739 Fts5Context *pFts, /* First arg to pass to pApi functions */
186740 sqlite3_context *pCtx, /* Context for returning result/error */
186741 int nVal, /* Number of values in apVal[] array */
186742 sqlite3_value **apVal /* Array of trailing arguments */
186744 HighlightContext ctx;
186745 int rc;
186746 int iCol;
186748 if( nVal!=3 ){
186749 const char *zErr = "wrong number of arguments to function highlight()";
186750 sqlite3_result_error(pCtx, zErr, -1);
186751 return;
186754 iCol = sqlite3_value_int(apVal[0]);
186755 memset(&ctx, 0, sizeof(HighlightContext));
186756 ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
186757 ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
186758 rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
186760 if( ctx.zIn ){
186761 if( rc==SQLITE_OK ){
186762 rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
186765 if( rc==SQLITE_OK ){
186766 rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
186768 fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
186770 if( rc==SQLITE_OK ){
186771 sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
186773 sqlite3_free(ctx.zOut);
186775 if( rc!=SQLITE_OK ){
186776 sqlite3_result_error_code(pCtx, rc);
186780 ** End of highlight() implementation.
186781 **************************************************************************/
186784 ** Context object passed to the fts5SentenceFinderCb() function.
186786 typedef struct Fts5SFinder Fts5SFinder;
186787 struct Fts5SFinder {
186788 int iPos; /* Current token position */
186789 int nFirstAlloc; /* Allocated size of aFirst[] */
186790 int nFirst; /* Number of entries in aFirst[] */
186791 int *aFirst; /* Array of first token in each sentence */
186792 const char *zDoc; /* Document being tokenized */
186796 ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
186797 ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
186798 ** error occurs.
186800 static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
186801 if( p->nFirstAlloc==p->nFirst ){
186802 int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
186803 int *aNew;
186805 aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
186806 if( aNew==0 ) return SQLITE_NOMEM;
186807 p->aFirst = aNew;
186808 p->nFirstAlloc = nNew;
186810 p->aFirst[p->nFirst++] = iAdd;
186811 return SQLITE_OK;
186815 ** This function is an xTokenize() callback used by the auxiliary snippet()
186816 ** function. Its job is to identify tokens that are the first in a sentence.
186817 ** For each such token, an entry is added to the SFinder.aFirst[] array.
186819 static int fts5SentenceFinderCb(
186820 void *pContext, /* Pointer to HighlightContext object */
186821 int tflags, /* Mask of FTS5_TOKEN_* flags */
186822 const char *pToken, /* Buffer containing token */
186823 int nToken, /* Size of token in bytes */
186824 int iStartOff, /* Start offset of token */
186825 int iEndOff /* End offset of token */
186827 int rc = SQLITE_OK;
186829 UNUSED_PARAM2(pToken, nToken);
186830 UNUSED_PARAM(iEndOff);
186832 if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
186833 Fts5SFinder *p = (Fts5SFinder*)pContext;
186834 if( p->iPos>0 ){
186835 int i;
186836 char c = 0;
186837 for(i=iStartOff-1; i>=0; i--){
186838 c = p->zDoc[i];
186839 if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
186841 if( i!=iStartOff-1 && (c=='.' || c==':') ){
186842 rc = fts5SentenceFinderAdd(p, p->iPos);
186844 }else{
186845 rc = fts5SentenceFinderAdd(p, 0);
186847 p->iPos++;
186849 return rc;
186852 static int fts5SnippetScore(
186853 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
186854 Fts5Context *pFts, /* First arg to pass to pApi functions */
186855 int nDocsize, /* Size of column in tokens */
186856 unsigned char *aSeen, /* Array with one element per query phrase */
186857 int iCol, /* Column to score */
186858 int iPos, /* Starting offset to score */
186859 int nToken, /* Max tokens per snippet */
186860 int *pnScore, /* OUT: Score */
186861 int *piPos /* OUT: Adjusted offset */
186863 int rc;
186864 int i;
186865 int ip = 0;
186866 int ic = 0;
186867 int iOff = 0;
186868 int iFirst = -1;
186869 int nInst;
186870 int nScore = 0;
186871 int iLast = 0;
186873 rc = pApi->xInstCount(pFts, &nInst);
186874 for(i=0; i<nInst && rc==SQLITE_OK; i++){
186875 rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
186876 if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
186877 nScore += (aSeen[ip] ? 1 : 1000);
186878 aSeen[ip] = 1;
186879 if( iFirst<0 ) iFirst = iOff;
186880 iLast = iOff + pApi->xPhraseSize(pFts, ip);
186884 *pnScore = nScore;
186885 if( piPos ){
186886 int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
186887 if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
186888 if( iAdj<0 ) iAdj = 0;
186889 *piPos = iAdj;
186892 return rc;
186896 ** Implementation of snippet() function.
186898 static void fts5SnippetFunction(
186899 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
186900 Fts5Context *pFts, /* First arg to pass to pApi functions */
186901 sqlite3_context *pCtx, /* Context for returning result/error */
186902 int nVal, /* Number of values in apVal[] array */
186903 sqlite3_value **apVal /* Array of trailing arguments */
186905 HighlightContext ctx;
186906 int rc = SQLITE_OK; /* Return code */
186907 int iCol; /* 1st argument to snippet() */
186908 const char *zEllips; /* 4th argument to snippet() */
186909 int nToken; /* 5th argument to snippet() */
186910 int nInst = 0; /* Number of instance matches this row */
186911 int i; /* Used to iterate through instances */
186912 int nPhrase; /* Number of phrases in query */
186913 unsigned char *aSeen; /* Array of "seen instance" flags */
186914 int iBestCol; /* Column containing best snippet */
186915 int iBestStart = 0; /* First token of best snippet */
186916 int nBestScore = 0; /* Score of best snippet */
186917 int nColSize = 0; /* Total size of iBestCol in tokens */
186918 Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
186919 int nCol;
186921 if( nVal!=5 ){
186922 const char *zErr = "wrong number of arguments to function snippet()";
186923 sqlite3_result_error(pCtx, zErr, -1);
186924 return;
186927 nCol = pApi->xColumnCount(pFts);
186928 memset(&ctx, 0, sizeof(HighlightContext));
186929 iCol = sqlite3_value_int(apVal[0]);
186930 ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
186931 ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
186932 zEllips = (const char*)sqlite3_value_text(apVal[3]);
186933 nToken = sqlite3_value_int(apVal[4]);
186935 iBestCol = (iCol>=0 ? iCol : 0);
186936 nPhrase = pApi->xPhraseCount(pFts);
186937 aSeen = sqlite3_malloc(nPhrase);
186938 if( aSeen==0 ){
186939 rc = SQLITE_NOMEM;
186941 if( rc==SQLITE_OK ){
186942 rc = pApi->xInstCount(pFts, &nInst);
186945 memset(&sFinder, 0, sizeof(Fts5SFinder));
186946 for(i=0; i<nCol; i++){
186947 if( iCol<0 || iCol==i ){
186948 int nDoc;
186949 int nDocsize;
186950 int ii;
186951 sFinder.iPos = 0;
186952 sFinder.nFirst = 0;
186953 rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
186954 if( rc!=SQLITE_OK ) break;
186955 rc = pApi->xTokenize(pFts,
186956 sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
186958 if( rc!=SQLITE_OK ) break;
186959 rc = pApi->xColumnSize(pFts, i, &nDocsize);
186960 if( rc!=SQLITE_OK ) break;
186962 for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
186963 int ip, ic, io;
186964 int iAdj;
186965 int nScore;
186966 int jj;
186968 rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
186969 if( ic!=i || rc!=SQLITE_OK ) continue;
186970 memset(aSeen, 0, nPhrase);
186971 rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
186972 io, nToken, &nScore, &iAdj
186974 if( rc==SQLITE_OK && nScore>nBestScore ){
186975 nBestScore = nScore;
186976 iBestCol = i;
186977 iBestStart = iAdj;
186978 nColSize = nDocsize;
186981 if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
186982 for(jj=0; jj<(sFinder.nFirst-1); jj++){
186983 if( sFinder.aFirst[jj+1]>io ) break;
186986 if( sFinder.aFirst[jj]<io ){
186987 memset(aSeen, 0, nPhrase);
186988 rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
186989 sFinder.aFirst[jj], nToken, &nScore, 0
186992 nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
186993 if( rc==SQLITE_OK && nScore>nBestScore ){
186994 nBestScore = nScore;
186995 iBestCol = i;
186996 iBestStart = sFinder.aFirst[jj];
186997 nColSize = nDocsize;
187005 if( rc==SQLITE_OK ){
187006 rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
187008 if( rc==SQLITE_OK && nColSize==0 ){
187009 rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
187011 if( ctx.zIn ){
187012 if( rc==SQLITE_OK ){
187013 rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
187016 ctx.iRangeStart = iBestStart;
187017 ctx.iRangeEnd = iBestStart + nToken - 1;
187019 if( iBestStart>0 ){
187020 fts5HighlightAppend(&rc, &ctx, zEllips, -1);
187023 /* Advance iterator ctx.iter so that it points to the first coalesced
187024 ** phrase instance at or following position iBestStart. */
187025 while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
187026 rc = fts5CInstIterNext(&ctx.iter);
187029 if( rc==SQLITE_OK ){
187030 rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
187032 if( ctx.iRangeEnd>=(nColSize-1) ){
187033 fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
187034 }else{
187035 fts5HighlightAppend(&rc, &ctx, zEllips, -1);
187038 if( rc==SQLITE_OK ){
187039 sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
187040 }else{
187041 sqlite3_result_error_code(pCtx, rc);
187043 sqlite3_free(ctx.zOut);
187044 sqlite3_free(aSeen);
187045 sqlite3_free(sFinder.aFirst);
187048 /************************************************************************/
187051 ** The first time the bm25() function is called for a query, an instance
187052 ** of the following structure is allocated and populated.
187054 typedef struct Fts5Bm25Data Fts5Bm25Data;
187055 struct Fts5Bm25Data {
187056 int nPhrase; /* Number of phrases in query */
187057 double avgdl; /* Average number of tokens in each row */
187058 double *aIDF; /* IDF for each phrase */
187059 double *aFreq; /* Array used to calculate phrase freq. */
187063 ** Callback used by fts5Bm25GetData() to count the number of rows in the
187064 ** table matched by each individual phrase within the query.
187066 static int fts5CountCb(
187067 const Fts5ExtensionApi *pApi,
187068 Fts5Context *pFts,
187069 void *pUserData /* Pointer to sqlite3_int64 variable */
187071 sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
187072 UNUSED_PARAM2(pApi, pFts);
187073 (*pn)++;
187074 return SQLITE_OK;
187078 ** Set *ppData to point to the Fts5Bm25Data object for the current query.
187079 ** If the object has not already been allocated, allocate and populate it
187080 ** now.
187082 static int fts5Bm25GetData(
187083 const Fts5ExtensionApi *pApi,
187084 Fts5Context *pFts,
187085 Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
187087 int rc = SQLITE_OK; /* Return code */
187088 Fts5Bm25Data *p; /* Object to return */
187090 p = pApi->xGetAuxdata(pFts, 0);
187091 if( p==0 ){
187092 int nPhrase; /* Number of phrases in query */
187093 sqlite3_int64 nRow = 0; /* Number of rows in table */
187094 sqlite3_int64 nToken = 0; /* Number of tokens in table */
187095 int nByte; /* Bytes of space to allocate */
187096 int i;
187098 /* Allocate the Fts5Bm25Data object */
187099 nPhrase = pApi->xPhraseCount(pFts);
187100 nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
187101 p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
187102 if( p==0 ){
187103 rc = SQLITE_NOMEM;
187104 }else{
187105 memset(p, 0, nByte);
187106 p->nPhrase = nPhrase;
187107 p->aIDF = (double*)&p[1];
187108 p->aFreq = &p->aIDF[nPhrase];
187111 /* Calculate the average document length for this FTS5 table */
187112 if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
187113 if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
187114 if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
187116 /* Calculate an IDF for each phrase in the query */
187117 for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
187118 sqlite3_int64 nHit = 0;
187119 rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
187120 if( rc==SQLITE_OK ){
187121 /* Calculate the IDF (Inverse Document Frequency) for phrase i.
187122 ** This is done using the standard BM25 formula as found on wikipedia:
187124 ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
187126 ** where "N" is the total number of documents in the set and nHit
187127 ** is the number that contain at least one instance of the phrase
187128 ** under consideration.
187130 ** The problem with this is that if (N < 2*nHit), the IDF is
187131 ** negative. Which is undesirable. So the mimimum allowable IDF is
187132 ** (1e-6) - roughly the same as a term that appears in just over
187133 ** half of set of 5,000,000 documents. */
187134 double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
187135 if( idf<=0.0 ) idf = 1e-6;
187136 p->aIDF[i] = idf;
187140 if( rc!=SQLITE_OK ){
187141 sqlite3_free(p);
187142 }else{
187143 rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
187145 if( rc!=SQLITE_OK ) p = 0;
187147 *ppData = p;
187148 return rc;
187152 ** Implementation of bm25() function.
187154 static void fts5Bm25Function(
187155 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
187156 Fts5Context *pFts, /* First arg to pass to pApi functions */
187157 sqlite3_context *pCtx, /* Context for returning result/error */
187158 int nVal, /* Number of values in apVal[] array */
187159 sqlite3_value **apVal /* Array of trailing arguments */
187161 const double k1 = 1.2; /* Constant "k1" from BM25 formula */
187162 const double b = 0.75; /* Constant "b" from BM25 formula */
187163 int rc = SQLITE_OK; /* Error code */
187164 double score = 0.0; /* SQL function return value */
187165 Fts5Bm25Data *pData; /* Values allocated/calculated once only */
187166 int i; /* Iterator variable */
187167 int nInst = 0; /* Value returned by xInstCount() */
187168 double D = 0.0; /* Total number of tokens in row */
187169 double *aFreq = 0; /* Array of phrase freq. for current row */
187171 /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
187172 ** for each phrase in the query for the current row. */
187173 rc = fts5Bm25GetData(pApi, pFts, &pData);
187174 if( rc==SQLITE_OK ){
187175 aFreq = pData->aFreq;
187176 memset(aFreq, 0, sizeof(double) * pData->nPhrase);
187177 rc = pApi->xInstCount(pFts, &nInst);
187179 for(i=0; rc==SQLITE_OK && i<nInst; i++){
187180 int ip; int ic; int io;
187181 rc = pApi->xInst(pFts, i, &ip, &ic, &io);
187182 if( rc==SQLITE_OK ){
187183 double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
187184 aFreq[ip] += w;
187188 /* Figure out the total size of the current row in tokens. */
187189 if( rc==SQLITE_OK ){
187190 int nTok;
187191 rc = pApi->xColumnSize(pFts, -1, &nTok);
187192 D = (double)nTok;
187195 /* Determine the BM25 score for the current row. */
187196 for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
187197 score += pData->aIDF[i] * (
187198 ( aFreq[i] * (k1 + 1.0) ) /
187199 ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
187203 /* If no error has occurred, return the calculated score. Otherwise,
187204 ** throw an SQL exception. */
187205 if( rc==SQLITE_OK ){
187206 sqlite3_result_double(pCtx, -1.0 * score);
187207 }else{
187208 sqlite3_result_error_code(pCtx, rc);
187212 static int sqlite3Fts5AuxInit(fts5_api *pApi){
187213 struct Builtin {
187214 const char *zFunc; /* Function name (nul-terminated) */
187215 void *pUserData; /* User-data pointer */
187216 fts5_extension_function xFunc;/* Callback function */
187217 void (*xDestroy)(void*); /* Destructor function */
187218 } aBuiltin [] = {
187219 { "snippet", 0, fts5SnippetFunction, 0 },
187220 { "highlight", 0, fts5HighlightFunction, 0 },
187221 { "bm25", 0, fts5Bm25Function, 0 },
187223 int rc = SQLITE_OK; /* Return code */
187224 int i; /* To iterate through builtin functions */
187226 for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
187227 rc = pApi->xCreateFunction(pApi,
187228 aBuiltin[i].zFunc,
187229 aBuiltin[i].pUserData,
187230 aBuiltin[i].xFunc,
187231 aBuiltin[i].xDestroy
187235 return rc;
187241 ** 2014 May 31
187243 ** The author disclaims copyright to this source code. In place of
187244 ** a legal notice, here is a blessing:
187246 ** May you do good and not evil.
187247 ** May you find forgiveness for yourself and forgive others.
187248 ** May you share freely, never taking more than you give.
187250 ******************************************************************************
187255 /* #include "fts5Int.h" */
187257 static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
187258 if( (u32)pBuf->nSpace<nByte ){
187259 u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
187260 u8 *pNew;
187261 while( nNew<nByte ){
187262 nNew = nNew * 2;
187264 pNew = sqlite3_realloc(pBuf->p, nNew);
187265 if( pNew==0 ){
187266 *pRc = SQLITE_NOMEM;
187267 return 1;
187268 }else{
187269 pBuf->nSpace = nNew;
187270 pBuf->p = pNew;
187273 return 0;
187278 ** Encode value iVal as an SQLite varint and append it to the buffer object
187279 ** pBuf. If an OOM error occurs, set the error code in p.
187281 static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
187282 if( fts5BufferGrow(pRc, pBuf, 9) ) return;
187283 pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
187286 static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
187287 aBuf[0] = (iVal>>24) & 0x00FF;
187288 aBuf[1] = (iVal>>16) & 0x00FF;
187289 aBuf[2] = (iVal>> 8) & 0x00FF;
187290 aBuf[3] = (iVal>> 0) & 0x00FF;
187293 static int sqlite3Fts5Get32(const u8 *aBuf){
187294 return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
187298 ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
187299 ** the error code in p. If an error has already occurred when this function
187300 ** is called, it is a no-op.
187302 static void sqlite3Fts5BufferAppendBlob(
187303 int *pRc,
187304 Fts5Buffer *pBuf,
187305 u32 nData,
187306 const u8 *pData
187308 assert_nc( *pRc || nData>=0 );
187309 if( nData ){
187310 if( fts5BufferGrow(pRc, pBuf, nData) ) return;
187311 memcpy(&pBuf->p[pBuf->n], pData, nData);
187312 pBuf->n += nData;
187317 ** Append the nul-terminated string zStr to the buffer pBuf. This function
187318 ** ensures that the byte following the buffer data is set to 0x00, even
187319 ** though this byte is not included in the pBuf->n count.
187321 static void sqlite3Fts5BufferAppendString(
187322 int *pRc,
187323 Fts5Buffer *pBuf,
187324 const char *zStr
187326 int nStr = (int)strlen(zStr);
187327 sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
187328 pBuf->n--;
187332 ** Argument zFmt is a printf() style format string. This function performs
187333 ** the printf() style processing, then appends the results to buffer pBuf.
187335 ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
187336 ** following the buffer data is set to 0x00, even though this byte is not
187337 ** included in the pBuf->n count.
187339 static void sqlite3Fts5BufferAppendPrintf(
187340 int *pRc,
187341 Fts5Buffer *pBuf,
187342 char *zFmt, ...
187344 if( *pRc==SQLITE_OK ){
187345 char *zTmp;
187346 va_list ap;
187347 va_start(ap, zFmt);
187348 zTmp = sqlite3_vmprintf(zFmt, ap);
187349 va_end(ap);
187351 if( zTmp==0 ){
187352 *pRc = SQLITE_NOMEM;
187353 }else{
187354 sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
187355 sqlite3_free(zTmp);
187360 static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
187361 char *zRet = 0;
187362 if( *pRc==SQLITE_OK ){
187363 va_list ap;
187364 va_start(ap, zFmt);
187365 zRet = sqlite3_vmprintf(zFmt, ap);
187366 va_end(ap);
187367 if( zRet==0 ){
187368 *pRc = SQLITE_NOMEM;
187371 return zRet;
187376 ** Free any buffer allocated by pBuf. Zero the structure before returning.
187378 static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
187379 sqlite3_free(pBuf->p);
187380 memset(pBuf, 0, sizeof(Fts5Buffer));
187384 ** Zero the contents of the buffer object. But do not free the associated
187385 ** memory allocation.
187387 static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
187388 pBuf->n = 0;
187392 ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
187393 ** the error code in p. If an error has already occurred when this function
187394 ** is called, it is a no-op.
187396 static void sqlite3Fts5BufferSet(
187397 int *pRc,
187398 Fts5Buffer *pBuf,
187399 int nData,
187400 const u8 *pData
187402 pBuf->n = 0;
187403 sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
187406 static int sqlite3Fts5PoslistNext64(
187407 const u8 *a, int n, /* Buffer containing poslist */
187408 int *pi, /* IN/OUT: Offset within a[] */
187409 i64 *piOff /* IN/OUT: Current offset */
187411 int i = *pi;
187412 if( i>=n ){
187413 /* EOF */
187414 *piOff = -1;
187415 return 1;
187416 }else{
187417 i64 iOff = *piOff;
187418 int iVal;
187419 fts5FastGetVarint32(a, i, iVal);
187420 if( iVal==1 ){
187421 fts5FastGetVarint32(a, i, iVal);
187422 iOff = ((i64)iVal) << 32;
187423 fts5FastGetVarint32(a, i, iVal);
187425 *piOff = iOff + (iVal-2);
187426 *pi = i;
187427 return 0;
187433 ** Advance the iterator object passed as the only argument. Return true
187434 ** if the iterator reaches EOF, or false otherwise.
187436 static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
187437 if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
187438 pIter->bEof = 1;
187440 return pIter->bEof;
187443 static int sqlite3Fts5PoslistReaderInit(
187444 const u8 *a, int n, /* Poslist buffer to iterate through */
187445 Fts5PoslistReader *pIter /* Iterator object to initialize */
187447 memset(pIter, 0, sizeof(*pIter));
187448 pIter->a = a;
187449 pIter->n = n;
187450 sqlite3Fts5PoslistReaderNext(pIter);
187451 return pIter->bEof;
187455 ** Append position iPos to the position list being accumulated in buffer
187456 ** pBuf, which must be already be large enough to hold the new data.
187457 ** The previous position written to this list is *piPrev. *piPrev is set
187458 ** to iPos before returning.
187460 static void sqlite3Fts5PoslistSafeAppend(
187461 Fts5Buffer *pBuf,
187462 i64 *piPrev,
187463 i64 iPos
187465 static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
187466 if( (iPos & colmask) != (*piPrev & colmask) ){
187467 pBuf->p[pBuf->n++] = 1;
187468 pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
187469 *piPrev = (iPos & colmask);
187471 pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
187472 *piPrev = iPos;
187475 static int sqlite3Fts5PoslistWriterAppend(
187476 Fts5Buffer *pBuf,
187477 Fts5PoslistWriter *pWriter,
187478 i64 iPos
187480 int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
187481 if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
187482 sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
187483 return SQLITE_OK;
187486 static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
187487 void *pRet = 0;
187488 if( *pRc==SQLITE_OK ){
187489 pRet = sqlite3_malloc(nByte);
187490 if( pRet==0 ){
187491 if( nByte>0 ) *pRc = SQLITE_NOMEM;
187492 }else{
187493 memset(pRet, 0, nByte);
187496 return pRet;
187500 ** Return a nul-terminated copy of the string indicated by pIn. If nIn
187501 ** is non-negative, then it is the length of the string in bytes. Otherwise,
187502 ** the length of the string is determined using strlen().
187504 ** It is the responsibility of the caller to eventually free the returned
187505 ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
187507 static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
187508 char *zRet = 0;
187509 if( *pRc==SQLITE_OK ){
187510 if( nIn<0 ){
187511 nIn = (int)strlen(pIn);
187513 zRet = (char*)sqlite3_malloc(nIn+1);
187514 if( zRet ){
187515 memcpy(zRet, pIn, nIn);
187516 zRet[nIn] = '\0';
187517 }else{
187518 *pRc = SQLITE_NOMEM;
187521 return zRet;
187526 ** Return true if character 't' may be part of an FTS5 bareword, or false
187527 ** otherwise. Characters that may be part of barewords:
187529 ** * All non-ASCII characters,
187530 ** * The 52 upper and lower case ASCII characters, and
187531 ** * The 10 integer ASCII characters.
187532 ** * The underscore character "_" (0x5F).
187533 ** * The unicode "subsitute" character (0x1A).
187535 static int sqlite3Fts5IsBareword(char t){
187536 u8 aBareword[128] = {
187537 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
187538 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
187539 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
187540 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
187541 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
187542 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
187543 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
187544 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
187547 return (t & 0x80) || aBareword[(int)t];
187551 /*************************************************************************
187553 typedef struct Fts5TermsetEntry Fts5TermsetEntry;
187554 struct Fts5TermsetEntry {
187555 char *pTerm;
187556 int nTerm;
187557 int iIdx; /* Index (main or aPrefix[] entry) */
187558 Fts5TermsetEntry *pNext;
187561 struct Fts5Termset {
187562 Fts5TermsetEntry *apHash[512];
187565 static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
187566 int rc = SQLITE_OK;
187567 *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
187568 return rc;
187571 static int sqlite3Fts5TermsetAdd(
187572 Fts5Termset *p,
187573 int iIdx,
187574 const char *pTerm, int nTerm,
187575 int *pbPresent
187577 int rc = SQLITE_OK;
187578 *pbPresent = 0;
187579 if( p ){
187580 int i;
187581 u32 hash = 13;
187582 Fts5TermsetEntry *pEntry;
187584 /* Calculate a hash value for this term. This is the same hash checksum
187585 ** used by the fts5_hash.c module. This is not important for correct
187586 ** operation of the module, but is necessary to ensure that some tests
187587 ** designed to produce hash table collisions really do work. */
187588 for(i=nTerm-1; i>=0; i--){
187589 hash = (hash << 3) ^ hash ^ pTerm[i];
187591 hash = (hash << 3) ^ hash ^ iIdx;
187592 hash = hash % ArraySize(p->apHash);
187594 for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
187595 if( pEntry->iIdx==iIdx
187596 && pEntry->nTerm==nTerm
187597 && memcmp(pEntry->pTerm, pTerm, nTerm)==0
187599 *pbPresent = 1;
187600 break;
187604 if( pEntry==0 ){
187605 pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
187606 if( pEntry ){
187607 pEntry->pTerm = (char*)&pEntry[1];
187608 pEntry->nTerm = nTerm;
187609 pEntry->iIdx = iIdx;
187610 memcpy(pEntry->pTerm, pTerm, nTerm);
187611 pEntry->pNext = p->apHash[hash];
187612 p->apHash[hash] = pEntry;
187617 return rc;
187620 static void sqlite3Fts5TermsetFree(Fts5Termset *p){
187621 if( p ){
187622 u32 i;
187623 for(i=0; i<ArraySize(p->apHash); i++){
187624 Fts5TermsetEntry *pEntry = p->apHash[i];
187625 while( pEntry ){
187626 Fts5TermsetEntry *pDel = pEntry;
187627 pEntry = pEntry->pNext;
187628 sqlite3_free(pDel);
187631 sqlite3_free(p);
187636 ** 2014 Jun 09
187638 ** The author disclaims copyright to this source code. In place of
187639 ** a legal notice, here is a blessing:
187641 ** May you do good and not evil.
187642 ** May you find forgiveness for yourself and forgive others.
187643 ** May you share freely, never taking more than you give.
187645 ******************************************************************************
187647 ** This is an SQLite module implementing full-text search.
187651 /* #include "fts5Int.h" */
187653 #define FTS5_DEFAULT_PAGE_SIZE 4050
187654 #define FTS5_DEFAULT_AUTOMERGE 4
187655 #define FTS5_DEFAULT_USERMERGE 4
187656 #define FTS5_DEFAULT_CRISISMERGE 16
187657 #define FTS5_DEFAULT_HASHSIZE (1024*1024)
187659 /* Maximum allowed page size */
187660 #define FTS5_MAX_PAGE_SIZE (128*1024)
187662 static int fts5_iswhitespace(char x){
187663 return (x==' ');
187666 static int fts5_isopenquote(char x){
187667 return (x=='"' || x=='\'' || x=='[' || x=='`');
187671 ** Argument pIn points to a character that is part of a nul-terminated
187672 ** string. Return a pointer to the first character following *pIn in
187673 ** the string that is not a white-space character.
187675 static const char *fts5ConfigSkipWhitespace(const char *pIn){
187676 const char *p = pIn;
187677 if( p ){
187678 while( fts5_iswhitespace(*p) ){ p++; }
187680 return p;
187684 ** Argument pIn points to a character that is part of a nul-terminated
187685 ** string. Return a pointer to the first character following *pIn in
187686 ** the string that is not a "bareword" character.
187688 static const char *fts5ConfigSkipBareword(const char *pIn){
187689 const char *p = pIn;
187690 while ( sqlite3Fts5IsBareword(*p) ) p++;
187691 if( p==pIn ) p = 0;
187692 return p;
187695 static int fts5_isdigit(char a){
187696 return (a>='0' && a<='9');
187701 static const char *fts5ConfigSkipLiteral(const char *pIn){
187702 const char *p = pIn;
187703 switch( *p ){
187704 case 'n': case 'N':
187705 if( sqlite3_strnicmp("null", p, 4)==0 ){
187706 p = &p[4];
187707 }else{
187708 p = 0;
187710 break;
187712 case 'x': case 'X':
187714 if( *p=='\'' ){
187716 while( (*p>='a' && *p<='f')
187717 || (*p>='A' && *p<='F')
187718 || (*p>='0' && *p<='9')
187722 if( *p=='\'' && 0==((p-pIn)%2) ){
187724 }else{
187725 p = 0;
187727 }else{
187728 p = 0;
187730 break;
187732 case '\'':
187734 while( p ){
187735 if( *p=='\'' ){
187737 if( *p!='\'' ) break;
187740 if( *p==0 ) p = 0;
187742 break;
187744 default:
187745 /* maybe a number */
187746 if( *p=='+' || *p=='-' ) p++;
187747 while( fts5_isdigit(*p) ) p++;
187749 /* At this point, if the literal was an integer, the parse is
187750 ** finished. Or, if it is a floating point value, it may continue
187751 ** with either a decimal point or an 'E' character. */
187752 if( *p=='.' && fts5_isdigit(p[1]) ){
187753 p += 2;
187754 while( fts5_isdigit(*p) ) p++;
187756 if( p==pIn ) p = 0;
187758 break;
187761 return p;
187765 ** The first character of the string pointed to by argument z is guaranteed
187766 ** to be an open-quote character (see function fts5_isopenquote()).
187768 ** This function searches for the corresponding close-quote character within
187769 ** the string and, if found, dequotes the string in place and adds a new
187770 ** nul-terminator byte.
187772 ** If the close-quote is found, the value returned is the byte offset of
187773 ** the character immediately following it. Or, if the close-quote is not
187774 ** found, -1 is returned. If -1 is returned, the buffer is left in an
187775 ** undefined state.
187777 static int fts5Dequote(char *z){
187778 char q;
187779 int iIn = 1;
187780 int iOut = 0;
187781 q = z[0];
187783 /* Set stack variable q to the close-quote character */
187784 assert( q=='[' || q=='\'' || q=='"' || q=='`' );
187785 if( q=='[' ) q = ']';
187787 while( ALWAYS(z[iIn]) ){
187788 if( z[iIn]==q ){
187789 if( z[iIn+1]!=q ){
187790 /* Character iIn was the close quote. */
187791 iIn++;
187792 break;
187793 }else{
187794 /* Character iIn and iIn+1 form an escaped quote character. Skip
187795 ** the input cursor past both and copy a single quote character
187796 ** to the output buffer. */
187797 iIn += 2;
187798 z[iOut++] = q;
187800 }else{
187801 z[iOut++] = z[iIn++];
187805 z[iOut] = '\0';
187806 return iIn;
187810 ** Convert an SQL-style quoted string into a normal string by removing
187811 ** the quote characters. The conversion is done in-place. If the
187812 ** input does not begin with a quote character, then this routine
187813 ** is a no-op.
187815 ** Examples:
187817 ** "abc" becomes abc
187818 ** 'xyz' becomes xyz
187819 ** [pqr] becomes pqr
187820 ** `mno` becomes mno
187822 static void sqlite3Fts5Dequote(char *z){
187823 char quote; /* Quote character (if any ) */
187825 assert( 0==fts5_iswhitespace(z[0]) );
187826 quote = z[0];
187827 if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
187828 fts5Dequote(z);
187833 struct Fts5Enum {
187834 const char *zName;
187835 int eVal;
187837 typedef struct Fts5Enum Fts5Enum;
187839 static int fts5ConfigSetEnum(
187840 const Fts5Enum *aEnum,
187841 const char *zEnum,
187842 int *peVal
187844 int nEnum = (int)strlen(zEnum);
187845 int i;
187846 int iVal = -1;
187848 for(i=0; aEnum[i].zName; i++){
187849 if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
187850 if( iVal>=0 ) return SQLITE_ERROR;
187851 iVal = aEnum[i].eVal;
187855 *peVal = iVal;
187856 return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
187860 ** Parse a "special" CREATE VIRTUAL TABLE directive and update
187861 ** configuration object pConfig as appropriate.
187863 ** If successful, object pConfig is updated and SQLITE_OK returned. If
187864 ** an error occurs, an SQLite error code is returned and an error message
187865 ** may be left in *pzErr. It is the responsibility of the caller to
187866 ** eventually free any such error message using sqlite3_free().
187868 static int fts5ConfigParseSpecial(
187869 Fts5Global *pGlobal,
187870 Fts5Config *pConfig, /* Configuration object to update */
187871 const char *zCmd, /* Special command to parse */
187872 const char *zArg, /* Argument to parse */
187873 char **pzErr /* OUT: Error message */
187875 int rc = SQLITE_OK;
187876 int nCmd = (int)strlen(zCmd);
187877 if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
187878 const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
187879 const char *p;
187880 int bFirst = 1;
187881 if( pConfig->aPrefix==0 ){
187882 pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
187883 if( rc ) return rc;
187886 p = zArg;
187887 while( 1 ){
187888 int nPre = 0;
187890 while( p[0]==' ' ) p++;
187891 if( bFirst==0 && p[0]==',' ){
187893 while( p[0]==' ' ) p++;
187894 }else if( p[0]=='\0' ){
187895 break;
187897 if( p[0]<'0' || p[0]>'9' ){
187898 *pzErr = sqlite3_mprintf("malformed prefix=... directive");
187899 rc = SQLITE_ERROR;
187900 break;
187903 if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
187904 *pzErr = sqlite3_mprintf(
187905 "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
187907 rc = SQLITE_ERROR;
187908 break;
187911 while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
187912 nPre = nPre*10 + (p[0] - '0');
187916 if( nPre<=0 || nPre>=1000 ){
187917 *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
187918 rc = SQLITE_ERROR;
187919 break;
187922 pConfig->aPrefix[pConfig->nPrefix] = nPre;
187923 pConfig->nPrefix++;
187924 bFirst = 0;
187926 assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
187927 return rc;
187930 if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
187931 const char *p = (const char*)zArg;
187932 int nArg = (int)strlen(zArg) + 1;
187933 char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
187934 char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
187935 char *pSpace = pDel;
187937 if( azArg && pSpace ){
187938 if( pConfig->pTok ){
187939 *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
187940 rc = SQLITE_ERROR;
187941 }else{
187942 for(nArg=0; p && *p; nArg++){
187943 const char *p2 = fts5ConfigSkipWhitespace(p);
187944 if( *p2=='\'' ){
187945 p = fts5ConfigSkipLiteral(p2);
187946 }else{
187947 p = fts5ConfigSkipBareword(p2);
187949 if( p ){
187950 memcpy(pSpace, p2, p-p2);
187951 azArg[nArg] = pSpace;
187952 sqlite3Fts5Dequote(pSpace);
187953 pSpace += (p - p2) + 1;
187954 p = fts5ConfigSkipWhitespace(p);
187957 if( p==0 ){
187958 *pzErr = sqlite3_mprintf("parse error in tokenize directive");
187959 rc = SQLITE_ERROR;
187960 }else{
187961 rc = sqlite3Fts5GetTokenizer(pGlobal,
187962 (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
187963 pzErr
187969 sqlite3_free(azArg);
187970 sqlite3_free(pDel);
187971 return rc;
187974 if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
187975 if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
187976 *pzErr = sqlite3_mprintf("multiple content=... directives");
187977 rc = SQLITE_ERROR;
187978 }else{
187979 if( zArg[0] ){
187980 pConfig->eContent = FTS5_CONTENT_EXTERNAL;
187981 pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
187982 }else{
187983 pConfig->eContent = FTS5_CONTENT_NONE;
187986 return rc;
187989 if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
187990 if( pConfig->zContentRowid ){
187991 *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
187992 rc = SQLITE_ERROR;
187993 }else{
187994 pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
187996 return rc;
187999 if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
188000 if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
188001 *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
188002 rc = SQLITE_ERROR;
188003 }else{
188004 pConfig->bColumnsize = (zArg[0]=='1');
188006 return rc;
188009 if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
188010 const Fts5Enum aDetail[] = {
188011 { "none", FTS5_DETAIL_NONE },
188012 { "full", FTS5_DETAIL_FULL },
188013 { "columns", FTS5_DETAIL_COLUMNS },
188014 { 0, 0 }
188017 if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
188018 *pzErr = sqlite3_mprintf("malformed detail=... directive");
188020 return rc;
188023 *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
188024 return SQLITE_ERROR;
188028 ** Allocate an instance of the default tokenizer ("simple") at
188029 ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
188030 ** code if an error occurs.
188032 static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
188033 assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
188034 return sqlite3Fts5GetTokenizer(
188035 pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
188040 ** Gobble up the first bareword or quoted word from the input buffer zIn.
188041 ** Return a pointer to the character immediately following the last in
188042 ** the gobbled word if successful, or a NULL pointer otherwise (failed
188043 ** to find close-quote character).
188045 ** Before returning, set pzOut to point to a new buffer containing a
188046 ** nul-terminated, dequoted copy of the gobbled word. If the word was
188047 ** quoted, *pbQuoted is also set to 1 before returning.
188049 ** If *pRc is other than SQLITE_OK when this function is called, it is
188050 ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
188051 ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
188052 ** set if a parse error (failed to find close quote) occurs.
188054 static const char *fts5ConfigGobbleWord(
188055 int *pRc, /* IN/OUT: Error code */
188056 const char *zIn, /* Buffer to gobble string/bareword from */
188057 char **pzOut, /* OUT: malloc'd buffer containing str/bw */
188058 int *pbQuoted /* OUT: Set to true if dequoting required */
188060 const char *zRet = 0;
188062 int nIn = (int)strlen(zIn);
188063 char *zOut = sqlite3_malloc(nIn+1);
188065 assert( *pRc==SQLITE_OK );
188066 *pbQuoted = 0;
188067 *pzOut = 0;
188069 if( zOut==0 ){
188070 *pRc = SQLITE_NOMEM;
188071 }else{
188072 memcpy(zOut, zIn, nIn+1);
188073 if( fts5_isopenquote(zOut[0]) ){
188074 int ii = fts5Dequote(zOut);
188075 zRet = &zIn[ii];
188076 *pbQuoted = 1;
188077 }else{
188078 zRet = fts5ConfigSkipBareword(zIn);
188079 if( zRet ){
188080 zOut[zRet-zIn] = '\0';
188085 if( zRet==0 ){
188086 sqlite3_free(zOut);
188087 }else{
188088 *pzOut = zOut;
188091 return zRet;
188094 static int fts5ConfigParseColumn(
188095 Fts5Config *p,
188096 char *zCol,
188097 char *zArg,
188098 char **pzErr
188100 int rc = SQLITE_OK;
188101 if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
188102 || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
188104 *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
188105 rc = SQLITE_ERROR;
188106 }else if( zArg ){
188107 if( 0==sqlite3_stricmp(zArg, "unindexed") ){
188108 p->abUnindexed[p->nCol] = 1;
188109 }else{
188110 *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
188111 rc = SQLITE_ERROR;
188115 p->azCol[p->nCol++] = zCol;
188116 return rc;
188120 ** Populate the Fts5Config.zContentExprlist string.
188122 static int fts5ConfigMakeExprlist(Fts5Config *p){
188123 int i;
188124 int rc = SQLITE_OK;
188125 Fts5Buffer buf = {0, 0, 0};
188127 sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
188128 if( p->eContent!=FTS5_CONTENT_NONE ){
188129 for(i=0; i<p->nCol; i++){
188130 if( p->eContent==FTS5_CONTENT_EXTERNAL ){
188131 sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
188132 }else{
188133 sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
188138 assert( p->zContentExprlist==0 );
188139 p->zContentExprlist = (char*)buf.p;
188140 return rc;
188144 ** Arguments nArg/azArg contain the string arguments passed to the xCreate
188145 ** or xConnect method of the virtual table. This function attempts to
188146 ** allocate an instance of Fts5Config containing the results of parsing
188147 ** those arguments.
188149 ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
188150 ** new Fts5Config object. If an error occurs, an SQLite error code is
188151 ** returned, *ppOut is set to NULL and an error message may be left in
188152 ** *pzErr. It is the responsibility of the caller to eventually free any
188153 ** such error message using sqlite3_free().
188155 static int sqlite3Fts5ConfigParse(
188156 Fts5Global *pGlobal,
188157 sqlite3 *db,
188158 int nArg, /* Number of arguments */
188159 const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
188160 Fts5Config **ppOut, /* OUT: Results of parse */
188161 char **pzErr /* OUT: Error message */
188163 int rc = SQLITE_OK; /* Return code */
188164 Fts5Config *pRet; /* New object to return */
188165 int i;
188166 int nByte;
188168 *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
188169 if( pRet==0 ) return SQLITE_NOMEM;
188170 memset(pRet, 0, sizeof(Fts5Config));
188171 pRet->db = db;
188172 pRet->iCookie = -1;
188174 nByte = nArg * (sizeof(char*) + sizeof(u8));
188175 pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
188176 pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
188177 pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
188178 pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
188179 pRet->bColumnsize = 1;
188180 pRet->eDetail = FTS5_DETAIL_FULL;
188181 #ifdef SQLITE_DEBUG
188182 pRet->bPrefixIndex = 1;
188183 #endif
188184 if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
188185 *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
188186 rc = SQLITE_ERROR;
188189 for(i=3; rc==SQLITE_OK && i<nArg; i++){
188190 const char *zOrig = azArg[i];
188191 const char *z;
188192 char *zOne = 0;
188193 char *zTwo = 0;
188194 int bOption = 0;
188195 int bMustBeCol = 0;
188197 z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
188198 z = fts5ConfigSkipWhitespace(z);
188199 if( z && *z=='=' ){
188200 bOption = 1;
188202 if( bMustBeCol ) z = 0;
188204 z = fts5ConfigSkipWhitespace(z);
188205 if( z && z[0] ){
188206 int bDummy;
188207 z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
188208 if( z && z[0] ) z = 0;
188211 if( rc==SQLITE_OK ){
188212 if( z==0 ){
188213 *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
188214 rc = SQLITE_ERROR;
188215 }else{
188216 if( bOption ){
188217 rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
188218 }else{
188219 rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
188220 zOne = 0;
188225 sqlite3_free(zOne);
188226 sqlite3_free(zTwo);
188229 /* If a tokenizer= option was successfully parsed, the tokenizer has
188230 ** already been allocated. Otherwise, allocate an instance of the default
188231 ** tokenizer (unicode61) now. */
188232 if( rc==SQLITE_OK && pRet->pTok==0 ){
188233 rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
188236 /* If no zContent option was specified, fill in the default values. */
188237 if( rc==SQLITE_OK && pRet->zContent==0 ){
188238 const char *zTail = 0;
188239 assert( pRet->eContent==FTS5_CONTENT_NORMAL
188240 || pRet->eContent==FTS5_CONTENT_NONE
188242 if( pRet->eContent==FTS5_CONTENT_NORMAL ){
188243 zTail = "content";
188244 }else if( pRet->bColumnsize ){
188245 zTail = "docsize";
188248 if( zTail ){
188249 pRet->zContent = sqlite3Fts5Mprintf(
188250 &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
188255 if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
188256 pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
188259 /* Formulate the zContentExprlist text */
188260 if( rc==SQLITE_OK ){
188261 rc = fts5ConfigMakeExprlist(pRet);
188264 if( rc!=SQLITE_OK ){
188265 sqlite3Fts5ConfigFree(pRet);
188266 *ppOut = 0;
188268 return rc;
188272 ** Free the configuration object passed as the only argument.
188274 static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
188275 if( pConfig ){
188276 int i;
188277 if( pConfig->pTok ){
188278 pConfig->pTokApi->xDelete(pConfig->pTok);
188280 sqlite3_free(pConfig->zDb);
188281 sqlite3_free(pConfig->zName);
188282 for(i=0; i<pConfig->nCol; i++){
188283 sqlite3_free(pConfig->azCol[i]);
188285 sqlite3_free(pConfig->azCol);
188286 sqlite3_free(pConfig->aPrefix);
188287 sqlite3_free(pConfig->zRank);
188288 sqlite3_free(pConfig->zRankArgs);
188289 sqlite3_free(pConfig->zContent);
188290 sqlite3_free(pConfig->zContentRowid);
188291 sqlite3_free(pConfig->zContentExprlist);
188292 sqlite3_free(pConfig);
188297 ** Call sqlite3_declare_vtab() based on the contents of the configuration
188298 ** object passed as the only argument. Return SQLITE_OK if successful, or
188299 ** an SQLite error code if an error occurs.
188301 static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
188302 int i;
188303 int rc = SQLITE_OK;
188304 char *zSql;
188306 zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
188307 for(i=0; zSql && i<pConfig->nCol; i++){
188308 const char *zSep = (i==0?"":", ");
188309 zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
188311 zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
188312 zSql, pConfig->zName, FTS5_RANK_NAME
188315 assert( zSql || rc==SQLITE_NOMEM );
188316 if( zSql ){
188317 rc = sqlite3_declare_vtab(pConfig->db, zSql);
188318 sqlite3_free(zSql);
188321 return rc;
188325 ** Tokenize the text passed via the second and third arguments.
188327 ** The callback is invoked once for each token in the input text. The
188328 ** arguments passed to it are, in order:
188330 ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
188331 ** const char *pToken // Pointer to buffer containing token
188332 ** int nToken // Size of token in bytes
188333 ** int iStart // Byte offset of start of token within input text
188334 ** int iEnd // Byte offset of end of token within input text
188335 ** int iPos // Position of token in input (first token is 0)
188337 ** If the callback returns a non-zero value the tokenization is abandoned
188338 ** and no further callbacks are issued.
188340 ** This function returns SQLITE_OK if successful or an SQLite error code
188341 ** if an error occurs. If the tokenization was abandoned early because
188342 ** the callback returned SQLITE_DONE, this is not an error and this function
188343 ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
188344 ** because the callback returned another non-zero value, it is assumed
188345 ** to be an SQLite error code and returned to the caller.
188347 static int sqlite3Fts5Tokenize(
188348 Fts5Config *pConfig, /* FTS5 Configuration object */
188349 int flags, /* FTS5_TOKENIZE_* flags */
188350 const char *pText, int nText, /* Text to tokenize */
188351 void *pCtx, /* Context passed to xToken() */
188352 int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
188354 if( pText==0 ) return SQLITE_OK;
188355 return pConfig->pTokApi->xTokenize(
188356 pConfig->pTok, pCtx, flags, pText, nText, xToken
188361 ** Argument pIn points to the first character in what is expected to be
188362 ** a comma-separated list of SQL literals followed by a ')' character.
188363 ** If it actually is this, return a pointer to the ')'. Otherwise, return
188364 ** NULL to indicate a parse error.
188366 static const char *fts5ConfigSkipArgs(const char *pIn){
188367 const char *p = pIn;
188369 while( 1 ){
188370 p = fts5ConfigSkipWhitespace(p);
188371 p = fts5ConfigSkipLiteral(p);
188372 p = fts5ConfigSkipWhitespace(p);
188373 if( p==0 || *p==')' ) break;
188374 if( *p!=',' ){
188375 p = 0;
188376 break;
188381 return p;
188385 ** Parameter zIn contains a rank() function specification. The format of
188386 ** this is:
188388 ** + Bareword (function name)
188389 ** + Open parenthesis - "("
188390 ** + Zero or more SQL literals in a comma separated list
188391 ** + Close parenthesis - ")"
188393 static int sqlite3Fts5ConfigParseRank(
188394 const char *zIn, /* Input string */
188395 char **pzRank, /* OUT: Rank function name */
188396 char **pzRankArgs /* OUT: Rank function arguments */
188398 const char *p = zIn;
188399 const char *pRank;
188400 char *zRank = 0;
188401 char *zRankArgs = 0;
188402 int rc = SQLITE_OK;
188404 *pzRank = 0;
188405 *pzRankArgs = 0;
188407 if( p==0 ){
188408 rc = SQLITE_ERROR;
188409 }else{
188410 p = fts5ConfigSkipWhitespace(p);
188411 pRank = p;
188412 p = fts5ConfigSkipBareword(p);
188414 if( p ){
188415 zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
188416 if( zRank ) memcpy(zRank, pRank, p-pRank);
188417 }else{
188418 rc = SQLITE_ERROR;
188421 if( rc==SQLITE_OK ){
188422 p = fts5ConfigSkipWhitespace(p);
188423 if( *p!='(' ) rc = SQLITE_ERROR;
188426 if( rc==SQLITE_OK ){
188427 const char *pArgs;
188428 p = fts5ConfigSkipWhitespace(p);
188429 pArgs = p;
188430 if( *p!=')' ){
188431 p = fts5ConfigSkipArgs(p);
188432 if( p==0 ){
188433 rc = SQLITE_ERROR;
188434 }else{
188435 zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
188436 if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
188442 if( rc!=SQLITE_OK ){
188443 sqlite3_free(zRank);
188444 assert( zRankArgs==0 );
188445 }else{
188446 *pzRank = zRank;
188447 *pzRankArgs = zRankArgs;
188449 return rc;
188452 static int sqlite3Fts5ConfigSetValue(
188453 Fts5Config *pConfig,
188454 const char *zKey,
188455 sqlite3_value *pVal,
188456 int *pbBadkey
188458 int rc = SQLITE_OK;
188460 if( 0==sqlite3_stricmp(zKey, "pgsz") ){
188461 int pgsz = 0;
188462 if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
188463 pgsz = sqlite3_value_int(pVal);
188465 if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
188466 *pbBadkey = 1;
188467 }else{
188468 pConfig->pgsz = pgsz;
188472 else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
188473 int nHashSize = -1;
188474 if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
188475 nHashSize = sqlite3_value_int(pVal);
188477 if( nHashSize<=0 ){
188478 *pbBadkey = 1;
188479 }else{
188480 pConfig->nHashSize = nHashSize;
188484 else if( 0==sqlite3_stricmp(zKey, "automerge") ){
188485 int nAutomerge = -1;
188486 if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
188487 nAutomerge = sqlite3_value_int(pVal);
188489 if( nAutomerge<0 || nAutomerge>64 ){
188490 *pbBadkey = 1;
188491 }else{
188492 if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
188493 pConfig->nAutomerge = nAutomerge;
188497 else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
188498 int nUsermerge = -1;
188499 if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
188500 nUsermerge = sqlite3_value_int(pVal);
188502 if( nUsermerge<2 || nUsermerge>16 ){
188503 *pbBadkey = 1;
188504 }else{
188505 pConfig->nUsermerge = nUsermerge;
188509 else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
188510 int nCrisisMerge = -1;
188511 if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
188512 nCrisisMerge = sqlite3_value_int(pVal);
188514 if( nCrisisMerge<0 ){
188515 *pbBadkey = 1;
188516 }else{
188517 if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
188518 pConfig->nCrisisMerge = nCrisisMerge;
188522 else if( 0==sqlite3_stricmp(zKey, "rank") ){
188523 const char *zIn = (const char*)sqlite3_value_text(pVal);
188524 char *zRank;
188525 char *zRankArgs;
188526 rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
188527 if( rc==SQLITE_OK ){
188528 sqlite3_free(pConfig->zRank);
188529 sqlite3_free(pConfig->zRankArgs);
188530 pConfig->zRank = zRank;
188531 pConfig->zRankArgs = zRankArgs;
188532 }else if( rc==SQLITE_ERROR ){
188533 rc = SQLITE_OK;
188534 *pbBadkey = 1;
188536 }else{
188537 *pbBadkey = 1;
188539 return rc;
188543 ** Load the contents of the %_config table into memory.
188545 static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
188546 const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
188547 char *zSql;
188548 sqlite3_stmt *p = 0;
188549 int rc = SQLITE_OK;
188550 int iVersion = 0;
188552 /* Set default values */
188553 pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
188554 pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
188555 pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
188556 pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
188557 pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
188559 zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
188560 if( zSql ){
188561 rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
188562 sqlite3_free(zSql);
188565 assert( rc==SQLITE_OK || p==0 );
188566 if( rc==SQLITE_OK ){
188567 while( SQLITE_ROW==sqlite3_step(p) ){
188568 const char *zK = (const char*)sqlite3_column_text(p, 0);
188569 sqlite3_value *pVal = sqlite3_column_value(p, 1);
188570 if( 0==sqlite3_stricmp(zK, "version") ){
188571 iVersion = sqlite3_value_int(pVal);
188572 }else{
188573 int bDummy = 0;
188574 sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
188577 rc = sqlite3_finalize(p);
188580 if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
188581 rc = SQLITE_ERROR;
188582 if( pConfig->pzErrmsg ){
188583 assert( 0==*pConfig->pzErrmsg );
188584 *pConfig->pzErrmsg = sqlite3_mprintf(
188585 "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
188586 iVersion, FTS5_CURRENT_VERSION
188591 if( rc==SQLITE_OK ){
188592 pConfig->iCookie = iCookie;
188594 return rc;
188598 ** 2014 May 31
188600 ** The author disclaims copyright to this source code. In place of
188601 ** a legal notice, here is a blessing:
188603 ** May you do good and not evil.
188604 ** May you find forgiveness for yourself and forgive others.
188605 ** May you share freely, never taking more than you give.
188607 ******************************************************************************
188613 /* #include "fts5Int.h" */
188614 /* #include "fts5parse.h" */
188617 ** All token types in the generated fts5parse.h file are greater than 0.
188619 #define FTS5_EOF 0
188621 #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
188623 typedef struct Fts5ExprTerm Fts5ExprTerm;
188626 ** Functions generated by lemon from fts5parse.y.
188628 static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
188629 static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
188630 static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
188631 #ifndef NDEBUG
188632 /* #include <stdio.h> */
188633 static void sqlite3Fts5ParserTrace(FILE*, char*);
188634 #endif
188637 struct Fts5Expr {
188638 Fts5Index *pIndex;
188639 Fts5Config *pConfig;
188640 Fts5ExprNode *pRoot;
188641 int bDesc; /* Iterate in descending rowid order */
188642 int nPhrase; /* Number of phrases in expression */
188643 Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
188647 ** eType:
188648 ** Expression node type. Always one of:
188650 ** FTS5_AND (nChild, apChild valid)
188651 ** FTS5_OR (nChild, apChild valid)
188652 ** FTS5_NOT (nChild, apChild valid)
188653 ** FTS5_STRING (pNear valid)
188654 ** FTS5_TERM (pNear valid)
188656 struct Fts5ExprNode {
188657 int eType; /* Node type */
188658 int bEof; /* True at EOF */
188659 int bNomatch; /* True if entry is not a match */
188661 /* Next method for this node. */
188662 int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
188664 i64 iRowid; /* Current rowid */
188665 Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
188667 /* Child nodes. For a NOT node, this array always contains 2 entries. For
188668 ** AND or OR nodes, it contains 2 or more entries. */
188669 int nChild; /* Number of child nodes */
188670 Fts5ExprNode *apChild[1]; /* Array of child nodes */
188673 #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
188676 ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
188677 ** used as if it has the same signature as the xNext() methods themselves.
188679 #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
188682 ** An instance of the following structure represents a single search term
188683 ** or term prefix.
188685 struct Fts5ExprTerm {
188686 int bPrefix; /* True for a prefix term */
188687 char *zTerm; /* nul-terminated term */
188688 Fts5IndexIter *pIter; /* Iterator for this term */
188689 Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
188693 ** A phrase. One or more terms that must appear in a contiguous sequence
188694 ** within a document for it to match.
188696 struct Fts5ExprPhrase {
188697 Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
188698 Fts5Buffer poslist; /* Current position list */
188699 int nTerm; /* Number of entries in aTerm[] */
188700 Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
188704 ** One or more phrases that must appear within a certain token distance of
188705 ** each other within each matching document.
188707 struct Fts5ExprNearset {
188708 int nNear; /* NEAR parameter */
188709 Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
188710 int nPhrase; /* Number of entries in aPhrase[] array */
188711 Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
188716 ** Parse context.
188718 struct Fts5Parse {
188719 Fts5Config *pConfig;
188720 char *zErr;
188721 int rc;
188722 int nPhrase; /* Size of apPhrase array */
188723 Fts5ExprPhrase **apPhrase; /* Array of all phrases */
188724 Fts5ExprNode *pExpr; /* Result of a successful parse */
188727 static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
188728 va_list ap;
188729 va_start(ap, zFmt);
188730 if( pParse->rc==SQLITE_OK ){
188731 pParse->zErr = sqlite3_vmprintf(zFmt, ap);
188732 pParse->rc = SQLITE_ERROR;
188734 va_end(ap);
188737 static int fts5ExprIsspace(char t){
188738 return t==' ' || t=='\t' || t=='\n' || t=='\r';
188742 ** Read the first token from the nul-terminated string at *pz.
188744 static int fts5ExprGetToken(
188745 Fts5Parse *pParse,
188746 const char **pz, /* IN/OUT: Pointer into buffer */
188747 Fts5Token *pToken
188749 const char *z = *pz;
188750 int tok;
188752 /* Skip past any whitespace */
188753 while( fts5ExprIsspace(*z) ) z++;
188755 pToken->p = z;
188756 pToken->n = 1;
188757 switch( *z ){
188758 case '(': tok = FTS5_LP; break;
188759 case ')': tok = FTS5_RP; break;
188760 case '{': tok = FTS5_LCP; break;
188761 case '}': tok = FTS5_RCP; break;
188762 case ':': tok = FTS5_COLON; break;
188763 case ',': tok = FTS5_COMMA; break;
188764 case '+': tok = FTS5_PLUS; break;
188765 case '*': tok = FTS5_STAR; break;
188766 case '-': tok = FTS5_MINUS; break;
188767 case '\0': tok = FTS5_EOF; break;
188769 case '"': {
188770 const char *z2;
188771 tok = FTS5_STRING;
188773 for(z2=&z[1]; 1; z2++){
188774 if( z2[0]=='"' ){
188775 z2++;
188776 if( z2[0]!='"' ) break;
188778 if( z2[0]=='\0' ){
188779 sqlite3Fts5ParseError(pParse, "unterminated string");
188780 return FTS5_EOF;
188783 pToken->n = (z2 - z);
188784 break;
188787 default: {
188788 const char *z2;
188789 if( sqlite3Fts5IsBareword(z[0])==0 ){
188790 sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
188791 return FTS5_EOF;
188793 tok = FTS5_STRING;
188794 for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
188795 pToken->n = (z2 - z);
188796 if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
188797 if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
188798 if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
188799 break;
188803 *pz = &pToken->p[pToken->n];
188804 return tok;
188807 static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
188808 static void fts5ParseFree(void *p){ sqlite3_free(p); }
188810 static int sqlite3Fts5ExprNew(
188811 Fts5Config *pConfig, /* FTS5 Configuration */
188812 int iCol,
188813 const char *zExpr, /* Expression text */
188814 Fts5Expr **ppNew,
188815 char **pzErr
188817 Fts5Parse sParse;
188818 Fts5Token token;
188819 const char *z = zExpr;
188820 int t; /* Next token type */
188821 void *pEngine;
188822 Fts5Expr *pNew;
188824 *ppNew = 0;
188825 *pzErr = 0;
188826 memset(&sParse, 0, sizeof(sParse));
188827 pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
188828 if( pEngine==0 ){ return SQLITE_NOMEM; }
188829 sParse.pConfig = pConfig;
188832 t = fts5ExprGetToken(&sParse, &z, &token);
188833 sqlite3Fts5Parser(pEngine, t, token, &sParse);
188834 }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
188835 sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
188837 /* If the LHS of the MATCH expression was a user column, apply the
188838 ** implicit column-filter. */
188839 if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
188840 int n = sizeof(Fts5Colset);
188841 Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
188842 if( pColset ){
188843 pColset->nCol = 1;
188844 pColset->aiCol[0] = iCol;
188845 sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
188849 assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
188850 if( sParse.rc==SQLITE_OK ){
188851 *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
188852 if( pNew==0 ){
188853 sParse.rc = SQLITE_NOMEM;
188854 sqlite3Fts5ParseNodeFree(sParse.pExpr);
188855 }else{
188856 if( !sParse.pExpr ){
188857 const int nByte = sizeof(Fts5ExprNode);
188858 pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
188859 if( pNew->pRoot ){
188860 pNew->pRoot->bEof = 1;
188862 }else{
188863 pNew->pRoot = sParse.pExpr;
188865 pNew->pIndex = 0;
188866 pNew->pConfig = pConfig;
188867 pNew->apExprPhrase = sParse.apPhrase;
188868 pNew->nPhrase = sParse.nPhrase;
188869 sParse.apPhrase = 0;
188871 }else{
188872 sqlite3Fts5ParseNodeFree(sParse.pExpr);
188875 sqlite3_free(sParse.apPhrase);
188876 *pzErr = sParse.zErr;
188877 return sParse.rc;
188881 ** Free the expression node object passed as the only argument.
188883 static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
188884 if( p ){
188885 int i;
188886 for(i=0; i<p->nChild; i++){
188887 sqlite3Fts5ParseNodeFree(p->apChild[i]);
188889 sqlite3Fts5ParseNearsetFree(p->pNear);
188890 sqlite3_free(p);
188895 ** Free the expression object passed as the only argument.
188897 static void sqlite3Fts5ExprFree(Fts5Expr *p){
188898 if( p ){
188899 sqlite3Fts5ParseNodeFree(p->pRoot);
188900 sqlite3_free(p->apExprPhrase);
188901 sqlite3_free(p);
188906 ** Argument pTerm must be a synonym iterator. Return the current rowid
188907 ** that it points to.
188909 static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
188910 i64 iRet = 0;
188911 int bRetValid = 0;
188912 Fts5ExprTerm *p;
188914 assert( pTerm->pSynonym );
188915 assert( bDesc==0 || bDesc==1 );
188916 for(p=pTerm; p; p=p->pSynonym){
188917 if( 0==sqlite3Fts5IterEof(p->pIter) ){
188918 i64 iRowid = p->pIter->iRowid;
188919 if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
188920 iRet = iRowid;
188921 bRetValid = 1;
188926 if( pbEof && bRetValid==0 ) *pbEof = 1;
188927 return iRet;
188931 ** Argument pTerm must be a synonym iterator.
188933 static int fts5ExprSynonymList(
188934 Fts5ExprTerm *pTerm,
188935 i64 iRowid,
188936 Fts5Buffer *pBuf, /* Use this buffer for space if required */
188937 u8 **pa, int *pn
188939 Fts5PoslistReader aStatic[4];
188940 Fts5PoslistReader *aIter = aStatic;
188941 int nIter = 0;
188942 int nAlloc = 4;
188943 int rc = SQLITE_OK;
188944 Fts5ExprTerm *p;
188946 assert( pTerm->pSynonym );
188947 for(p=pTerm; p; p=p->pSynonym){
188948 Fts5IndexIter *pIter = p->pIter;
188949 if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
188950 if( pIter->nData==0 ) continue;
188951 if( nIter==nAlloc ){
188952 int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
188953 Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
188954 if( aNew==0 ){
188955 rc = SQLITE_NOMEM;
188956 goto synonym_poslist_out;
188958 memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
188959 nAlloc = nAlloc*2;
188960 if( aIter!=aStatic ) sqlite3_free(aIter);
188961 aIter = aNew;
188963 sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
188964 assert( aIter[nIter].bEof==0 );
188965 nIter++;
188969 if( nIter==1 ){
188970 *pa = (u8*)aIter[0].a;
188971 *pn = aIter[0].n;
188972 }else{
188973 Fts5PoslistWriter writer = {0};
188974 i64 iPrev = -1;
188975 fts5BufferZero(pBuf);
188976 while( 1 ){
188977 int i;
188978 i64 iMin = FTS5_LARGEST_INT64;
188979 for(i=0; i<nIter; i++){
188980 if( aIter[i].bEof==0 ){
188981 if( aIter[i].iPos==iPrev ){
188982 if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
188984 if( aIter[i].iPos<iMin ){
188985 iMin = aIter[i].iPos;
188989 if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
188990 rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
188991 iPrev = iMin;
188993 if( rc==SQLITE_OK ){
188994 *pa = pBuf->p;
188995 *pn = pBuf->n;
188999 synonym_poslist_out:
189000 if( aIter!=aStatic ) sqlite3_free(aIter);
189001 return rc;
189006 ** All individual term iterators in pPhrase are guaranteed to be valid and
189007 ** pointing to the same rowid when this function is called. This function
189008 ** checks if the current rowid really is a match, and if so populates
189009 ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
189010 ** is set to true if this is really a match, or false otherwise.
189012 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
189013 ** otherwise. It is not considered an error code if the current rowid is
189014 ** not a match.
189016 static int fts5ExprPhraseIsMatch(
189017 Fts5ExprNode *pNode, /* Node pPhrase belongs to */
189018 Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
189019 int *pbMatch /* OUT: Set to true if really a match */
189021 Fts5PoslistWriter writer = {0};
189022 Fts5PoslistReader aStatic[4];
189023 Fts5PoslistReader *aIter = aStatic;
189024 int i;
189025 int rc = SQLITE_OK;
189027 fts5BufferZero(&pPhrase->poslist);
189029 /* If the aStatic[] array is not large enough, allocate a large array
189030 ** using sqlite3_malloc(). This approach could be improved upon. */
189031 if( pPhrase->nTerm>ArraySize(aStatic) ){
189032 int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
189033 aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
189034 if( !aIter ) return SQLITE_NOMEM;
189036 memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
189038 /* Initialize a term iterator for each term in the phrase */
189039 for(i=0; i<pPhrase->nTerm; i++){
189040 Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
189041 int n = 0;
189042 int bFlag = 0;
189043 u8 *a = 0;
189044 if( pTerm->pSynonym ){
189045 Fts5Buffer buf = {0, 0, 0};
189046 rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
189047 if( rc ){
189048 sqlite3_free(a);
189049 goto ismatch_out;
189051 if( a==buf.p ) bFlag = 1;
189052 }else{
189053 a = (u8*)pTerm->pIter->pData;
189054 n = pTerm->pIter->nData;
189056 sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
189057 aIter[i].bFlag = (u8)bFlag;
189058 if( aIter[i].bEof ) goto ismatch_out;
189061 while( 1 ){
189062 int bMatch;
189063 i64 iPos = aIter[0].iPos;
189065 bMatch = 1;
189066 for(i=0; i<pPhrase->nTerm; i++){
189067 Fts5PoslistReader *pPos = &aIter[i];
189068 i64 iAdj = iPos + i;
189069 if( pPos->iPos!=iAdj ){
189070 bMatch = 0;
189071 while( pPos->iPos<iAdj ){
189072 if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
189074 if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
189077 }while( bMatch==0 );
189079 /* Append position iPos to the output */
189080 rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
189081 if( rc!=SQLITE_OK ) goto ismatch_out;
189083 for(i=0; i<pPhrase->nTerm; i++){
189084 if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
189088 ismatch_out:
189089 *pbMatch = (pPhrase->poslist.n>0);
189090 for(i=0; i<pPhrase->nTerm; i++){
189091 if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
189093 if( aIter!=aStatic ) sqlite3_free(aIter);
189094 return rc;
189097 typedef struct Fts5LookaheadReader Fts5LookaheadReader;
189098 struct Fts5LookaheadReader {
189099 const u8 *a; /* Buffer containing position list */
189100 int n; /* Size of buffer a[] in bytes */
189101 int i; /* Current offset in position list */
189102 i64 iPos; /* Current position */
189103 i64 iLookahead; /* Next position */
189106 #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
189108 static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
189109 p->iPos = p->iLookahead;
189110 if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
189111 p->iLookahead = FTS5_LOOKAHEAD_EOF;
189113 return (p->iPos==FTS5_LOOKAHEAD_EOF);
189116 static int fts5LookaheadReaderInit(
189117 const u8 *a, int n, /* Buffer to read position list from */
189118 Fts5LookaheadReader *p /* Iterator object to initialize */
189120 memset(p, 0, sizeof(Fts5LookaheadReader));
189121 p->a = a;
189122 p->n = n;
189123 fts5LookaheadReaderNext(p);
189124 return fts5LookaheadReaderNext(p);
189127 typedef struct Fts5NearTrimmer Fts5NearTrimmer;
189128 struct Fts5NearTrimmer {
189129 Fts5LookaheadReader reader; /* Input iterator */
189130 Fts5PoslistWriter writer; /* Writer context */
189131 Fts5Buffer *pOut; /* Output poslist */
189135 ** The near-set object passed as the first argument contains more than
189136 ** one phrase. All phrases currently point to the same row. The
189137 ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
189138 ** tests if the current row contains instances of each phrase sufficiently
189139 ** close together to meet the NEAR constraint. Non-zero is returned if it
189140 ** does, or zero otherwise.
189142 ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
189143 ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
189144 ** occurs within this function (*pRc) is set accordingly before returning.
189145 ** The return value is undefined in both these cases.
189147 ** If no error occurs and non-zero (a match) is returned, the position-list
189148 ** of each phrase object is edited to contain only those entries that
189149 ** meet the constraint before returning.
189151 static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
189152 Fts5NearTrimmer aStatic[4];
189153 Fts5NearTrimmer *a = aStatic;
189154 Fts5ExprPhrase **apPhrase = pNear->apPhrase;
189156 int i;
189157 int rc = *pRc;
189158 int bMatch;
189160 assert( pNear->nPhrase>1 );
189162 /* If the aStatic[] array is not large enough, allocate a large array
189163 ** using sqlite3_malloc(). This approach could be improved upon. */
189164 if( pNear->nPhrase>ArraySize(aStatic) ){
189165 int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
189166 a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
189167 }else{
189168 memset(aStatic, 0, sizeof(aStatic));
189170 if( rc!=SQLITE_OK ){
189171 *pRc = rc;
189172 return 0;
189175 /* Initialize a lookahead iterator for each phrase. After passing the
189176 ** buffer and buffer size to the lookaside-reader init function, zero
189177 ** the phrase poslist buffer. The new poslist for the phrase (containing
189178 ** the same entries as the original with some entries removed on account
189179 ** of the NEAR constraint) is written over the original even as it is
189180 ** being read. This is safe as the entries for the new poslist are a
189181 ** subset of the old, so it is not possible for data yet to be read to
189182 ** be overwritten. */
189183 for(i=0; i<pNear->nPhrase; i++){
189184 Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
189185 fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
189186 pPoslist->n = 0;
189187 a[i].pOut = pPoslist;
189190 while( 1 ){
189191 int iAdv;
189192 i64 iMin;
189193 i64 iMax;
189195 /* This block advances the phrase iterators until they point to a set of
189196 ** entries that together comprise a match. */
189197 iMax = a[0].reader.iPos;
189199 bMatch = 1;
189200 for(i=0; i<pNear->nPhrase; i++){
189201 Fts5LookaheadReader *pPos = &a[i].reader;
189202 iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
189203 if( pPos->iPos<iMin || pPos->iPos>iMax ){
189204 bMatch = 0;
189205 while( pPos->iPos<iMin ){
189206 if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
189208 if( pPos->iPos>iMax ) iMax = pPos->iPos;
189211 }while( bMatch==0 );
189213 /* Add an entry to each output position list */
189214 for(i=0; i<pNear->nPhrase; i++){
189215 i64 iPos = a[i].reader.iPos;
189216 Fts5PoslistWriter *pWriter = &a[i].writer;
189217 if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
189218 sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
189222 iAdv = 0;
189223 iMin = a[0].reader.iLookahead;
189224 for(i=0; i<pNear->nPhrase; i++){
189225 if( a[i].reader.iLookahead < iMin ){
189226 iMin = a[i].reader.iLookahead;
189227 iAdv = i;
189230 if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
189233 ismatch_out: {
189234 int bRet = a[0].pOut->n>0;
189235 *pRc = rc;
189236 if( a!=aStatic ) sqlite3_free(a);
189237 return bRet;
189242 ** Advance iterator pIter until it points to a value equal to or laster
189243 ** than the initial value of *piLast. If this means the iterator points
189244 ** to a value laster than *piLast, update *piLast to the new lastest value.
189246 ** If the iterator reaches EOF, set *pbEof to true before returning. If
189247 ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
189248 ** are set, return a non-zero value. Otherwise, return zero.
189250 static int fts5ExprAdvanceto(
189251 Fts5IndexIter *pIter, /* Iterator to advance */
189252 int bDesc, /* True if iterator is "rowid DESC" */
189253 i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
189254 int *pRc, /* OUT: Error code */
189255 int *pbEof /* OUT: Set to true if EOF */
189257 i64 iLast = *piLast;
189258 i64 iRowid;
189260 iRowid = pIter->iRowid;
189261 if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
189262 int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
189263 if( rc || sqlite3Fts5IterEof(pIter) ){
189264 *pRc = rc;
189265 *pbEof = 1;
189266 return 1;
189268 iRowid = pIter->iRowid;
189269 assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
189271 *piLast = iRowid;
189273 return 0;
189276 static int fts5ExprSynonymAdvanceto(
189277 Fts5ExprTerm *pTerm, /* Term iterator to advance */
189278 int bDesc, /* True if iterator is "rowid DESC" */
189279 i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
189280 int *pRc /* OUT: Error code */
189282 int rc = SQLITE_OK;
189283 i64 iLast = *piLast;
189284 Fts5ExprTerm *p;
189285 int bEof = 0;
189287 for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
189288 if( sqlite3Fts5IterEof(p->pIter)==0 ){
189289 i64 iRowid = p->pIter->iRowid;
189290 if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
189291 rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
189296 if( rc!=SQLITE_OK ){
189297 *pRc = rc;
189298 bEof = 1;
189299 }else{
189300 *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
189302 return bEof;
189306 static int fts5ExprNearTest(
189307 int *pRc,
189308 Fts5Expr *pExpr, /* Expression that pNear is a part of */
189309 Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
189311 Fts5ExprNearset *pNear = pNode->pNear;
189312 int rc = *pRc;
189314 if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
189315 Fts5ExprTerm *pTerm;
189316 Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
189317 pPhrase->poslist.n = 0;
189318 for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
189319 Fts5IndexIter *pIter = pTerm->pIter;
189320 if( sqlite3Fts5IterEof(pIter)==0 ){
189321 if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
189322 pPhrase->poslist.n = 1;
189326 return pPhrase->poslist.n;
189327 }else{
189328 int i;
189330 /* Check that each phrase in the nearset matches the current row.
189331 ** Populate the pPhrase->poslist buffers at the same time. If any
189332 ** phrase is not a match, break out of the loop early. */
189333 for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
189334 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
189335 if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
189336 int bMatch = 0;
189337 rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
189338 if( bMatch==0 ) break;
189339 }else{
189340 Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
189341 fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
189345 *pRc = rc;
189346 if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
189347 return 1;
189349 return 0;
189355 ** Initialize all term iterators in the pNear object. If any term is found
189356 ** to match no documents at all, return immediately without initializing any
189357 ** further iterators.
189359 ** If an error occurs, return an SQLite error code. Otherwise, return
189360 ** SQLITE_OK. It is not considered an error if some term matches zero
189361 ** documents.
189363 static int fts5ExprNearInitAll(
189364 Fts5Expr *pExpr,
189365 Fts5ExprNode *pNode
189367 Fts5ExprNearset *pNear = pNode->pNear;
189368 int i;
189370 assert( pNode->bNomatch==0 );
189371 for(i=0; i<pNear->nPhrase; i++){
189372 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
189373 if( pPhrase->nTerm==0 ){
189374 pNode->bEof = 1;
189375 return SQLITE_OK;
189376 }else{
189377 int j;
189378 for(j=0; j<pPhrase->nTerm; j++){
189379 Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
189380 Fts5ExprTerm *p;
189381 int bHit = 0;
189383 for(p=pTerm; p; p=p->pSynonym){
189384 int rc;
189385 if( p->pIter ){
189386 sqlite3Fts5IterClose(p->pIter);
189387 p->pIter = 0;
189389 rc = sqlite3Fts5IndexQuery(
189390 pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
189391 (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
189392 (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
189393 pNear->pColset,
189394 &p->pIter
189396 assert( (rc==SQLITE_OK)==(p->pIter!=0) );
189397 if( rc!=SQLITE_OK ) return rc;
189398 if( 0==sqlite3Fts5IterEof(p->pIter) ){
189399 bHit = 1;
189403 if( bHit==0 ){
189404 pNode->bEof = 1;
189405 return SQLITE_OK;
189411 pNode->bEof = 0;
189412 return SQLITE_OK;
189416 ** If pExpr is an ASC iterator, this function returns a value with the
189417 ** same sign as:
189419 ** (iLhs - iRhs)
189421 ** Otherwise, if this is a DESC iterator, the opposite is returned:
189423 ** (iRhs - iLhs)
189425 static int fts5RowidCmp(
189426 Fts5Expr *pExpr,
189427 i64 iLhs,
189428 i64 iRhs
189430 assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
189431 if( pExpr->bDesc==0 ){
189432 if( iLhs<iRhs ) return -1;
189433 return (iLhs > iRhs);
189434 }else{
189435 if( iLhs>iRhs ) return -1;
189436 return (iLhs < iRhs);
189440 static void fts5ExprSetEof(Fts5ExprNode *pNode){
189441 int i;
189442 pNode->bEof = 1;
189443 pNode->bNomatch = 0;
189444 for(i=0; i<pNode->nChild; i++){
189445 fts5ExprSetEof(pNode->apChild[i]);
189449 static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
189450 if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
189451 Fts5ExprNearset *pNear = pNode->pNear;
189452 int i;
189453 for(i=0; i<pNear->nPhrase; i++){
189454 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
189455 pPhrase->poslist.n = 0;
189457 }else{
189458 int i;
189459 for(i=0; i<pNode->nChild; i++){
189460 fts5ExprNodeZeroPoslist(pNode->apChild[i]);
189468 ** Compare the values currently indicated by the two nodes as follows:
189470 ** res = (*p1) - (*p2)
189472 ** Nodes that point to values that come later in the iteration order are
189473 ** considered to be larger. Nodes at EOF are the largest of all.
189475 ** This means that if the iteration order is ASC, then numerically larger
189476 ** rowids are considered larger. Or if it is the default DESC, numerically
189477 ** smaller rowids are larger.
189479 static int fts5NodeCompare(
189480 Fts5Expr *pExpr,
189481 Fts5ExprNode *p1,
189482 Fts5ExprNode *p2
189484 if( p2->bEof ) return -1;
189485 if( p1->bEof ) return +1;
189486 return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
189490 ** All individual term iterators in pNear are guaranteed to be valid when
189491 ** this function is called. This function checks if all term iterators
189492 ** point to the same rowid, and if not, advances them until they do.
189493 ** If an EOF is reached before this happens, *pbEof is set to true before
189494 ** returning.
189496 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
189497 ** otherwise. It is not considered an error code if an iterator reaches
189498 ** EOF.
189500 static int fts5ExprNodeTest_STRING(
189501 Fts5Expr *pExpr, /* Expression pPhrase belongs to */
189502 Fts5ExprNode *pNode
189504 Fts5ExprNearset *pNear = pNode->pNear;
189505 Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
189506 int rc = SQLITE_OK;
189507 i64 iLast; /* Lastest rowid any iterator points to */
189508 int i, j; /* Phrase and token index, respectively */
189509 int bMatch; /* True if all terms are at the same rowid */
189510 const int bDesc = pExpr->bDesc;
189512 /* Check that this node should not be FTS5_TERM */
189513 assert( pNear->nPhrase>1
189514 || pNear->apPhrase[0]->nTerm>1
189515 || pNear->apPhrase[0]->aTerm[0].pSynonym
189518 /* Initialize iLast, the "lastest" rowid any iterator points to. If the
189519 ** iterator skips through rowids in the default ascending order, this means
189520 ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
189521 ** means the minimum rowid. */
189522 if( pLeft->aTerm[0].pSynonym ){
189523 iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
189524 }else{
189525 iLast = pLeft->aTerm[0].pIter->iRowid;
189529 bMatch = 1;
189530 for(i=0; i<pNear->nPhrase; i++){
189531 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
189532 for(j=0; j<pPhrase->nTerm; j++){
189533 Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
189534 if( pTerm->pSynonym ){
189535 i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
189536 if( iRowid==iLast ) continue;
189537 bMatch = 0;
189538 if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
189539 pNode->bNomatch = 0;
189540 pNode->bEof = 1;
189541 return rc;
189543 }else{
189544 Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
189545 if( pIter->iRowid==iLast || pIter->bEof ) continue;
189546 bMatch = 0;
189547 if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
189548 return rc;
189553 }while( bMatch==0 );
189555 pNode->iRowid = iLast;
189556 pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
189557 assert( pNode->bEof==0 || pNode->bNomatch==0 );
189559 return rc;
189563 ** Advance the first term iterator in the first phrase of pNear. Set output
189564 ** variable *pbEof to true if it reaches EOF or if an error occurs.
189566 ** Return SQLITE_OK if successful, or an SQLite error code if an error
189567 ** occurs.
189569 static int fts5ExprNodeNext_STRING(
189570 Fts5Expr *pExpr, /* Expression pPhrase belongs to */
189571 Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
189572 int bFromValid,
189573 i64 iFrom
189575 Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
189576 int rc = SQLITE_OK;
189578 pNode->bNomatch = 0;
189579 if( pTerm->pSynonym ){
189580 int bEof = 1;
189581 Fts5ExprTerm *p;
189583 /* Find the firstest rowid any synonym points to. */
189584 i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
189586 /* Advance each iterator that currently points to iRowid. Or, if iFrom
189587 ** is valid - each iterator that points to a rowid before iFrom. */
189588 for(p=pTerm; p; p=p->pSynonym){
189589 if( sqlite3Fts5IterEof(p->pIter)==0 ){
189590 i64 ii = p->pIter->iRowid;
189591 if( ii==iRowid
189592 || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
189594 if( bFromValid ){
189595 rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
189596 }else{
189597 rc = sqlite3Fts5IterNext(p->pIter);
189599 if( rc!=SQLITE_OK ) break;
189600 if( sqlite3Fts5IterEof(p->pIter)==0 ){
189601 bEof = 0;
189603 }else{
189604 bEof = 0;
189609 /* Set the EOF flag if either all synonym iterators are at EOF or an
189610 ** error has occurred. */
189611 pNode->bEof = (rc || bEof);
189612 }else{
189613 Fts5IndexIter *pIter = pTerm->pIter;
189615 assert( Fts5NodeIsString(pNode) );
189616 if( bFromValid ){
189617 rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
189618 }else{
189619 rc = sqlite3Fts5IterNext(pIter);
189622 pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
189625 if( pNode->bEof==0 ){
189626 assert( rc==SQLITE_OK );
189627 rc = fts5ExprNodeTest_STRING(pExpr, pNode);
189630 return rc;
189634 static int fts5ExprNodeTest_TERM(
189635 Fts5Expr *pExpr, /* Expression that pNear is a part of */
189636 Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
189638 /* As this "NEAR" object is actually a single phrase that consists
189639 ** of a single term only, grab pointers into the poslist managed by the
189640 ** fts5_index.c iterator object. This is much faster than synthesizing
189641 ** a new poslist the way we have to for more complicated phrase or NEAR
189642 ** expressions. */
189643 Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
189644 Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
189646 assert( pNode->eType==FTS5_TERM );
189647 assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
189648 assert( pPhrase->aTerm[0].pSynonym==0 );
189650 pPhrase->poslist.n = pIter->nData;
189651 if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
189652 pPhrase->poslist.p = (u8*)pIter->pData;
189654 pNode->iRowid = pIter->iRowid;
189655 pNode->bNomatch = (pPhrase->poslist.n==0);
189656 return SQLITE_OK;
189660 ** xNext() method for a node of type FTS5_TERM.
189662 static int fts5ExprNodeNext_TERM(
189663 Fts5Expr *pExpr,
189664 Fts5ExprNode *pNode,
189665 int bFromValid,
189666 i64 iFrom
189668 int rc;
189669 Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
189671 assert( pNode->bEof==0 );
189672 if( bFromValid ){
189673 rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
189674 }else{
189675 rc = sqlite3Fts5IterNext(pIter);
189677 if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
189678 rc = fts5ExprNodeTest_TERM(pExpr, pNode);
189679 }else{
189680 pNode->bEof = 1;
189681 pNode->bNomatch = 0;
189683 return rc;
189686 static void fts5ExprNodeTest_OR(
189687 Fts5Expr *pExpr, /* Expression of which pNode is a part */
189688 Fts5ExprNode *pNode /* Expression node to test */
189690 Fts5ExprNode *pNext = pNode->apChild[0];
189691 int i;
189693 for(i=1; i<pNode->nChild; i++){
189694 Fts5ExprNode *pChild = pNode->apChild[i];
189695 int cmp = fts5NodeCompare(pExpr, pNext, pChild);
189696 if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
189697 pNext = pChild;
189700 pNode->iRowid = pNext->iRowid;
189701 pNode->bEof = pNext->bEof;
189702 pNode->bNomatch = pNext->bNomatch;
189705 static int fts5ExprNodeNext_OR(
189706 Fts5Expr *pExpr,
189707 Fts5ExprNode *pNode,
189708 int bFromValid,
189709 i64 iFrom
189711 int i;
189712 i64 iLast = pNode->iRowid;
189714 for(i=0; i<pNode->nChild; i++){
189715 Fts5ExprNode *p1 = pNode->apChild[i];
189716 assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
189717 if( p1->bEof==0 ){
189718 if( (p1->iRowid==iLast)
189719 || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
189721 int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
189722 if( rc!=SQLITE_OK ){
189723 pNode->bNomatch = 0;
189724 return rc;
189730 fts5ExprNodeTest_OR(pExpr, pNode);
189731 return SQLITE_OK;
189735 ** Argument pNode is an FTS5_AND node.
189737 static int fts5ExprNodeTest_AND(
189738 Fts5Expr *pExpr, /* Expression pPhrase belongs to */
189739 Fts5ExprNode *pAnd /* FTS5_AND node to advance */
189741 int iChild;
189742 i64 iLast = pAnd->iRowid;
189743 int rc = SQLITE_OK;
189744 int bMatch;
189746 assert( pAnd->bEof==0 );
189748 pAnd->bNomatch = 0;
189749 bMatch = 1;
189750 for(iChild=0; iChild<pAnd->nChild; iChild++){
189751 Fts5ExprNode *pChild = pAnd->apChild[iChild];
189752 int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
189753 if( cmp>0 ){
189754 /* Advance pChild until it points to iLast or laster */
189755 rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
189756 if( rc!=SQLITE_OK ){
189757 pAnd->bNomatch = 0;
189758 return rc;
189762 /* If the child node is now at EOF, so is the parent AND node. Otherwise,
189763 ** the child node is guaranteed to have advanced at least as far as
189764 ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
189765 ** new lastest rowid seen so far. */
189766 assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
189767 if( pChild->bEof ){
189768 fts5ExprSetEof(pAnd);
189769 bMatch = 1;
189770 break;
189771 }else if( iLast!=pChild->iRowid ){
189772 bMatch = 0;
189773 iLast = pChild->iRowid;
189776 if( pChild->bNomatch ){
189777 pAnd->bNomatch = 1;
189780 }while( bMatch==0 );
189782 if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
189783 fts5ExprNodeZeroPoslist(pAnd);
189785 pAnd->iRowid = iLast;
189786 return SQLITE_OK;
189789 static int fts5ExprNodeNext_AND(
189790 Fts5Expr *pExpr,
189791 Fts5ExprNode *pNode,
189792 int bFromValid,
189793 i64 iFrom
189795 int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
189796 if( rc==SQLITE_OK ){
189797 rc = fts5ExprNodeTest_AND(pExpr, pNode);
189798 }else{
189799 pNode->bNomatch = 0;
189801 return rc;
189804 static int fts5ExprNodeTest_NOT(
189805 Fts5Expr *pExpr, /* Expression pPhrase belongs to */
189806 Fts5ExprNode *pNode /* FTS5_NOT node to advance */
189808 int rc = SQLITE_OK;
189809 Fts5ExprNode *p1 = pNode->apChild[0];
189810 Fts5ExprNode *p2 = pNode->apChild[1];
189811 assert( pNode->nChild==2 );
189813 while( rc==SQLITE_OK && p1->bEof==0 ){
189814 int cmp = fts5NodeCompare(pExpr, p1, p2);
189815 if( cmp>0 ){
189816 rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
189817 cmp = fts5NodeCompare(pExpr, p1, p2);
189819 assert( rc!=SQLITE_OK || cmp<=0 );
189820 if( cmp || p2->bNomatch ) break;
189821 rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
189823 pNode->bEof = p1->bEof;
189824 pNode->bNomatch = p1->bNomatch;
189825 pNode->iRowid = p1->iRowid;
189826 if( p1->bEof ){
189827 fts5ExprNodeZeroPoslist(p2);
189829 return rc;
189832 static int fts5ExprNodeNext_NOT(
189833 Fts5Expr *pExpr,
189834 Fts5ExprNode *pNode,
189835 int bFromValid,
189836 i64 iFrom
189838 int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
189839 if( rc==SQLITE_OK ){
189840 rc = fts5ExprNodeTest_NOT(pExpr, pNode);
189842 if( rc!=SQLITE_OK ){
189843 pNode->bNomatch = 0;
189845 return rc;
189849 ** If pNode currently points to a match, this function returns SQLITE_OK
189850 ** without modifying it. Otherwise, pNode is advanced until it does point
189851 ** to a match or EOF is reached.
189853 static int fts5ExprNodeTest(
189854 Fts5Expr *pExpr, /* Expression of which pNode is a part */
189855 Fts5ExprNode *pNode /* Expression node to test */
189857 int rc = SQLITE_OK;
189858 if( pNode->bEof==0 ){
189859 switch( pNode->eType ){
189861 case FTS5_STRING: {
189862 rc = fts5ExprNodeTest_STRING(pExpr, pNode);
189863 break;
189866 case FTS5_TERM: {
189867 rc = fts5ExprNodeTest_TERM(pExpr, pNode);
189868 break;
189871 case FTS5_AND: {
189872 rc = fts5ExprNodeTest_AND(pExpr, pNode);
189873 break;
189876 case FTS5_OR: {
189877 fts5ExprNodeTest_OR(pExpr, pNode);
189878 break;
189881 default: assert( pNode->eType==FTS5_NOT ); {
189882 rc = fts5ExprNodeTest_NOT(pExpr, pNode);
189883 break;
189887 return rc;
189892 ** Set node pNode, which is part of expression pExpr, to point to the first
189893 ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
189895 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
189896 ** It is not an error if there are no matches.
189898 static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
189899 int rc = SQLITE_OK;
189900 pNode->bEof = 0;
189901 pNode->bNomatch = 0;
189903 if( Fts5NodeIsString(pNode) ){
189904 /* Initialize all term iterators in the NEAR object. */
189905 rc = fts5ExprNearInitAll(pExpr, pNode);
189906 }else if( pNode->xNext==0 ){
189907 pNode->bEof = 1;
189908 }else{
189909 int i;
189910 int nEof = 0;
189911 for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
189912 Fts5ExprNode *pChild = pNode->apChild[i];
189913 rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
189914 assert( pChild->bEof==0 || pChild->bEof==1 );
189915 nEof += pChild->bEof;
189917 pNode->iRowid = pNode->apChild[0]->iRowid;
189919 switch( pNode->eType ){
189920 case FTS5_AND:
189921 if( nEof>0 ) fts5ExprSetEof(pNode);
189922 break;
189924 case FTS5_OR:
189925 if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
189926 break;
189928 default:
189929 assert( pNode->eType==FTS5_NOT );
189930 pNode->bEof = pNode->apChild[0]->bEof;
189931 break;
189935 if( rc==SQLITE_OK ){
189936 rc = fts5ExprNodeTest(pExpr, pNode);
189938 return rc;
189943 ** Begin iterating through the set of documents in index pIdx matched by
189944 ** the MATCH expression passed as the first argument. If the "bDesc"
189945 ** parameter is passed a non-zero value, iteration is in descending rowid
189946 ** order. Or, if it is zero, in ascending order.
189948 ** If iterating in ascending rowid order (bDesc==0), the first document
189949 ** visited is that with the smallest rowid that is larger than or equal
189950 ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
189951 ** then the first document visited must have a rowid smaller than or
189952 ** equal to iFirst.
189954 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
189955 ** is not considered an error if the query does not match any documents.
189957 static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
189958 Fts5ExprNode *pRoot = p->pRoot;
189959 int rc; /* Return code */
189961 p->pIndex = pIdx;
189962 p->bDesc = bDesc;
189963 rc = fts5ExprNodeFirst(p, pRoot);
189965 /* If not at EOF but the current rowid occurs earlier than iFirst in
189966 ** the iteration order, move to document iFirst or later. */
189967 if( rc==SQLITE_OK
189968 && 0==pRoot->bEof
189969 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
189971 rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
189974 /* If the iterator is not at a real match, skip forward until it is. */
189975 while( pRoot->bNomatch ){
189976 assert( pRoot->bEof==0 && rc==SQLITE_OK );
189977 rc = fts5ExprNodeNext(p, pRoot, 0, 0);
189979 return rc;
189983 ** Move to the next document
189985 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
189986 ** is not considered an error if the query does not match any documents.
189988 static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
189989 int rc;
189990 Fts5ExprNode *pRoot = p->pRoot;
189991 assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
189993 rc = fts5ExprNodeNext(p, pRoot, 0, 0);
189994 assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
189995 }while( pRoot->bNomatch );
189996 if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
189997 pRoot->bEof = 1;
189999 return rc;
190002 static int sqlite3Fts5ExprEof(Fts5Expr *p){
190003 return p->pRoot->bEof;
190006 static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
190007 return p->pRoot->iRowid;
190010 static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
190011 int rc = SQLITE_OK;
190012 *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
190013 return rc;
190017 ** Free the phrase object passed as the only argument.
190019 static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
190020 if( pPhrase ){
190021 int i;
190022 for(i=0; i<pPhrase->nTerm; i++){
190023 Fts5ExprTerm *pSyn;
190024 Fts5ExprTerm *pNext;
190025 Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
190026 sqlite3_free(pTerm->zTerm);
190027 sqlite3Fts5IterClose(pTerm->pIter);
190028 for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
190029 pNext = pSyn->pSynonym;
190030 sqlite3Fts5IterClose(pSyn->pIter);
190031 fts5BufferFree((Fts5Buffer*)&pSyn[1]);
190032 sqlite3_free(pSyn);
190035 if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
190036 sqlite3_free(pPhrase);
190041 ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
190042 ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
190043 ** appended to it and the results returned.
190045 ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
190046 ** NULL returned.
190048 static Fts5ExprNearset *sqlite3Fts5ParseNearset(
190049 Fts5Parse *pParse, /* Parse context */
190050 Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
190051 Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
190053 const int SZALLOC = 8;
190054 Fts5ExprNearset *pRet = 0;
190056 if( pParse->rc==SQLITE_OK ){
190057 if( pPhrase==0 ){
190058 return pNear;
190060 if( pNear==0 ){
190061 int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
190062 pRet = sqlite3_malloc(nByte);
190063 if( pRet==0 ){
190064 pParse->rc = SQLITE_NOMEM;
190065 }else{
190066 memset(pRet, 0, nByte);
190068 }else if( (pNear->nPhrase % SZALLOC)==0 ){
190069 int nNew = pNear->nPhrase + SZALLOC;
190070 int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
190072 pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
190073 if( pRet==0 ){
190074 pParse->rc = SQLITE_NOMEM;
190076 }else{
190077 pRet = pNear;
190081 if( pRet==0 ){
190082 assert( pParse->rc!=SQLITE_OK );
190083 sqlite3Fts5ParseNearsetFree(pNear);
190084 sqlite3Fts5ParsePhraseFree(pPhrase);
190085 }else{
190086 if( pRet->nPhrase>0 ){
190087 Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
190088 assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
190089 if( pPhrase->nTerm==0 ){
190090 fts5ExprPhraseFree(pPhrase);
190091 pRet->nPhrase--;
190092 pParse->nPhrase--;
190093 pPhrase = pLast;
190094 }else if( pLast->nTerm==0 ){
190095 fts5ExprPhraseFree(pLast);
190096 pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
190097 pParse->nPhrase--;
190098 pRet->nPhrase--;
190101 pRet->apPhrase[pRet->nPhrase++] = pPhrase;
190103 return pRet;
190106 typedef struct TokenCtx TokenCtx;
190107 struct TokenCtx {
190108 Fts5ExprPhrase *pPhrase;
190109 int rc;
190113 ** Callback for tokenizing terms used by ParseTerm().
190115 static int fts5ParseTokenize(
190116 void *pContext, /* Pointer to Fts5InsertCtx object */
190117 int tflags, /* Mask of FTS5_TOKEN_* flags */
190118 const char *pToken, /* Buffer containing token */
190119 int nToken, /* Size of token in bytes */
190120 int iUnused1, /* Start offset of token */
190121 int iUnused2 /* End offset of token */
190123 int rc = SQLITE_OK;
190124 const int SZALLOC = 8;
190125 TokenCtx *pCtx = (TokenCtx*)pContext;
190126 Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
190128 UNUSED_PARAM2(iUnused1, iUnused2);
190130 /* If an error has already occurred, this is a no-op */
190131 if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
190132 if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
190134 if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
190135 Fts5ExprTerm *pSyn;
190136 int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
190137 pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
190138 if( pSyn==0 ){
190139 rc = SQLITE_NOMEM;
190140 }else{
190141 memset(pSyn, 0, nByte);
190142 pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
190143 memcpy(pSyn->zTerm, pToken, nToken);
190144 pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
190145 pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
190147 }else{
190148 Fts5ExprTerm *pTerm;
190149 if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
190150 Fts5ExprPhrase *pNew;
190151 int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
190153 pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
190154 sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
190156 if( pNew==0 ){
190157 rc = SQLITE_NOMEM;
190158 }else{
190159 if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
190160 pCtx->pPhrase = pPhrase = pNew;
190161 pNew->nTerm = nNew - SZALLOC;
190165 if( rc==SQLITE_OK ){
190166 pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
190167 memset(pTerm, 0, sizeof(Fts5ExprTerm));
190168 pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
190172 pCtx->rc = rc;
190173 return rc;
190178 ** Free the phrase object passed as the only argument.
190180 static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
190181 fts5ExprPhraseFree(pPhrase);
190185 ** Free the phrase object passed as the second argument.
190187 static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
190188 if( pNear ){
190189 int i;
190190 for(i=0; i<pNear->nPhrase; i++){
190191 fts5ExprPhraseFree(pNear->apPhrase[i]);
190193 sqlite3_free(pNear->pColset);
190194 sqlite3_free(pNear);
190198 static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
190199 assert( pParse->pExpr==0 );
190200 pParse->pExpr = p;
190204 ** This function is called by the parser to process a string token. The
190205 ** string may or may not be quoted. In any case it is tokenized and a
190206 ** phrase object consisting of all tokens returned.
190208 static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
190209 Fts5Parse *pParse, /* Parse context */
190210 Fts5ExprPhrase *pAppend, /* Phrase to append to */
190211 Fts5Token *pToken, /* String to tokenize */
190212 int bPrefix /* True if there is a trailing "*" */
190214 Fts5Config *pConfig = pParse->pConfig;
190215 TokenCtx sCtx; /* Context object passed to callback */
190216 int rc; /* Tokenize return code */
190217 char *z = 0;
190219 memset(&sCtx, 0, sizeof(TokenCtx));
190220 sCtx.pPhrase = pAppend;
190222 rc = fts5ParseStringFromToken(pToken, &z);
190223 if( rc==SQLITE_OK ){
190224 int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
190225 int n;
190226 sqlite3Fts5Dequote(z);
190227 n = (int)strlen(z);
190228 rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
190230 sqlite3_free(z);
190231 if( rc || (rc = sCtx.rc) ){
190232 pParse->rc = rc;
190233 fts5ExprPhraseFree(sCtx.pPhrase);
190234 sCtx.pPhrase = 0;
190235 }else{
190237 if( pAppend==0 ){
190238 if( (pParse->nPhrase % 8)==0 ){
190239 int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
190240 Fts5ExprPhrase **apNew;
190241 apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
190242 if( apNew==0 ){
190243 pParse->rc = SQLITE_NOMEM;
190244 fts5ExprPhraseFree(sCtx.pPhrase);
190245 return 0;
190247 pParse->apPhrase = apNew;
190249 pParse->nPhrase++;
190252 if( sCtx.pPhrase==0 ){
190253 /* This happens when parsing a token or quoted phrase that contains
190254 ** no token characters at all. (e.g ... MATCH '""'). */
190255 sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
190256 }else if( sCtx.pPhrase->nTerm ){
190257 sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
190259 pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
190262 return sCtx.pPhrase;
190266 ** Create a new FTS5 expression by cloning phrase iPhrase of the
190267 ** expression passed as the second argument.
190269 static int sqlite3Fts5ExprClonePhrase(
190270 Fts5Expr *pExpr,
190271 int iPhrase,
190272 Fts5Expr **ppNew
190274 int rc = SQLITE_OK; /* Return code */
190275 Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
190276 Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
190277 TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
190279 pOrig = pExpr->apExprPhrase[iPhrase];
190280 pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
190281 if( rc==SQLITE_OK ){
190282 pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
190283 sizeof(Fts5ExprPhrase*));
190285 if( rc==SQLITE_OK ){
190286 pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
190287 sizeof(Fts5ExprNode));
190289 if( rc==SQLITE_OK ){
190290 pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
190291 sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
190293 if( rc==SQLITE_OK ){
190294 Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
190295 if( pColsetOrig ){
190296 int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
190297 Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
190298 if( pColset ){
190299 memcpy(pColset, pColsetOrig, nByte);
190301 pNew->pRoot->pNear->pColset = pColset;
190305 if( pOrig->nTerm ){
190306 int i; /* Used to iterate through phrase terms */
190307 for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
190308 int tflags = 0;
190309 Fts5ExprTerm *p;
190310 for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
190311 const char *zTerm = p->zTerm;
190312 rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
190313 0, 0);
190314 tflags = FTS5_TOKEN_COLOCATED;
190316 if( rc==SQLITE_OK ){
190317 sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
190320 }else{
190321 /* This happens when parsing a token or quoted phrase that contains
190322 ** no token characters at all. (e.g ... MATCH '""'). */
190323 sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
190326 if( rc==SQLITE_OK ){
190327 /* All the allocations succeeded. Put the expression object together. */
190328 pNew->pIndex = pExpr->pIndex;
190329 pNew->pConfig = pExpr->pConfig;
190330 pNew->nPhrase = 1;
190331 pNew->apExprPhrase[0] = sCtx.pPhrase;
190332 pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
190333 pNew->pRoot->pNear->nPhrase = 1;
190334 sCtx.pPhrase->pNode = pNew->pRoot;
190336 if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
190337 pNew->pRoot->eType = FTS5_TERM;
190338 pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
190339 }else{
190340 pNew->pRoot->eType = FTS5_STRING;
190341 pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
190343 }else{
190344 sqlite3Fts5ExprFree(pNew);
190345 fts5ExprPhraseFree(sCtx.pPhrase);
190346 pNew = 0;
190349 *ppNew = pNew;
190350 return rc;
190355 ** Token pTok has appeared in a MATCH expression where the NEAR operator
190356 ** is expected. If token pTok does not contain "NEAR", store an error
190357 ** in the pParse object.
190359 static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
190360 if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
190361 sqlite3Fts5ParseError(
190362 pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
190367 static void sqlite3Fts5ParseSetDistance(
190368 Fts5Parse *pParse,
190369 Fts5ExprNearset *pNear,
190370 Fts5Token *p
190372 if( pNear ){
190373 int nNear = 0;
190374 int i;
190375 if( p->n ){
190376 for(i=0; i<p->n; i++){
190377 char c = (char)p->p[i];
190378 if( c<'0' || c>'9' ){
190379 sqlite3Fts5ParseError(
190380 pParse, "expected integer, got \"%.*s\"", p->n, p->p
190382 return;
190384 nNear = nNear * 10 + (p->p[i] - '0');
190386 }else{
190387 nNear = FTS5_DEFAULT_NEARDIST;
190389 pNear->nNear = nNear;
190394 ** The second argument passed to this function may be NULL, or it may be
190395 ** an existing Fts5Colset object. This function returns a pointer to
190396 ** a new colset object containing the contents of (p) with new value column
190397 ** number iCol appended.
190399 ** If an OOM error occurs, store an error code in pParse and return NULL.
190400 ** The old colset object (if any) is not freed in this case.
190402 static Fts5Colset *fts5ParseColset(
190403 Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
190404 Fts5Colset *p, /* Existing colset object */
190405 int iCol /* New column to add to colset object */
190407 int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
190408 Fts5Colset *pNew; /* New colset object to return */
190410 assert( pParse->rc==SQLITE_OK );
190411 assert( iCol>=0 && iCol<pParse->pConfig->nCol );
190413 pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
190414 if( pNew==0 ){
190415 pParse->rc = SQLITE_NOMEM;
190416 }else{
190417 int *aiCol = pNew->aiCol;
190418 int i, j;
190419 for(i=0; i<nCol; i++){
190420 if( aiCol[i]==iCol ) return pNew;
190421 if( aiCol[i]>iCol ) break;
190423 for(j=nCol; j>i; j--){
190424 aiCol[j] = aiCol[j-1];
190426 aiCol[i] = iCol;
190427 pNew->nCol = nCol+1;
190429 #ifndef NDEBUG
190430 /* Check that the array is in order and contains no duplicate entries. */
190431 for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
190432 #endif
190435 return pNew;
190439 ** Allocate and return an Fts5Colset object specifying the inverse of
190440 ** the colset passed as the second argument. Free the colset passed
190441 ** as the second argument before returning.
190443 static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
190444 Fts5Colset *pRet;
190445 int nCol = pParse->pConfig->nCol;
190447 pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
190448 sizeof(Fts5Colset) + sizeof(int)*nCol
190450 if( pRet ){
190451 int i;
190452 int iOld = 0;
190453 for(i=0; i<nCol; i++){
190454 if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
190455 pRet->aiCol[pRet->nCol++] = i;
190456 }else{
190457 iOld++;
190462 sqlite3_free(p);
190463 return pRet;
190466 static Fts5Colset *sqlite3Fts5ParseColset(
190467 Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
190468 Fts5Colset *pColset, /* Existing colset object */
190469 Fts5Token *p
190471 Fts5Colset *pRet = 0;
190472 int iCol;
190473 char *z; /* Dequoted copy of token p */
190475 z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
190476 if( pParse->rc==SQLITE_OK ){
190477 Fts5Config *pConfig = pParse->pConfig;
190478 sqlite3Fts5Dequote(z);
190479 for(iCol=0; iCol<pConfig->nCol; iCol++){
190480 if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
190482 if( iCol==pConfig->nCol ){
190483 sqlite3Fts5ParseError(pParse, "no such column: %s", z);
190484 }else{
190485 pRet = fts5ParseColset(pParse, pColset, iCol);
190487 sqlite3_free(z);
190490 if( pRet==0 ){
190491 assert( pParse->rc!=SQLITE_OK );
190492 sqlite3_free(pColset);
190495 return pRet;
190499 ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
190500 ** SQLITE_OK when this function is called, NULL is returned.
190502 ** Otherwise, a copy of (*pOrig) is made into memory obtained from
190503 ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
190504 ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
190506 static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
190507 Fts5Colset *pRet;
190508 if( pOrig ){
190509 int nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
190510 pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
190511 if( pRet ){
190512 memcpy(pRet, pOrig, nByte);
190514 }else{
190515 pRet = 0;
190517 return pRet;
190521 ** Remove from colset pColset any columns that are not also in colset pMerge.
190523 static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
190524 int iIn = 0; /* Next input in pColset */
190525 int iMerge = 0; /* Next input in pMerge */
190526 int iOut = 0; /* Next output slot in pColset */
190528 while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
190529 int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
190530 if( iDiff==0 ){
190531 pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
190532 iMerge++;
190533 iIn++;
190534 }else if( iDiff>0 ){
190535 iMerge++;
190536 }else{
190537 iIn++;
190540 pColset->nCol = iOut;
190544 ** Recursively apply colset pColset to expression node pNode and all of
190545 ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
190546 ** of pColset. This function may use the spare copy and set (*ppFree) to
190547 ** zero, or it may create copies of pColset using fts5CloneColset().
190549 static void fts5ParseSetColset(
190550 Fts5Parse *pParse,
190551 Fts5ExprNode *pNode,
190552 Fts5Colset *pColset,
190553 Fts5Colset **ppFree
190555 if( pParse->rc==SQLITE_OK ){
190556 assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
190557 || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
190558 || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
190560 if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
190561 Fts5ExprNearset *pNear = pNode->pNear;
190562 if( pNear->pColset ){
190563 fts5MergeColset(pNear->pColset, pColset);
190564 if( pNear->pColset->nCol==0 ){
190565 pNode->eType = FTS5_EOF;
190566 pNode->xNext = 0;
190568 }else if( *ppFree ){
190569 pNear->pColset = pColset;
190570 *ppFree = 0;
190571 }else{
190572 pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
190574 }else{
190575 int i;
190576 assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
190577 for(i=0; i<pNode->nChild; i++){
190578 fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
190585 ** Apply colset pColset to expression node pExpr and all of its descendents.
190587 static void sqlite3Fts5ParseSetColset(
190588 Fts5Parse *pParse,
190589 Fts5ExprNode *pExpr,
190590 Fts5Colset *pColset
190592 Fts5Colset *pFree = pColset;
190593 if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
190594 pParse->rc = SQLITE_ERROR;
190595 pParse->zErr = sqlite3_mprintf(
190596 "fts5: column queries are not supported (detail=none)"
190598 }else{
190599 fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
190601 sqlite3_free(pFree);
190604 static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
190605 switch( pNode->eType ){
190606 case FTS5_STRING: {
190607 Fts5ExprNearset *pNear = pNode->pNear;
190608 if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
190609 && pNear->apPhrase[0]->aTerm[0].pSynonym==0
190611 pNode->eType = FTS5_TERM;
190612 pNode->xNext = fts5ExprNodeNext_TERM;
190613 }else{
190614 pNode->xNext = fts5ExprNodeNext_STRING;
190616 break;
190619 case FTS5_OR: {
190620 pNode->xNext = fts5ExprNodeNext_OR;
190621 break;
190624 case FTS5_AND: {
190625 pNode->xNext = fts5ExprNodeNext_AND;
190626 break;
190629 default: assert( pNode->eType==FTS5_NOT ); {
190630 pNode->xNext = fts5ExprNodeNext_NOT;
190631 break;
190636 static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
190637 if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
190638 int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
190639 memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
190640 p->nChild += pSub->nChild;
190641 sqlite3_free(pSub);
190642 }else{
190643 p->apChild[p->nChild++] = pSub;
190648 ** Allocate and return a new expression object. If anything goes wrong (i.e.
190649 ** OOM error), leave an error code in pParse and return NULL.
190651 static Fts5ExprNode *sqlite3Fts5ParseNode(
190652 Fts5Parse *pParse, /* Parse context */
190653 int eType, /* FTS5_STRING, AND, OR or NOT */
190654 Fts5ExprNode *pLeft, /* Left hand child expression */
190655 Fts5ExprNode *pRight, /* Right hand child expression */
190656 Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
190658 Fts5ExprNode *pRet = 0;
190660 if( pParse->rc==SQLITE_OK ){
190661 int nChild = 0; /* Number of children of returned node */
190662 int nByte; /* Bytes of space to allocate for this node */
190664 assert( (eType!=FTS5_STRING && !pNear)
190665 || (eType==FTS5_STRING && !pLeft && !pRight)
190667 if( eType==FTS5_STRING && pNear==0 ) return 0;
190668 if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
190669 if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
190671 if( eType==FTS5_NOT ){
190672 nChild = 2;
190673 }else if( eType==FTS5_AND || eType==FTS5_OR ){
190674 nChild = 2;
190675 if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
190676 if( pRight->eType==eType ) nChild += pRight->nChild-1;
190679 nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
190680 pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
190682 if( pRet ){
190683 pRet->eType = eType;
190684 pRet->pNear = pNear;
190685 fts5ExprAssignXNext(pRet);
190686 if( eType==FTS5_STRING ){
190687 int iPhrase;
190688 for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
190689 pNear->apPhrase[iPhrase]->pNode = pRet;
190690 if( pNear->apPhrase[iPhrase]->nTerm==0 ){
190691 pRet->xNext = 0;
190692 pRet->eType = FTS5_EOF;
190696 if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
190697 && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
190699 assert( pParse->rc==SQLITE_OK );
190700 pParse->rc = SQLITE_ERROR;
190701 assert( pParse->zErr==0 );
190702 pParse->zErr = sqlite3_mprintf(
190703 "fts5: %s queries are not supported (detail!=full)",
190704 pNear->nPhrase==1 ? "phrase": "NEAR"
190706 sqlite3_free(pRet);
190707 pRet = 0;
190710 }else{
190711 fts5ExprAddChildren(pRet, pLeft);
190712 fts5ExprAddChildren(pRet, pRight);
190717 if( pRet==0 ){
190718 assert( pParse->rc!=SQLITE_OK );
190719 sqlite3Fts5ParseNodeFree(pLeft);
190720 sqlite3Fts5ParseNodeFree(pRight);
190721 sqlite3Fts5ParseNearsetFree(pNear);
190723 return pRet;
190726 static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
190727 Fts5Parse *pParse, /* Parse context */
190728 Fts5ExprNode *pLeft, /* Left hand child expression */
190729 Fts5ExprNode *pRight /* Right hand child expression */
190731 Fts5ExprNode *pRet = 0;
190732 Fts5ExprNode *pPrev;
190734 if( pParse->rc ){
190735 sqlite3Fts5ParseNodeFree(pLeft);
190736 sqlite3Fts5ParseNodeFree(pRight);
190737 }else{
190739 assert( pLeft->eType==FTS5_STRING
190740 || pLeft->eType==FTS5_TERM
190741 || pLeft->eType==FTS5_EOF
190742 || pLeft->eType==FTS5_AND
190744 assert( pRight->eType==FTS5_STRING
190745 || pRight->eType==FTS5_TERM
190746 || pRight->eType==FTS5_EOF
190749 if( pLeft->eType==FTS5_AND ){
190750 pPrev = pLeft->apChild[pLeft->nChild-1];
190751 }else{
190752 pPrev = pLeft;
190754 assert( pPrev->eType==FTS5_STRING
190755 || pPrev->eType==FTS5_TERM
190756 || pPrev->eType==FTS5_EOF
190759 if( pRight->eType==FTS5_EOF ){
190760 assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
190761 sqlite3Fts5ParseNodeFree(pRight);
190762 pRet = pLeft;
190763 pParse->nPhrase--;
190765 else if( pPrev->eType==FTS5_EOF ){
190766 Fts5ExprPhrase **ap;
190768 if( pPrev==pLeft ){
190769 pRet = pRight;
190770 }else{
190771 pLeft->apChild[pLeft->nChild-1] = pRight;
190772 pRet = pLeft;
190775 ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
190776 assert( ap[0]==pPrev->pNear->apPhrase[0] );
190777 memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
190778 pParse->nPhrase--;
190780 sqlite3Fts5ParseNodeFree(pPrev);
190782 else{
190783 pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
190787 return pRet;
190790 static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
190791 int nByte = 0;
190792 Fts5ExprTerm *p;
190793 char *zQuoted;
190795 /* Determine the maximum amount of space required. */
190796 for(p=pTerm; p; p=p->pSynonym){
190797 nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
190799 zQuoted = sqlite3_malloc(nByte);
190801 if( zQuoted ){
190802 int i = 0;
190803 for(p=pTerm; p; p=p->pSynonym){
190804 char *zIn = p->zTerm;
190805 zQuoted[i++] = '"';
190806 while( *zIn ){
190807 if( *zIn=='"' ) zQuoted[i++] = '"';
190808 zQuoted[i++] = *zIn++;
190810 zQuoted[i++] = '"';
190811 if( p->pSynonym ) zQuoted[i++] = '|';
190813 if( pTerm->bPrefix ){
190814 zQuoted[i++] = ' ';
190815 zQuoted[i++] = '*';
190817 zQuoted[i++] = '\0';
190819 return zQuoted;
190822 static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
190823 char *zNew;
190824 va_list ap;
190825 va_start(ap, zFmt);
190826 zNew = sqlite3_vmprintf(zFmt, ap);
190827 va_end(ap);
190828 if( zApp && zNew ){
190829 char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
190830 sqlite3_free(zNew);
190831 zNew = zNew2;
190833 sqlite3_free(zApp);
190834 return zNew;
190838 ** Compose a tcl-readable representation of expression pExpr. Return a
190839 ** pointer to a buffer containing that representation. It is the
190840 ** responsibility of the caller to at some point free the buffer using
190841 ** sqlite3_free().
190843 static char *fts5ExprPrintTcl(
190844 Fts5Config *pConfig,
190845 const char *zNearsetCmd,
190846 Fts5ExprNode *pExpr
190848 char *zRet = 0;
190849 if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
190850 Fts5ExprNearset *pNear = pExpr->pNear;
190851 int i;
190852 int iTerm;
190854 zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
190855 if( zRet==0 ) return 0;
190856 if( pNear->pColset ){
190857 int *aiCol = pNear->pColset->aiCol;
190858 int nCol = pNear->pColset->nCol;
190859 if( nCol==1 ){
190860 zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
190861 }else{
190862 zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
190863 for(i=1; i<pNear->pColset->nCol; i++){
190864 zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
190866 zRet = fts5PrintfAppend(zRet, "} ");
190868 if( zRet==0 ) return 0;
190871 if( pNear->nPhrase>1 ){
190872 zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
190873 if( zRet==0 ) return 0;
190876 zRet = fts5PrintfAppend(zRet, "--");
190877 if( zRet==0 ) return 0;
190879 for(i=0; i<pNear->nPhrase; i++){
190880 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
190882 zRet = fts5PrintfAppend(zRet, " {");
190883 for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
190884 char *zTerm = pPhrase->aTerm[iTerm].zTerm;
190885 zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
190886 if( pPhrase->aTerm[iTerm].bPrefix ){
190887 zRet = fts5PrintfAppend(zRet, "*");
190891 if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
190892 if( zRet==0 ) return 0;
190895 }else{
190896 char const *zOp = 0;
190897 int i;
190898 switch( pExpr->eType ){
190899 case FTS5_AND: zOp = "AND"; break;
190900 case FTS5_NOT: zOp = "NOT"; break;
190901 default:
190902 assert( pExpr->eType==FTS5_OR );
190903 zOp = "OR";
190904 break;
190907 zRet = sqlite3_mprintf("%s", zOp);
190908 for(i=0; zRet && i<pExpr->nChild; i++){
190909 char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
190910 if( !z ){
190911 sqlite3_free(zRet);
190912 zRet = 0;
190913 }else{
190914 zRet = fts5PrintfAppend(zRet, " [%z]", z);
190919 return zRet;
190922 static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
190923 char *zRet = 0;
190924 if( pExpr->eType==0 ){
190925 return sqlite3_mprintf("\"\"");
190926 }else
190927 if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
190928 Fts5ExprNearset *pNear = pExpr->pNear;
190929 int i;
190930 int iTerm;
190932 if( pNear->pColset ){
190933 int iCol = pNear->pColset->aiCol[0];
190934 zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
190935 if( zRet==0 ) return 0;
190938 if( pNear->nPhrase>1 ){
190939 zRet = fts5PrintfAppend(zRet, "NEAR(");
190940 if( zRet==0 ) return 0;
190943 for(i=0; i<pNear->nPhrase; i++){
190944 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
190945 if( i!=0 ){
190946 zRet = fts5PrintfAppend(zRet, " ");
190947 if( zRet==0 ) return 0;
190949 for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
190950 char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
190951 if( zTerm ){
190952 zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
190953 sqlite3_free(zTerm);
190955 if( zTerm==0 || zRet==0 ){
190956 sqlite3_free(zRet);
190957 return 0;
190962 if( pNear->nPhrase>1 ){
190963 zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
190964 if( zRet==0 ) return 0;
190967 }else{
190968 char const *zOp = 0;
190969 int i;
190971 switch( pExpr->eType ){
190972 case FTS5_AND: zOp = " AND "; break;
190973 case FTS5_NOT: zOp = " NOT "; break;
190974 default:
190975 assert( pExpr->eType==FTS5_OR );
190976 zOp = " OR ";
190977 break;
190980 for(i=0; i<pExpr->nChild; i++){
190981 char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
190982 if( z==0 ){
190983 sqlite3_free(zRet);
190984 zRet = 0;
190985 }else{
190986 int e = pExpr->apChild[i]->eType;
190987 int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
190988 zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
190989 (i==0 ? "" : zOp),
190990 (b?"(":""), z, (b?")":"")
190993 if( zRet==0 ) break;
190997 return zRet;
191001 ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
191002 ** and fts5_expr_tcl() (bTcl!=0).
191004 static void fts5ExprFunction(
191005 sqlite3_context *pCtx, /* Function call context */
191006 int nArg, /* Number of args */
191007 sqlite3_value **apVal, /* Function arguments */
191008 int bTcl
191010 Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
191011 sqlite3 *db = sqlite3_context_db_handle(pCtx);
191012 const char *zExpr = 0;
191013 char *zErr = 0;
191014 Fts5Expr *pExpr = 0;
191015 int rc;
191016 int i;
191018 const char **azConfig; /* Array of arguments for Fts5Config */
191019 const char *zNearsetCmd = "nearset";
191020 int nConfig; /* Size of azConfig[] */
191021 Fts5Config *pConfig = 0;
191022 int iArg = 1;
191024 if( nArg<1 ){
191025 zErr = sqlite3_mprintf("wrong number of arguments to function %s",
191026 bTcl ? "fts5_expr_tcl" : "fts5_expr"
191028 sqlite3_result_error(pCtx, zErr, -1);
191029 sqlite3_free(zErr);
191030 return;
191033 if( bTcl && nArg>1 ){
191034 zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
191035 iArg = 2;
191038 nConfig = 3 + (nArg-iArg);
191039 azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
191040 if( azConfig==0 ){
191041 sqlite3_result_error_nomem(pCtx);
191042 return;
191044 azConfig[0] = 0;
191045 azConfig[1] = "main";
191046 azConfig[2] = "tbl";
191047 for(i=3; iArg<nArg; iArg++){
191048 azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
191051 zExpr = (const char*)sqlite3_value_text(apVal[0]);
191053 rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
191054 if( rc==SQLITE_OK ){
191055 rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
191057 if( rc==SQLITE_OK ){
191058 char *zText;
191059 if( pExpr->pRoot->xNext==0 ){
191060 zText = sqlite3_mprintf("");
191061 }else if( bTcl ){
191062 zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
191063 }else{
191064 zText = fts5ExprPrint(pConfig, pExpr->pRoot);
191066 if( zText==0 ){
191067 rc = SQLITE_NOMEM;
191068 }else{
191069 sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
191070 sqlite3_free(zText);
191074 if( rc!=SQLITE_OK ){
191075 if( zErr ){
191076 sqlite3_result_error(pCtx, zErr, -1);
191077 sqlite3_free(zErr);
191078 }else{
191079 sqlite3_result_error_code(pCtx, rc);
191082 sqlite3_free((void *)azConfig);
191083 sqlite3Fts5ConfigFree(pConfig);
191084 sqlite3Fts5ExprFree(pExpr);
191087 static void fts5ExprFunctionHr(
191088 sqlite3_context *pCtx, /* Function call context */
191089 int nArg, /* Number of args */
191090 sqlite3_value **apVal /* Function arguments */
191092 fts5ExprFunction(pCtx, nArg, apVal, 0);
191094 static void fts5ExprFunctionTcl(
191095 sqlite3_context *pCtx, /* Function call context */
191096 int nArg, /* Number of args */
191097 sqlite3_value **apVal /* Function arguments */
191099 fts5ExprFunction(pCtx, nArg, apVal, 1);
191103 ** The implementation of an SQLite user-defined-function that accepts a
191104 ** single integer as an argument. If the integer is an alpha-numeric
191105 ** unicode code point, 1 is returned. Otherwise 0.
191107 static void fts5ExprIsAlnum(
191108 sqlite3_context *pCtx, /* Function call context */
191109 int nArg, /* Number of args */
191110 sqlite3_value **apVal /* Function arguments */
191112 int iCode;
191113 if( nArg!=1 ){
191114 sqlite3_result_error(pCtx,
191115 "wrong number of arguments to function fts5_isalnum", -1
191117 return;
191119 iCode = sqlite3_value_int(apVal[0]);
191120 sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
191123 static void fts5ExprFold(
191124 sqlite3_context *pCtx, /* Function call context */
191125 int nArg, /* Number of args */
191126 sqlite3_value **apVal /* Function arguments */
191128 if( nArg!=1 && nArg!=2 ){
191129 sqlite3_result_error(pCtx,
191130 "wrong number of arguments to function fts5_fold", -1
191132 }else{
191133 int iCode;
191134 int bRemoveDiacritics = 0;
191135 iCode = sqlite3_value_int(apVal[0]);
191136 if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
191137 sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
191142 ** This is called during initialization to register the fts5_expr() scalar
191143 ** UDF with the SQLite handle passed as the only argument.
191145 static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
191146 struct Fts5ExprFunc {
191147 const char *z;
191148 void (*x)(sqlite3_context*,int,sqlite3_value**);
191149 } aFunc[] = {
191150 { "fts5_expr", fts5ExprFunctionHr },
191151 { "fts5_expr_tcl", fts5ExprFunctionTcl },
191152 { "fts5_isalnum", fts5ExprIsAlnum },
191153 { "fts5_fold", fts5ExprFold },
191155 int i;
191156 int rc = SQLITE_OK;
191157 void *pCtx = (void*)pGlobal;
191159 for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
191160 struct Fts5ExprFunc *p = &aFunc[i];
191161 rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
191164 /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
191165 #ifndef NDEBUG
191166 (void)sqlite3Fts5ParserTrace;
191167 #endif
191169 return rc;
191173 ** Return the number of phrases in expression pExpr.
191175 static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
191176 return (pExpr ? pExpr->nPhrase : 0);
191180 ** Return the number of terms in the iPhrase'th phrase in pExpr.
191182 static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
191183 if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
191184 return pExpr->apExprPhrase[iPhrase]->nTerm;
191188 ** This function is used to access the current position list for phrase
191189 ** iPhrase.
191191 static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
191192 int nRet;
191193 Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
191194 Fts5ExprNode *pNode = pPhrase->pNode;
191195 if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
191196 *pa = pPhrase->poslist.p;
191197 nRet = pPhrase->poslist.n;
191198 }else{
191199 *pa = 0;
191200 nRet = 0;
191202 return nRet;
191205 struct Fts5PoslistPopulator {
191206 Fts5PoslistWriter writer;
191207 int bOk; /* True if ok to populate */
191208 int bMiss;
191211 static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
191212 Fts5PoslistPopulator *pRet;
191213 pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
191214 if( pRet ){
191215 int i;
191216 memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
191217 for(i=0; i<pExpr->nPhrase; i++){
191218 Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
191219 Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
191220 assert( pExpr->apExprPhrase[i]->nTerm==1 );
191221 if( bLive &&
191222 (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
191224 pRet[i].bMiss = 1;
191225 }else{
191226 pBuf->n = 0;
191230 return pRet;
191233 struct Fts5ExprCtx {
191234 Fts5Expr *pExpr;
191235 Fts5PoslistPopulator *aPopulator;
191236 i64 iOff;
191238 typedef struct Fts5ExprCtx Fts5ExprCtx;
191241 ** TODO: Make this more efficient!
191243 static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
191244 int i;
191245 for(i=0; i<pColset->nCol; i++){
191246 if( pColset->aiCol[i]==iCol ) return 1;
191248 return 0;
191251 static int fts5ExprPopulatePoslistsCb(
191252 void *pCtx, /* Copy of 2nd argument to xTokenize() */
191253 int tflags, /* Mask of FTS5_TOKEN_* flags */
191254 const char *pToken, /* Pointer to buffer containing token */
191255 int nToken, /* Size of token in bytes */
191256 int iUnused1, /* Byte offset of token within input text */
191257 int iUnused2 /* Byte offset of end of token within input text */
191259 Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
191260 Fts5Expr *pExpr = p->pExpr;
191261 int i;
191263 UNUSED_PARAM2(iUnused1, iUnused2);
191265 if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
191266 if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
191267 for(i=0; i<pExpr->nPhrase; i++){
191268 Fts5ExprTerm *pTerm;
191269 if( p->aPopulator[i].bOk==0 ) continue;
191270 for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
191271 int nTerm = (int)strlen(pTerm->zTerm);
191272 if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
191273 && memcmp(pTerm->zTerm, pToken, nTerm)==0
191275 int rc = sqlite3Fts5PoslistWriterAppend(
191276 &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
191278 if( rc ) return rc;
191279 break;
191283 return SQLITE_OK;
191286 static int sqlite3Fts5ExprPopulatePoslists(
191287 Fts5Config *pConfig,
191288 Fts5Expr *pExpr,
191289 Fts5PoslistPopulator *aPopulator,
191290 int iCol,
191291 const char *z, int n
191293 int i;
191294 Fts5ExprCtx sCtx;
191295 sCtx.pExpr = pExpr;
191296 sCtx.aPopulator = aPopulator;
191297 sCtx.iOff = (((i64)iCol) << 32) - 1;
191299 for(i=0; i<pExpr->nPhrase; i++){
191300 Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
191301 Fts5Colset *pColset = pNode->pNear->pColset;
191302 if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
191303 || aPopulator[i].bMiss
191305 aPopulator[i].bOk = 0;
191306 }else{
191307 aPopulator[i].bOk = 1;
191311 return sqlite3Fts5Tokenize(pConfig,
191312 FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
191316 static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
191317 if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
191318 pNode->pNear->apPhrase[0]->poslist.n = 0;
191319 }else{
191320 int i;
191321 for(i=0; i<pNode->nChild; i++){
191322 fts5ExprClearPoslists(pNode->apChild[i]);
191327 static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
191328 pNode->iRowid = iRowid;
191329 pNode->bEof = 0;
191330 switch( pNode->eType ){
191331 case FTS5_TERM:
191332 case FTS5_STRING:
191333 return (pNode->pNear->apPhrase[0]->poslist.n>0);
191335 case FTS5_AND: {
191336 int i;
191337 for(i=0; i<pNode->nChild; i++){
191338 if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
191339 fts5ExprClearPoslists(pNode);
191340 return 0;
191343 break;
191346 case FTS5_OR: {
191347 int i;
191348 int bRet = 0;
191349 for(i=0; i<pNode->nChild; i++){
191350 if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
191351 bRet = 1;
191354 return bRet;
191357 default: {
191358 assert( pNode->eType==FTS5_NOT );
191359 if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
191360 || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
191362 fts5ExprClearPoslists(pNode);
191363 return 0;
191365 break;
191368 return 1;
191371 static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
191372 fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
191376 ** This function is only called for detail=columns tables.
191378 static int sqlite3Fts5ExprPhraseCollist(
191379 Fts5Expr *pExpr,
191380 int iPhrase,
191381 const u8 **ppCollist,
191382 int *pnCollist
191384 Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
191385 Fts5ExprNode *pNode = pPhrase->pNode;
191386 int rc = SQLITE_OK;
191388 assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
191389 assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
191391 if( pNode->bEof==0
191392 && pNode->iRowid==pExpr->pRoot->iRowid
191393 && pPhrase->poslist.n>0
191395 Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
191396 if( pTerm->pSynonym ){
191397 Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
191398 rc = fts5ExprSynonymList(
191399 pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
191401 }else{
191402 *ppCollist = pPhrase->aTerm[0].pIter->pData;
191403 *pnCollist = pPhrase->aTerm[0].pIter->nData;
191405 }else{
191406 *ppCollist = 0;
191407 *pnCollist = 0;
191410 return rc;
191415 ** 2014 August 11
191417 ** The author disclaims copyright to this source code. In place of
191418 ** a legal notice, here is a blessing:
191420 ** May you do good and not evil.
191421 ** May you find forgiveness for yourself and forgive others.
191422 ** May you share freely, never taking more than you give.
191424 ******************************************************************************
191430 /* #include "fts5Int.h" */
191432 typedef struct Fts5HashEntry Fts5HashEntry;
191435 ** This file contains the implementation of an in-memory hash table used
191436 ** to accumuluate "term -> doclist" content before it is flused to a level-0
191437 ** segment.
191441 struct Fts5Hash {
191442 int eDetail; /* Copy of Fts5Config.eDetail */
191443 int *pnByte; /* Pointer to bytes counter */
191444 int nEntry; /* Number of entries currently in hash */
191445 int nSlot; /* Size of aSlot[] array */
191446 Fts5HashEntry *pScan; /* Current ordered scan item */
191447 Fts5HashEntry **aSlot; /* Array of hash slots */
191451 ** Each entry in the hash table is represented by an object of the
191452 ** following type. Each object, its key (a nul-terminated string) and
191453 ** its current data are stored in a single memory allocation. The
191454 ** key immediately follows the object in memory. The position list
191455 ** data immediately follows the key data in memory.
191457 ** The data that follows the key is in a similar, but not identical format
191458 ** to the doclist data stored in the database. It is:
191460 ** * Rowid, as a varint
191461 ** * Position list, without 0x00 terminator.
191462 ** * Size of previous position list and rowid, as a 4 byte
191463 ** big-endian integer.
191465 ** iRowidOff:
191466 ** Offset of last rowid written to data area. Relative to first byte of
191467 ** structure.
191469 ** nData:
191470 ** Bytes of data written since iRowidOff.
191472 struct Fts5HashEntry {
191473 Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
191474 Fts5HashEntry *pScanNext; /* Next entry in sorted order */
191476 int nAlloc; /* Total size of allocation */
191477 int iSzPoslist; /* Offset of space for 4-byte poslist size */
191478 int nData; /* Total bytes of data (incl. structure) */
191479 int nKey; /* Length of key in bytes */
191480 u8 bDel; /* Set delete-flag @ iSzPoslist */
191481 u8 bContent; /* Set content-flag (detail=none mode) */
191482 i16 iCol; /* Column of last value written */
191483 int iPos; /* Position of last value written */
191484 i64 iRowid; /* Rowid of last value written */
191488 ** Eqivalent to:
191490 ** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
191492 #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
191496 ** Allocate a new hash table.
191498 static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
191499 int rc = SQLITE_OK;
191500 Fts5Hash *pNew;
191502 *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
191503 if( pNew==0 ){
191504 rc = SQLITE_NOMEM;
191505 }else{
191506 int nByte;
191507 memset(pNew, 0, sizeof(Fts5Hash));
191508 pNew->pnByte = pnByte;
191509 pNew->eDetail = pConfig->eDetail;
191511 pNew->nSlot = 1024;
191512 nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
191513 pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
191514 if( pNew->aSlot==0 ){
191515 sqlite3_free(pNew);
191516 *ppNew = 0;
191517 rc = SQLITE_NOMEM;
191518 }else{
191519 memset(pNew->aSlot, 0, nByte);
191522 return rc;
191526 ** Free a hash table object.
191528 static void sqlite3Fts5HashFree(Fts5Hash *pHash){
191529 if( pHash ){
191530 sqlite3Fts5HashClear(pHash);
191531 sqlite3_free(pHash->aSlot);
191532 sqlite3_free(pHash);
191537 ** Empty (but do not delete) a hash table.
191539 static void sqlite3Fts5HashClear(Fts5Hash *pHash){
191540 int i;
191541 for(i=0; i<pHash->nSlot; i++){
191542 Fts5HashEntry *pNext;
191543 Fts5HashEntry *pSlot;
191544 for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
191545 pNext = pSlot->pHashNext;
191546 sqlite3_free(pSlot);
191549 memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
191550 pHash->nEntry = 0;
191553 static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
191554 int i;
191555 unsigned int h = 13;
191556 for(i=n-1; i>=0; i--){
191557 h = (h << 3) ^ h ^ p[i];
191559 return (h % nSlot);
191562 static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
191563 int i;
191564 unsigned int h = 13;
191565 for(i=n-1; i>=0; i--){
191566 h = (h << 3) ^ h ^ p[i];
191568 h = (h << 3) ^ h ^ b;
191569 return (h % nSlot);
191573 ** Resize the hash table by doubling the number of slots.
191575 static int fts5HashResize(Fts5Hash *pHash){
191576 int nNew = pHash->nSlot*2;
191577 int i;
191578 Fts5HashEntry **apNew;
191579 Fts5HashEntry **apOld = pHash->aSlot;
191581 apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
191582 if( !apNew ) return SQLITE_NOMEM;
191583 memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
191585 for(i=0; i<pHash->nSlot; i++){
191586 while( apOld[i] ){
191587 unsigned int iHash;
191588 Fts5HashEntry *p = apOld[i];
191589 apOld[i] = p->pHashNext;
191590 iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
191591 (int)strlen(fts5EntryKey(p)));
191592 p->pHashNext = apNew[iHash];
191593 apNew[iHash] = p;
191597 sqlite3_free(apOld);
191598 pHash->nSlot = nNew;
191599 pHash->aSlot = apNew;
191600 return SQLITE_OK;
191603 static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
191604 if( p->iSzPoslist ){
191605 u8 *pPtr = (u8*)p;
191606 if( pHash->eDetail==FTS5_DETAIL_NONE ){
191607 assert( p->nData==p->iSzPoslist );
191608 if( p->bDel ){
191609 pPtr[p->nData++] = 0x00;
191610 if( p->bContent ){
191611 pPtr[p->nData++] = 0x00;
191614 }else{
191615 int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
191616 int nPos = nSz*2 + p->bDel; /* Value of nPos field */
191618 assert( p->bDel==0 || p->bDel==1 );
191619 if( nPos<=127 ){
191620 pPtr[p->iSzPoslist] = (u8)nPos;
191621 }else{
191622 int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
191623 memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
191624 sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
191625 p->nData += (nByte-1);
191629 p->iSzPoslist = 0;
191630 p->bDel = 0;
191631 p->bContent = 0;
191636 ** Add an entry to the in-memory hash table. The key is the concatenation
191637 ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
191639 ** (bByte || pToken) -> (iRowid,iCol,iPos)
191641 ** Or, if iCol is negative, then the value is a delete marker.
191643 static int sqlite3Fts5HashWrite(
191644 Fts5Hash *pHash,
191645 i64 iRowid, /* Rowid for this entry */
191646 int iCol, /* Column token appears in (-ve -> delete) */
191647 int iPos, /* Position of token within column */
191648 char bByte, /* First byte of token */
191649 const char *pToken, int nToken /* Token to add or remove to or from index */
191651 unsigned int iHash;
191652 Fts5HashEntry *p;
191653 u8 *pPtr;
191654 int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
191655 int bNew; /* If non-delete entry should be written */
191657 bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
191659 /* Attempt to locate an existing hash entry */
191660 iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
191661 for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
191662 char *zKey = fts5EntryKey(p);
191663 if( zKey[0]==bByte
191664 && p->nKey==nToken
191665 && memcmp(&zKey[1], pToken, nToken)==0
191667 break;
191671 /* If an existing hash entry cannot be found, create a new one. */
191672 if( p==0 ){
191673 /* Figure out how much space to allocate */
191674 char *zKey;
191675 int nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
191676 if( nByte<128 ) nByte = 128;
191678 /* Grow the Fts5Hash.aSlot[] array if necessary. */
191679 if( (pHash->nEntry*2)>=pHash->nSlot ){
191680 int rc = fts5HashResize(pHash);
191681 if( rc!=SQLITE_OK ) return rc;
191682 iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
191685 /* Allocate new Fts5HashEntry and add it to the hash table. */
191686 p = (Fts5HashEntry*)sqlite3_malloc(nByte);
191687 if( !p ) return SQLITE_NOMEM;
191688 memset(p, 0, sizeof(Fts5HashEntry));
191689 p->nAlloc = nByte;
191690 zKey = fts5EntryKey(p);
191691 zKey[0] = bByte;
191692 memcpy(&zKey[1], pToken, nToken);
191693 assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
191694 p->nKey = nToken;
191695 zKey[nToken+1] = '\0';
191696 p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
191697 p->pHashNext = pHash->aSlot[iHash];
191698 pHash->aSlot[iHash] = p;
191699 pHash->nEntry++;
191701 /* Add the first rowid field to the hash-entry */
191702 p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
191703 p->iRowid = iRowid;
191705 p->iSzPoslist = p->nData;
191706 if( pHash->eDetail!=FTS5_DETAIL_NONE ){
191707 p->nData += 1;
191708 p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
191711 nIncr += p->nData;
191712 }else{
191714 /* Appending to an existing hash-entry. Check that there is enough
191715 ** space to append the largest possible new entry. Worst case scenario
191716 ** is:
191718 ** + 9 bytes for a new rowid,
191719 ** + 4 byte reserved for the "poslist size" varint.
191720 ** + 1 byte for a "new column" byte,
191721 ** + 3 bytes for a new column number (16-bit max) as a varint,
191722 ** + 5 bytes for the new position offset (32-bit max).
191724 if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
191725 int nNew = p->nAlloc * 2;
191726 Fts5HashEntry *pNew;
191727 Fts5HashEntry **pp;
191728 pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
191729 if( pNew==0 ) return SQLITE_NOMEM;
191730 pNew->nAlloc = nNew;
191731 for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
191732 *pp = pNew;
191733 p = pNew;
191735 nIncr -= p->nData;
191737 assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
191739 pPtr = (u8*)p;
191741 /* If this is a new rowid, append the 4-byte size field for the previous
191742 ** entry, and the new rowid for this entry. */
191743 if( iRowid!=p->iRowid ){
191744 fts5HashAddPoslistSize(pHash, p);
191745 p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
191746 p->iRowid = iRowid;
191747 bNew = 1;
191748 p->iSzPoslist = p->nData;
191749 if( pHash->eDetail!=FTS5_DETAIL_NONE ){
191750 p->nData += 1;
191751 p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
191752 p->iPos = 0;
191756 if( iCol>=0 ){
191757 if( pHash->eDetail==FTS5_DETAIL_NONE ){
191758 p->bContent = 1;
191759 }else{
191760 /* Append a new column value, if necessary */
191761 assert( iCol>=p->iCol );
191762 if( iCol!=p->iCol ){
191763 if( pHash->eDetail==FTS5_DETAIL_FULL ){
191764 pPtr[p->nData++] = 0x01;
191765 p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
191766 p->iCol = (i16)iCol;
191767 p->iPos = 0;
191768 }else{
191769 bNew = 1;
191770 p->iCol = (i16)(iPos = iCol);
191774 /* Append the new position offset, if necessary */
191775 if( bNew ){
191776 p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
191777 p->iPos = iPos;
191780 }else{
191781 /* This is a delete. Set the delete flag. */
191782 p->bDel = 1;
191785 nIncr += p->nData;
191786 *pHash->pnByte += nIncr;
191787 return SQLITE_OK;
191792 ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
191793 ** each sorted in key order. This function merges the two lists into a
191794 ** single list and returns a pointer to its first element.
191796 static Fts5HashEntry *fts5HashEntryMerge(
191797 Fts5HashEntry *pLeft,
191798 Fts5HashEntry *pRight
191800 Fts5HashEntry *p1 = pLeft;
191801 Fts5HashEntry *p2 = pRight;
191802 Fts5HashEntry *pRet = 0;
191803 Fts5HashEntry **ppOut = &pRet;
191805 while( p1 || p2 ){
191806 if( p1==0 ){
191807 *ppOut = p2;
191808 p2 = 0;
191809 }else if( p2==0 ){
191810 *ppOut = p1;
191811 p1 = 0;
191812 }else{
191813 int i = 0;
191814 char *zKey1 = fts5EntryKey(p1);
191815 char *zKey2 = fts5EntryKey(p2);
191816 while( zKey1[i]==zKey2[i] ) i++;
191818 if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
191819 /* p2 is smaller */
191820 *ppOut = p2;
191821 ppOut = &p2->pScanNext;
191822 p2 = p2->pScanNext;
191823 }else{
191824 /* p1 is smaller */
191825 *ppOut = p1;
191826 ppOut = &p1->pScanNext;
191827 p1 = p1->pScanNext;
191829 *ppOut = 0;
191833 return pRet;
191837 ** Extract all tokens from hash table iHash and link them into a list
191838 ** in sorted order. The hash table is cleared before returning. It is
191839 ** the responsibility of the caller to free the elements of the returned
191840 ** list.
191842 static int fts5HashEntrySort(
191843 Fts5Hash *pHash,
191844 const char *pTerm, int nTerm, /* Query prefix, if any */
191845 Fts5HashEntry **ppSorted
191847 const int nMergeSlot = 32;
191848 Fts5HashEntry **ap;
191849 Fts5HashEntry *pList;
191850 int iSlot;
191851 int i;
191853 *ppSorted = 0;
191854 ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
191855 if( !ap ) return SQLITE_NOMEM;
191856 memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
191858 for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
191859 Fts5HashEntry *pIter;
191860 for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
191861 if( pTerm==0 || 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm) ){
191862 Fts5HashEntry *pEntry = pIter;
191863 pEntry->pScanNext = 0;
191864 for(i=0; ap[i]; i++){
191865 pEntry = fts5HashEntryMerge(pEntry, ap[i]);
191866 ap[i] = 0;
191868 ap[i] = pEntry;
191873 pList = 0;
191874 for(i=0; i<nMergeSlot; i++){
191875 pList = fts5HashEntryMerge(pList, ap[i]);
191878 pHash->nEntry = 0;
191879 sqlite3_free(ap);
191880 *ppSorted = pList;
191881 return SQLITE_OK;
191885 ** Query the hash table for a doclist associated with term pTerm/nTerm.
191887 static int sqlite3Fts5HashQuery(
191888 Fts5Hash *pHash, /* Hash table to query */
191889 const char *pTerm, int nTerm, /* Query term */
191890 const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
191891 int *pnDoclist /* OUT: Size of doclist in bytes */
191893 unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
191894 char *zKey = 0;
191895 Fts5HashEntry *p;
191897 for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
191898 zKey = fts5EntryKey(p);
191899 if( memcmp(zKey, pTerm, nTerm)==0 && zKey[nTerm]==0 ) break;
191902 if( p ){
191903 fts5HashAddPoslistSize(pHash, p);
191904 *ppDoclist = (const u8*)&zKey[nTerm+1];
191905 *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
191906 }else{
191907 *ppDoclist = 0;
191908 *pnDoclist = 0;
191911 return SQLITE_OK;
191914 static int sqlite3Fts5HashScanInit(
191915 Fts5Hash *p, /* Hash table to query */
191916 const char *pTerm, int nTerm /* Query prefix */
191918 return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
191921 static void sqlite3Fts5HashScanNext(Fts5Hash *p){
191922 assert( !sqlite3Fts5HashScanEof(p) );
191923 p->pScan = p->pScan->pScanNext;
191926 static int sqlite3Fts5HashScanEof(Fts5Hash *p){
191927 return (p->pScan==0);
191930 static void sqlite3Fts5HashScanEntry(
191931 Fts5Hash *pHash,
191932 const char **pzTerm, /* OUT: term (nul-terminated) */
191933 const u8 **ppDoclist, /* OUT: pointer to doclist */
191934 int *pnDoclist /* OUT: size of doclist in bytes */
191936 Fts5HashEntry *p;
191937 if( (p = pHash->pScan) ){
191938 char *zKey = fts5EntryKey(p);
191939 int nTerm = (int)strlen(zKey);
191940 fts5HashAddPoslistSize(pHash, p);
191941 *pzTerm = zKey;
191942 *ppDoclist = (const u8*)&zKey[nTerm+1];
191943 *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
191944 }else{
191945 *pzTerm = 0;
191946 *ppDoclist = 0;
191947 *pnDoclist = 0;
191953 ** 2014 May 31
191955 ** The author disclaims copyright to this source code. In place of
191956 ** a legal notice, here is a blessing:
191958 ** May you do good and not evil.
191959 ** May you find forgiveness for yourself and forgive others.
191960 ** May you share freely, never taking more than you give.
191962 ******************************************************************************
191964 ** Low level access to the FTS index stored in the database file. The
191965 ** routines in this file file implement all read and write access to the
191966 ** %_data table. Other parts of the system access this functionality via
191967 ** the interface defined in fts5Int.h.
191971 /* #include "fts5Int.h" */
191974 ** Overview:
191976 ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
191977 ** As well as the main term index, there may be up to 31 prefix indexes.
191978 ** The format is similar to FTS3/4, except that:
191980 ** * all segment b-tree leaf data is stored in fixed size page records
191981 ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
191982 ** taken to ensure it is possible to iterate in either direction through
191983 ** the entries in a doclist, or to seek to a specific entry within a
191984 ** doclist, without loading it into memory.
191986 ** * large doclists that span many pages have associated "doclist index"
191987 ** records that contain a copy of the first rowid on each page spanned by
191988 ** the doclist. This is used to speed up seek operations, and merges of
191989 ** large doclists with very small doclists.
191991 ** * extra fields in the "structure record" record the state of ongoing
191992 ** incremental merge operations.
191997 #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
191998 #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
192000 #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
192002 #define FTS5_MAIN_PREFIX '0'
192004 #if FTS5_MAX_PREFIX_INDEXES > 31
192005 # error "FTS5_MAX_PREFIX_INDEXES is too large"
192006 #endif
192009 ** Details:
192011 ** The %_data table managed by this module,
192013 ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
192015 ** , contains the following 5 types of records. See the comments surrounding
192016 ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
192017 ** assigned to each fo them.
192019 ** 1. Structure Records:
192021 ** The set of segments that make up an index - the index structure - are
192022 ** recorded in a single record within the %_data table. The record consists
192023 ** of a single 32-bit configuration cookie value followed by a list of
192024 ** SQLite varints. If the FTS table features more than one index (because
192025 ** there are one or more prefix indexes), it is guaranteed that all share
192026 ** the same cookie value.
192028 ** Immediately following the configuration cookie, the record begins with
192029 ** three varints:
192031 ** + number of levels,
192032 ** + total number of segments on all levels,
192033 ** + value of write counter.
192035 ** Then, for each level from 0 to nMax:
192037 ** + number of input segments in ongoing merge.
192038 ** + total number of segments in level.
192039 ** + for each segment from oldest to newest:
192040 ** + segment id (always > 0)
192041 ** + first leaf page number (often 1, always greater than 0)
192042 ** + final leaf page number
192044 ** 2. The Averages Record:
192046 ** A single record within the %_data table. The data is a list of varints.
192047 ** The first value is the number of rows in the index. Then, for each column
192048 ** from left to right, the total number of tokens in the column for all
192049 ** rows of the table.
192051 ** 3. Segment leaves:
192053 ** TERM/DOCLIST FORMAT:
192055 ** Most of each segment leaf is taken up by term/doclist data. The
192056 ** general format of term/doclist, starting with the first term
192057 ** on the leaf page, is:
192059 ** varint : size of first term
192060 ** blob: first term data
192061 ** doclist: first doclist
192062 ** zero-or-more {
192063 ** varint: number of bytes in common with previous term
192064 ** varint: number of bytes of new term data (nNew)
192065 ** blob: nNew bytes of new term data
192066 ** doclist: next doclist
192069 ** doclist format:
192071 ** varint: first rowid
192072 ** poslist: first poslist
192073 ** zero-or-more {
192074 ** varint: rowid delta (always > 0)
192075 ** poslist: next poslist
192078 ** poslist format:
192080 ** varint: size of poslist in bytes multiplied by 2, not including
192081 ** this field. Plus 1 if this entry carries the "delete" flag.
192082 ** collist: collist for column 0
192083 ** zero-or-more {
192084 ** 0x01 byte
192085 ** varint: column number (I)
192086 ** collist: collist for column I
192089 ** collist format:
192091 ** varint: first offset + 2
192092 ** zero-or-more {
192093 ** varint: offset delta + 2
192096 ** PAGE FORMAT
192098 ** Each leaf page begins with a 4-byte header containing 2 16-bit
192099 ** unsigned integer fields in big-endian format. They are:
192101 ** * The byte offset of the first rowid on the page, if it exists
192102 ** and occurs before the first term (otherwise 0).
192104 ** * The byte offset of the start of the page footer. If the page
192105 ** footer is 0 bytes in size, then this field is the same as the
192106 ** size of the leaf page in bytes.
192108 ** The page footer consists of a single varint for each term located
192109 ** on the page. Each varint is the byte offset of the current term
192110 ** within the page, delta-compressed against the previous value. In
192111 ** other words, the first varint in the footer is the byte offset of
192112 ** the first term, the second is the byte offset of the second less that
192113 ** of the first, and so on.
192115 ** The term/doclist format described above is accurate if the entire
192116 ** term/doclist data fits on a single leaf page. If this is not the case,
192117 ** the format is changed in two ways:
192119 ** + if the first rowid on a page occurs before the first term, it
192120 ** is stored as a literal value:
192122 ** varint: first rowid
192124 ** + the first term on each page is stored in the same way as the
192125 ** very first term of the segment:
192127 ** varint : size of first term
192128 ** blob: first term data
192130 ** 5. Segment doclist indexes:
192132 ** Doclist indexes are themselves b-trees, however they usually consist of
192133 ** a single leaf record only. The format of each doclist index leaf page
192134 ** is:
192136 ** * Flags byte. Bits are:
192137 ** 0x01: Clear if leaf is also the root page, otherwise set.
192139 ** * Page number of fts index leaf page. As a varint.
192141 ** * First rowid on page indicated by previous field. As a varint.
192143 ** * A list of varints, one for each subsequent termless page. A
192144 ** positive delta if the termless page contains at least one rowid,
192145 ** or an 0x00 byte otherwise.
192147 ** Internal doclist index nodes are:
192149 ** * Flags byte. Bits are:
192150 ** 0x01: Clear for root page, otherwise set.
192152 ** * Page number of first child page. As a varint.
192154 ** * Copy of first rowid on page indicated by previous field. As a varint.
192156 ** * A list of delta-encoded varints - the first rowid on each subsequent
192157 ** child page.
192162 ** Rowids for the averages and structure records in the %_data table.
192164 #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
192165 #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
192168 ** Macros determining the rowids used by segment leaves and dlidx leaves
192169 ** and nodes. All nodes and leaves are stored in the %_data table with large
192170 ** positive rowids.
192172 ** Each segment has a unique non-zero 16-bit id.
192174 ** The rowid for each segment leaf is found by passing the segment id and
192175 ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
192176 ** sequentially starting from 1.
192178 #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
192179 #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
192180 #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
192181 #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
192183 #define fts5_dri(segid, dlidx, height, pgno) ( \
192184 ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
192185 ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
192186 ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
192187 ((i64)(pgno)) \
192190 #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
192191 #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
192194 ** Maximum segments permitted in a single index
192196 #define FTS5_MAX_SEGMENT 2000
192198 #ifdef SQLITE_DEBUG
192199 static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
192200 #endif
192204 ** Each time a blob is read from the %_data table, it is padded with this
192205 ** many zero bytes. This makes it easier to decode the various record formats
192206 ** without overreading if the records are corrupt.
192208 #define FTS5_DATA_ZERO_PADDING 8
192209 #define FTS5_DATA_PADDING 20
192211 typedef struct Fts5Data Fts5Data;
192212 typedef struct Fts5DlidxIter Fts5DlidxIter;
192213 typedef struct Fts5DlidxLvl Fts5DlidxLvl;
192214 typedef struct Fts5DlidxWriter Fts5DlidxWriter;
192215 typedef struct Fts5Iter Fts5Iter;
192216 typedef struct Fts5PageWriter Fts5PageWriter;
192217 typedef struct Fts5SegIter Fts5SegIter;
192218 typedef struct Fts5DoclistIter Fts5DoclistIter;
192219 typedef struct Fts5SegWriter Fts5SegWriter;
192220 typedef struct Fts5Structure Fts5Structure;
192221 typedef struct Fts5StructureLevel Fts5StructureLevel;
192222 typedef struct Fts5StructureSegment Fts5StructureSegment;
192224 struct Fts5Data {
192225 u8 *p; /* Pointer to buffer containing record */
192226 int nn; /* Size of record in bytes */
192227 int szLeaf; /* Size of leaf without page-index */
192231 ** One object per %_data table.
192233 struct Fts5Index {
192234 Fts5Config *pConfig; /* Virtual table configuration */
192235 char *zDataTbl; /* Name of %_data table */
192236 int nWorkUnit; /* Leaf pages in a "unit" of work */
192239 ** Variables related to the accumulation of tokens and doclists within the
192240 ** in-memory hash tables before they are flushed to disk.
192242 Fts5Hash *pHash; /* Hash table for in-memory data */
192243 int nPendingData; /* Current bytes of pending data */
192244 i64 iWriteRowid; /* Rowid for current doc being written */
192245 int bDelete; /* Current write is a delete */
192247 /* Error state. */
192248 int rc; /* Current error code */
192250 /* State used by the fts5DataXXX() functions. */
192251 sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
192252 sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
192253 sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
192254 sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
192255 sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
192256 sqlite3_stmt *pIdxSelect;
192257 int nRead; /* Total number of blocks read */
192259 sqlite3_stmt *pDataVersion;
192260 i64 iStructVersion; /* data_version when pStruct read */
192261 Fts5Structure *pStruct; /* Current db structure (or NULL) */
192264 struct Fts5DoclistIter {
192265 u8 *aEof; /* Pointer to 1 byte past end of doclist */
192267 /* Output variables. aPoslist==0 at EOF */
192268 i64 iRowid;
192269 u8 *aPoslist;
192270 int nPoslist;
192271 int nSize;
192275 ** The contents of the "structure" record for each index are represented
192276 ** using an Fts5Structure record in memory. Which uses instances of the
192277 ** other Fts5StructureXXX types as components.
192279 struct Fts5StructureSegment {
192280 int iSegid; /* Segment id */
192281 int pgnoFirst; /* First leaf page number in segment */
192282 int pgnoLast; /* Last leaf page number in segment */
192284 struct Fts5StructureLevel {
192285 int nMerge; /* Number of segments in incr-merge */
192286 int nSeg; /* Total number of segments on level */
192287 Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
192289 struct Fts5Structure {
192290 int nRef; /* Object reference count */
192291 u64 nWriteCounter; /* Total leaves written to level 0 */
192292 int nSegment; /* Total segments in this structure */
192293 int nLevel; /* Number of levels in this index */
192294 Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
192298 ** An object of type Fts5SegWriter is used to write to segments.
192300 struct Fts5PageWriter {
192301 int pgno; /* Page number for this page */
192302 int iPrevPgidx; /* Previous value written into pgidx */
192303 Fts5Buffer buf; /* Buffer containing leaf data */
192304 Fts5Buffer pgidx; /* Buffer containing page-index */
192305 Fts5Buffer term; /* Buffer containing previous term on page */
192307 struct Fts5DlidxWriter {
192308 int pgno; /* Page number for this page */
192309 int bPrevValid; /* True if iPrev is valid */
192310 i64 iPrev; /* Previous rowid value written to page */
192311 Fts5Buffer buf; /* Buffer containing page data */
192313 struct Fts5SegWriter {
192314 int iSegid; /* Segid to write to */
192315 Fts5PageWriter writer; /* PageWriter object */
192316 i64 iPrevRowid; /* Previous rowid written to current leaf */
192317 u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
192318 u8 bFirstRowidInPage; /* True if next rowid is first in page */
192319 /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
192320 u8 bFirstTermInPage; /* True if next term will be first in leaf */
192321 int nLeafWritten; /* Number of leaf pages written */
192322 int nEmpty; /* Number of contiguous term-less nodes */
192324 int nDlidx; /* Allocated size of aDlidx[] array */
192325 Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
192327 /* Values to insert into the %_idx table */
192328 Fts5Buffer btterm; /* Next term to insert into %_idx table */
192329 int iBtPage; /* Page number corresponding to btterm */
192332 typedef struct Fts5CResult Fts5CResult;
192333 struct Fts5CResult {
192334 u16 iFirst; /* aSeg[] index of firstest iterator */
192335 u8 bTermEq; /* True if the terms are equal */
192339 ** Object for iterating through a single segment, visiting each term/rowid
192340 ** pair in the segment.
192342 ** pSeg:
192343 ** The segment to iterate through.
192345 ** iLeafPgno:
192346 ** Current leaf page number within segment.
192348 ** iLeafOffset:
192349 ** Byte offset within the current leaf that is the first byte of the
192350 ** position list data (one byte passed the position-list size field).
192351 ** rowid field of the current entry. Usually this is the size field of the
192352 ** position list data. The exception is if the rowid for the current entry
192353 ** is the last thing on the leaf page.
192355 ** pLeaf:
192356 ** Buffer containing current leaf page data. Set to NULL at EOF.
192358 ** iTermLeafPgno, iTermLeafOffset:
192359 ** Leaf page number containing the last term read from the segment. And
192360 ** the offset immediately following the term data.
192362 ** flags:
192363 ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
192365 ** FTS5_SEGITER_ONETERM:
192366 ** If set, set the iterator to point to EOF after the current doclist
192367 ** has been exhausted. Do not proceed to the next term in the segment.
192369 ** FTS5_SEGITER_REVERSE:
192370 ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
192371 ** it is set, iterate through rowid in descending order instead of the
192372 ** default ascending order.
192374 ** iRowidOffset/nRowidOffset/aRowidOffset:
192375 ** These are used if the FTS5_SEGITER_REVERSE flag is set.
192377 ** For each rowid on the page corresponding to the current term, the
192378 ** corresponding aRowidOffset[] entry is set to the byte offset of the
192379 ** start of the "position-list-size" field within the page.
192381 ** iTermIdx:
192382 ** Index of current term on iTermLeafPgno.
192384 struct Fts5SegIter {
192385 Fts5StructureSegment *pSeg; /* Segment to iterate through */
192386 int flags; /* Mask of configuration flags */
192387 int iLeafPgno; /* Current leaf page number */
192388 Fts5Data *pLeaf; /* Current leaf data */
192389 Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
192390 int iLeafOffset; /* Byte offset within current leaf */
192392 /* Next method */
192393 void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
192395 /* The page and offset from which the current term was read. The offset
192396 ** is the offset of the first rowid in the current doclist. */
192397 int iTermLeafPgno;
192398 int iTermLeafOffset;
192400 int iPgidxOff; /* Next offset in pgidx */
192401 int iEndofDoclist;
192403 /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
192404 int iRowidOffset; /* Current entry in aRowidOffset[] */
192405 int nRowidOffset; /* Allocated size of aRowidOffset[] array */
192406 int *aRowidOffset; /* Array of offset to rowid fields */
192408 Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
192410 /* Variables populated based on current entry. */
192411 Fts5Buffer term; /* Current term */
192412 i64 iRowid; /* Current rowid */
192413 int nPos; /* Number of bytes in current position list */
192414 u8 bDel; /* True if the delete flag is set */
192418 ** Argument is a pointer to an Fts5Data structure that contains a
192419 ** leaf page.
192421 #define ASSERT_SZLEAF_OK(x) assert( \
192422 (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
192425 #define FTS5_SEGITER_ONETERM 0x01
192426 #define FTS5_SEGITER_REVERSE 0x02
192429 ** Argument is a pointer to an Fts5Data structure that contains a leaf
192430 ** page. This macro evaluates to true if the leaf contains no terms, or
192431 ** false if it contains at least one term.
192433 #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
192435 #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
192437 #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
192440 ** Object for iterating through the merged results of one or more segments,
192441 ** visiting each term/rowid pair in the merged data.
192443 ** nSeg is always a power of two greater than or equal to the number of
192444 ** segments that this object is merging data from. Both the aSeg[] and
192445 ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
192446 ** with zeroed objects - these are handled as if they were iterators opened
192447 ** on empty segments.
192449 ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
192450 ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
192451 ** comparison in this context is the index of the iterator that currently
192452 ** points to the smaller term/rowid combination. Iterators at EOF are
192453 ** considered to be greater than all other iterators.
192455 ** aFirst[1] contains the index in aSeg[] of the iterator that points to
192456 ** the smallest key overall. aFirst[0] is unused.
192458 ** poslist:
192459 ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
192460 ** There is no way to tell if this is populated or not.
192462 struct Fts5Iter {
192463 Fts5IndexIter base; /* Base class containing output vars */
192465 Fts5Index *pIndex; /* Index that owns this iterator */
192466 Fts5Structure *pStruct; /* Database structure for this iterator */
192467 Fts5Buffer poslist; /* Buffer containing current poslist */
192468 Fts5Colset *pColset; /* Restrict matches to these columns */
192470 /* Invoked to set output variables. */
192471 void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
192473 int nSeg; /* Size of aSeg[] array */
192474 int bRev; /* True to iterate in reverse order */
192475 u8 bSkipEmpty; /* True to skip deleted entries */
192477 i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
192478 Fts5CResult *aFirst; /* Current merge state (see above) */
192479 Fts5SegIter aSeg[1]; /* Array of segment iterators */
192484 ** An instance of the following type is used to iterate through the contents
192485 ** of a doclist-index record.
192487 ** pData:
192488 ** Record containing the doclist-index data.
192490 ** bEof:
192491 ** Set to true once iterator has reached EOF.
192493 ** iOff:
192494 ** Set to the current offset within record pData.
192496 struct Fts5DlidxLvl {
192497 Fts5Data *pData; /* Data for current page of this level */
192498 int iOff; /* Current offset into pData */
192499 int bEof; /* At EOF already */
192500 int iFirstOff; /* Used by reverse iterators */
192502 /* Output variables */
192503 int iLeafPgno; /* Page number of current leaf page */
192504 i64 iRowid; /* First rowid on leaf iLeafPgno */
192506 struct Fts5DlidxIter {
192507 int nLvl;
192508 int iSegid;
192509 Fts5DlidxLvl aLvl[1];
192512 static void fts5PutU16(u8 *aOut, u16 iVal){
192513 aOut[0] = (iVal>>8);
192514 aOut[1] = (iVal&0xFF);
192517 static u16 fts5GetU16(const u8 *aIn){
192518 return ((u16)aIn[0] << 8) + aIn[1];
192522 ** Allocate and return a buffer at least nByte bytes in size.
192524 ** If an OOM error is encountered, return NULL and set the error code in
192525 ** the Fts5Index handle passed as the first argument.
192527 static void *fts5IdxMalloc(Fts5Index *p, int nByte){
192528 return sqlite3Fts5MallocZero(&p->rc, nByte);
192532 ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
192534 ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
192535 ** +ve if pRight is smaller than pLeft. In other words:
192537 ** res = *pLeft - *pRight
192539 #ifdef SQLITE_DEBUG
192540 static int fts5BufferCompareBlob(
192541 Fts5Buffer *pLeft, /* Left hand side of comparison */
192542 const u8 *pRight, int nRight /* Right hand side of comparison */
192544 int nCmp = MIN(pLeft->n, nRight);
192545 int res = memcmp(pLeft->p, pRight, nCmp);
192546 return (res==0 ? (pLeft->n - nRight) : res);
192548 #endif
192551 ** Compare the contents of the two buffers using memcmp(). If one buffer
192552 ** is a prefix of the other, it is considered the lesser.
192554 ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
192555 ** +ve if pRight is smaller than pLeft. In other words:
192557 ** res = *pLeft - *pRight
192559 static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
192560 int nCmp = MIN(pLeft->n, pRight->n);
192561 int res = memcmp(pLeft->p, pRight->p, nCmp);
192562 return (res==0 ? (pLeft->n - pRight->n) : res);
192565 static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
192566 int ret;
192567 fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
192568 return ret;
192572 ** Close the read-only blob handle, if it is open.
192574 static void fts5CloseReader(Fts5Index *p){
192575 if( p->pReader ){
192576 sqlite3_blob *pReader = p->pReader;
192577 p->pReader = 0;
192578 sqlite3_blob_close(pReader);
192583 ** Retrieve a record from the %_data table.
192585 ** If an error occurs, NULL is returned and an error left in the
192586 ** Fts5Index object.
192588 static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
192589 Fts5Data *pRet = 0;
192590 if( p->rc==SQLITE_OK ){
192591 int rc = SQLITE_OK;
192593 if( p->pReader ){
192594 /* This call may return SQLITE_ABORT if there has been a savepoint
192595 ** rollback since it was last used. In this case a new blob handle
192596 ** is required. */
192597 sqlite3_blob *pBlob = p->pReader;
192598 p->pReader = 0;
192599 rc = sqlite3_blob_reopen(pBlob, iRowid);
192600 assert( p->pReader==0 );
192601 p->pReader = pBlob;
192602 if( rc!=SQLITE_OK ){
192603 fts5CloseReader(p);
192605 if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
192608 /* If the blob handle is not open at this point, open it and seek
192609 ** to the requested entry. */
192610 if( p->pReader==0 && rc==SQLITE_OK ){
192611 Fts5Config *pConfig = p->pConfig;
192612 rc = sqlite3_blob_open(pConfig->db,
192613 pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
192617 /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
192618 ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
192619 ** All the reasons those functions might return SQLITE_ERROR - missing
192620 ** table, missing row, non-blob/text in block column - indicate
192621 ** backing store corruption. */
192622 if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
192624 if( rc==SQLITE_OK ){
192625 u8 *aOut = 0; /* Read blob data into this buffer */
192626 int nByte = sqlite3_blob_bytes(p->pReader);
192627 int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
192628 pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
192629 if( pRet ){
192630 pRet->nn = nByte;
192631 aOut = pRet->p = (u8*)&pRet[1];
192632 }else{
192633 rc = SQLITE_NOMEM;
192636 if( rc==SQLITE_OK ){
192637 rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
192639 if( rc!=SQLITE_OK ){
192640 sqlite3_free(pRet);
192641 pRet = 0;
192642 }else{
192643 /* TODO1: Fix this */
192644 pRet->szLeaf = fts5GetU16(&pRet->p[2]);
192647 p->rc = rc;
192648 p->nRead++;
192651 assert( (pRet==0)==(p->rc!=SQLITE_OK) );
192652 return pRet;
192656 ** Release a reference to data record returned by an earlier call to
192657 ** fts5DataRead().
192659 static void fts5DataRelease(Fts5Data *pData){
192660 sqlite3_free(pData);
192663 static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
192664 Fts5Data *pRet = fts5DataRead(p, iRowid);
192665 if( pRet ){
192666 if( pRet->szLeaf>pRet->nn ){
192667 p->rc = FTS5_CORRUPT;
192668 fts5DataRelease(pRet);
192669 pRet = 0;
192672 return pRet;
192675 static int fts5IndexPrepareStmt(
192676 Fts5Index *p,
192677 sqlite3_stmt **ppStmt,
192678 char *zSql
192680 if( p->rc==SQLITE_OK ){
192681 if( zSql ){
192682 p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
192683 SQLITE_PREPARE_PERSISTENT, ppStmt, 0);
192684 }else{
192685 p->rc = SQLITE_NOMEM;
192688 sqlite3_free(zSql);
192689 return p->rc;
192694 ** INSERT OR REPLACE a record into the %_data table.
192696 static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
192697 if( p->rc!=SQLITE_OK ) return;
192699 if( p->pWriter==0 ){
192700 Fts5Config *pConfig = p->pConfig;
192701 fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
192702 "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
192703 pConfig->zDb, pConfig->zName
192705 if( p->rc ) return;
192708 sqlite3_bind_int64(p->pWriter, 1, iRowid);
192709 sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
192710 sqlite3_step(p->pWriter);
192711 p->rc = sqlite3_reset(p->pWriter);
192715 ** Execute the following SQL:
192717 ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
192719 static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
192720 if( p->rc!=SQLITE_OK ) return;
192722 if( p->pDeleter==0 ){
192723 int rc;
192724 Fts5Config *pConfig = p->pConfig;
192725 char *zSql = sqlite3_mprintf(
192726 "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
192727 pConfig->zDb, pConfig->zName
192729 if( zSql==0 ){
192730 rc = SQLITE_NOMEM;
192731 }else{
192732 rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
192733 SQLITE_PREPARE_PERSISTENT, &p->pDeleter, 0);
192734 sqlite3_free(zSql);
192736 if( rc!=SQLITE_OK ){
192737 p->rc = rc;
192738 return;
192742 sqlite3_bind_int64(p->pDeleter, 1, iFirst);
192743 sqlite3_bind_int64(p->pDeleter, 2, iLast);
192744 sqlite3_step(p->pDeleter);
192745 p->rc = sqlite3_reset(p->pDeleter);
192749 ** Remove all records associated with segment iSegid.
192751 static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
192752 i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
192753 i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
192754 fts5DataDelete(p, iFirst, iLast);
192755 if( p->pIdxDeleter==0 ){
192756 Fts5Config *pConfig = p->pConfig;
192757 fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
192758 "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
192759 pConfig->zDb, pConfig->zName
192762 if( p->rc==SQLITE_OK ){
192763 sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
192764 sqlite3_step(p->pIdxDeleter);
192765 p->rc = sqlite3_reset(p->pIdxDeleter);
192770 ** Release a reference to an Fts5Structure object returned by an earlier
192771 ** call to fts5StructureRead() or fts5StructureDecode().
192773 static void fts5StructureRelease(Fts5Structure *pStruct){
192774 if( pStruct && 0>=(--pStruct->nRef) ){
192775 int i;
192776 assert( pStruct->nRef==0 );
192777 for(i=0; i<pStruct->nLevel; i++){
192778 sqlite3_free(pStruct->aLevel[i].aSeg);
192780 sqlite3_free(pStruct);
192784 static void fts5StructureRef(Fts5Structure *pStruct){
192785 pStruct->nRef++;
192789 ** Deserialize and return the structure record currently stored in serialized
192790 ** form within buffer pData/nData.
192792 ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
192793 ** are over-allocated by one slot. This allows the structure contents
192794 ** to be more easily edited.
192796 ** If an error occurs, *ppOut is set to NULL and an SQLite error code
192797 ** returned. Otherwise, *ppOut is set to point to the new object and
192798 ** SQLITE_OK returned.
192800 static int fts5StructureDecode(
192801 const u8 *pData, /* Buffer containing serialized structure */
192802 int nData, /* Size of buffer pData in bytes */
192803 int *piCookie, /* Configuration cookie value */
192804 Fts5Structure **ppOut /* OUT: Deserialized object */
192806 int rc = SQLITE_OK;
192807 int i = 0;
192808 int iLvl;
192809 int nLevel = 0;
192810 int nSegment = 0;
192811 int nByte; /* Bytes of space to allocate at pRet */
192812 Fts5Structure *pRet = 0; /* Structure object to return */
192814 /* Grab the cookie value */
192815 if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
192816 i = 4;
192818 /* Read the total number of levels and segments from the start of the
192819 ** structure record. */
192820 i += fts5GetVarint32(&pData[i], nLevel);
192821 i += fts5GetVarint32(&pData[i], nSegment);
192822 nByte = (
192823 sizeof(Fts5Structure) + /* Main structure */
192824 sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
192826 pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
192828 if( pRet ){
192829 pRet->nRef = 1;
192830 pRet->nLevel = nLevel;
192831 pRet->nSegment = nSegment;
192832 i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
192834 for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
192835 Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
192836 int nTotal = 0;
192837 int iSeg;
192839 if( i>=nData ){
192840 rc = FTS5_CORRUPT;
192841 }else{
192842 i += fts5GetVarint32(&pData[i], pLvl->nMerge);
192843 i += fts5GetVarint32(&pData[i], nTotal);
192844 assert( nTotal>=pLvl->nMerge );
192845 pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
192846 nTotal * sizeof(Fts5StructureSegment)
192850 if( rc==SQLITE_OK ){
192851 pLvl->nSeg = nTotal;
192852 for(iSeg=0; iSeg<nTotal; iSeg++){
192853 if( i>=nData ){
192854 rc = FTS5_CORRUPT;
192855 break;
192857 i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
192858 i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
192859 i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
192863 if( rc!=SQLITE_OK ){
192864 fts5StructureRelease(pRet);
192865 pRet = 0;
192869 *ppOut = pRet;
192870 return rc;
192876 static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
192877 if( *pRc==SQLITE_OK ){
192878 Fts5Structure *pStruct = *ppStruct;
192879 int nLevel = pStruct->nLevel;
192880 int nByte = (
192881 sizeof(Fts5Structure) + /* Main structure */
192882 sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
192885 pStruct = sqlite3_realloc(pStruct, nByte);
192886 if( pStruct ){
192887 memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
192888 pStruct->nLevel++;
192889 *ppStruct = pStruct;
192890 }else{
192891 *pRc = SQLITE_NOMEM;
192897 ** Extend level iLvl so that there is room for at least nExtra more
192898 ** segments.
192900 static void fts5StructureExtendLevel(
192901 int *pRc,
192902 Fts5Structure *pStruct,
192903 int iLvl,
192904 int nExtra,
192905 int bInsert
192907 if( *pRc==SQLITE_OK ){
192908 Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
192909 Fts5StructureSegment *aNew;
192910 int nByte;
192912 nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
192913 aNew = sqlite3_realloc(pLvl->aSeg, nByte);
192914 if( aNew ){
192915 if( bInsert==0 ){
192916 memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
192917 }else{
192918 int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
192919 memmove(&aNew[nExtra], aNew, nMove);
192920 memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
192922 pLvl->aSeg = aNew;
192923 }else{
192924 *pRc = SQLITE_NOMEM;
192929 static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
192930 Fts5Structure *pRet = 0;
192931 Fts5Config *pConfig = p->pConfig;
192932 int iCookie; /* Configuration cookie */
192933 Fts5Data *pData;
192935 pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
192936 if( p->rc==SQLITE_OK ){
192937 /* TODO: Do we need this if the leaf-index is appended? Probably... */
192938 memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
192939 p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
192940 if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
192941 p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
192943 fts5DataRelease(pData);
192944 if( p->rc!=SQLITE_OK ){
192945 fts5StructureRelease(pRet);
192946 pRet = 0;
192950 return pRet;
192953 static i64 fts5IndexDataVersion(Fts5Index *p){
192954 i64 iVersion = 0;
192956 if( p->rc==SQLITE_OK ){
192957 if( p->pDataVersion==0 ){
192958 p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
192959 sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
192961 if( p->rc ) return 0;
192964 if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
192965 iVersion = sqlite3_column_int64(p->pDataVersion, 0);
192967 p->rc = sqlite3_reset(p->pDataVersion);
192970 return iVersion;
192974 ** Read, deserialize and return the structure record.
192976 ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
192977 ** are over-allocated as described for function fts5StructureDecode()
192978 ** above.
192980 ** If an error occurs, NULL is returned and an error code left in the
192981 ** Fts5Index handle. If an error has already occurred when this function
192982 ** is called, it is a no-op.
192984 static Fts5Structure *fts5StructureRead(Fts5Index *p){
192986 if( p->pStruct==0 ){
192987 p->iStructVersion = fts5IndexDataVersion(p);
192988 if( p->rc==SQLITE_OK ){
192989 p->pStruct = fts5StructureReadUncached(p);
192993 #if 0
192994 else{
192995 Fts5Structure *pTest = fts5StructureReadUncached(p);
192996 if( pTest ){
192997 int i, j;
192998 assert_nc( p->pStruct->nSegment==pTest->nSegment );
192999 assert_nc( p->pStruct->nLevel==pTest->nLevel );
193000 for(i=0; i<pTest->nLevel; i++){
193001 assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
193002 assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
193003 for(j=0; j<pTest->aLevel[i].nSeg; j++){
193004 Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
193005 Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
193006 assert_nc( p1->iSegid==p2->iSegid );
193007 assert_nc( p1->pgnoFirst==p2->pgnoFirst );
193008 assert_nc( p1->pgnoLast==p2->pgnoLast );
193011 fts5StructureRelease(pTest);
193014 #endif
193016 if( p->rc!=SQLITE_OK ) return 0;
193017 assert( p->iStructVersion!=0 );
193018 assert( p->pStruct!=0 );
193019 fts5StructureRef(p->pStruct);
193020 return p->pStruct;
193023 static void fts5StructureInvalidate(Fts5Index *p){
193024 if( p->pStruct ){
193025 fts5StructureRelease(p->pStruct);
193026 p->pStruct = 0;
193031 ** Return the total number of segments in index structure pStruct. This
193032 ** function is only ever used as part of assert() conditions.
193034 #ifdef SQLITE_DEBUG
193035 static int fts5StructureCountSegments(Fts5Structure *pStruct){
193036 int nSegment = 0; /* Total number of segments */
193037 if( pStruct ){
193038 int iLvl; /* Used to iterate through levels */
193039 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
193040 nSegment += pStruct->aLevel[iLvl].nSeg;
193044 return nSegment;
193046 #endif
193048 #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
193049 assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
193050 memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
193051 (pBuf)->n += nBlob; \
193054 #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
193055 (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
193056 assert( (pBuf)->nSpace>=(pBuf)->n ); \
193061 ** Serialize and store the "structure" record.
193063 ** If an error occurs, leave an error code in the Fts5Index object. If an
193064 ** error has already occurred, this function is a no-op.
193066 static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
193067 if( p->rc==SQLITE_OK ){
193068 Fts5Buffer buf; /* Buffer to serialize record into */
193069 int iLvl; /* Used to iterate through levels */
193070 int iCookie; /* Cookie value to store */
193072 assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
193073 memset(&buf, 0, sizeof(Fts5Buffer));
193075 /* Append the current configuration cookie */
193076 iCookie = p->pConfig->iCookie;
193077 if( iCookie<0 ) iCookie = 0;
193079 if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
193080 sqlite3Fts5Put32(buf.p, iCookie);
193081 buf.n = 4;
193082 fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
193083 fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
193084 fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
193087 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
193088 int iSeg; /* Used to iterate through segments */
193089 Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
193090 fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
193091 fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
193092 assert( pLvl->nMerge<=pLvl->nSeg );
193094 for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
193095 fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
193096 fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
193097 fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
193101 fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
193102 fts5BufferFree(&buf);
193106 #if 0
193107 static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
193108 static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
193109 int rc = SQLITE_OK;
193110 Fts5Buffer buf;
193111 memset(&buf, 0, sizeof(buf));
193112 fts5DebugStructure(&rc, &buf, pStruct);
193113 fprintf(stdout, "%s: %s\n", zCaption, buf.p);
193114 fflush(stdout);
193115 fts5BufferFree(&buf);
193117 #else
193118 # define fts5PrintStructure(x,y)
193119 #endif
193121 static int fts5SegmentSize(Fts5StructureSegment *pSeg){
193122 return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
193126 ** Return a copy of index structure pStruct. Except, promote as many
193127 ** segments as possible to level iPromote. If an OOM occurs, NULL is
193128 ** returned.
193130 static void fts5StructurePromoteTo(
193131 Fts5Index *p,
193132 int iPromote,
193133 int szPromote,
193134 Fts5Structure *pStruct
193136 int il, is;
193137 Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
193139 if( pOut->nMerge==0 ){
193140 for(il=iPromote+1; il<pStruct->nLevel; il++){
193141 Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
193142 if( pLvl->nMerge ) return;
193143 for(is=pLvl->nSeg-1; is>=0; is--){
193144 int sz = fts5SegmentSize(&pLvl->aSeg[is]);
193145 if( sz>szPromote ) return;
193146 fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
193147 if( p->rc ) return;
193148 memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
193149 pOut->nSeg++;
193150 pLvl->nSeg--;
193157 ** A new segment has just been written to level iLvl of index structure
193158 ** pStruct. This function determines if any segments should be promoted
193159 ** as a result. Segments are promoted in two scenarios:
193161 ** a) If the segment just written is smaller than one or more segments
193162 ** within the previous populated level, it is promoted to the previous
193163 ** populated level.
193165 ** b) If the segment just written is larger than the newest segment on
193166 ** the next populated level, then that segment, and any other adjacent
193167 ** segments that are also smaller than the one just written, are
193168 ** promoted.
193170 ** If one or more segments are promoted, the structure object is updated
193171 ** to reflect this.
193173 static void fts5StructurePromote(
193174 Fts5Index *p, /* FTS5 backend object */
193175 int iLvl, /* Index level just updated */
193176 Fts5Structure *pStruct /* Index structure */
193178 if( p->rc==SQLITE_OK ){
193179 int iTst;
193180 int iPromote = -1;
193181 int szPromote = 0; /* Promote anything this size or smaller */
193182 Fts5StructureSegment *pSeg; /* Segment just written */
193183 int szSeg; /* Size of segment just written */
193184 int nSeg = pStruct->aLevel[iLvl].nSeg;
193186 if( nSeg==0 ) return;
193187 pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
193188 szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
193190 /* Check for condition (a) */
193191 for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
193192 if( iTst>=0 ){
193193 int i;
193194 int szMax = 0;
193195 Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
193196 assert( pTst->nMerge==0 );
193197 for(i=0; i<pTst->nSeg; i++){
193198 int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
193199 if( sz>szMax ) szMax = sz;
193201 if( szMax>=szSeg ){
193202 /* Condition (a) is true. Promote the newest segment on level
193203 ** iLvl to level iTst. */
193204 iPromote = iTst;
193205 szPromote = szMax;
193209 /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
193210 ** is a no-op if it is not. */
193211 if( iPromote<0 ){
193212 iPromote = iLvl;
193213 szPromote = szSeg;
193215 fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
193221 ** Advance the iterator passed as the only argument. If the end of the
193222 ** doclist-index page is reached, return non-zero.
193224 static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
193225 Fts5Data *pData = pLvl->pData;
193227 if( pLvl->iOff==0 ){
193228 assert( pLvl->bEof==0 );
193229 pLvl->iOff = 1;
193230 pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
193231 pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
193232 pLvl->iFirstOff = pLvl->iOff;
193233 }else{
193234 int iOff;
193235 for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
193236 if( pData->p[iOff] ) break;
193239 if( iOff<pData->nn ){
193240 i64 iVal;
193241 pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
193242 iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
193243 pLvl->iRowid += iVal;
193244 pLvl->iOff = iOff;
193245 }else{
193246 pLvl->bEof = 1;
193250 return pLvl->bEof;
193254 ** Advance the iterator passed as the only argument.
193256 static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
193257 Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
193259 assert( iLvl<pIter->nLvl );
193260 if( fts5DlidxLvlNext(pLvl) ){
193261 if( (iLvl+1) < pIter->nLvl ){
193262 fts5DlidxIterNextR(p, pIter, iLvl+1);
193263 if( pLvl[1].bEof==0 ){
193264 fts5DataRelease(pLvl->pData);
193265 memset(pLvl, 0, sizeof(Fts5DlidxLvl));
193266 pLvl->pData = fts5DataRead(p,
193267 FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
193269 if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
193274 return pIter->aLvl[0].bEof;
193276 static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
193277 return fts5DlidxIterNextR(p, pIter, 0);
193281 ** The iterator passed as the first argument has the following fields set
193282 ** as follows. This function sets up the rest of the iterator so that it
193283 ** points to the first rowid in the doclist-index.
193285 ** pData:
193286 ** pointer to doclist-index record,
193288 ** When this function is called pIter->iLeafPgno is the page number the
193289 ** doclist is associated with (the one featuring the term).
193291 static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
193292 int i;
193293 for(i=0; i<pIter->nLvl; i++){
193294 fts5DlidxLvlNext(&pIter->aLvl[i]);
193296 return pIter->aLvl[0].bEof;
193300 static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
193301 return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
193304 static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
193305 int i;
193307 /* Advance each level to the last entry on the last page */
193308 for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
193309 Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
193310 while( fts5DlidxLvlNext(pLvl)==0 );
193311 pLvl->bEof = 0;
193313 if( i>0 ){
193314 Fts5DlidxLvl *pChild = &pLvl[-1];
193315 fts5DataRelease(pChild->pData);
193316 memset(pChild, 0, sizeof(Fts5DlidxLvl));
193317 pChild->pData = fts5DataRead(p,
193318 FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
193325 ** Move the iterator passed as the only argument to the previous entry.
193327 static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
193328 int iOff = pLvl->iOff;
193330 assert( pLvl->bEof==0 );
193331 if( iOff<=pLvl->iFirstOff ){
193332 pLvl->bEof = 1;
193333 }else{
193334 u8 *a = pLvl->pData->p;
193335 i64 iVal;
193336 int iLimit;
193337 int ii;
193338 int nZero = 0;
193340 /* Currently iOff points to the first byte of a varint. This block
193341 ** decrements iOff until it points to the first byte of the previous
193342 ** varint. Taking care not to read any memory locations that occur
193343 ** before the buffer in memory. */
193344 iLimit = (iOff>9 ? iOff-9 : 0);
193345 for(iOff--; iOff>iLimit; iOff--){
193346 if( (a[iOff-1] & 0x80)==0 ) break;
193349 fts5GetVarint(&a[iOff], (u64*)&iVal);
193350 pLvl->iRowid -= iVal;
193351 pLvl->iLeafPgno--;
193353 /* Skip backwards past any 0x00 varints. */
193354 for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
193355 nZero++;
193357 if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
193358 /* The byte immediately before the last 0x00 byte has the 0x80 bit
193359 ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
193360 ** bytes before a[ii]. */
193361 int bZero = 0; /* True if last 0x00 counts */
193362 if( (ii-8)>=pLvl->iFirstOff ){
193363 int j;
193364 for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
193365 bZero = (j>8);
193367 if( bZero==0 ) nZero--;
193369 pLvl->iLeafPgno -= nZero;
193370 pLvl->iOff = iOff - nZero;
193373 return pLvl->bEof;
193376 static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
193377 Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
193379 assert( iLvl<pIter->nLvl );
193380 if( fts5DlidxLvlPrev(pLvl) ){
193381 if( (iLvl+1) < pIter->nLvl ){
193382 fts5DlidxIterPrevR(p, pIter, iLvl+1);
193383 if( pLvl[1].bEof==0 ){
193384 fts5DataRelease(pLvl->pData);
193385 memset(pLvl, 0, sizeof(Fts5DlidxLvl));
193386 pLvl->pData = fts5DataRead(p,
193387 FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
193389 if( pLvl->pData ){
193390 while( fts5DlidxLvlNext(pLvl)==0 );
193391 pLvl->bEof = 0;
193397 return pIter->aLvl[0].bEof;
193399 static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
193400 return fts5DlidxIterPrevR(p, pIter, 0);
193404 ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
193406 static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
193407 if( pIter ){
193408 int i;
193409 for(i=0; i<pIter->nLvl; i++){
193410 fts5DataRelease(pIter->aLvl[i].pData);
193412 sqlite3_free(pIter);
193416 static Fts5DlidxIter *fts5DlidxIterInit(
193417 Fts5Index *p, /* Fts5 Backend to iterate within */
193418 int bRev, /* True for ORDER BY ASC */
193419 int iSegid, /* Segment id */
193420 int iLeafPg /* Leaf page number to load dlidx for */
193422 Fts5DlidxIter *pIter = 0;
193423 int i;
193424 int bDone = 0;
193426 for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
193427 int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
193428 Fts5DlidxIter *pNew;
193430 pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
193431 if( pNew==0 ){
193432 p->rc = SQLITE_NOMEM;
193433 }else{
193434 i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
193435 Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
193436 pIter = pNew;
193437 memset(pLvl, 0, sizeof(Fts5DlidxLvl));
193438 pLvl->pData = fts5DataRead(p, iRowid);
193439 if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
193440 bDone = 1;
193442 pIter->nLvl = i+1;
193446 if( p->rc==SQLITE_OK ){
193447 pIter->iSegid = iSegid;
193448 if( bRev==0 ){
193449 fts5DlidxIterFirst(pIter);
193450 }else{
193451 fts5DlidxIterLast(p, pIter);
193455 if( p->rc!=SQLITE_OK ){
193456 fts5DlidxIterFree(pIter);
193457 pIter = 0;
193460 return pIter;
193463 static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
193464 return pIter->aLvl[0].iRowid;
193466 static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
193467 return pIter->aLvl[0].iLeafPgno;
193471 ** Load the next leaf page into the segment iterator.
193473 static void fts5SegIterNextPage(
193474 Fts5Index *p, /* FTS5 backend object */
193475 Fts5SegIter *pIter /* Iterator to advance to next page */
193477 Fts5Data *pLeaf;
193478 Fts5StructureSegment *pSeg = pIter->pSeg;
193479 fts5DataRelease(pIter->pLeaf);
193480 pIter->iLeafPgno++;
193481 if( pIter->pNextLeaf ){
193482 pIter->pLeaf = pIter->pNextLeaf;
193483 pIter->pNextLeaf = 0;
193484 }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
193485 pIter->pLeaf = fts5LeafRead(p,
193486 FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
193488 }else{
193489 pIter->pLeaf = 0;
193491 pLeaf = pIter->pLeaf;
193493 if( pLeaf ){
193494 pIter->iPgidxOff = pLeaf->szLeaf;
193495 if( fts5LeafIsTermless(pLeaf) ){
193496 pIter->iEndofDoclist = pLeaf->nn+1;
193497 }else{
193498 pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
193499 pIter->iEndofDoclist
193506 ** Argument p points to a buffer containing a varint to be interpreted as a
193507 ** position list size field. Read the varint and return the number of bytes
193508 ** read. Before returning, set *pnSz to the number of bytes in the position
193509 ** list, and *pbDel to true if the delete flag is set, or false otherwise.
193511 static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
193512 int nSz;
193513 int n = 0;
193514 fts5FastGetVarint32(p, n, nSz);
193515 assert_nc( nSz>=0 );
193516 *pnSz = nSz/2;
193517 *pbDel = nSz & 0x0001;
193518 return n;
193522 ** Fts5SegIter.iLeafOffset currently points to the first byte of a
193523 ** position-list size field. Read the value of the field and store it
193524 ** in the following variables:
193526 ** Fts5SegIter.nPos
193527 ** Fts5SegIter.bDel
193529 ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
193530 ** position list content (if any).
193532 static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
193533 if( p->rc==SQLITE_OK ){
193534 int iOff = pIter->iLeafOffset; /* Offset to read at */
193535 ASSERT_SZLEAF_OK(pIter->pLeaf);
193536 if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
193537 int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
193538 pIter->bDel = 0;
193539 pIter->nPos = 1;
193540 if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
193541 pIter->bDel = 1;
193542 iOff++;
193543 if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
193544 pIter->nPos = 1;
193545 iOff++;
193546 }else{
193547 pIter->nPos = 0;
193550 }else{
193551 int nSz;
193552 fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
193553 pIter->bDel = (nSz & 0x0001);
193554 pIter->nPos = nSz>>1;
193555 assert_nc( pIter->nPos>=0 );
193557 pIter->iLeafOffset = iOff;
193561 static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
193562 u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
193563 int iOff = pIter->iLeafOffset;
193565 ASSERT_SZLEAF_OK(pIter->pLeaf);
193566 if( iOff>=pIter->pLeaf->szLeaf ){
193567 fts5SegIterNextPage(p, pIter);
193568 if( pIter->pLeaf==0 ){
193569 if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
193570 return;
193572 iOff = 4;
193573 a = pIter->pLeaf->p;
193575 iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
193576 pIter->iLeafOffset = iOff;
193580 ** Fts5SegIter.iLeafOffset currently points to the first byte of the
193581 ** "nSuffix" field of a term. Function parameter nKeep contains the value
193582 ** of the "nPrefix" field (if there was one - it is passed 0 if this is
193583 ** the first term in the segment).
193585 ** This function populates:
193587 ** Fts5SegIter.term
193588 ** Fts5SegIter.rowid
193590 ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
193591 ** the first position list. The position list belonging to document
193592 ** (Fts5SegIter.iRowid).
193594 static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
193595 u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
193596 int iOff = pIter->iLeafOffset; /* Offset to read at */
193597 int nNew; /* Bytes of new data */
193599 iOff += fts5GetVarint32(&a[iOff], nNew);
193600 if( iOff+nNew>pIter->pLeaf->nn ){
193601 p->rc = FTS5_CORRUPT;
193602 return;
193604 pIter->term.n = nKeep;
193605 fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
193606 iOff += nNew;
193607 pIter->iTermLeafOffset = iOff;
193608 pIter->iTermLeafPgno = pIter->iLeafPgno;
193609 pIter->iLeafOffset = iOff;
193611 if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
193612 pIter->iEndofDoclist = pIter->pLeaf->nn+1;
193613 }else{
193614 int nExtra;
193615 pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
193616 pIter->iEndofDoclist += nExtra;
193619 fts5SegIterLoadRowid(p, pIter);
193622 static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
193623 static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
193624 static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
193626 static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
193627 if( pIter->flags & FTS5_SEGITER_REVERSE ){
193628 pIter->xNext = fts5SegIterNext_Reverse;
193629 }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
193630 pIter->xNext = fts5SegIterNext_None;
193631 }else{
193632 pIter->xNext = fts5SegIterNext;
193637 ** Initialize the iterator object pIter to iterate through the entries in
193638 ** segment pSeg. The iterator is left pointing to the first entry when
193639 ** this function returns.
193641 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
193642 ** an error has already occurred when this function is called, it is a no-op.
193644 static void fts5SegIterInit(
193645 Fts5Index *p, /* FTS index object */
193646 Fts5StructureSegment *pSeg, /* Description of segment */
193647 Fts5SegIter *pIter /* Object to populate */
193649 if( pSeg->pgnoFirst==0 ){
193650 /* This happens if the segment is being used as an input to an incremental
193651 ** merge and all data has already been "trimmed". See function
193652 ** fts5TrimSegments() for details. In this case leave the iterator empty.
193653 ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
193654 ** at EOF already. */
193655 assert( pIter->pLeaf==0 );
193656 return;
193659 if( p->rc==SQLITE_OK ){
193660 memset(pIter, 0, sizeof(*pIter));
193661 fts5SegIterSetNext(p, pIter);
193662 pIter->pSeg = pSeg;
193663 pIter->iLeafPgno = pSeg->pgnoFirst-1;
193664 fts5SegIterNextPage(p, pIter);
193667 if( p->rc==SQLITE_OK ){
193668 pIter->iLeafOffset = 4;
193669 assert_nc( pIter->pLeaf->nn>4 );
193670 assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
193671 pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
193672 fts5SegIterLoadTerm(p, pIter, 0);
193673 fts5SegIterLoadNPos(p, pIter);
193678 ** This function is only ever called on iterators created by calls to
193679 ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
193681 ** The iterator is in an unusual state when this function is called: the
193682 ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
193683 ** the position-list size field for the first relevant rowid on the page.
193684 ** Fts5SegIter.rowid is set, but nPos and bDel are not.
193686 ** This function advances the iterator so that it points to the last
193687 ** relevant rowid on the page and, if necessary, initializes the
193688 ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
193689 ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
193690 ** byte of the position list content associated with said rowid.
193692 static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
193693 int eDetail = p->pConfig->eDetail;
193694 int n = pIter->pLeaf->szLeaf;
193695 int i = pIter->iLeafOffset;
193696 u8 *a = pIter->pLeaf->p;
193697 int iRowidOffset = 0;
193699 if( n>pIter->iEndofDoclist ){
193700 n = pIter->iEndofDoclist;
193703 ASSERT_SZLEAF_OK(pIter->pLeaf);
193704 while( 1 ){
193705 i64 iDelta = 0;
193707 if( eDetail==FTS5_DETAIL_NONE ){
193708 /* todo */
193709 if( i<n && a[i]==0 ){
193711 if( i<n && a[i]==0 ) i++;
193713 }else{
193714 int nPos;
193715 int bDummy;
193716 i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
193717 i += nPos;
193719 if( i>=n ) break;
193720 i += fts5GetVarint(&a[i], (u64*)&iDelta);
193721 pIter->iRowid += iDelta;
193723 /* If necessary, grow the pIter->aRowidOffset[] array. */
193724 if( iRowidOffset>=pIter->nRowidOffset ){
193725 int nNew = pIter->nRowidOffset + 8;
193726 int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
193727 if( aNew==0 ){
193728 p->rc = SQLITE_NOMEM;
193729 break;
193731 pIter->aRowidOffset = aNew;
193732 pIter->nRowidOffset = nNew;
193735 pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
193736 pIter->iLeafOffset = i;
193738 pIter->iRowidOffset = iRowidOffset;
193739 fts5SegIterLoadNPos(p, pIter);
193745 static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
193746 assert( pIter->flags & FTS5_SEGITER_REVERSE );
193747 assert( pIter->flags & FTS5_SEGITER_ONETERM );
193749 fts5DataRelease(pIter->pLeaf);
193750 pIter->pLeaf = 0;
193751 while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
193752 Fts5Data *pNew;
193753 pIter->iLeafPgno--;
193754 pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
193755 pIter->pSeg->iSegid, pIter->iLeafPgno
193757 if( pNew ){
193758 /* iTermLeafOffset may be equal to szLeaf if the term is the last
193759 ** thing on the page - i.e. the first rowid is on the following page.
193760 ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
193761 if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
193762 assert( pIter->pLeaf==0 );
193763 if( pIter->iTermLeafOffset<pNew->szLeaf ){
193764 pIter->pLeaf = pNew;
193765 pIter->iLeafOffset = pIter->iTermLeafOffset;
193767 }else{
193768 int iRowidOff;
193769 iRowidOff = fts5LeafFirstRowidOff(pNew);
193770 if( iRowidOff ){
193771 pIter->pLeaf = pNew;
193772 pIter->iLeafOffset = iRowidOff;
193776 if( pIter->pLeaf ){
193777 u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
193778 pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
193779 break;
193780 }else{
193781 fts5DataRelease(pNew);
193786 if( pIter->pLeaf ){
193787 pIter->iEndofDoclist = pIter->pLeaf->nn+1;
193788 fts5SegIterReverseInitPage(p, pIter);
193793 ** Return true if the iterator passed as the second argument currently
193794 ** points to a delete marker. A delete marker is an entry with a 0 byte
193795 ** position-list.
193797 static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
193798 Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
193799 return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
193803 ** Advance iterator pIter to the next entry.
193805 ** This version of fts5SegIterNext() is only used by reverse iterators.
193807 static void fts5SegIterNext_Reverse(
193808 Fts5Index *p, /* FTS5 backend object */
193809 Fts5SegIter *pIter, /* Iterator to advance */
193810 int *pbUnused /* Unused */
193812 assert( pIter->flags & FTS5_SEGITER_REVERSE );
193813 assert( pIter->pNextLeaf==0 );
193814 UNUSED_PARAM(pbUnused);
193816 if( pIter->iRowidOffset>0 ){
193817 u8 *a = pIter->pLeaf->p;
193818 int iOff;
193819 i64 iDelta;
193821 pIter->iRowidOffset--;
193822 pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
193823 fts5SegIterLoadNPos(p, pIter);
193824 iOff = pIter->iLeafOffset;
193825 if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
193826 iOff += pIter->nPos;
193828 fts5GetVarint(&a[iOff], (u64*)&iDelta);
193829 pIter->iRowid -= iDelta;
193830 }else{
193831 fts5SegIterReverseNewPage(p, pIter);
193836 ** Advance iterator pIter to the next entry.
193838 ** This version of fts5SegIterNext() is only used if detail=none and the
193839 ** iterator is not a reverse direction iterator.
193841 static void fts5SegIterNext_None(
193842 Fts5Index *p, /* FTS5 backend object */
193843 Fts5SegIter *pIter, /* Iterator to advance */
193844 int *pbNewTerm /* OUT: Set for new term */
193846 int iOff;
193848 assert( p->rc==SQLITE_OK );
193849 assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
193850 assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
193852 ASSERT_SZLEAF_OK(pIter->pLeaf);
193853 iOff = pIter->iLeafOffset;
193855 /* Next entry is on the next page */
193856 if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
193857 fts5SegIterNextPage(p, pIter);
193858 if( p->rc || pIter->pLeaf==0 ) return;
193859 pIter->iRowid = 0;
193860 iOff = 4;
193863 if( iOff<pIter->iEndofDoclist ){
193864 /* Next entry is on the current page */
193865 i64 iDelta;
193866 iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
193867 pIter->iLeafOffset = iOff;
193868 pIter->iRowid += iDelta;
193869 }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
193870 if( pIter->pSeg ){
193871 int nKeep = 0;
193872 if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
193873 iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
193875 pIter->iLeafOffset = iOff;
193876 fts5SegIterLoadTerm(p, pIter, nKeep);
193877 }else{
193878 const u8 *pList = 0;
193879 const char *zTerm = 0;
193880 int nList;
193881 sqlite3Fts5HashScanNext(p->pHash);
193882 sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
193883 if( pList==0 ) goto next_none_eof;
193884 pIter->pLeaf->p = (u8*)pList;
193885 pIter->pLeaf->nn = nList;
193886 pIter->pLeaf->szLeaf = nList;
193887 pIter->iEndofDoclist = nList;
193888 sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
193889 pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
193892 if( pbNewTerm ) *pbNewTerm = 1;
193893 }else{
193894 goto next_none_eof;
193897 fts5SegIterLoadNPos(p, pIter);
193899 return;
193900 next_none_eof:
193901 fts5DataRelease(pIter->pLeaf);
193902 pIter->pLeaf = 0;
193907 ** Advance iterator pIter to the next entry.
193909 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
193910 ** is not considered an error if the iterator reaches EOF. If an error has
193911 ** already occurred when this function is called, it is a no-op.
193913 static void fts5SegIterNext(
193914 Fts5Index *p, /* FTS5 backend object */
193915 Fts5SegIter *pIter, /* Iterator to advance */
193916 int *pbNewTerm /* OUT: Set for new term */
193918 Fts5Data *pLeaf = pIter->pLeaf;
193919 int iOff;
193920 int bNewTerm = 0;
193921 int nKeep = 0;
193922 u8 *a;
193923 int n;
193925 assert( pbNewTerm==0 || *pbNewTerm==0 );
193926 assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
193928 /* Search for the end of the position list within the current page. */
193929 a = pLeaf->p;
193930 n = pLeaf->szLeaf;
193932 ASSERT_SZLEAF_OK(pLeaf);
193933 iOff = pIter->iLeafOffset + pIter->nPos;
193935 if( iOff<n ){
193936 /* The next entry is on the current page. */
193937 assert_nc( iOff<=pIter->iEndofDoclist );
193938 if( iOff>=pIter->iEndofDoclist ){
193939 bNewTerm = 1;
193940 if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
193941 iOff += fts5GetVarint32(&a[iOff], nKeep);
193943 }else{
193944 u64 iDelta;
193945 iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
193946 pIter->iRowid += iDelta;
193947 assert_nc( iDelta>0 );
193949 pIter->iLeafOffset = iOff;
193951 }else if( pIter->pSeg==0 ){
193952 const u8 *pList = 0;
193953 const char *zTerm = 0;
193954 int nList = 0;
193955 assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
193956 if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
193957 sqlite3Fts5HashScanNext(p->pHash);
193958 sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
193960 if( pList==0 ){
193961 fts5DataRelease(pIter->pLeaf);
193962 pIter->pLeaf = 0;
193963 }else{
193964 pIter->pLeaf->p = (u8*)pList;
193965 pIter->pLeaf->nn = nList;
193966 pIter->pLeaf->szLeaf = nList;
193967 pIter->iEndofDoclist = nList+1;
193968 sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
193969 (u8*)zTerm);
193970 pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
193971 *pbNewTerm = 1;
193973 }else{
193974 iOff = 0;
193975 /* Next entry is not on the current page */
193976 while( iOff==0 ){
193977 fts5SegIterNextPage(p, pIter);
193978 pLeaf = pIter->pLeaf;
193979 if( pLeaf==0 ) break;
193980 ASSERT_SZLEAF_OK(pLeaf);
193981 if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
193982 iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
193983 pIter->iLeafOffset = iOff;
193985 if( pLeaf->nn>pLeaf->szLeaf ){
193986 pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
193987 &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
193991 else if( pLeaf->nn>pLeaf->szLeaf ){
193992 pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
193993 &pLeaf->p[pLeaf->szLeaf], iOff
193995 pIter->iLeafOffset = iOff;
193996 pIter->iEndofDoclist = iOff;
193997 bNewTerm = 1;
193999 assert_nc( iOff<pLeaf->szLeaf );
194000 if( iOff>pLeaf->szLeaf ){
194001 p->rc = FTS5_CORRUPT;
194002 return;
194007 /* Check if the iterator is now at EOF. If so, return early. */
194008 if( pIter->pLeaf ){
194009 if( bNewTerm ){
194010 if( pIter->flags & FTS5_SEGITER_ONETERM ){
194011 fts5DataRelease(pIter->pLeaf);
194012 pIter->pLeaf = 0;
194013 }else{
194014 fts5SegIterLoadTerm(p, pIter, nKeep);
194015 fts5SegIterLoadNPos(p, pIter);
194016 if( pbNewTerm ) *pbNewTerm = 1;
194018 }else{
194019 /* The following could be done by calling fts5SegIterLoadNPos(). But
194020 ** this block is particularly performance critical, so equivalent
194021 ** code is inlined.
194023 ** Later: Switched back to fts5SegIterLoadNPos() because it supports
194024 ** detail=none mode. Not ideal.
194026 int nSz;
194027 assert( p->rc==SQLITE_OK );
194028 assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
194029 fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
194030 pIter->bDel = (nSz & 0x0001);
194031 pIter->nPos = nSz>>1;
194032 assert_nc( pIter->nPos>=0 );
194037 #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
194039 #define fts5IndexSkipVarint(a, iOff) { \
194040 int iEnd = iOff+9; \
194041 while( (a[iOff++] & 0x80) && iOff<iEnd ); \
194045 ** Iterator pIter currently points to the first rowid in a doclist. This
194046 ** function sets the iterator up so that iterates in reverse order through
194047 ** the doclist.
194049 static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
194050 Fts5DlidxIter *pDlidx = pIter->pDlidx;
194051 Fts5Data *pLast = 0;
194052 int pgnoLast = 0;
194054 if( pDlidx ){
194055 int iSegid = pIter->pSeg->iSegid;
194056 pgnoLast = fts5DlidxIterPgno(pDlidx);
194057 pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
194058 }else{
194059 Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
194061 /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
194062 ** position-list content for the current rowid. Back it up so that it
194063 ** points to the start of the position-list size field. */
194064 int iPoslist;
194065 if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
194066 iPoslist = pIter->iTermLeafOffset;
194067 }else{
194068 iPoslist = 4;
194070 fts5IndexSkipVarint(pLeaf->p, iPoslist);
194071 pIter->iLeafOffset = iPoslist;
194073 /* If this condition is true then the largest rowid for the current
194074 ** term may not be stored on the current page. So search forward to
194075 ** see where said rowid really is. */
194076 if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
194077 int pgno;
194078 Fts5StructureSegment *pSeg = pIter->pSeg;
194080 /* The last rowid in the doclist may not be on the current page. Search
194081 ** forward to find the page containing the last rowid. */
194082 for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
194083 i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
194084 Fts5Data *pNew = fts5DataRead(p, iAbs);
194085 if( pNew ){
194086 int iRowid, bTermless;
194087 iRowid = fts5LeafFirstRowidOff(pNew);
194088 bTermless = fts5LeafIsTermless(pNew);
194089 if( iRowid ){
194090 SWAPVAL(Fts5Data*, pNew, pLast);
194091 pgnoLast = pgno;
194093 fts5DataRelease(pNew);
194094 if( bTermless==0 ) break;
194100 /* If pLast is NULL at this point, then the last rowid for this doclist
194101 ** lies on the page currently indicated by the iterator. In this case
194102 ** pIter->iLeafOffset is already set to point to the position-list size
194103 ** field associated with the first relevant rowid on the page.
194105 ** Or, if pLast is non-NULL, then it is the page that contains the last
194106 ** rowid. In this case configure the iterator so that it points to the
194107 ** first rowid on this page.
194109 if( pLast ){
194110 int iOff;
194111 fts5DataRelease(pIter->pLeaf);
194112 pIter->pLeaf = pLast;
194113 pIter->iLeafPgno = pgnoLast;
194114 iOff = fts5LeafFirstRowidOff(pLast);
194115 iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
194116 pIter->iLeafOffset = iOff;
194118 if( fts5LeafIsTermless(pLast) ){
194119 pIter->iEndofDoclist = pLast->nn+1;
194120 }else{
194121 pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
194126 fts5SegIterReverseInitPage(p, pIter);
194130 ** Iterator pIter currently points to the first rowid of a doclist.
194131 ** There is a doclist-index associated with the final term on the current
194132 ** page. If the current term is the last term on the page, load the
194133 ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
194135 static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
194136 int iSeg = pIter->pSeg->iSegid;
194137 int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
194138 Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
194140 assert( pIter->flags & FTS5_SEGITER_ONETERM );
194141 assert( pIter->pDlidx==0 );
194143 /* Check if the current doclist ends on this page. If it does, return
194144 ** early without loading the doclist-index (as it belongs to a different
194145 ** term. */
194146 if( pIter->iTermLeafPgno==pIter->iLeafPgno
194147 && pIter->iEndofDoclist<pLeaf->szLeaf
194149 return;
194152 pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
194156 ** The iterator object passed as the second argument currently contains
194157 ** no valid values except for the Fts5SegIter.pLeaf member variable. This
194158 ** function searches the leaf page for a term matching (pTerm/nTerm).
194160 ** If the specified term is found on the page, then the iterator is left
194161 ** pointing to it. If argument bGe is zero and the term is not found,
194162 ** the iterator is left pointing at EOF.
194164 ** If bGe is non-zero and the specified term is not found, then the
194165 ** iterator is left pointing to the smallest term in the segment that
194166 ** is larger than the specified term, even if this term is not on the
194167 ** current page.
194169 static void fts5LeafSeek(
194170 Fts5Index *p, /* Leave any error code here */
194171 int bGe, /* True for a >= search */
194172 Fts5SegIter *pIter, /* Iterator to seek */
194173 const u8 *pTerm, int nTerm /* Term to search for */
194175 int iOff;
194176 const u8 *a = pIter->pLeaf->p;
194177 int szLeaf = pIter->pLeaf->szLeaf;
194178 int n = pIter->pLeaf->nn;
194180 int nMatch = 0;
194181 int nKeep = 0;
194182 int nNew = 0;
194183 int iTermOff;
194184 int iPgidx; /* Current offset in pgidx */
194185 int bEndOfPage = 0;
194187 assert( p->rc==SQLITE_OK );
194189 iPgidx = szLeaf;
194190 iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
194191 iOff = iTermOff;
194192 if( iOff>n ){
194193 p->rc = FTS5_CORRUPT;
194194 return;
194197 while( 1 ){
194199 /* Figure out how many new bytes are in this term */
194200 fts5FastGetVarint32(a, iOff, nNew);
194201 if( nKeep<nMatch ){
194202 goto search_failed;
194205 assert( nKeep>=nMatch );
194206 if( nKeep==nMatch ){
194207 int nCmp;
194208 int i;
194209 nCmp = MIN(nNew, nTerm-nMatch);
194210 for(i=0; i<nCmp; i++){
194211 if( a[iOff+i]!=pTerm[nMatch+i] ) break;
194213 nMatch += i;
194215 if( nTerm==nMatch ){
194216 if( i==nNew ){
194217 goto search_success;
194218 }else{
194219 goto search_failed;
194221 }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
194222 goto search_failed;
194226 if( iPgidx>=n ){
194227 bEndOfPage = 1;
194228 break;
194231 iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
194232 iTermOff += nKeep;
194233 iOff = iTermOff;
194235 if( iOff>=n ){
194236 p->rc = FTS5_CORRUPT;
194237 return;
194240 /* Read the nKeep field of the next term. */
194241 fts5FastGetVarint32(a, iOff, nKeep);
194244 search_failed:
194245 if( bGe==0 ){
194246 fts5DataRelease(pIter->pLeaf);
194247 pIter->pLeaf = 0;
194248 return;
194249 }else if( bEndOfPage ){
194251 fts5SegIterNextPage(p, pIter);
194252 if( pIter->pLeaf==0 ) return;
194253 a = pIter->pLeaf->p;
194254 if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
194255 iPgidx = pIter->pLeaf->szLeaf;
194256 iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
194257 if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
194258 p->rc = FTS5_CORRUPT;
194259 }else{
194260 nKeep = 0;
194261 iTermOff = iOff;
194262 n = pIter->pLeaf->nn;
194263 iOff += fts5GetVarint32(&a[iOff], nNew);
194264 break;
194267 }while( 1 );
194270 search_success:
194272 pIter->iLeafOffset = iOff + nNew;
194273 pIter->iTermLeafOffset = pIter->iLeafOffset;
194274 pIter->iTermLeafPgno = pIter->iLeafPgno;
194276 fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
194277 fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
194279 if( iPgidx>=n ){
194280 pIter->iEndofDoclist = pIter->pLeaf->nn+1;
194281 }else{
194282 int nExtra;
194283 iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
194284 pIter->iEndofDoclist = iTermOff + nExtra;
194286 pIter->iPgidxOff = iPgidx;
194288 fts5SegIterLoadRowid(p, pIter);
194289 fts5SegIterLoadNPos(p, pIter);
194292 static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
194293 if( p->pIdxSelect==0 ){
194294 Fts5Config *pConfig = p->pConfig;
194295 fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
194296 "SELECT pgno FROM '%q'.'%q_idx' WHERE "
194297 "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
194298 pConfig->zDb, pConfig->zName
194301 return p->pIdxSelect;
194305 ** Initialize the object pIter to point to term pTerm/nTerm within segment
194306 ** pSeg. If there is no such term in the index, the iterator is set to EOF.
194308 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
194309 ** an error has already occurred when this function is called, it is a no-op.
194311 static void fts5SegIterSeekInit(
194312 Fts5Index *p, /* FTS5 backend */
194313 const u8 *pTerm, int nTerm, /* Term to seek to */
194314 int flags, /* Mask of FTS5INDEX_XXX flags */
194315 Fts5StructureSegment *pSeg, /* Description of segment */
194316 Fts5SegIter *pIter /* Object to populate */
194318 int iPg = 1;
194319 int bGe = (flags & FTS5INDEX_QUERY_SCAN);
194320 int bDlidx = 0; /* True if there is a doclist-index */
194321 sqlite3_stmt *pIdxSelect = 0;
194323 assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
194324 assert( pTerm && nTerm );
194325 memset(pIter, 0, sizeof(*pIter));
194326 pIter->pSeg = pSeg;
194328 /* This block sets stack variable iPg to the leaf page number that may
194329 ** contain term (pTerm/nTerm), if it is present in the segment. */
194330 pIdxSelect = fts5IdxSelectStmt(p);
194331 if( p->rc ) return;
194332 sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
194333 sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
194334 if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
194335 i64 val = sqlite3_column_int(pIdxSelect, 0);
194336 iPg = (int)(val>>1);
194337 bDlidx = (val & 0x0001);
194339 p->rc = sqlite3_reset(pIdxSelect);
194341 if( iPg<pSeg->pgnoFirst ){
194342 iPg = pSeg->pgnoFirst;
194343 bDlidx = 0;
194346 pIter->iLeafPgno = iPg - 1;
194347 fts5SegIterNextPage(p, pIter);
194349 if( pIter->pLeaf ){
194350 fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
194353 if( p->rc==SQLITE_OK && bGe==0 ){
194354 pIter->flags |= FTS5_SEGITER_ONETERM;
194355 if( pIter->pLeaf ){
194356 if( flags & FTS5INDEX_QUERY_DESC ){
194357 pIter->flags |= FTS5_SEGITER_REVERSE;
194359 if( bDlidx ){
194360 fts5SegIterLoadDlidx(p, pIter);
194362 if( flags & FTS5INDEX_QUERY_DESC ){
194363 fts5SegIterReverse(p, pIter);
194368 fts5SegIterSetNext(p, pIter);
194370 /* Either:
194372 ** 1) an error has occurred, or
194373 ** 2) the iterator points to EOF, or
194374 ** 3) the iterator points to an entry with term (pTerm/nTerm), or
194375 ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
194376 ** to an entry with a term greater than or equal to (pTerm/nTerm).
194378 assert( p->rc!=SQLITE_OK /* 1 */
194379 || pIter->pLeaf==0 /* 2 */
194380 || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
194381 || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
194386 ** Initialize the object pIter to point to term pTerm/nTerm within the
194387 ** in-memory hash table. If there is no such term in the hash-table, the
194388 ** iterator is set to EOF.
194390 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
194391 ** an error has already occurred when this function is called, it is a no-op.
194393 static void fts5SegIterHashInit(
194394 Fts5Index *p, /* FTS5 backend */
194395 const u8 *pTerm, int nTerm, /* Term to seek to */
194396 int flags, /* Mask of FTS5INDEX_XXX flags */
194397 Fts5SegIter *pIter /* Object to populate */
194399 const u8 *pList = 0;
194400 int nList = 0;
194401 const u8 *z = 0;
194402 int n = 0;
194404 assert( p->pHash );
194405 assert( p->rc==SQLITE_OK );
194407 if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
194408 p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
194409 sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
194410 n = (z ? (int)strlen((const char*)z) : 0);
194411 }else{
194412 pIter->flags |= FTS5_SEGITER_ONETERM;
194413 sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
194414 z = pTerm;
194415 n = nTerm;
194418 if( pList ){
194419 Fts5Data *pLeaf;
194420 sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
194421 pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
194422 if( pLeaf==0 ) return;
194423 pLeaf->p = (u8*)pList;
194424 pLeaf->nn = pLeaf->szLeaf = nList;
194425 pIter->pLeaf = pLeaf;
194426 pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
194427 pIter->iEndofDoclist = pLeaf->nn;
194429 if( flags & FTS5INDEX_QUERY_DESC ){
194430 pIter->flags |= FTS5_SEGITER_REVERSE;
194431 fts5SegIterReverseInitPage(p, pIter);
194432 }else{
194433 fts5SegIterLoadNPos(p, pIter);
194437 fts5SegIterSetNext(p, pIter);
194441 ** Zero the iterator passed as the only argument.
194443 static void fts5SegIterClear(Fts5SegIter *pIter){
194444 fts5BufferFree(&pIter->term);
194445 fts5DataRelease(pIter->pLeaf);
194446 fts5DataRelease(pIter->pNextLeaf);
194447 fts5DlidxIterFree(pIter->pDlidx);
194448 sqlite3_free(pIter->aRowidOffset);
194449 memset(pIter, 0, sizeof(Fts5SegIter));
194452 #ifdef SQLITE_DEBUG
194455 ** This function is used as part of the big assert() procedure implemented by
194456 ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
194457 ** in *pRes is the correct result of comparing the current positions of the
194458 ** two iterators.
194460 static void fts5AssertComparisonResult(
194461 Fts5Iter *pIter,
194462 Fts5SegIter *p1,
194463 Fts5SegIter *p2,
194464 Fts5CResult *pRes
194466 int i1 = p1 - pIter->aSeg;
194467 int i2 = p2 - pIter->aSeg;
194469 if( p1->pLeaf || p2->pLeaf ){
194470 if( p1->pLeaf==0 ){
194471 assert( pRes->iFirst==i2 );
194472 }else if( p2->pLeaf==0 ){
194473 assert( pRes->iFirst==i1 );
194474 }else{
194475 int nMin = MIN(p1->term.n, p2->term.n);
194476 int res = memcmp(p1->term.p, p2->term.p, nMin);
194477 if( res==0 ) res = p1->term.n - p2->term.n;
194479 if( res==0 ){
194480 assert( pRes->bTermEq==1 );
194481 assert( p1->iRowid!=p2->iRowid );
194482 res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
194483 }else{
194484 assert( pRes->bTermEq==0 );
194487 if( res<0 ){
194488 assert( pRes->iFirst==i1 );
194489 }else{
194490 assert( pRes->iFirst==i2 );
194497 ** This function is a no-op unless SQLITE_DEBUG is defined when this module
194498 ** is compiled. In that case, this function is essentially an assert()
194499 ** statement used to verify that the contents of the pIter->aFirst[] array
194500 ** are correct.
194502 static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
194503 if( p->rc==SQLITE_OK ){
194504 Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
194505 int i;
194507 assert( (pFirst->pLeaf==0)==pIter->base.bEof );
194509 /* Check that pIter->iSwitchRowid is set correctly. */
194510 for(i=0; i<pIter->nSeg; i++){
194511 Fts5SegIter *p1 = &pIter->aSeg[i];
194512 assert( p1==pFirst
194513 || p1->pLeaf==0
194514 || fts5BufferCompare(&pFirst->term, &p1->term)
194515 || p1->iRowid==pIter->iSwitchRowid
194516 || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
194520 for(i=0; i<pIter->nSeg; i+=2){
194521 Fts5SegIter *p1 = &pIter->aSeg[i];
194522 Fts5SegIter *p2 = &pIter->aSeg[i+1];
194523 Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
194524 fts5AssertComparisonResult(pIter, p1, p2, pRes);
194527 for(i=1; i<(pIter->nSeg / 2); i+=2){
194528 Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
194529 Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
194530 Fts5CResult *pRes = &pIter->aFirst[i];
194531 fts5AssertComparisonResult(pIter, p1, p2, pRes);
194535 #else
194536 # define fts5AssertMultiIterSetup(x,y)
194537 #endif
194540 ** Do the comparison necessary to populate pIter->aFirst[iOut].
194542 ** If the returned value is non-zero, then it is the index of an entry
194543 ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
194544 ** to a key that is a duplicate of another, higher priority,
194545 ** segment-iterator in the pSeg->aSeg[] array.
194547 static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
194548 int i1; /* Index of left-hand Fts5SegIter */
194549 int i2; /* Index of right-hand Fts5SegIter */
194550 int iRes;
194551 Fts5SegIter *p1; /* Left-hand Fts5SegIter */
194552 Fts5SegIter *p2; /* Right-hand Fts5SegIter */
194553 Fts5CResult *pRes = &pIter->aFirst[iOut];
194555 assert( iOut<pIter->nSeg && iOut>0 );
194556 assert( pIter->bRev==0 || pIter->bRev==1 );
194558 if( iOut>=(pIter->nSeg/2) ){
194559 i1 = (iOut - pIter->nSeg/2) * 2;
194560 i2 = i1 + 1;
194561 }else{
194562 i1 = pIter->aFirst[iOut*2].iFirst;
194563 i2 = pIter->aFirst[iOut*2+1].iFirst;
194565 p1 = &pIter->aSeg[i1];
194566 p2 = &pIter->aSeg[i2];
194568 pRes->bTermEq = 0;
194569 if( p1->pLeaf==0 ){ /* If p1 is at EOF */
194570 iRes = i2;
194571 }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
194572 iRes = i1;
194573 }else{
194574 int res = fts5BufferCompare(&p1->term, &p2->term);
194575 if( res==0 ){
194576 assert( i2>i1 );
194577 assert( i2!=0 );
194578 pRes->bTermEq = 1;
194579 if( p1->iRowid==p2->iRowid ){
194580 p1->bDel = p2->bDel;
194581 return i2;
194583 res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
194585 assert( res!=0 );
194586 if( res<0 ){
194587 iRes = i1;
194588 }else{
194589 iRes = i2;
194593 pRes->iFirst = (u16)iRes;
194594 return 0;
194598 ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
194599 ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
194601 static void fts5SegIterGotoPage(
194602 Fts5Index *p, /* FTS5 backend object */
194603 Fts5SegIter *pIter, /* Iterator to advance */
194604 int iLeafPgno
194606 assert( iLeafPgno>pIter->iLeafPgno );
194608 if( iLeafPgno>pIter->pSeg->pgnoLast ){
194609 p->rc = FTS5_CORRUPT;
194610 }else{
194611 fts5DataRelease(pIter->pNextLeaf);
194612 pIter->pNextLeaf = 0;
194613 pIter->iLeafPgno = iLeafPgno-1;
194614 fts5SegIterNextPage(p, pIter);
194615 assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
194617 if( p->rc==SQLITE_OK ){
194618 int iOff;
194619 u8 *a = pIter->pLeaf->p;
194620 int n = pIter->pLeaf->szLeaf;
194622 iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
194623 if( iOff<4 || iOff>=n ){
194624 p->rc = FTS5_CORRUPT;
194625 }else{
194626 iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
194627 pIter->iLeafOffset = iOff;
194628 fts5SegIterLoadNPos(p, pIter);
194635 ** Advance the iterator passed as the second argument until it is at or
194636 ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
194637 ** always advanced at least once.
194639 static void fts5SegIterNextFrom(
194640 Fts5Index *p, /* FTS5 backend object */
194641 Fts5SegIter *pIter, /* Iterator to advance */
194642 i64 iMatch /* Advance iterator at least this far */
194644 int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
194645 Fts5DlidxIter *pDlidx = pIter->pDlidx;
194646 int iLeafPgno = pIter->iLeafPgno;
194647 int bMove = 1;
194649 assert( pIter->flags & FTS5_SEGITER_ONETERM );
194650 assert( pIter->pDlidx );
194651 assert( pIter->pLeaf );
194653 if( bRev==0 ){
194654 while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
194655 iLeafPgno = fts5DlidxIterPgno(pDlidx);
194656 fts5DlidxIterNext(p, pDlidx);
194658 assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
194659 if( iLeafPgno>pIter->iLeafPgno ){
194660 fts5SegIterGotoPage(p, pIter, iLeafPgno);
194661 bMove = 0;
194663 }else{
194664 assert( pIter->pNextLeaf==0 );
194665 assert( iMatch<pIter->iRowid );
194666 while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
194667 fts5DlidxIterPrev(p, pDlidx);
194669 iLeafPgno = fts5DlidxIterPgno(pDlidx);
194671 assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
194673 if( iLeafPgno<pIter->iLeafPgno ){
194674 pIter->iLeafPgno = iLeafPgno+1;
194675 fts5SegIterReverseNewPage(p, pIter);
194676 bMove = 0;
194681 if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
194682 if( pIter->pLeaf==0 ) break;
194683 if( bRev==0 && pIter->iRowid>=iMatch ) break;
194684 if( bRev!=0 && pIter->iRowid<=iMatch ) break;
194685 bMove = 1;
194686 }while( p->rc==SQLITE_OK );
194691 ** Free the iterator object passed as the second argument.
194693 static void fts5MultiIterFree(Fts5Iter *pIter){
194694 if( pIter ){
194695 int i;
194696 for(i=0; i<pIter->nSeg; i++){
194697 fts5SegIterClear(&pIter->aSeg[i]);
194699 fts5StructureRelease(pIter->pStruct);
194700 fts5BufferFree(&pIter->poslist);
194701 sqlite3_free(pIter);
194705 static void fts5MultiIterAdvanced(
194706 Fts5Index *p, /* FTS5 backend to iterate within */
194707 Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
194708 int iChanged, /* Index of sub-iterator just advanced */
194709 int iMinset /* Minimum entry in aFirst[] to set */
194711 int i;
194712 for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
194713 int iEq;
194714 if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
194715 Fts5SegIter *pSeg = &pIter->aSeg[iEq];
194716 assert( p->rc==SQLITE_OK );
194717 pSeg->xNext(p, pSeg, 0);
194718 i = pIter->nSeg + iEq;
194724 ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
194725 ** points to the same term though - just a different rowid. This function
194726 ** attempts to update the contents of the pIter->aFirst[] accordingly.
194727 ** If it does so successfully, 0 is returned. Otherwise 1.
194729 ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
194730 ** on the iterator instead. That function does the same as this one, except
194731 ** that it deals with more complicated cases as well.
194733 static int fts5MultiIterAdvanceRowid(
194734 Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
194735 int iChanged, /* Index of sub-iterator just advanced */
194736 Fts5SegIter **ppFirst
194738 Fts5SegIter *pNew = &pIter->aSeg[iChanged];
194740 if( pNew->iRowid==pIter->iSwitchRowid
194741 || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
194743 int i;
194744 Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
194745 pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
194746 for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
194747 Fts5CResult *pRes = &pIter->aFirst[i];
194749 assert( pNew->pLeaf );
194750 assert( pRes->bTermEq==0 || pOther->pLeaf );
194752 if( pRes->bTermEq ){
194753 if( pNew->iRowid==pOther->iRowid ){
194754 return 1;
194755 }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
194756 pIter->iSwitchRowid = pOther->iRowid;
194757 pNew = pOther;
194758 }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
194759 pIter->iSwitchRowid = pOther->iRowid;
194762 pRes->iFirst = (u16)(pNew - pIter->aSeg);
194763 if( i==1 ) break;
194765 pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
194769 *ppFirst = pNew;
194770 return 0;
194774 ** Set the pIter->bEof variable based on the state of the sub-iterators.
194776 static void fts5MultiIterSetEof(Fts5Iter *pIter){
194777 Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
194778 pIter->base.bEof = pSeg->pLeaf==0;
194779 pIter->iSwitchRowid = pSeg->iRowid;
194783 ** Move the iterator to the next entry.
194785 ** If an error occurs, an error code is left in Fts5Index.rc. It is not
194786 ** considered an error if the iterator reaches EOF, or if it is already at
194787 ** EOF when this function is called.
194789 static void fts5MultiIterNext(
194790 Fts5Index *p,
194791 Fts5Iter *pIter,
194792 int bFrom, /* True if argument iFrom is valid */
194793 i64 iFrom /* Advance at least as far as this */
194795 int bUseFrom = bFrom;
194796 assert( pIter->base.bEof==0 );
194797 while( p->rc==SQLITE_OK ){
194798 int iFirst = pIter->aFirst[1].iFirst;
194799 int bNewTerm = 0;
194800 Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
194801 assert( p->rc==SQLITE_OK );
194802 if( bUseFrom && pSeg->pDlidx ){
194803 fts5SegIterNextFrom(p, pSeg, iFrom);
194804 }else{
194805 pSeg->xNext(p, pSeg, &bNewTerm);
194808 if( pSeg->pLeaf==0 || bNewTerm
194809 || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
194811 fts5MultiIterAdvanced(p, pIter, iFirst, 1);
194812 fts5MultiIterSetEof(pIter);
194813 pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
194814 if( pSeg->pLeaf==0 ) return;
194817 fts5AssertMultiIterSetup(p, pIter);
194818 assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
194819 if( pIter->bSkipEmpty==0 || pSeg->nPos ){
194820 pIter->xSetOutputs(pIter, pSeg);
194821 return;
194823 bUseFrom = 0;
194827 static void fts5MultiIterNext2(
194828 Fts5Index *p,
194829 Fts5Iter *pIter,
194830 int *pbNewTerm /* OUT: True if *might* be new term */
194832 assert( pIter->bSkipEmpty );
194833 if( p->rc==SQLITE_OK ){
194834 *pbNewTerm = 0;
194836 int iFirst = pIter->aFirst[1].iFirst;
194837 Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
194838 int bNewTerm = 0;
194840 assert( p->rc==SQLITE_OK );
194841 pSeg->xNext(p, pSeg, &bNewTerm);
194842 if( pSeg->pLeaf==0 || bNewTerm
194843 || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
194845 fts5MultiIterAdvanced(p, pIter, iFirst, 1);
194846 fts5MultiIterSetEof(pIter);
194847 *pbNewTerm = 1;
194849 fts5AssertMultiIterSetup(p, pIter);
194851 }while( fts5MultiIterIsEmpty(p, pIter) );
194855 static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
194856 UNUSED_PARAM2(pUnused1, pUnused2);
194859 static Fts5Iter *fts5MultiIterAlloc(
194860 Fts5Index *p, /* FTS5 backend to iterate within */
194861 int nSeg
194863 Fts5Iter *pNew;
194864 int nSlot; /* Power of two >= nSeg */
194866 for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
194867 pNew = fts5IdxMalloc(p,
194868 sizeof(Fts5Iter) + /* pNew */
194869 sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
194870 sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
194872 if( pNew ){
194873 pNew->nSeg = nSlot;
194874 pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
194875 pNew->pIndex = p;
194876 pNew->xSetOutputs = fts5IterSetOutputs_Noop;
194878 return pNew;
194881 static void fts5PoslistCallback(
194882 Fts5Index *pUnused,
194883 void *pContext,
194884 const u8 *pChunk, int nChunk
194886 UNUSED_PARAM(pUnused);
194887 assert_nc( nChunk>=0 );
194888 if( nChunk>0 ){
194889 fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
194893 typedef struct PoslistCallbackCtx PoslistCallbackCtx;
194894 struct PoslistCallbackCtx {
194895 Fts5Buffer *pBuf; /* Append to this buffer */
194896 Fts5Colset *pColset; /* Restrict matches to this column */
194897 int eState; /* See above */
194900 typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
194901 struct PoslistOffsetsCtx {
194902 Fts5Buffer *pBuf; /* Append to this buffer */
194903 Fts5Colset *pColset; /* Restrict matches to this column */
194904 int iRead;
194905 int iWrite;
194909 ** TODO: Make this more efficient!
194911 static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
194912 int i;
194913 for(i=0; i<pColset->nCol; i++){
194914 if( pColset->aiCol[i]==iCol ) return 1;
194916 return 0;
194919 static void fts5PoslistOffsetsCallback(
194920 Fts5Index *pUnused,
194921 void *pContext,
194922 const u8 *pChunk, int nChunk
194924 PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
194925 UNUSED_PARAM(pUnused);
194926 assert_nc( nChunk>=0 );
194927 if( nChunk>0 ){
194928 int i = 0;
194929 while( i<nChunk ){
194930 int iVal;
194931 i += fts5GetVarint32(&pChunk[i], iVal);
194932 iVal += pCtx->iRead - 2;
194933 pCtx->iRead = iVal;
194934 if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
194935 fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
194936 pCtx->iWrite = iVal;
194942 static void fts5PoslistFilterCallback(
194943 Fts5Index *pUnused,
194944 void *pContext,
194945 const u8 *pChunk, int nChunk
194947 PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
194948 UNUSED_PARAM(pUnused);
194949 assert_nc( nChunk>=0 );
194950 if( nChunk>0 ){
194951 /* Search through to find the first varint with value 1. This is the
194952 ** start of the next columns hits. */
194953 int i = 0;
194954 int iStart = 0;
194956 if( pCtx->eState==2 ){
194957 int iCol;
194958 fts5FastGetVarint32(pChunk, i, iCol);
194959 if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
194960 pCtx->eState = 1;
194961 fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
194962 }else{
194963 pCtx->eState = 0;
194968 while( i<nChunk && pChunk[i]!=0x01 ){
194969 while( pChunk[i] & 0x80 ) i++;
194972 if( pCtx->eState ){
194973 fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
194975 if( i<nChunk ){
194976 int iCol;
194977 iStart = i;
194979 if( i>=nChunk ){
194980 pCtx->eState = 2;
194981 }else{
194982 fts5FastGetVarint32(pChunk, i, iCol);
194983 pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
194984 if( pCtx->eState ){
194985 fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
194986 iStart = i;
194990 }while( i<nChunk );
194994 static void fts5ChunkIterate(
194995 Fts5Index *p, /* Index object */
194996 Fts5SegIter *pSeg, /* Poslist of this iterator */
194997 void *pCtx, /* Context pointer for xChunk callback */
194998 void (*xChunk)(Fts5Index*, void*, const u8*, int)
195000 int nRem = pSeg->nPos; /* Number of bytes still to come */
195001 Fts5Data *pData = 0;
195002 u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
195003 int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
195004 int pgno = pSeg->iLeafPgno;
195005 int pgnoSave = 0;
195007 /* This function does notmwork with detail=none databases. */
195008 assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
195010 if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
195011 pgnoSave = pgno+1;
195014 while( 1 ){
195015 xChunk(p, pCtx, pChunk, nChunk);
195016 nRem -= nChunk;
195017 fts5DataRelease(pData);
195018 if( nRem<=0 ){
195019 break;
195020 }else{
195021 pgno++;
195022 pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
195023 if( pData==0 ) break;
195024 pChunk = &pData->p[4];
195025 nChunk = MIN(nRem, pData->szLeaf - 4);
195026 if( pgno==pgnoSave ){
195027 assert( pSeg->pNextLeaf==0 );
195028 pSeg->pNextLeaf = pData;
195029 pData = 0;
195036 ** Iterator pIter currently points to a valid entry (not EOF). This
195037 ** function appends the position list data for the current entry to
195038 ** buffer pBuf. It does not make a copy of the position-list size
195039 ** field.
195041 static void fts5SegiterPoslist(
195042 Fts5Index *p,
195043 Fts5SegIter *pSeg,
195044 Fts5Colset *pColset,
195045 Fts5Buffer *pBuf
195047 if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
195048 if( pColset==0 ){
195049 fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
195050 }else{
195051 if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
195052 PoslistCallbackCtx sCtx;
195053 sCtx.pBuf = pBuf;
195054 sCtx.pColset = pColset;
195055 sCtx.eState = fts5IndexColsetTest(pColset, 0);
195056 assert( sCtx.eState==0 || sCtx.eState==1 );
195057 fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
195058 }else{
195059 PoslistOffsetsCtx sCtx;
195060 memset(&sCtx, 0, sizeof(sCtx));
195061 sCtx.pBuf = pBuf;
195062 sCtx.pColset = pColset;
195063 fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
195070 ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
195071 ** the position list contains entries for column iCol, then (*pa) is set
195072 ** to point to the sub-position-list for that column and the number of
195073 ** bytes in it returned. Or, if the argument position list does not
195074 ** contain any entries for column iCol, return 0.
195076 static int fts5IndexExtractCol(
195077 const u8 **pa, /* IN/OUT: Pointer to poslist */
195078 int n, /* IN: Size of poslist in bytes */
195079 int iCol /* Column to extract from poslist */
195081 int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
195082 const u8 *p = *pa;
195083 const u8 *pEnd = &p[n]; /* One byte past end of position list */
195085 while( iCol>iCurrent ){
195086 /* Advance pointer p until it points to pEnd or an 0x01 byte that is
195087 ** not part of a varint. Note that it is not possible for a negative
195088 ** or extremely large varint to occur within an uncorrupted position
195089 ** list. So the last byte of each varint may be assumed to have a clear
195090 ** 0x80 bit. */
195091 while( *p!=0x01 ){
195092 while( *p++ & 0x80 );
195093 if( p>=pEnd ) return 0;
195095 *pa = p++;
195096 iCurrent = *p++;
195097 if( iCurrent & 0x80 ){
195099 p += fts5GetVarint32(p, iCurrent);
195102 if( iCol!=iCurrent ) return 0;
195104 /* Advance pointer p until it points to pEnd or an 0x01 byte that is
195105 ** not part of a varint */
195106 while( p<pEnd && *p!=0x01 ){
195107 while( *p++ & 0x80 );
195110 return p - (*pa);
195113 static void fts5IndexExtractColset(
195114 int *pRc,
195115 Fts5Colset *pColset, /* Colset to filter on */
195116 const u8 *pPos, int nPos, /* Position list */
195117 Fts5Buffer *pBuf /* Output buffer */
195119 if( *pRc==SQLITE_OK ){
195120 int i;
195121 fts5BufferZero(pBuf);
195122 for(i=0; i<pColset->nCol; i++){
195123 const u8 *pSub = pPos;
195124 int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
195125 if( nSub ){
195126 fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
195133 ** xSetOutputs callback used by detail=none tables.
195135 static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
195136 assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
195137 pIter->base.iRowid = pSeg->iRowid;
195138 pIter->base.nData = pSeg->nPos;
195142 ** xSetOutputs callback used by detail=full and detail=col tables when no
195143 ** column filters are specified.
195145 static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
195146 pIter->base.iRowid = pSeg->iRowid;
195147 pIter->base.nData = pSeg->nPos;
195149 assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
195150 assert( pIter->pColset==0 );
195152 if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
195153 /* All data is stored on the current page. Populate the output
195154 ** variables to point into the body of the page object. */
195155 pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
195156 }else{
195157 /* The data is distributed over two or more pages. Copy it into the
195158 ** Fts5Iter.poslist buffer and then set the output pointer to point
195159 ** to this buffer. */
195160 fts5BufferZero(&pIter->poslist);
195161 fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
195162 pIter->base.pData = pIter->poslist.p;
195167 ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
195168 ** against no columns at all).
195170 static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
195171 UNUSED_PARAM(pSeg);
195172 pIter->base.nData = 0;
195176 ** xSetOutputs callback used by detail=col when there is a column filter
195177 ** and there are 100 or more columns. Also called as a fallback from
195178 ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
195180 static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
195181 fts5BufferZero(&pIter->poslist);
195182 fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
195183 pIter->base.iRowid = pSeg->iRowid;
195184 pIter->base.pData = pIter->poslist.p;
195185 pIter->base.nData = pIter->poslist.n;
195189 ** xSetOutputs callback used when:
195191 ** * detail=col,
195192 ** * there is a column filter, and
195193 ** * the table contains 100 or fewer columns.
195195 ** The last point is to ensure all column numbers are stored as
195196 ** single-byte varints.
195198 static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
195200 assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
195201 assert( pIter->pColset );
195203 if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
195204 fts5IterSetOutputs_Col(pIter, pSeg);
195205 }else{
195206 u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
195207 u8 *pEnd = (u8*)&a[pSeg->nPos];
195208 int iPrev = 0;
195209 int *aiCol = pIter->pColset->aiCol;
195210 int *aiColEnd = &aiCol[pIter->pColset->nCol];
195212 u8 *aOut = pIter->poslist.p;
195213 int iPrevOut = 0;
195215 pIter->base.iRowid = pSeg->iRowid;
195217 while( a<pEnd ){
195218 iPrev += (int)a++[0] - 2;
195219 while( *aiCol<iPrev ){
195220 aiCol++;
195221 if( aiCol==aiColEnd ) goto setoutputs_col_out;
195223 if( *aiCol==iPrev ){
195224 *aOut++ = (u8)((iPrev - iPrevOut) + 2);
195225 iPrevOut = iPrev;
195229 setoutputs_col_out:
195230 pIter->base.pData = pIter->poslist.p;
195231 pIter->base.nData = aOut - pIter->poslist.p;
195236 ** xSetOutputs callback used by detail=full when there is a column filter.
195238 static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
195239 Fts5Colset *pColset = pIter->pColset;
195240 pIter->base.iRowid = pSeg->iRowid;
195242 assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
195243 assert( pColset );
195245 if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
195246 /* All data is stored on the current page. Populate the output
195247 ** variables to point into the body of the page object. */
195248 const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
195249 if( pColset->nCol==1 ){
195250 pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
195251 pIter->base.pData = a;
195252 }else{
195253 int *pRc = &pIter->pIndex->rc;
195254 fts5BufferZero(&pIter->poslist);
195255 fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
195256 pIter->base.pData = pIter->poslist.p;
195257 pIter->base.nData = pIter->poslist.n;
195259 }else{
195260 /* The data is distributed over two or more pages. Copy it into the
195261 ** Fts5Iter.poslist buffer and then set the output pointer to point
195262 ** to this buffer. */
195263 fts5BufferZero(&pIter->poslist);
195264 fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
195265 pIter->base.pData = pIter->poslist.p;
195266 pIter->base.nData = pIter->poslist.n;
195270 static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
195271 if( *pRc==SQLITE_OK ){
195272 Fts5Config *pConfig = pIter->pIndex->pConfig;
195273 if( pConfig->eDetail==FTS5_DETAIL_NONE ){
195274 pIter->xSetOutputs = fts5IterSetOutputs_None;
195277 else if( pIter->pColset==0 ){
195278 pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
195281 else if( pIter->pColset->nCol==0 ){
195282 pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
195285 else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
195286 pIter->xSetOutputs = fts5IterSetOutputs_Full;
195289 else{
195290 assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
195291 if( pConfig->nCol<=100 ){
195292 pIter->xSetOutputs = fts5IterSetOutputs_Col100;
195293 sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
195294 }else{
195295 pIter->xSetOutputs = fts5IterSetOutputs_Col;
195303 ** Allocate a new Fts5Iter object.
195305 ** The new object will be used to iterate through data in structure pStruct.
195306 ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
195307 ** is zero or greater, data from the first nSegment segments on level iLevel
195308 ** is merged.
195310 ** The iterator initially points to the first term/rowid entry in the
195311 ** iterated data.
195313 static void fts5MultiIterNew(
195314 Fts5Index *p, /* FTS5 backend to iterate within */
195315 Fts5Structure *pStruct, /* Structure of specific index */
195316 int flags, /* FTS5INDEX_QUERY_XXX flags */
195317 Fts5Colset *pColset, /* Colset to filter on (or NULL) */
195318 const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
195319 int iLevel, /* Level to iterate (-1 for all) */
195320 int nSegment, /* Number of segments to merge (iLevel>=0) */
195321 Fts5Iter **ppOut /* New object */
195323 int nSeg = 0; /* Number of segment-iters in use */
195324 int iIter = 0; /* */
195325 int iSeg; /* Used to iterate through segments */
195326 Fts5StructureLevel *pLvl;
195327 Fts5Iter *pNew;
195329 assert( (pTerm==0 && nTerm==0) || iLevel<0 );
195331 /* Allocate space for the new multi-seg-iterator. */
195332 if( p->rc==SQLITE_OK ){
195333 if( iLevel<0 ){
195334 assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
195335 nSeg = pStruct->nSegment;
195336 nSeg += (p->pHash ? 1 : 0);
195337 }else{
195338 nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
195341 *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
195342 if( pNew==0 ) return;
195343 pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
195344 pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
195345 pNew->pStruct = pStruct;
195346 pNew->pColset = pColset;
195347 fts5StructureRef(pStruct);
195348 if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
195349 fts5IterSetOutputCb(&p->rc, pNew);
195352 /* Initialize each of the component segment iterators. */
195353 if( p->rc==SQLITE_OK ){
195354 if( iLevel<0 ){
195355 Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
195356 if( p->pHash ){
195357 /* Add a segment iterator for the current contents of the hash table. */
195358 Fts5SegIter *pIter = &pNew->aSeg[iIter++];
195359 fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
195361 for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
195362 for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
195363 Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
195364 Fts5SegIter *pIter = &pNew->aSeg[iIter++];
195365 if( pTerm==0 ){
195366 fts5SegIterInit(p, pSeg, pIter);
195367 }else{
195368 fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
195372 }else{
195373 pLvl = &pStruct->aLevel[iLevel];
195374 for(iSeg=nSeg-1; iSeg>=0; iSeg--){
195375 fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
195378 assert( iIter==nSeg );
195381 /* If the above was successful, each component iterators now points
195382 ** to the first entry in its segment. In this case initialize the
195383 ** aFirst[] array. Or, if an error has occurred, free the iterator
195384 ** object and set the output variable to NULL. */
195385 if( p->rc==SQLITE_OK ){
195386 for(iIter=pNew->nSeg-1; iIter>0; iIter--){
195387 int iEq;
195388 if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
195389 Fts5SegIter *pSeg = &pNew->aSeg[iEq];
195390 if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
195391 fts5MultiIterAdvanced(p, pNew, iEq, iIter);
195394 fts5MultiIterSetEof(pNew);
195395 fts5AssertMultiIterSetup(p, pNew);
195397 if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
195398 fts5MultiIterNext(p, pNew, 0, 0);
195399 }else if( pNew->base.bEof==0 ){
195400 Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
195401 pNew->xSetOutputs(pNew, pSeg);
195404 }else{
195405 fts5MultiIterFree(pNew);
195406 *ppOut = 0;
195411 ** Create an Fts5Iter that iterates through the doclist provided
195412 ** as the second argument.
195414 static void fts5MultiIterNew2(
195415 Fts5Index *p, /* FTS5 backend to iterate within */
195416 Fts5Data *pData, /* Doclist to iterate through */
195417 int bDesc, /* True for descending rowid order */
195418 Fts5Iter **ppOut /* New object */
195420 Fts5Iter *pNew;
195421 pNew = fts5MultiIterAlloc(p, 2);
195422 if( pNew ){
195423 Fts5SegIter *pIter = &pNew->aSeg[1];
195425 pIter->flags = FTS5_SEGITER_ONETERM;
195426 if( pData->szLeaf>0 ){
195427 pIter->pLeaf = pData;
195428 pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
195429 pIter->iEndofDoclist = pData->nn;
195430 pNew->aFirst[1].iFirst = 1;
195431 if( bDesc ){
195432 pNew->bRev = 1;
195433 pIter->flags |= FTS5_SEGITER_REVERSE;
195434 fts5SegIterReverseInitPage(p, pIter);
195435 }else{
195436 fts5SegIterLoadNPos(p, pIter);
195438 pData = 0;
195439 }else{
195440 pNew->base.bEof = 1;
195442 fts5SegIterSetNext(p, pIter);
195444 *ppOut = pNew;
195447 fts5DataRelease(pData);
195451 ** Return true if the iterator is at EOF or if an error has occurred.
195452 ** False otherwise.
195454 static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
195455 assert( p->rc
195456 || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
195458 return (p->rc || pIter->base.bEof);
195462 ** Return the rowid of the entry that the iterator currently points
195463 ** to. If the iterator points to EOF when this function is called the
195464 ** results are undefined.
195466 static i64 fts5MultiIterRowid(Fts5Iter *pIter){
195467 assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
195468 return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
195472 ** Move the iterator to the next entry at or following iMatch.
195474 static void fts5MultiIterNextFrom(
195475 Fts5Index *p,
195476 Fts5Iter *pIter,
195477 i64 iMatch
195479 while( 1 ){
195480 i64 iRowid;
195481 fts5MultiIterNext(p, pIter, 1, iMatch);
195482 if( fts5MultiIterEof(p, pIter) ) break;
195483 iRowid = fts5MultiIterRowid(pIter);
195484 if( pIter->bRev==0 && iRowid>=iMatch ) break;
195485 if( pIter->bRev!=0 && iRowid<=iMatch ) break;
195490 ** Return a pointer to a buffer containing the term associated with the
195491 ** entry that the iterator currently points to.
195493 static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
195494 Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
195495 *pn = p->term.n;
195496 return p->term.p;
195500 ** Allocate a new segment-id for the structure pStruct. The new segment
195501 ** id must be between 1 and 65335 inclusive, and must not be used by
195502 ** any currently existing segment. If a free segment id cannot be found,
195503 ** SQLITE_FULL is returned.
195505 ** If an error has already occurred, this function is a no-op. 0 is
195506 ** returned in this case.
195508 static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
195509 int iSegid = 0;
195511 if( p->rc==SQLITE_OK ){
195512 if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
195513 p->rc = SQLITE_FULL;
195514 }else{
195515 /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
195516 ** array is 63 elements, or 252 bytes, in size. */
195517 u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
195518 int iLvl, iSeg;
195519 int i;
195520 u32 mask;
195521 memset(aUsed, 0, sizeof(aUsed));
195522 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
195523 for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
195524 int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
195525 if( iId<=FTS5_MAX_SEGMENT ){
195526 aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
195531 for(i=0; aUsed[i]==0xFFFFFFFF; i++);
195532 mask = aUsed[i];
195533 for(iSegid=0; mask & (1 << iSegid); iSegid++);
195534 iSegid += 1 + i*32;
195536 #ifdef SQLITE_DEBUG
195537 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
195538 for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
195539 assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
195542 assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
195545 sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
195546 if( p->rc==SQLITE_OK ){
195547 u8 aBlob[2] = {0xff, 0xff};
195548 sqlite3_bind_int(pIdxSelect, 1, iSegid);
195549 sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
195550 assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
195551 p->rc = sqlite3_reset(pIdxSelect);
195554 #endif
195558 return iSegid;
195562 ** Discard all data currently cached in the hash-tables.
195564 static void fts5IndexDiscardData(Fts5Index *p){
195565 assert( p->pHash || p->nPendingData==0 );
195566 if( p->pHash ){
195567 sqlite3Fts5HashClear(p->pHash);
195568 p->nPendingData = 0;
195573 ** Return the size of the prefix, in bytes, that buffer
195574 ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
195576 ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
195577 ** than buffer (pOld/nOld).
195579 static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
195580 int i;
195581 for(i=0; i<nOld; i++){
195582 if( pOld[i]!=pNew[i] ) break;
195584 return i;
195587 static void fts5WriteDlidxClear(
195588 Fts5Index *p,
195589 Fts5SegWriter *pWriter,
195590 int bFlush /* If true, write dlidx to disk */
195592 int i;
195593 assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
195594 for(i=0; i<pWriter->nDlidx; i++){
195595 Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
195596 if( pDlidx->buf.n==0 ) break;
195597 if( bFlush ){
195598 assert( pDlidx->pgno!=0 );
195599 fts5DataWrite(p,
195600 FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
195601 pDlidx->buf.p, pDlidx->buf.n
195604 sqlite3Fts5BufferZero(&pDlidx->buf);
195605 pDlidx->bPrevValid = 0;
195610 ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
195611 ** Any new array elements are zeroed before returning.
195613 static int fts5WriteDlidxGrow(
195614 Fts5Index *p,
195615 Fts5SegWriter *pWriter,
195616 int nLvl
195618 if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
195619 Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
195620 pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
195622 if( aDlidx==0 ){
195623 p->rc = SQLITE_NOMEM;
195624 }else{
195625 int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
195626 memset(&aDlidx[pWriter->nDlidx], 0, nByte);
195627 pWriter->aDlidx = aDlidx;
195628 pWriter->nDlidx = nLvl;
195631 return p->rc;
195635 ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
195636 ** enough, flush it to disk and return 1. Otherwise discard it and return
195637 ** zero.
195639 static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
195640 int bFlag = 0;
195642 /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
195643 ** to the database, also write the doclist-index to disk. */
195644 if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
195645 bFlag = 1;
195647 fts5WriteDlidxClear(p, pWriter, bFlag);
195648 pWriter->nEmpty = 0;
195649 return bFlag;
195653 ** This function is called whenever processing of the doclist for the
195654 ** last term on leaf page (pWriter->iBtPage) is completed.
195656 ** The doclist-index for that term is currently stored in-memory within the
195657 ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
195658 ** writes it out to disk. Or, if it is too small to bother with, discards
195659 ** it.
195661 ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
195663 static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
195664 int bFlag;
195666 assert( pWriter->iBtPage || pWriter->nEmpty==0 );
195667 if( pWriter->iBtPage==0 ) return;
195668 bFlag = fts5WriteFlushDlidx(p, pWriter);
195670 if( p->rc==SQLITE_OK ){
195671 const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
195672 /* The following was already done in fts5WriteInit(): */
195673 /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
195674 sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
195675 sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
195676 sqlite3_step(p->pIdxWriter);
195677 p->rc = sqlite3_reset(p->pIdxWriter);
195679 pWriter->iBtPage = 0;
195683 ** This is called once for each leaf page except the first that contains
195684 ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
195685 ** is larger than all terms written to earlier leaves, and equal to or
195686 ** smaller than the first term on the new leaf.
195688 ** If an error occurs, an error code is left in Fts5Index.rc. If an error
195689 ** has already occurred when this function is called, it is a no-op.
195691 static void fts5WriteBtreeTerm(
195692 Fts5Index *p, /* FTS5 backend object */
195693 Fts5SegWriter *pWriter, /* Writer object */
195694 int nTerm, const u8 *pTerm /* First term on new page */
195696 fts5WriteFlushBtree(p, pWriter);
195697 fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
195698 pWriter->iBtPage = pWriter->writer.pgno;
195702 ** This function is called when flushing a leaf page that contains no
195703 ** terms at all to disk.
195705 static void fts5WriteBtreeNoTerm(
195706 Fts5Index *p, /* FTS5 backend object */
195707 Fts5SegWriter *pWriter /* Writer object */
195709 /* If there were no rowids on the leaf page either and the doclist-index
195710 ** has already been started, append an 0x00 byte to it. */
195711 if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
195712 Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
195713 assert( pDlidx->bPrevValid );
195714 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
195717 /* Increment the "number of sequential leaves without a term" counter. */
195718 pWriter->nEmpty++;
195721 static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
195722 i64 iRowid;
195723 int iOff;
195725 iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
195726 fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
195727 return iRowid;
195731 ** Rowid iRowid has just been appended to the current leaf page. It is the
195732 ** first on the page. This function appends an appropriate entry to the current
195733 ** doclist-index.
195735 static void fts5WriteDlidxAppend(
195736 Fts5Index *p,
195737 Fts5SegWriter *pWriter,
195738 i64 iRowid
195740 int i;
195741 int bDone = 0;
195743 for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
195744 i64 iVal;
195745 Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
195747 if( pDlidx->buf.n>=p->pConfig->pgsz ){
195748 /* The current doclist-index page is full. Write it to disk and push
195749 ** a copy of iRowid (which will become the first rowid on the next
195750 ** doclist-index leaf page) up into the next level of the b-tree
195751 ** hierarchy. If the node being flushed is currently the root node,
195752 ** also push its first rowid upwards. */
195753 pDlidx->buf.p[0] = 0x01; /* Not the root node */
195754 fts5DataWrite(p,
195755 FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
195756 pDlidx->buf.p, pDlidx->buf.n
195758 fts5WriteDlidxGrow(p, pWriter, i+2);
195759 pDlidx = &pWriter->aDlidx[i];
195760 if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
195761 i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
195763 /* This was the root node. Push its first rowid up to the new root. */
195764 pDlidx[1].pgno = pDlidx->pgno;
195765 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
195766 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
195767 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
195768 pDlidx[1].bPrevValid = 1;
195769 pDlidx[1].iPrev = iFirst;
195772 sqlite3Fts5BufferZero(&pDlidx->buf);
195773 pDlidx->bPrevValid = 0;
195774 pDlidx->pgno++;
195775 }else{
195776 bDone = 1;
195779 if( pDlidx->bPrevValid ){
195780 iVal = iRowid - pDlidx->iPrev;
195781 }else{
195782 i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
195783 assert( pDlidx->buf.n==0 );
195784 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
195785 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
195786 iVal = iRowid;
195789 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
195790 pDlidx->bPrevValid = 1;
195791 pDlidx->iPrev = iRowid;
195795 static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
195796 static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
195797 Fts5PageWriter *pPage = &pWriter->writer;
195798 i64 iRowid;
195800 assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
195802 /* Set the szLeaf header field. */
195803 assert( 0==fts5GetU16(&pPage->buf.p[2]) );
195804 fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
195806 if( pWriter->bFirstTermInPage ){
195807 /* No term was written to this page. */
195808 assert( pPage->pgidx.n==0 );
195809 fts5WriteBtreeNoTerm(p, pWriter);
195810 }else{
195811 /* Append the pgidx to the page buffer. Set the szLeaf header field. */
195812 fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
195815 /* Write the page out to disk */
195816 iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
195817 fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
195819 /* Initialize the next page. */
195820 fts5BufferZero(&pPage->buf);
195821 fts5BufferZero(&pPage->pgidx);
195822 fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
195823 pPage->iPrevPgidx = 0;
195824 pPage->pgno++;
195826 /* Increase the leaves written counter */
195827 pWriter->nLeafWritten++;
195829 /* The new leaf holds no terms or rowids */
195830 pWriter->bFirstTermInPage = 1;
195831 pWriter->bFirstRowidInPage = 1;
195835 ** Append term pTerm/nTerm to the segment being written by the writer passed
195836 ** as the second argument.
195838 ** If an error occurs, set the Fts5Index.rc error code. If an error has
195839 ** already occurred, this function is a no-op.
195841 static void fts5WriteAppendTerm(
195842 Fts5Index *p,
195843 Fts5SegWriter *pWriter,
195844 int nTerm, const u8 *pTerm
195846 int nPrefix; /* Bytes of prefix compression for term */
195847 Fts5PageWriter *pPage = &pWriter->writer;
195848 Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
195850 assert( p->rc==SQLITE_OK );
195851 assert( pPage->buf.n>=4 );
195852 assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
195854 /* If the current leaf page is full, flush it to disk. */
195855 if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
195856 if( pPage->buf.n>4 ){
195857 fts5WriteFlushLeaf(p, pWriter);
195859 fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
195862 /* TODO1: Updating pgidx here. */
195863 pPgidx->n += sqlite3Fts5PutVarint(
195864 &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
195866 pPage->iPrevPgidx = pPage->buf.n;
195867 #if 0
195868 fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
195869 pPgidx->n += 2;
195870 #endif
195872 if( pWriter->bFirstTermInPage ){
195873 nPrefix = 0;
195874 if( pPage->pgno!=1 ){
195875 /* This is the first term on a leaf that is not the leftmost leaf in
195876 ** the segment b-tree. In this case it is necessary to add a term to
195877 ** the b-tree hierarchy that is (a) larger than the largest term
195878 ** already written to the segment and (b) smaller than or equal to
195879 ** this term. In other words, a prefix of (pTerm/nTerm) that is one
195880 ** byte longer than the longest prefix (pTerm/nTerm) shares with the
195881 ** previous term.
195883 ** Usually, the previous term is available in pPage->term. The exception
195884 ** is if this is the first term written in an incremental-merge step.
195885 ** In this case the previous term is not available, so just write a
195886 ** copy of (pTerm/nTerm) into the parent node. This is slightly
195887 ** inefficient, but still correct. */
195888 int n = nTerm;
195889 if( pPage->term.n ){
195890 n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
195892 fts5WriteBtreeTerm(p, pWriter, n, pTerm);
195893 pPage = &pWriter->writer;
195895 }else{
195896 nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
195897 fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
195900 /* Append the number of bytes of new data, then the term data itself
195901 ** to the page. */
195902 fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
195903 fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
195905 /* Update the Fts5PageWriter.term field. */
195906 fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
195907 pWriter->bFirstTermInPage = 0;
195909 pWriter->bFirstRowidInPage = 0;
195910 pWriter->bFirstRowidInDoclist = 1;
195912 assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
195913 pWriter->aDlidx[0].pgno = pPage->pgno;
195917 ** Append a rowid and position-list size field to the writers output.
195919 static void fts5WriteAppendRowid(
195920 Fts5Index *p,
195921 Fts5SegWriter *pWriter,
195922 i64 iRowid
195924 if( p->rc==SQLITE_OK ){
195925 Fts5PageWriter *pPage = &pWriter->writer;
195927 if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
195928 fts5WriteFlushLeaf(p, pWriter);
195931 /* If this is to be the first rowid written to the page, set the
195932 ** rowid-pointer in the page-header. Also append a value to the dlidx
195933 ** buffer, in case a doclist-index is required. */
195934 if( pWriter->bFirstRowidInPage ){
195935 fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
195936 fts5WriteDlidxAppend(p, pWriter, iRowid);
195939 /* Write the rowid. */
195940 if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
195941 fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
195942 }else{
195943 assert( p->rc || iRowid>pWriter->iPrevRowid );
195944 fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
195946 pWriter->iPrevRowid = iRowid;
195947 pWriter->bFirstRowidInDoclist = 0;
195948 pWriter->bFirstRowidInPage = 0;
195952 static void fts5WriteAppendPoslistData(
195953 Fts5Index *p,
195954 Fts5SegWriter *pWriter,
195955 const u8 *aData,
195956 int nData
195958 Fts5PageWriter *pPage = &pWriter->writer;
195959 const u8 *a = aData;
195960 int n = nData;
195962 assert( p->pConfig->pgsz>0 );
195963 while( p->rc==SQLITE_OK
195964 && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
195966 int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
195967 int nCopy = 0;
195968 while( nCopy<nReq ){
195969 i64 dummy;
195970 nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
195972 fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
195973 a += nCopy;
195974 n -= nCopy;
195975 fts5WriteFlushLeaf(p, pWriter);
195977 if( n>0 ){
195978 fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
195983 ** Flush any data cached by the writer object to the database. Free any
195984 ** allocations associated with the writer.
195986 static void fts5WriteFinish(
195987 Fts5Index *p,
195988 Fts5SegWriter *pWriter, /* Writer object */
195989 int *pnLeaf /* OUT: Number of leaf pages in b-tree */
195991 int i;
195992 Fts5PageWriter *pLeaf = &pWriter->writer;
195993 if( p->rc==SQLITE_OK ){
195994 assert( pLeaf->pgno>=1 );
195995 if( pLeaf->buf.n>4 ){
195996 fts5WriteFlushLeaf(p, pWriter);
195998 *pnLeaf = pLeaf->pgno-1;
195999 if( pLeaf->pgno>1 ){
196000 fts5WriteFlushBtree(p, pWriter);
196003 fts5BufferFree(&pLeaf->term);
196004 fts5BufferFree(&pLeaf->buf);
196005 fts5BufferFree(&pLeaf->pgidx);
196006 fts5BufferFree(&pWriter->btterm);
196008 for(i=0; i<pWriter->nDlidx; i++){
196009 sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
196011 sqlite3_free(pWriter->aDlidx);
196014 static void fts5WriteInit(
196015 Fts5Index *p,
196016 Fts5SegWriter *pWriter,
196017 int iSegid
196019 const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
196021 memset(pWriter, 0, sizeof(Fts5SegWriter));
196022 pWriter->iSegid = iSegid;
196024 fts5WriteDlidxGrow(p, pWriter, 1);
196025 pWriter->writer.pgno = 1;
196026 pWriter->bFirstTermInPage = 1;
196027 pWriter->iBtPage = 1;
196029 assert( pWriter->writer.buf.n==0 );
196030 assert( pWriter->writer.pgidx.n==0 );
196032 /* Grow the two buffers to pgsz + padding bytes in size. */
196033 sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
196034 sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
196036 if( p->pIdxWriter==0 ){
196037 Fts5Config *pConfig = p->pConfig;
196038 fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
196039 "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
196040 pConfig->zDb, pConfig->zName
196044 if( p->rc==SQLITE_OK ){
196045 /* Initialize the 4-byte leaf-page header to 0x00. */
196046 memset(pWriter->writer.buf.p, 0, 4);
196047 pWriter->writer.buf.n = 4;
196049 /* Bind the current output segment id to the index-writer. This is an
196050 ** optimization over binding the same value over and over as rows are
196051 ** inserted into %_idx by the current writer. */
196052 sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
196057 ** Iterator pIter was used to iterate through the input segments of on an
196058 ** incremental merge operation. This function is called if the incremental
196059 ** merge step has finished but the input has not been completely exhausted.
196061 static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
196062 int i;
196063 Fts5Buffer buf;
196064 memset(&buf, 0, sizeof(Fts5Buffer));
196065 for(i=0; i<pIter->nSeg; i++){
196066 Fts5SegIter *pSeg = &pIter->aSeg[i];
196067 if( pSeg->pSeg==0 ){
196068 /* no-op */
196069 }else if( pSeg->pLeaf==0 ){
196070 /* All keys from this input segment have been transfered to the output.
196071 ** Set both the first and last page-numbers to 0 to indicate that the
196072 ** segment is now empty. */
196073 pSeg->pSeg->pgnoLast = 0;
196074 pSeg->pSeg->pgnoFirst = 0;
196075 }else{
196076 int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
196077 i64 iLeafRowid;
196078 Fts5Data *pData;
196079 int iId = pSeg->pSeg->iSegid;
196080 u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
196082 iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
196083 pData = fts5DataRead(p, iLeafRowid);
196084 if( pData ){
196085 fts5BufferZero(&buf);
196086 fts5BufferGrow(&p->rc, &buf, pData->nn);
196087 fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
196088 fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
196089 fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
196090 fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
196091 if( p->rc==SQLITE_OK ){
196092 /* Set the szLeaf field */
196093 fts5PutU16(&buf.p[2], (u16)buf.n);
196096 /* Set up the new page-index array */
196097 fts5BufferAppendVarint(&p->rc, &buf, 4);
196098 if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
196099 && pSeg->iEndofDoclist<pData->szLeaf
196101 int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
196102 fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
196103 fts5BufferAppendBlob(&p->rc, &buf,
196104 pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
196108 fts5DataRelease(pData);
196109 pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
196110 fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
196111 fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
196115 fts5BufferFree(&buf);
196118 static void fts5MergeChunkCallback(
196119 Fts5Index *p,
196120 void *pCtx,
196121 const u8 *pChunk, int nChunk
196123 Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
196124 fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
196130 static void fts5IndexMergeLevel(
196131 Fts5Index *p, /* FTS5 backend object */
196132 Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
196133 int iLvl, /* Level to read input from */
196134 int *pnRem /* Write up to this many output leaves */
196136 Fts5Structure *pStruct = *ppStruct;
196137 Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
196138 Fts5StructureLevel *pLvlOut;
196139 Fts5Iter *pIter = 0; /* Iterator to read input data */
196140 int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
196141 int nInput; /* Number of input segments */
196142 Fts5SegWriter writer; /* Writer object */
196143 Fts5StructureSegment *pSeg; /* Output segment */
196144 Fts5Buffer term;
196145 int bOldest; /* True if the output segment is the oldest */
196146 int eDetail = p->pConfig->eDetail;
196147 const int flags = FTS5INDEX_QUERY_NOOUTPUT;
196148 int bTermWritten = 0; /* True if current term already output */
196150 assert( iLvl<pStruct->nLevel );
196151 assert( pLvl->nMerge<=pLvl->nSeg );
196153 memset(&writer, 0, sizeof(Fts5SegWriter));
196154 memset(&term, 0, sizeof(Fts5Buffer));
196155 if( pLvl->nMerge ){
196156 pLvlOut = &pStruct->aLevel[iLvl+1];
196157 assert( pLvlOut->nSeg>0 );
196158 nInput = pLvl->nMerge;
196159 pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
196161 fts5WriteInit(p, &writer, pSeg->iSegid);
196162 writer.writer.pgno = pSeg->pgnoLast+1;
196163 writer.iBtPage = 0;
196164 }else{
196165 int iSegid = fts5AllocateSegid(p, pStruct);
196167 /* Extend the Fts5Structure object as required to ensure the output
196168 ** segment exists. */
196169 if( iLvl==pStruct->nLevel-1 ){
196170 fts5StructureAddLevel(&p->rc, ppStruct);
196171 pStruct = *ppStruct;
196173 fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
196174 if( p->rc ) return;
196175 pLvl = &pStruct->aLevel[iLvl];
196176 pLvlOut = &pStruct->aLevel[iLvl+1];
196178 fts5WriteInit(p, &writer, iSegid);
196180 /* Add the new segment to the output level */
196181 pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
196182 pLvlOut->nSeg++;
196183 pSeg->pgnoFirst = 1;
196184 pSeg->iSegid = iSegid;
196185 pStruct->nSegment++;
196187 /* Read input from all segments in the input level */
196188 nInput = pLvl->nSeg;
196190 bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
196192 assert( iLvl>=0 );
196193 for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
196194 fts5MultiIterEof(p, pIter)==0;
196195 fts5MultiIterNext(p, pIter, 0, 0)
196197 Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
196198 int nPos; /* position-list size field value */
196199 int nTerm;
196200 const u8 *pTerm;
196202 pTerm = fts5MultiIterTerm(pIter, &nTerm);
196203 if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
196204 if( pnRem && writer.nLeafWritten>nRem ){
196205 break;
196207 fts5BufferSet(&p->rc, &term, nTerm, pTerm);
196208 bTermWritten =0;
196211 /* Check for key annihilation. */
196212 if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
196214 if( p->rc==SQLITE_OK && bTermWritten==0 ){
196215 /* This is a new term. Append a term to the output segment. */
196216 fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
196217 bTermWritten = 1;
196220 /* Append the rowid to the output */
196221 /* WRITEPOSLISTSIZE */
196222 fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
196224 if( eDetail==FTS5_DETAIL_NONE ){
196225 if( pSegIter->bDel ){
196226 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
196227 if( pSegIter->nPos>0 ){
196228 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
196231 }else{
196232 /* Append the position-list data to the output */
196233 nPos = pSegIter->nPos*2 + pSegIter->bDel;
196234 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
196235 fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
196239 /* Flush the last leaf page to disk. Set the output segment b-tree height
196240 ** and last leaf page number at the same time. */
196241 fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
196243 if( fts5MultiIterEof(p, pIter) ){
196244 int i;
196246 /* Remove the redundant segments from the %_data table */
196247 for(i=0; i<nInput; i++){
196248 fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
196251 /* Remove the redundant segments from the input level */
196252 if( pLvl->nSeg!=nInput ){
196253 int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
196254 memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
196256 pStruct->nSegment -= nInput;
196257 pLvl->nSeg -= nInput;
196258 pLvl->nMerge = 0;
196259 if( pSeg->pgnoLast==0 ){
196260 pLvlOut->nSeg--;
196261 pStruct->nSegment--;
196263 }else{
196264 assert( pSeg->pgnoLast>0 );
196265 fts5TrimSegments(p, pIter);
196266 pLvl->nMerge = nInput;
196269 fts5MultiIterFree(pIter);
196270 fts5BufferFree(&term);
196271 if( pnRem ) *pnRem -= writer.nLeafWritten;
196275 ** Do up to nPg pages of automerge work on the index.
196277 ** Return true if any changes were actually made, or false otherwise.
196279 static int fts5IndexMerge(
196280 Fts5Index *p, /* FTS5 backend object */
196281 Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
196282 int nPg, /* Pages of work to do */
196283 int nMin /* Minimum number of segments to merge */
196285 int nRem = nPg;
196286 int bRet = 0;
196287 Fts5Structure *pStruct = *ppStruct;
196288 while( nRem>0 && p->rc==SQLITE_OK ){
196289 int iLvl; /* To iterate through levels */
196290 int iBestLvl = 0; /* Level offering the most input segments */
196291 int nBest = 0; /* Number of input segments on best level */
196293 /* Set iBestLvl to the level to read input segments from. */
196294 assert( pStruct->nLevel>0 );
196295 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
196296 Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
196297 if( pLvl->nMerge ){
196298 if( pLvl->nMerge>nBest ){
196299 iBestLvl = iLvl;
196300 nBest = pLvl->nMerge;
196302 break;
196304 if( pLvl->nSeg>nBest ){
196305 nBest = pLvl->nSeg;
196306 iBestLvl = iLvl;
196310 /* If nBest is still 0, then the index must be empty. */
196311 #ifdef SQLITE_DEBUG
196312 for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
196313 assert( pStruct->aLevel[iLvl].nSeg==0 );
196315 #endif
196317 if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
196318 break;
196320 bRet = 1;
196321 fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
196322 if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
196323 fts5StructurePromote(p, iBestLvl+1, pStruct);
196326 *ppStruct = pStruct;
196327 return bRet;
196331 ** A total of nLeaf leaf pages of data has just been flushed to a level-0
196332 ** segment. This function updates the write-counter accordingly and, if
196333 ** necessary, performs incremental merge work.
196335 ** If an error occurs, set the Fts5Index.rc error code. If an error has
196336 ** already occurred, this function is a no-op.
196338 static void fts5IndexAutomerge(
196339 Fts5Index *p, /* FTS5 backend object */
196340 Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
196341 int nLeaf /* Number of output leaves just written */
196343 if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
196344 Fts5Structure *pStruct = *ppStruct;
196345 u64 nWrite; /* Initial value of write-counter */
196346 int nWork; /* Number of work-quanta to perform */
196347 int nRem; /* Number of leaf pages left to write */
196349 /* Update the write-counter. While doing so, set nWork. */
196350 nWrite = pStruct->nWriteCounter;
196351 nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
196352 pStruct->nWriteCounter += nLeaf;
196353 nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
196355 fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
196359 static void fts5IndexCrisismerge(
196360 Fts5Index *p, /* FTS5 backend object */
196361 Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
196363 const int nCrisis = p->pConfig->nCrisisMerge;
196364 Fts5Structure *pStruct = *ppStruct;
196365 int iLvl = 0;
196367 assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
196368 while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
196369 fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
196370 assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
196371 fts5StructurePromote(p, iLvl+1, pStruct);
196372 iLvl++;
196374 *ppStruct = pStruct;
196377 static int fts5IndexReturn(Fts5Index *p){
196378 int rc = p->rc;
196379 p->rc = SQLITE_OK;
196380 return rc;
196383 typedef struct Fts5FlushCtx Fts5FlushCtx;
196384 struct Fts5FlushCtx {
196385 Fts5Index *pIdx;
196386 Fts5SegWriter writer;
196390 ** Buffer aBuf[] contains a list of varints, all small enough to fit
196391 ** in a 32-bit integer. Return the size of the largest prefix of this
196392 ** list nMax bytes or less in size.
196394 static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
196395 int ret;
196396 u32 dummy;
196397 ret = fts5GetVarint32(aBuf, dummy);
196398 if( ret<nMax ){
196399 while( 1 ){
196400 int i = fts5GetVarint32(&aBuf[ret], dummy);
196401 if( (ret + i) > nMax ) break;
196402 ret += i;
196405 return ret;
196409 ** Flush the contents of in-memory hash table iHash to a new level-0
196410 ** segment on disk. Also update the corresponding structure record.
196412 ** If an error occurs, set the Fts5Index.rc error code. If an error has
196413 ** already occurred, this function is a no-op.
196415 static void fts5FlushOneHash(Fts5Index *p){
196416 Fts5Hash *pHash = p->pHash;
196417 Fts5Structure *pStruct;
196418 int iSegid;
196419 int pgnoLast = 0; /* Last leaf page number in segment */
196421 /* Obtain a reference to the index structure and allocate a new segment-id
196422 ** for the new level-0 segment. */
196423 pStruct = fts5StructureRead(p);
196424 iSegid = fts5AllocateSegid(p, pStruct);
196425 fts5StructureInvalidate(p);
196427 if( iSegid ){
196428 const int pgsz = p->pConfig->pgsz;
196429 int eDetail = p->pConfig->eDetail;
196430 Fts5StructureSegment *pSeg; /* New segment within pStruct */
196431 Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
196432 Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
196434 Fts5SegWriter writer;
196435 fts5WriteInit(p, &writer, iSegid);
196437 pBuf = &writer.writer.buf;
196438 pPgidx = &writer.writer.pgidx;
196440 /* fts5WriteInit() should have initialized the buffers to (most likely)
196441 ** the maximum space required. */
196442 assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
196443 assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
196445 /* Begin scanning through hash table entries. This loop runs once for each
196446 ** term/doclist currently stored within the hash table. */
196447 if( p->rc==SQLITE_OK ){
196448 p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
196450 while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
196451 const char *zTerm; /* Buffer containing term */
196452 const u8 *pDoclist; /* Pointer to doclist for this term */
196453 int nDoclist; /* Size of doclist in bytes */
196455 /* Write the term for this entry to disk. */
196456 sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
196457 fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
196459 assert( writer.bFirstRowidInPage==0 );
196460 if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
196461 /* The entire doclist will fit on the current leaf. */
196462 fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
196463 }else{
196464 i64 iRowid = 0;
196465 i64 iDelta = 0;
196466 int iOff = 0;
196468 /* The entire doclist will not fit on this leaf. The following
196469 ** loop iterates through the poslists that make up the current
196470 ** doclist. */
196471 while( p->rc==SQLITE_OK && iOff<nDoclist ){
196472 iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
196473 iRowid += iDelta;
196475 if( writer.bFirstRowidInPage ){
196476 fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
196477 pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
196478 writer.bFirstRowidInPage = 0;
196479 fts5WriteDlidxAppend(p, &writer, iRowid);
196480 }else{
196481 pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
196483 assert( pBuf->n<=pBuf->nSpace );
196485 if( eDetail==FTS5_DETAIL_NONE ){
196486 if( iOff<nDoclist && pDoclist[iOff]==0 ){
196487 pBuf->p[pBuf->n++] = 0;
196488 iOff++;
196489 if( iOff<nDoclist && pDoclist[iOff]==0 ){
196490 pBuf->p[pBuf->n++] = 0;
196491 iOff++;
196494 if( (pBuf->n + pPgidx->n)>=pgsz ){
196495 fts5WriteFlushLeaf(p, &writer);
196497 }else{
196498 int bDummy;
196499 int nPos;
196500 int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
196501 nCopy += nPos;
196502 if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
196503 /* The entire poslist will fit on the current leaf. So copy
196504 ** it in one go. */
196505 fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
196506 }else{
196507 /* The entire poslist will not fit on this leaf. So it needs
196508 ** to be broken into sections. The only qualification being
196509 ** that each varint must be stored contiguously. */
196510 const u8 *pPoslist = &pDoclist[iOff];
196511 int iPos = 0;
196512 while( p->rc==SQLITE_OK ){
196513 int nSpace = pgsz - pBuf->n - pPgidx->n;
196514 int n = 0;
196515 if( (nCopy - iPos)<=nSpace ){
196516 n = nCopy - iPos;
196517 }else{
196518 n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
196520 assert( n>0 );
196521 fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
196522 iPos += n;
196523 if( (pBuf->n + pPgidx->n)>=pgsz ){
196524 fts5WriteFlushLeaf(p, &writer);
196526 if( iPos>=nCopy ) break;
196529 iOff += nCopy;
196534 /* TODO2: Doclist terminator written here. */
196535 /* pBuf->p[pBuf->n++] = '\0'; */
196536 assert( pBuf->n<=pBuf->nSpace );
196537 sqlite3Fts5HashScanNext(pHash);
196539 sqlite3Fts5HashClear(pHash);
196540 fts5WriteFinish(p, &writer, &pgnoLast);
196542 /* Update the Fts5Structure. It is written back to the database by the
196543 ** fts5StructureRelease() call below. */
196544 if( pStruct->nLevel==0 ){
196545 fts5StructureAddLevel(&p->rc, &pStruct);
196547 fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
196548 if( p->rc==SQLITE_OK ){
196549 pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
196550 pSeg->iSegid = iSegid;
196551 pSeg->pgnoFirst = 1;
196552 pSeg->pgnoLast = pgnoLast;
196553 pStruct->nSegment++;
196555 fts5StructurePromote(p, 0, pStruct);
196558 fts5IndexAutomerge(p, &pStruct, pgnoLast);
196559 fts5IndexCrisismerge(p, &pStruct);
196560 fts5StructureWrite(p, pStruct);
196561 fts5StructureRelease(pStruct);
196565 ** Flush any data stored in the in-memory hash tables to the database.
196567 static void fts5IndexFlush(Fts5Index *p){
196568 /* Unless it is empty, flush the hash table to disk */
196569 if( p->nPendingData ){
196570 assert( p->pHash );
196571 p->nPendingData = 0;
196572 fts5FlushOneHash(p);
196576 static Fts5Structure *fts5IndexOptimizeStruct(
196577 Fts5Index *p,
196578 Fts5Structure *pStruct
196580 Fts5Structure *pNew = 0;
196581 int nByte = sizeof(Fts5Structure);
196582 int nSeg = pStruct->nSegment;
196583 int i;
196585 /* Figure out if this structure requires optimization. A structure does
196586 ** not require optimization if either:
196588 ** + it consists of fewer than two segments, or
196589 ** + all segments are on the same level, or
196590 ** + all segments except one are currently inputs to a merge operation.
196592 ** In the first case, return NULL. In the second, increment the ref-count
196593 ** on *pStruct and return a copy of the pointer to it.
196595 if( nSeg<2 ) return 0;
196596 for(i=0; i<pStruct->nLevel; i++){
196597 int nThis = pStruct->aLevel[i].nSeg;
196598 if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
196599 fts5StructureRef(pStruct);
196600 return pStruct;
196602 assert( pStruct->aLevel[i].nMerge<=nThis );
196605 nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
196606 pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
196608 if( pNew ){
196609 Fts5StructureLevel *pLvl;
196610 nByte = nSeg * sizeof(Fts5StructureSegment);
196611 pNew->nLevel = pStruct->nLevel+1;
196612 pNew->nRef = 1;
196613 pNew->nWriteCounter = pStruct->nWriteCounter;
196614 pLvl = &pNew->aLevel[pStruct->nLevel];
196615 pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
196616 if( pLvl->aSeg ){
196617 int iLvl, iSeg;
196618 int iSegOut = 0;
196619 /* Iterate through all segments, from oldest to newest. Add them to
196620 ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
196621 ** segment in the data structure. */
196622 for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
196623 for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
196624 pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
196625 iSegOut++;
196628 pNew->nSegment = pLvl->nSeg = nSeg;
196629 }else{
196630 sqlite3_free(pNew);
196631 pNew = 0;
196635 return pNew;
196638 static int sqlite3Fts5IndexOptimize(Fts5Index *p){
196639 Fts5Structure *pStruct;
196640 Fts5Structure *pNew = 0;
196642 assert( p->rc==SQLITE_OK );
196643 fts5IndexFlush(p);
196644 pStruct = fts5StructureRead(p);
196645 fts5StructureInvalidate(p);
196647 if( pStruct ){
196648 pNew = fts5IndexOptimizeStruct(p, pStruct);
196650 fts5StructureRelease(pStruct);
196652 assert( pNew==0 || pNew->nSegment>0 );
196653 if( pNew ){
196654 int iLvl;
196655 for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
196656 while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
196657 int nRem = FTS5_OPT_WORK_UNIT;
196658 fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
196661 fts5StructureWrite(p, pNew);
196662 fts5StructureRelease(pNew);
196665 return fts5IndexReturn(p);
196669 ** This is called to implement the special "VALUES('merge', $nMerge)"
196670 ** INSERT command.
196672 static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
196673 Fts5Structure *pStruct = fts5StructureRead(p);
196674 if( pStruct ){
196675 int nMin = p->pConfig->nUsermerge;
196676 fts5StructureInvalidate(p);
196677 if( nMerge<0 ){
196678 Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
196679 fts5StructureRelease(pStruct);
196680 pStruct = pNew;
196681 nMin = 2;
196682 nMerge = nMerge*-1;
196684 if( pStruct && pStruct->nLevel ){
196685 if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
196686 fts5StructureWrite(p, pStruct);
196689 fts5StructureRelease(pStruct);
196691 return fts5IndexReturn(p);
196694 static void fts5AppendRowid(
196695 Fts5Index *p,
196696 i64 iDelta,
196697 Fts5Iter *pUnused,
196698 Fts5Buffer *pBuf
196700 UNUSED_PARAM(pUnused);
196701 fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
196704 static void fts5AppendPoslist(
196705 Fts5Index *p,
196706 i64 iDelta,
196707 Fts5Iter *pMulti,
196708 Fts5Buffer *pBuf
196710 int nData = pMulti->base.nData;
196711 assert( nData>0 );
196712 if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
196713 fts5BufferSafeAppendVarint(pBuf, iDelta);
196714 fts5BufferSafeAppendVarint(pBuf, nData*2);
196715 fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
196720 static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
196721 u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
196723 assert( pIter->aPoslist );
196724 if( p>=pIter->aEof ){
196725 pIter->aPoslist = 0;
196726 }else{
196727 i64 iDelta;
196729 p += fts5GetVarint(p, (u64*)&iDelta);
196730 pIter->iRowid += iDelta;
196732 /* Read position list size */
196733 if( p[0] & 0x80 ){
196734 int nPos;
196735 pIter->nSize = fts5GetVarint32(p, nPos);
196736 pIter->nPoslist = (nPos>>1);
196737 }else{
196738 pIter->nPoslist = ((int)(p[0])) >> 1;
196739 pIter->nSize = 1;
196742 pIter->aPoslist = p;
196746 static void fts5DoclistIterInit(
196747 Fts5Buffer *pBuf,
196748 Fts5DoclistIter *pIter
196750 memset(pIter, 0, sizeof(*pIter));
196751 pIter->aPoslist = pBuf->p;
196752 pIter->aEof = &pBuf->p[pBuf->n];
196753 fts5DoclistIterNext(pIter);
196756 #if 0
196758 ** Append a doclist to buffer pBuf.
196760 ** This function assumes that space within the buffer has already been
196761 ** allocated.
196763 static void fts5MergeAppendDocid(
196764 Fts5Buffer *pBuf, /* Buffer to write to */
196765 i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
196766 i64 iRowid /* Rowid to append */
196768 assert( pBuf->n!=0 || (*piLastRowid)==0 );
196769 fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
196770 *piLastRowid = iRowid;
196772 #endif
196774 #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
196775 assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
196776 fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
196777 (iLastRowid) = (iRowid); \
196781 ** Swap the contents of buffer *p1 with that of *p2.
196783 static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
196784 Fts5Buffer tmp = *p1;
196785 *p1 = *p2;
196786 *p2 = tmp;
196789 static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
196790 int i = *piOff;
196791 if( i>=pBuf->n ){
196792 *piOff = -1;
196793 }else{
196794 u64 iVal;
196795 *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
196796 *piRowid += iVal;
196801 ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
196802 ** In this case the buffers consist of a delta-encoded list of rowids only.
196804 static void fts5MergeRowidLists(
196805 Fts5Index *p, /* FTS5 backend object */
196806 Fts5Buffer *p1, /* First list to merge */
196807 Fts5Buffer *p2 /* Second list to merge */
196809 int i1 = 0;
196810 int i2 = 0;
196811 i64 iRowid1 = 0;
196812 i64 iRowid2 = 0;
196813 i64 iOut = 0;
196815 Fts5Buffer out;
196816 memset(&out, 0, sizeof(out));
196817 sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
196818 if( p->rc ) return;
196820 fts5NextRowid(p1, &i1, &iRowid1);
196821 fts5NextRowid(p2, &i2, &iRowid2);
196822 while( i1>=0 || i2>=0 ){
196823 if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
196824 assert( iOut==0 || iRowid1>iOut );
196825 fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
196826 iOut = iRowid1;
196827 fts5NextRowid(p1, &i1, &iRowid1);
196828 }else{
196829 assert( iOut==0 || iRowid2>iOut );
196830 fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
196831 iOut = iRowid2;
196832 if( i1>=0 && iRowid1==iRowid2 ){
196833 fts5NextRowid(p1, &i1, &iRowid1);
196835 fts5NextRowid(p2, &i2, &iRowid2);
196839 fts5BufferSwap(&out, p1);
196840 fts5BufferFree(&out);
196844 ** Buffers p1 and p2 contain doclists. This function merges the content
196845 ** of the two doclists together and sets buffer p1 to the result before
196846 ** returning.
196848 ** If an error occurs, an error code is left in p->rc. If an error has
196849 ** already occurred, this function is a no-op.
196851 static void fts5MergePrefixLists(
196852 Fts5Index *p, /* FTS5 backend object */
196853 Fts5Buffer *p1, /* First list to merge */
196854 Fts5Buffer *p2 /* Second list to merge */
196856 if( p2->n ){
196857 i64 iLastRowid = 0;
196858 Fts5DoclistIter i1;
196859 Fts5DoclistIter i2;
196860 Fts5Buffer out = {0, 0, 0};
196861 Fts5Buffer tmp = {0, 0, 0};
196863 if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
196864 fts5DoclistIterInit(p1, &i1);
196865 fts5DoclistIterInit(p2, &i2);
196867 while( 1 ){
196868 if( i1.iRowid<i2.iRowid ){
196869 /* Copy entry from i1 */
196870 fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
196871 fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
196872 fts5DoclistIterNext(&i1);
196873 if( i1.aPoslist==0 ) break;
196875 else if( i2.iRowid!=i1.iRowid ){
196876 /* Copy entry from i2 */
196877 fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
196878 fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
196879 fts5DoclistIterNext(&i2);
196880 if( i2.aPoslist==0 ) break;
196882 else{
196883 /* Merge the two position lists. */
196884 i64 iPos1 = 0;
196885 i64 iPos2 = 0;
196886 int iOff1 = 0;
196887 int iOff2 = 0;
196888 u8 *a1 = &i1.aPoslist[i1.nSize];
196889 u8 *a2 = &i2.aPoslist[i2.nSize];
196891 i64 iPrev = 0;
196892 Fts5PoslistWriter writer;
196893 memset(&writer, 0, sizeof(writer));
196895 fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
196896 fts5BufferZero(&tmp);
196897 sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
196898 if( p->rc ) break;
196900 sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
196901 sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
196902 assert( iPos1>=0 && iPos2>=0 );
196904 if( iPos1<iPos2 ){
196905 sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
196906 sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
196907 }else{
196908 sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
196909 sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
196912 if( iPos1>=0 && iPos2>=0 ){
196913 while( 1 ){
196914 if( iPos1<iPos2 ){
196915 if( iPos1!=iPrev ){
196916 sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
196918 sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
196919 if( iPos1<0 ) break;
196920 }else{
196921 assert( iPos2!=iPrev );
196922 sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
196923 sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
196924 if( iPos2<0 ) break;
196929 if( iPos1>=0 ){
196930 if( iPos1!=iPrev ){
196931 sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
196933 fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
196934 }else{
196935 assert( iPos2>=0 && iPos2!=iPrev );
196936 sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
196937 fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
196940 /* WRITEPOSLISTSIZE */
196941 fts5BufferSafeAppendVarint(&out, tmp.n * 2);
196942 fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
196943 fts5DoclistIterNext(&i1);
196944 fts5DoclistIterNext(&i2);
196945 if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
196949 if( i1.aPoslist ){
196950 fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
196951 fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
196953 else if( i2.aPoslist ){
196954 fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
196955 fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
196958 fts5BufferSet(&p->rc, p1, out.n, out.p);
196959 fts5BufferFree(&tmp);
196960 fts5BufferFree(&out);
196964 static void fts5SetupPrefixIter(
196965 Fts5Index *p, /* Index to read from */
196966 int bDesc, /* True for "ORDER BY rowid DESC" */
196967 const u8 *pToken, /* Buffer containing prefix to match */
196968 int nToken, /* Size of buffer pToken in bytes */
196969 Fts5Colset *pColset, /* Restrict matches to these columns */
196970 Fts5Iter **ppIter /* OUT: New iterator */
196972 Fts5Structure *pStruct;
196973 Fts5Buffer *aBuf;
196974 const int nBuf = 32;
196976 void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
196977 void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
196978 if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
196979 xMerge = fts5MergeRowidLists;
196980 xAppend = fts5AppendRowid;
196981 }else{
196982 xMerge = fts5MergePrefixLists;
196983 xAppend = fts5AppendPoslist;
196986 aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
196987 pStruct = fts5StructureRead(p);
196989 if( aBuf && pStruct ){
196990 const int flags = FTS5INDEX_QUERY_SCAN
196991 | FTS5INDEX_QUERY_SKIPEMPTY
196992 | FTS5INDEX_QUERY_NOOUTPUT;
196993 int i;
196994 i64 iLastRowid = 0;
196995 Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
196996 Fts5Data *pData;
196997 Fts5Buffer doclist;
196998 int bNewTerm = 1;
197000 memset(&doclist, 0, sizeof(doclist));
197001 fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
197002 fts5IterSetOutputCb(&p->rc, p1);
197003 for( /* no-op */ ;
197004 fts5MultiIterEof(p, p1)==0;
197005 fts5MultiIterNext2(p, p1, &bNewTerm)
197007 Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
197008 int nTerm = pSeg->term.n;
197009 const u8 *pTerm = pSeg->term.p;
197010 p1->xSetOutputs(p1, pSeg);
197012 assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
197013 if( bNewTerm ){
197014 if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
197017 if( p1->base.nData==0 ) continue;
197019 if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
197020 for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
197021 assert( i<nBuf );
197022 if( aBuf[i].n==0 ){
197023 fts5BufferSwap(&doclist, &aBuf[i]);
197024 fts5BufferZero(&doclist);
197025 }else{
197026 xMerge(p, &doclist, &aBuf[i]);
197027 fts5BufferZero(&aBuf[i]);
197030 iLastRowid = 0;
197033 xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
197034 iLastRowid = p1->base.iRowid;
197037 for(i=0; i<nBuf; i++){
197038 if( p->rc==SQLITE_OK ){
197039 xMerge(p, &doclist, &aBuf[i]);
197041 fts5BufferFree(&aBuf[i]);
197043 fts5MultiIterFree(p1);
197045 pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
197046 if( pData ){
197047 pData->p = (u8*)&pData[1];
197048 pData->nn = pData->szLeaf = doclist.n;
197049 if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
197050 fts5MultiIterNew2(p, pData, bDesc, ppIter);
197052 fts5BufferFree(&doclist);
197055 fts5StructureRelease(pStruct);
197056 sqlite3_free(aBuf);
197061 ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
197062 ** to the document with rowid iRowid.
197064 static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
197065 assert( p->rc==SQLITE_OK );
197067 /* Allocate the hash table if it has not already been allocated */
197068 if( p->pHash==0 ){
197069 p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
197072 /* Flush the hash table to disk if required */
197073 if( iRowid<p->iWriteRowid
197074 || (iRowid==p->iWriteRowid && p->bDelete==0)
197075 || (p->nPendingData > p->pConfig->nHashSize)
197077 fts5IndexFlush(p);
197080 p->iWriteRowid = iRowid;
197081 p->bDelete = bDelete;
197082 return fts5IndexReturn(p);
197086 ** Commit data to disk.
197088 static int sqlite3Fts5IndexSync(Fts5Index *p){
197089 assert( p->rc==SQLITE_OK );
197090 fts5IndexFlush(p);
197091 fts5CloseReader(p);
197092 return fts5IndexReturn(p);
197096 ** Discard any data stored in the in-memory hash tables. Do not write it
197097 ** to the database. Additionally, assume that the contents of the %_data
197098 ** table may have changed on disk. So any in-memory caches of %_data
197099 ** records must be invalidated.
197101 static int sqlite3Fts5IndexRollback(Fts5Index *p){
197102 fts5CloseReader(p);
197103 fts5IndexDiscardData(p);
197104 fts5StructureInvalidate(p);
197105 /* assert( p->rc==SQLITE_OK ); */
197106 return SQLITE_OK;
197110 ** The %_data table is completely empty when this function is called. This
197111 ** function populates it with the initial structure objects for each index,
197112 ** and the initial version of the "averages" record (a zero-byte blob).
197114 static int sqlite3Fts5IndexReinit(Fts5Index *p){
197115 Fts5Structure s;
197116 fts5StructureInvalidate(p);
197117 memset(&s, 0, sizeof(Fts5Structure));
197118 fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
197119 fts5StructureWrite(p, &s);
197120 return fts5IndexReturn(p);
197124 ** Open a new Fts5Index handle. If the bCreate argument is true, create
197125 ** and initialize the underlying %_data table.
197127 ** If successful, set *pp to point to the new object and return SQLITE_OK.
197128 ** Otherwise, set *pp to NULL and return an SQLite error code.
197130 static int sqlite3Fts5IndexOpen(
197131 Fts5Config *pConfig,
197132 int bCreate,
197133 Fts5Index **pp,
197134 char **pzErr
197136 int rc = SQLITE_OK;
197137 Fts5Index *p; /* New object */
197139 *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
197140 if( rc==SQLITE_OK ){
197141 p->pConfig = pConfig;
197142 p->nWorkUnit = FTS5_WORK_UNIT;
197143 p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
197144 if( p->zDataTbl && bCreate ){
197145 rc = sqlite3Fts5CreateTable(
197146 pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
197148 if( rc==SQLITE_OK ){
197149 rc = sqlite3Fts5CreateTable(pConfig, "idx",
197150 "segid, term, pgno, PRIMARY KEY(segid, term)",
197151 1, pzErr
197154 if( rc==SQLITE_OK ){
197155 rc = sqlite3Fts5IndexReinit(p);
197160 assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
197161 if( rc ){
197162 sqlite3Fts5IndexClose(p);
197163 *pp = 0;
197165 return rc;
197169 ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
197171 static int sqlite3Fts5IndexClose(Fts5Index *p){
197172 int rc = SQLITE_OK;
197173 if( p ){
197174 assert( p->pReader==0 );
197175 fts5StructureInvalidate(p);
197176 sqlite3_finalize(p->pWriter);
197177 sqlite3_finalize(p->pDeleter);
197178 sqlite3_finalize(p->pIdxWriter);
197179 sqlite3_finalize(p->pIdxDeleter);
197180 sqlite3_finalize(p->pIdxSelect);
197181 sqlite3_finalize(p->pDataVersion);
197182 sqlite3Fts5HashFree(p->pHash);
197183 sqlite3_free(p->zDataTbl);
197184 sqlite3_free(p);
197186 return rc;
197190 ** Argument p points to a buffer containing utf-8 text that is n bytes in
197191 ** size. Return the number of bytes in the nChar character prefix of the
197192 ** buffer, or 0 if there are less than nChar characters in total.
197194 static int sqlite3Fts5IndexCharlenToBytelen(
197195 const char *p,
197196 int nByte,
197197 int nChar
197199 int n = 0;
197200 int i;
197201 for(i=0; i<nChar; i++){
197202 if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
197203 if( (unsigned char)p[n++]>=0xc0 ){
197204 while( (p[n] & 0xc0)==0x80 ) n++;
197207 return n;
197211 ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
197212 ** unicode characters in the string.
197214 static int fts5IndexCharlen(const char *pIn, int nIn){
197215 int nChar = 0;
197216 int i = 0;
197217 while( i<nIn ){
197218 if( (unsigned char)pIn[i++]>=0xc0 ){
197219 while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
197221 nChar++;
197223 return nChar;
197227 ** Insert or remove data to or from the index. Each time a document is
197228 ** added to or removed from the index, this function is called one or more
197229 ** times.
197231 ** For an insert, it must be called once for each token in the new document.
197232 ** If the operation is a delete, it must be called (at least) once for each
197233 ** unique token in the document with an iCol value less than zero. The iPos
197234 ** argument is ignored for a delete.
197236 static int sqlite3Fts5IndexWrite(
197237 Fts5Index *p, /* Index to write to */
197238 int iCol, /* Column token appears in (-ve -> delete) */
197239 int iPos, /* Position of token within column */
197240 const char *pToken, int nToken /* Token to add or remove to or from index */
197242 int i; /* Used to iterate through indexes */
197243 int rc = SQLITE_OK; /* Return code */
197244 Fts5Config *pConfig = p->pConfig;
197246 assert( p->rc==SQLITE_OK );
197247 assert( (iCol<0)==p->bDelete );
197249 /* Add the entry to the main terms index. */
197250 rc = sqlite3Fts5HashWrite(
197251 p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
197254 for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
197255 const int nChar = pConfig->aPrefix[i];
197256 int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
197257 if( nByte ){
197258 rc = sqlite3Fts5HashWrite(p->pHash,
197259 p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
197260 nByte
197265 return rc;
197269 ** Open a new iterator to iterate though all rowid that match the
197270 ** specified token or token prefix.
197272 static int sqlite3Fts5IndexQuery(
197273 Fts5Index *p, /* FTS index to query */
197274 const char *pToken, int nToken, /* Token (or prefix) to query for */
197275 int flags, /* Mask of FTS5INDEX_QUERY_X flags */
197276 Fts5Colset *pColset, /* Match these columns only */
197277 Fts5IndexIter **ppIter /* OUT: New iterator object */
197279 Fts5Config *pConfig = p->pConfig;
197280 Fts5Iter *pRet = 0;
197281 Fts5Buffer buf = {0, 0, 0};
197283 /* If the QUERY_SCAN flag is set, all other flags must be clear. */
197284 assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
197286 if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
197287 int iIdx = 0; /* Index to search */
197288 if( nToken ) memcpy(&buf.p[1], pToken, nToken);
197290 /* Figure out which index to search and set iIdx accordingly. If this
197291 ** is a prefix query for which there is no prefix index, set iIdx to
197292 ** greater than pConfig->nPrefix to indicate that the query will be
197293 ** satisfied by scanning multiple terms in the main index.
197295 ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
197296 ** prefix-query. Instead of using a prefix-index (if one exists),
197297 ** evaluate the prefix query using the main FTS index. This is used
197298 ** for internal sanity checking by the integrity-check in debug
197299 ** mode only. */
197300 #ifdef SQLITE_DEBUG
197301 if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
197302 assert( flags & FTS5INDEX_QUERY_PREFIX );
197303 iIdx = 1+pConfig->nPrefix;
197304 }else
197305 #endif
197306 if( flags & FTS5INDEX_QUERY_PREFIX ){
197307 int nChar = fts5IndexCharlen(pToken, nToken);
197308 for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
197309 if( pConfig->aPrefix[iIdx-1]==nChar ) break;
197313 if( iIdx<=pConfig->nPrefix ){
197314 /* Straight index lookup */
197315 Fts5Structure *pStruct = fts5StructureRead(p);
197316 buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
197317 if( pStruct ){
197318 fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
197319 pColset, buf.p, nToken+1, -1, 0, &pRet
197321 fts5StructureRelease(pStruct);
197323 }else{
197324 /* Scan multiple terms in the main index */
197325 int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
197326 buf.p[0] = FTS5_MAIN_PREFIX;
197327 fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
197328 assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
197329 fts5IterSetOutputCb(&p->rc, pRet);
197330 if( p->rc==SQLITE_OK ){
197331 Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
197332 if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
197336 if( p->rc ){
197337 sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
197338 pRet = 0;
197339 fts5CloseReader(p);
197342 *ppIter = &pRet->base;
197343 sqlite3Fts5BufferFree(&buf);
197345 return fts5IndexReturn(p);
197349 ** Return true if the iterator passed as the only argument is at EOF.
197352 ** Move to the next matching rowid.
197354 static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
197355 Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
197356 assert( pIter->pIndex->rc==SQLITE_OK );
197357 fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
197358 return fts5IndexReturn(pIter->pIndex);
197362 ** Move to the next matching term/rowid. Used by the fts5vocab module.
197364 static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
197365 Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
197366 Fts5Index *p = pIter->pIndex;
197368 assert( pIter->pIndex->rc==SQLITE_OK );
197370 fts5MultiIterNext(p, pIter, 0, 0);
197371 if( p->rc==SQLITE_OK ){
197372 Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
197373 if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
197374 fts5DataRelease(pSeg->pLeaf);
197375 pSeg->pLeaf = 0;
197376 pIter->base.bEof = 1;
197380 return fts5IndexReturn(pIter->pIndex);
197384 ** Move to the next matching rowid that occurs at or after iMatch. The
197385 ** definition of "at or after" depends on whether this iterator iterates
197386 ** in ascending or descending rowid order.
197388 static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
197389 Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
197390 fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
197391 return fts5IndexReturn(pIter->pIndex);
197395 ** Return the current term.
197397 static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
197398 int n;
197399 const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
197400 *pn = n-1;
197401 return &z[1];
197405 ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
197407 static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
197408 if( pIndexIter ){
197409 Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
197410 Fts5Index *pIndex = pIter->pIndex;
197411 fts5MultiIterFree(pIter);
197412 fts5CloseReader(pIndex);
197417 ** Read and decode the "averages" record from the database.
197419 ** Parameter anSize must point to an array of size nCol, where nCol is
197420 ** the number of user defined columns in the FTS table.
197422 static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
197423 int nCol = p->pConfig->nCol;
197424 Fts5Data *pData;
197426 *pnRow = 0;
197427 memset(anSize, 0, sizeof(i64) * nCol);
197428 pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
197429 if( p->rc==SQLITE_OK && pData->nn ){
197430 int i = 0;
197431 int iCol;
197432 i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
197433 for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
197434 i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
197438 fts5DataRelease(pData);
197439 return fts5IndexReturn(p);
197443 ** Replace the current "averages" record with the contents of the buffer
197444 ** supplied as the second argument.
197446 static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
197447 assert( p->rc==SQLITE_OK );
197448 fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
197449 return fts5IndexReturn(p);
197453 ** Return the total number of blocks this module has read from the %_data
197454 ** table since it was created.
197456 static int sqlite3Fts5IndexReads(Fts5Index *p){
197457 return p->nRead;
197461 ** Set the 32-bit cookie value stored at the start of all structure
197462 ** records to the value passed as the second argument.
197464 ** Return SQLITE_OK if successful, or an SQLite error code if an error
197465 ** occurs.
197467 static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
197468 int rc; /* Return code */
197469 Fts5Config *pConfig = p->pConfig; /* Configuration object */
197470 u8 aCookie[4]; /* Binary representation of iNew */
197471 sqlite3_blob *pBlob = 0;
197473 assert( p->rc==SQLITE_OK );
197474 sqlite3Fts5Put32(aCookie, iNew);
197476 rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
197477 "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
197479 if( rc==SQLITE_OK ){
197480 sqlite3_blob_write(pBlob, aCookie, 4, 0);
197481 rc = sqlite3_blob_close(pBlob);
197484 return rc;
197487 static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
197488 Fts5Structure *pStruct;
197489 pStruct = fts5StructureRead(p);
197490 fts5StructureRelease(pStruct);
197491 return fts5IndexReturn(p);
197495 /*************************************************************************
197496 **************************************************************************
197497 ** Below this point is the implementation of the integrity-check
197498 ** functionality.
197502 ** Return a simple checksum value based on the arguments.
197504 static u64 sqlite3Fts5IndexEntryCksum(
197505 i64 iRowid,
197506 int iCol,
197507 int iPos,
197508 int iIdx,
197509 const char *pTerm,
197510 int nTerm
197512 int i;
197513 u64 ret = iRowid;
197514 ret += (ret<<3) + iCol;
197515 ret += (ret<<3) + iPos;
197516 if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
197517 for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
197518 return ret;
197521 #ifdef SQLITE_DEBUG
197523 ** This function is purely an internal test. It does not contribute to
197524 ** FTS functionality, or even the integrity-check, in any way.
197526 ** Instead, it tests that the same set of pgno/rowid combinations are
197527 ** visited regardless of whether the doclist-index identified by parameters
197528 ** iSegid/iLeaf is iterated in forwards or reverse order.
197530 static void fts5TestDlidxReverse(
197531 Fts5Index *p,
197532 int iSegid, /* Segment id to load from */
197533 int iLeaf /* Load doclist-index for this leaf */
197535 Fts5DlidxIter *pDlidx = 0;
197536 u64 cksum1 = 13;
197537 u64 cksum2 = 13;
197539 for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
197540 fts5DlidxIterEof(p, pDlidx)==0;
197541 fts5DlidxIterNext(p, pDlidx)
197543 i64 iRowid = fts5DlidxIterRowid(pDlidx);
197544 int pgno = fts5DlidxIterPgno(pDlidx);
197545 assert( pgno>iLeaf );
197546 cksum1 += iRowid + ((i64)pgno<<32);
197548 fts5DlidxIterFree(pDlidx);
197549 pDlidx = 0;
197551 for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
197552 fts5DlidxIterEof(p, pDlidx)==0;
197553 fts5DlidxIterPrev(p, pDlidx)
197555 i64 iRowid = fts5DlidxIterRowid(pDlidx);
197556 int pgno = fts5DlidxIterPgno(pDlidx);
197557 assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
197558 cksum2 += iRowid + ((i64)pgno<<32);
197560 fts5DlidxIterFree(pDlidx);
197561 pDlidx = 0;
197563 if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
197566 static int fts5QueryCksum(
197567 Fts5Index *p, /* Fts5 index object */
197568 int iIdx,
197569 const char *z, /* Index key to query for */
197570 int n, /* Size of index key in bytes */
197571 int flags, /* Flags for Fts5IndexQuery */
197572 u64 *pCksum /* IN/OUT: Checksum value */
197574 int eDetail = p->pConfig->eDetail;
197575 u64 cksum = *pCksum;
197576 Fts5IndexIter *pIter = 0;
197577 int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
197579 while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
197580 i64 rowid = pIter->iRowid;
197582 if( eDetail==FTS5_DETAIL_NONE ){
197583 cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
197584 }else{
197585 Fts5PoslistReader sReader;
197586 for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
197587 sReader.bEof==0;
197588 sqlite3Fts5PoslistReaderNext(&sReader)
197590 int iCol = FTS5_POS2COLUMN(sReader.iPos);
197591 int iOff = FTS5_POS2OFFSET(sReader.iPos);
197592 cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
197595 if( rc==SQLITE_OK ){
197596 rc = sqlite3Fts5IterNext(pIter);
197599 sqlite3Fts5IterClose(pIter);
197601 *pCksum = cksum;
197602 return rc;
197607 ** This function is also purely an internal test. It does not contribute to
197608 ** FTS functionality, or even the integrity-check, in any way.
197610 static void fts5TestTerm(
197611 Fts5Index *p,
197612 Fts5Buffer *pPrev, /* Previous term */
197613 const char *z, int n, /* Possibly new term to test */
197614 u64 expected,
197615 u64 *pCksum
197617 int rc = p->rc;
197618 if( pPrev->n==0 ){
197619 fts5BufferSet(&rc, pPrev, n, (const u8*)z);
197620 }else
197621 if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
197622 u64 cksum3 = *pCksum;
197623 const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
197624 int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
197625 int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
197626 int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
197627 u64 ck1 = 0;
197628 u64 ck2 = 0;
197630 /* Check that the results returned for ASC and DESC queries are
197631 ** the same. If not, call this corruption. */
197632 rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
197633 if( rc==SQLITE_OK ){
197634 int f = flags|FTS5INDEX_QUERY_DESC;
197635 rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
197637 if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
197639 /* If this is a prefix query, check that the results returned if the
197640 ** the index is disabled are the same. In both ASC and DESC order.
197642 ** This check may only be performed if the hash table is empty. This
197643 ** is because the hash table only supports a single scan query at
197644 ** a time, and the multi-iter loop from which this function is called
197645 ** is already performing such a scan. */
197646 if( p->nPendingData==0 ){
197647 if( iIdx>0 && rc==SQLITE_OK ){
197648 int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
197649 ck2 = 0;
197650 rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
197651 if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
197653 if( iIdx>0 && rc==SQLITE_OK ){
197654 int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
197655 ck2 = 0;
197656 rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
197657 if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
197661 cksum3 ^= ck1;
197662 fts5BufferSet(&rc, pPrev, n, (const u8*)z);
197664 if( rc==SQLITE_OK && cksum3!=expected ){
197665 rc = FTS5_CORRUPT;
197667 *pCksum = cksum3;
197669 p->rc = rc;
197672 #else
197673 # define fts5TestDlidxReverse(x,y,z)
197674 # define fts5TestTerm(u,v,w,x,y,z)
197675 #endif
197678 ** Check that:
197680 ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
197681 ** contain zero terms.
197682 ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
197683 ** contain zero rowids.
197685 static void fts5IndexIntegrityCheckEmpty(
197686 Fts5Index *p,
197687 Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
197688 int iFirst,
197689 int iNoRowid,
197690 int iLast
197692 int i;
197694 /* Now check that the iter.nEmpty leaves following the current leaf
197695 ** (a) exist and (b) contain no terms. */
197696 for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
197697 Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
197698 if( pLeaf ){
197699 if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
197700 if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
197702 fts5DataRelease(pLeaf);
197706 static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
197707 int iTermOff = 0;
197708 int ii;
197710 Fts5Buffer buf1 = {0,0,0};
197711 Fts5Buffer buf2 = {0,0,0};
197713 ii = pLeaf->szLeaf;
197714 while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
197715 int res;
197716 int iOff;
197717 int nIncr;
197719 ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
197720 iTermOff += nIncr;
197721 iOff = iTermOff;
197723 if( iOff>=pLeaf->szLeaf ){
197724 p->rc = FTS5_CORRUPT;
197725 }else if( iTermOff==nIncr ){
197726 int nByte;
197727 iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
197728 if( (iOff+nByte)>pLeaf->szLeaf ){
197729 p->rc = FTS5_CORRUPT;
197730 }else{
197731 fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
197733 }else{
197734 int nKeep, nByte;
197735 iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
197736 iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
197737 if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
197738 p->rc = FTS5_CORRUPT;
197739 }else{
197740 buf1.n = nKeep;
197741 fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
197744 if( p->rc==SQLITE_OK ){
197745 res = fts5BufferCompare(&buf1, &buf2);
197746 if( res<=0 ) p->rc = FTS5_CORRUPT;
197749 fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
197752 fts5BufferFree(&buf1);
197753 fts5BufferFree(&buf2);
197756 static void fts5IndexIntegrityCheckSegment(
197757 Fts5Index *p, /* FTS5 backend object */
197758 Fts5StructureSegment *pSeg /* Segment to check internal consistency */
197760 Fts5Config *pConfig = p->pConfig;
197761 sqlite3_stmt *pStmt = 0;
197762 int rc2;
197763 int iIdxPrevLeaf = pSeg->pgnoFirst-1;
197764 int iDlidxPrevLeaf = pSeg->pgnoLast;
197766 if( pSeg->pgnoFirst==0 ) return;
197768 fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
197769 "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
197770 pConfig->zDb, pConfig->zName, pSeg->iSegid
197773 /* Iterate through the b-tree hierarchy. */
197774 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
197775 i64 iRow; /* Rowid for this leaf */
197776 Fts5Data *pLeaf; /* Data for this leaf */
197778 int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
197779 const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
197780 int iIdxLeaf = sqlite3_column_int(pStmt, 2);
197781 int bIdxDlidx = sqlite3_column_int(pStmt, 3);
197783 /* If the leaf in question has already been trimmed from the segment,
197784 ** ignore this b-tree entry. Otherwise, load it into memory. */
197785 if( iIdxLeaf<pSeg->pgnoFirst ) continue;
197786 iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
197787 pLeaf = fts5LeafRead(p, iRow);
197788 if( pLeaf==0 ) break;
197790 /* Check that the leaf contains at least one term, and that it is equal
197791 ** to or larger than the split-key in zIdxTerm. Also check that if there
197792 ** is also a rowid pointer within the leaf page header, it points to a
197793 ** location before the term. */
197794 if( pLeaf->nn<=pLeaf->szLeaf ){
197795 p->rc = FTS5_CORRUPT;
197796 }else{
197797 int iOff; /* Offset of first term on leaf */
197798 int iRowidOff; /* Offset of first rowid on leaf */
197799 int nTerm; /* Size of term on leaf in bytes */
197800 int res; /* Comparison of term and split-key */
197802 iOff = fts5LeafFirstTermOff(pLeaf);
197803 iRowidOff = fts5LeafFirstRowidOff(pLeaf);
197804 if( iRowidOff>=iOff ){
197805 p->rc = FTS5_CORRUPT;
197806 }else{
197807 iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
197808 res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
197809 if( res==0 ) res = nTerm - nIdxTerm;
197810 if( res<0 ) p->rc = FTS5_CORRUPT;
197813 fts5IntegrityCheckPgidx(p, pLeaf);
197815 fts5DataRelease(pLeaf);
197816 if( p->rc ) break;
197818 /* Now check that the iter.nEmpty leaves following the current leaf
197819 ** (a) exist and (b) contain no terms. */
197820 fts5IndexIntegrityCheckEmpty(
197821 p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
197823 if( p->rc ) break;
197825 /* If there is a doclist-index, check that it looks right. */
197826 if( bIdxDlidx ){
197827 Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
197828 int iPrevLeaf = iIdxLeaf;
197829 int iSegid = pSeg->iSegid;
197830 int iPg = 0;
197831 i64 iKey;
197833 for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
197834 fts5DlidxIterEof(p, pDlidx)==0;
197835 fts5DlidxIterNext(p, pDlidx)
197838 /* Check any rowid-less pages that occur before the current leaf. */
197839 for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
197840 iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
197841 pLeaf = fts5DataRead(p, iKey);
197842 if( pLeaf ){
197843 if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
197844 fts5DataRelease(pLeaf);
197847 iPrevLeaf = fts5DlidxIterPgno(pDlidx);
197849 /* Check that the leaf page indicated by the iterator really does
197850 ** contain the rowid suggested by the same. */
197851 iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
197852 pLeaf = fts5DataRead(p, iKey);
197853 if( pLeaf ){
197854 i64 iRowid;
197855 int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
197856 ASSERT_SZLEAF_OK(pLeaf);
197857 if( iRowidOff>=pLeaf->szLeaf ){
197858 p->rc = FTS5_CORRUPT;
197859 }else{
197860 fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
197861 if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
197863 fts5DataRelease(pLeaf);
197867 iDlidxPrevLeaf = iPg;
197868 fts5DlidxIterFree(pDlidx);
197869 fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
197870 }else{
197871 iDlidxPrevLeaf = pSeg->pgnoLast;
197872 /* TODO: Check there is no doclist index */
197875 iIdxPrevLeaf = iIdxLeaf;
197878 rc2 = sqlite3_finalize(pStmt);
197879 if( p->rc==SQLITE_OK ) p->rc = rc2;
197881 /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
197882 #if 0
197883 if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
197884 p->rc = FTS5_CORRUPT;
197886 #endif
197891 ** Run internal checks to ensure that the FTS index (a) is internally
197892 ** consistent and (b) contains entries for which the XOR of the checksums
197893 ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
197895 ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
197896 ** checksum does not match. Return SQLITE_OK if all checks pass without
197897 ** error, or some other SQLite error code if another error (e.g. OOM)
197898 ** occurs.
197900 static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
197901 int eDetail = p->pConfig->eDetail;
197902 u64 cksum2 = 0; /* Checksum based on contents of indexes */
197903 Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
197904 Fts5Iter *pIter; /* Used to iterate through entire index */
197905 Fts5Structure *pStruct; /* Index structure */
197907 #ifdef SQLITE_DEBUG
197908 /* Used by extra internal tests only run if NDEBUG is not defined */
197909 u64 cksum3 = 0; /* Checksum based on contents of indexes */
197910 Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
197911 #endif
197912 const int flags = FTS5INDEX_QUERY_NOOUTPUT;
197914 /* Load the FTS index structure */
197915 pStruct = fts5StructureRead(p);
197917 /* Check that the internal nodes of each segment match the leaves */
197918 if( pStruct ){
197919 int iLvl, iSeg;
197920 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
197921 for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
197922 Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
197923 fts5IndexIntegrityCheckSegment(p, pSeg);
197928 /* The cksum argument passed to this function is a checksum calculated
197929 ** based on all expected entries in the FTS index (including prefix index
197930 ** entries). This block checks that a checksum calculated based on the
197931 ** actual contents of FTS index is identical.
197933 ** Two versions of the same checksum are calculated. The first (stack
197934 ** variable cksum2) based on entries extracted from the full-text index
197935 ** while doing a linear scan of each individual index in turn.
197937 ** As each term visited by the linear scans, a separate query for the
197938 ** same term is performed. cksum3 is calculated based on the entries
197939 ** extracted by these queries.
197941 for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
197942 fts5MultiIterEof(p, pIter)==0;
197943 fts5MultiIterNext(p, pIter, 0, 0)
197945 int n; /* Size of term in bytes */
197946 i64 iPos = 0; /* Position read from poslist */
197947 int iOff = 0; /* Offset within poslist */
197948 i64 iRowid = fts5MultiIterRowid(pIter);
197949 char *z = (char*)fts5MultiIterTerm(pIter, &n);
197951 /* If this is a new term, query for it. Update cksum3 with the results. */
197952 fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
197954 if( eDetail==FTS5_DETAIL_NONE ){
197955 if( 0==fts5MultiIterIsEmpty(p, pIter) ){
197956 cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
197958 }else{
197959 poslist.n = 0;
197960 fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
197961 while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
197962 int iCol = FTS5_POS2COLUMN(iPos);
197963 int iTokOff = FTS5_POS2OFFSET(iPos);
197964 cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
197968 fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
197970 fts5MultiIterFree(pIter);
197971 if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
197973 fts5StructureRelease(pStruct);
197974 #ifdef SQLITE_DEBUG
197975 fts5BufferFree(&term);
197976 #endif
197977 fts5BufferFree(&poslist);
197978 return fts5IndexReturn(p);
197981 /*************************************************************************
197982 **************************************************************************
197983 ** Below this point is the implementation of the fts5_decode() scalar
197984 ** function only.
197988 ** Decode a segment-data rowid from the %_data table. This function is
197989 ** the opposite of macro FTS5_SEGMENT_ROWID().
197991 static void fts5DecodeRowid(
197992 i64 iRowid, /* Rowid from %_data table */
197993 int *piSegid, /* OUT: Segment id */
197994 int *pbDlidx, /* OUT: Dlidx flag */
197995 int *piHeight, /* OUT: Height */
197996 int *piPgno /* OUT: Page number */
197998 *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
197999 iRowid >>= FTS5_DATA_PAGE_B;
198001 *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
198002 iRowid >>= FTS5_DATA_HEIGHT_B;
198004 *pbDlidx = (int)(iRowid & 0x0001);
198005 iRowid >>= FTS5_DATA_DLI_B;
198007 *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
198010 static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
198011 int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
198012 fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
198014 if( iSegid==0 ){
198015 if( iKey==FTS5_AVERAGES_ROWID ){
198016 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
198017 }else{
198018 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
198021 else{
198022 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
198023 bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
198028 static void fts5DebugStructure(
198029 int *pRc, /* IN/OUT: error code */
198030 Fts5Buffer *pBuf,
198031 Fts5Structure *p
198033 int iLvl, iSeg; /* Iterate through levels, segments */
198035 for(iLvl=0; iLvl<p->nLevel; iLvl++){
198036 Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
198037 sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
198038 " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
198040 for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
198041 Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
198042 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
198043 pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
198046 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
198051 ** This is part of the fts5_decode() debugging aid.
198053 ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
198054 ** function appends a human-readable representation of the same object
198055 ** to the buffer passed as the second argument.
198057 static void fts5DecodeStructure(
198058 int *pRc, /* IN/OUT: error code */
198059 Fts5Buffer *pBuf,
198060 const u8 *pBlob, int nBlob
198062 int rc; /* Return code */
198063 Fts5Structure *p = 0; /* Decoded structure object */
198065 rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
198066 if( rc!=SQLITE_OK ){
198067 *pRc = rc;
198068 return;
198071 fts5DebugStructure(pRc, pBuf, p);
198072 fts5StructureRelease(p);
198076 ** This is part of the fts5_decode() debugging aid.
198078 ** Arguments pBlob/nBlob contain an "averages" record. This function
198079 ** appends a human-readable representation of record to the buffer passed
198080 ** as the second argument.
198082 static void fts5DecodeAverages(
198083 int *pRc, /* IN/OUT: error code */
198084 Fts5Buffer *pBuf,
198085 const u8 *pBlob, int nBlob
198087 int i = 0;
198088 const char *zSpace = "";
198090 while( i<nBlob ){
198091 u64 iVal;
198092 i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
198093 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
198094 zSpace = " ";
198099 ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
198100 ** each varint and append its string representation to buffer pBuf. Return
198101 ** after either the input buffer is exhausted or a 0 value is read.
198103 ** The return value is the number of bytes read from the input buffer.
198105 static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
198106 int iOff = 0;
198107 while( iOff<n ){
198108 int iVal;
198109 iOff += fts5GetVarint32(&a[iOff], iVal);
198110 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
198112 return iOff;
198116 ** The start of buffer (a/n) contains the start of a doclist. The doclist
198117 ** may or may not finish within the buffer. This function appends a text
198118 ** representation of the part of the doclist that is present to buffer
198119 ** pBuf.
198121 ** The return value is the number of bytes read from the input buffer.
198123 static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
198124 i64 iDocid = 0;
198125 int iOff = 0;
198127 if( n>0 ){
198128 iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
198129 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
198131 while( iOff<n ){
198132 int nPos;
198133 int bDel;
198134 iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
198135 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
198136 iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
198137 if( iOff<n ){
198138 i64 iDelta;
198139 iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
198140 iDocid += iDelta;
198141 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
198145 return iOff;
198149 ** This function is part of the fts5_decode() debugging function. It is
198150 ** only ever used with detail=none tables.
198152 ** Buffer (pData/nData) contains a doclist in the format used by detail=none
198153 ** tables. This function appends a human-readable version of that list to
198154 ** buffer pBuf.
198156 ** If *pRc is other than SQLITE_OK when this function is called, it is a
198157 ** no-op. If an OOM or other error occurs within this function, *pRc is
198158 ** set to an SQLite error code before returning. The final state of buffer
198159 ** pBuf is undefined in this case.
198161 static void fts5DecodeRowidList(
198162 int *pRc, /* IN/OUT: Error code */
198163 Fts5Buffer *pBuf, /* Buffer to append text to */
198164 const u8 *pData, int nData /* Data to decode list-of-rowids from */
198166 int i = 0;
198167 i64 iRowid = 0;
198169 while( i<nData ){
198170 const char *zApp = "";
198171 u64 iVal;
198172 i += sqlite3Fts5GetVarint(&pData[i], &iVal);
198173 iRowid += iVal;
198175 if( i<nData && pData[i]==0x00 ){
198177 if( i<nData && pData[i]==0x00 ){
198179 zApp = "+";
198180 }else{
198181 zApp = "*";
198185 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
198190 ** The implementation of user-defined scalar function fts5_decode().
198192 static void fts5DecodeFunction(
198193 sqlite3_context *pCtx, /* Function call context */
198194 int nArg, /* Number of args (always 2) */
198195 sqlite3_value **apVal /* Function arguments */
198197 i64 iRowid; /* Rowid for record being decoded */
198198 int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
198199 const u8 *aBlob; int n; /* Record to decode */
198200 u8 *a = 0;
198201 Fts5Buffer s; /* Build up text to return here */
198202 int rc = SQLITE_OK; /* Return code */
198203 int nSpace = 0;
198204 int eDetailNone = (sqlite3_user_data(pCtx)!=0);
198206 assert( nArg==2 );
198207 UNUSED_PARAM(nArg);
198208 memset(&s, 0, sizeof(Fts5Buffer));
198209 iRowid = sqlite3_value_int64(apVal[0]);
198211 /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
198212 ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
198213 ** buffer overreads even if the record is corrupt. */
198214 n = sqlite3_value_bytes(apVal[1]);
198215 aBlob = sqlite3_value_blob(apVal[1]);
198216 nSpace = n + FTS5_DATA_ZERO_PADDING;
198217 a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
198218 if( a==0 ) goto decode_out;
198219 memcpy(a, aBlob, n);
198222 fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
198224 fts5DebugRowid(&rc, &s, iRowid);
198225 if( bDlidx ){
198226 Fts5Data dlidx;
198227 Fts5DlidxLvl lvl;
198229 dlidx.p = a;
198230 dlidx.nn = n;
198232 memset(&lvl, 0, sizeof(Fts5DlidxLvl));
198233 lvl.pData = &dlidx;
198234 lvl.iLeafPgno = iPgno;
198236 for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
198237 sqlite3Fts5BufferAppendPrintf(&rc, &s,
198238 " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
198241 }else if( iSegid==0 ){
198242 if( iRowid==FTS5_AVERAGES_ROWID ){
198243 fts5DecodeAverages(&rc, &s, a, n);
198244 }else{
198245 fts5DecodeStructure(&rc, &s, a, n);
198247 }else if( eDetailNone ){
198248 Fts5Buffer term; /* Current term read from page */
198249 int szLeaf;
198250 int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
198251 int iTermOff;
198252 int nKeep = 0;
198253 int iOff;
198255 memset(&term, 0, sizeof(Fts5Buffer));
198257 /* Decode any entries that occur before the first term. */
198258 if( szLeaf<n ){
198259 iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
198260 }else{
198261 iTermOff = szLeaf;
198263 fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
198265 iOff = iTermOff;
198266 while( iOff<szLeaf ){
198267 int nAppend;
198269 /* Read the term data for the next term*/
198270 iOff += fts5GetVarint32(&a[iOff], nAppend);
198271 term.n = nKeep;
198272 fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
198273 sqlite3Fts5BufferAppendPrintf(
198274 &rc, &s, " term=%.*s", term.n, (const char*)term.p
198276 iOff += nAppend;
198278 /* Figure out where the doclist for this term ends */
198279 if( iPgidxOff<n ){
198280 int nIncr;
198281 iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
198282 iTermOff += nIncr;
198283 }else{
198284 iTermOff = szLeaf;
198287 fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
198288 iOff = iTermOff;
198289 if( iOff<szLeaf ){
198290 iOff += fts5GetVarint32(&a[iOff], nKeep);
198294 fts5BufferFree(&term);
198295 }else{
198296 Fts5Buffer term; /* Current term read from page */
198297 int szLeaf; /* Offset of pgidx in a[] */
198298 int iPgidxOff;
198299 int iPgidxPrev = 0; /* Previous value read from pgidx */
198300 int iTermOff = 0;
198301 int iRowidOff = 0;
198302 int iOff;
198303 int nDoclist;
198305 memset(&term, 0, sizeof(Fts5Buffer));
198307 if( n<4 ){
198308 sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
198309 goto decode_out;
198310 }else{
198311 iRowidOff = fts5GetU16(&a[0]);
198312 iPgidxOff = szLeaf = fts5GetU16(&a[2]);
198313 if( iPgidxOff<n ){
198314 fts5GetVarint32(&a[iPgidxOff], iTermOff);
198318 /* Decode the position list tail at the start of the page */
198319 if( iRowidOff!=0 ){
198320 iOff = iRowidOff;
198321 }else if( iTermOff!=0 ){
198322 iOff = iTermOff;
198323 }else{
198324 iOff = szLeaf;
198326 fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
198328 /* Decode any more doclist data that appears on the page before the
198329 ** first term. */
198330 nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
198331 fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
198333 while( iPgidxOff<n ){
198334 int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
198335 int nByte; /* Bytes of data */
198336 int iEnd;
198338 iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
198339 iPgidxPrev += nByte;
198340 iOff = iPgidxPrev;
198342 if( iPgidxOff<n ){
198343 fts5GetVarint32(&a[iPgidxOff], nByte);
198344 iEnd = iPgidxPrev + nByte;
198345 }else{
198346 iEnd = szLeaf;
198349 if( bFirst==0 ){
198350 iOff += fts5GetVarint32(&a[iOff], nByte);
198351 term.n = nByte;
198353 iOff += fts5GetVarint32(&a[iOff], nByte);
198354 fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
198355 iOff += nByte;
198357 sqlite3Fts5BufferAppendPrintf(
198358 &rc, &s, " term=%.*s", term.n, (const char*)term.p
198360 iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
198363 fts5BufferFree(&term);
198366 decode_out:
198367 sqlite3_free(a);
198368 if( rc==SQLITE_OK ){
198369 sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
198370 }else{
198371 sqlite3_result_error_code(pCtx, rc);
198373 fts5BufferFree(&s);
198377 ** The implementation of user-defined scalar function fts5_rowid().
198379 static void fts5RowidFunction(
198380 sqlite3_context *pCtx, /* Function call context */
198381 int nArg, /* Number of args (always 2) */
198382 sqlite3_value **apVal /* Function arguments */
198384 const char *zArg;
198385 if( nArg==0 ){
198386 sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
198387 }else{
198388 zArg = (const char*)sqlite3_value_text(apVal[0]);
198389 if( 0==sqlite3_stricmp(zArg, "segment") ){
198390 i64 iRowid;
198391 int segid, pgno;
198392 if( nArg!=3 ){
198393 sqlite3_result_error(pCtx,
198394 "should be: fts5_rowid('segment', segid, pgno))", -1
198396 }else{
198397 segid = sqlite3_value_int(apVal[1]);
198398 pgno = sqlite3_value_int(apVal[2]);
198399 iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
198400 sqlite3_result_int64(pCtx, iRowid);
198402 }else{
198403 sqlite3_result_error(pCtx,
198404 "first arg to fts5_rowid() must be 'segment'" , -1
198411 ** This is called as part of registering the FTS5 module with database
198412 ** connection db. It registers several user-defined scalar functions useful
198413 ** with FTS5.
198415 ** If successful, SQLITE_OK is returned. If an error occurs, some other
198416 ** SQLite error code is returned instead.
198418 static int sqlite3Fts5IndexInit(sqlite3 *db){
198419 int rc = sqlite3_create_function(
198420 db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
198423 if( rc==SQLITE_OK ){
198424 rc = sqlite3_create_function(
198425 db, "fts5_decode_none", 2,
198426 SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
198430 if( rc==SQLITE_OK ){
198431 rc = sqlite3_create_function(
198432 db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
198435 return rc;
198439 static int sqlite3Fts5IndexReset(Fts5Index *p){
198440 assert( p->pStruct==0 || p->iStructVersion!=0 );
198441 if( fts5IndexDataVersion(p)!=p->iStructVersion ){
198442 fts5StructureInvalidate(p);
198444 return fts5IndexReturn(p);
198448 ** 2014 Jun 09
198450 ** The author disclaims copyright to this source code. In place of
198451 ** a legal notice, here is a blessing:
198453 ** May you do good and not evil.
198454 ** May you find forgiveness for yourself and forgive others.
198455 ** May you share freely, never taking more than you give.
198457 ******************************************************************************
198459 ** This is an SQLite module implementing full-text search.
198463 /* #include "fts5Int.h" */
198466 ** This variable is set to false when running tests for which the on disk
198467 ** structures should not be corrupt. Otherwise, true. If it is false, extra
198468 ** assert() conditions in the fts5 code are activated - conditions that are
198469 ** only true if it is guaranteed that the fts5 database is not corrupt.
198471 SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
198474 typedef struct Fts5Auxdata Fts5Auxdata;
198475 typedef struct Fts5Auxiliary Fts5Auxiliary;
198476 typedef struct Fts5Cursor Fts5Cursor;
198477 typedef struct Fts5Sorter Fts5Sorter;
198478 typedef struct Fts5Table Fts5Table;
198479 typedef struct Fts5TokenizerModule Fts5TokenizerModule;
198482 ** NOTES ON TRANSACTIONS:
198484 ** SQLite invokes the following virtual table methods as transactions are
198485 ** opened and closed by the user:
198487 ** xBegin(): Start of a new transaction.
198488 ** xSync(): Initial part of two-phase commit.
198489 ** xCommit(): Final part of two-phase commit.
198490 ** xRollback(): Rollback the transaction.
198492 ** Anything that is required as part of a commit that may fail is performed
198493 ** in the xSync() callback. Current versions of SQLite ignore any errors
198494 ** returned by xCommit().
198496 ** And as sub-transactions are opened/closed:
198498 ** xSavepoint(int S): Open savepoint S.
198499 ** xRelease(int S): Commit and close savepoint S.
198500 ** xRollbackTo(int S): Rollback to start of savepoint S.
198502 ** During a write-transaction the fts5_index.c module may cache some data
198503 ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
198504 ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
198505 ** is called.
198507 ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
198508 ** structure is used to record the current transaction state. This information
198509 ** is not required, but it is used in the assert() statements executed by
198510 ** function fts5CheckTransactionState() (see below).
198512 struct Fts5TransactionState {
198513 int eState; /* 0==closed, 1==open, 2==synced */
198514 int iSavepoint; /* Number of open savepoints (0 -> none) */
198518 ** A single object of this type is allocated when the FTS5 module is
198519 ** registered with a database handle. It is used to store pointers to
198520 ** all registered FTS5 extensions - tokenizers and auxiliary functions.
198522 struct Fts5Global {
198523 fts5_api api; /* User visible part of object (see fts5.h) */
198524 sqlite3 *db; /* Associated database connection */
198525 i64 iNextId; /* Used to allocate unique cursor ids */
198526 Fts5Auxiliary *pAux; /* First in list of all aux. functions */
198527 Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
198528 Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
198529 Fts5Cursor *pCsr; /* First in list of all open cursors */
198533 ** Each auxiliary function registered with the FTS5 module is represented
198534 ** by an object of the following type. All such objects are stored as part
198535 ** of the Fts5Global.pAux list.
198537 struct Fts5Auxiliary {
198538 Fts5Global *pGlobal; /* Global context for this function */
198539 char *zFunc; /* Function name (nul-terminated) */
198540 void *pUserData; /* User-data pointer */
198541 fts5_extension_function xFunc; /* Callback function */
198542 void (*xDestroy)(void*); /* Destructor function */
198543 Fts5Auxiliary *pNext; /* Next registered auxiliary function */
198547 ** Each tokenizer module registered with the FTS5 module is represented
198548 ** by an object of the following type. All such objects are stored as part
198549 ** of the Fts5Global.pTok list.
198551 struct Fts5TokenizerModule {
198552 char *zName; /* Name of tokenizer */
198553 void *pUserData; /* User pointer passed to xCreate() */
198554 fts5_tokenizer x; /* Tokenizer functions */
198555 void (*xDestroy)(void*); /* Destructor function */
198556 Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
198560 ** Virtual-table object.
198562 struct Fts5Table {
198563 sqlite3_vtab base; /* Base class used by SQLite core */
198564 Fts5Config *pConfig; /* Virtual table configuration */
198565 Fts5Index *pIndex; /* Full-text index */
198566 Fts5Storage *pStorage; /* Document store */
198567 Fts5Global *pGlobal; /* Global (connection wide) data */
198568 Fts5Cursor *pSortCsr; /* Sort data from this cursor */
198569 #ifdef SQLITE_DEBUG
198570 struct Fts5TransactionState ts;
198571 #endif
198574 struct Fts5MatchPhrase {
198575 Fts5Buffer *pPoslist; /* Pointer to current poslist */
198576 int nTerm; /* Size of phrase in terms */
198580 ** pStmt:
198581 ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
198583 ** aIdx[]:
198584 ** There is one entry in the aIdx[] array for each phrase in the query,
198585 ** the value of which is the offset within aPoslist[] following the last
198586 ** byte of the position list for the corresponding phrase.
198588 struct Fts5Sorter {
198589 sqlite3_stmt *pStmt;
198590 i64 iRowid; /* Current rowid */
198591 const u8 *aPoslist; /* Position lists for current row */
198592 int nIdx; /* Number of entries in aIdx[] */
198593 int aIdx[1]; /* Offsets into aPoslist for current row */
198598 ** Virtual-table cursor object.
198600 ** iSpecial:
198601 ** If this is a 'special' query (refer to function fts5SpecialMatch()),
198602 ** then this variable contains the result of the query.
198604 ** iFirstRowid, iLastRowid:
198605 ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
198606 ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
198607 ** limit of rowids to return, and iLastRowid the upper. In other words, the
198608 ** WHERE clause in the user's query might have been:
198610 ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
198612 ** If the cursor iterates in descending order of rowid, iFirstRowid
198613 ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
198614 ** the lower.
198616 struct Fts5Cursor {
198617 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
198618 Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
198619 int *aColumnSize; /* Values for xColumnSize() */
198620 i64 iCsrId; /* Cursor id */
198622 /* Zero from this point onwards on cursor reset */
198623 int ePlan; /* FTS5_PLAN_XXX value */
198624 int bDesc; /* True for "ORDER BY rowid DESC" queries */
198625 i64 iFirstRowid; /* Return no rowids earlier than this */
198626 i64 iLastRowid; /* Return no rowids later than this */
198627 sqlite3_stmt *pStmt; /* Statement used to read %_content */
198628 Fts5Expr *pExpr; /* Expression for MATCH queries */
198629 Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
198630 int csrflags; /* Mask of cursor flags (see below) */
198631 i64 iSpecial; /* Result of special query */
198633 /* "rank" function. Populated on demand from vtab.xColumn(). */
198634 char *zRank; /* Custom rank function */
198635 char *zRankArgs; /* Custom rank function args */
198636 Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
198637 int nRankArg; /* Number of trailing arguments for rank() */
198638 sqlite3_value **apRankArg; /* Array of trailing arguments */
198639 sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
198641 /* Auxiliary data storage */
198642 Fts5Auxiliary *pAux; /* Currently executing extension function */
198643 Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
198645 /* Cache used by auxiliary functions xInst() and xInstCount() */
198646 Fts5PoslistReader *aInstIter; /* One for each phrase */
198647 int nInstAlloc; /* Size of aInst[] array (entries / 3) */
198648 int nInstCount; /* Number of phrase instances */
198649 int *aInst; /* 3 integers per phrase instance */
198653 ** Bits that make up the "idxNum" parameter passed indirectly by
198654 ** xBestIndex() to xFilter().
198656 #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
198657 #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
198658 #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
198659 #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
198660 #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
198662 #define FTS5_BI_ORDER_RANK 0x0020
198663 #define FTS5_BI_ORDER_ROWID 0x0040
198664 #define FTS5_BI_ORDER_DESC 0x0080
198667 ** Values for Fts5Cursor.csrflags
198669 #define FTS5CSR_EOF 0x01
198670 #define FTS5CSR_REQUIRE_CONTENT 0x02
198671 #define FTS5CSR_REQUIRE_DOCSIZE 0x04
198672 #define FTS5CSR_REQUIRE_INST 0x08
198673 #define FTS5CSR_FREE_ZRANK 0x10
198674 #define FTS5CSR_REQUIRE_RESEEK 0x20
198675 #define FTS5CSR_REQUIRE_POSLIST 0x40
198677 #define BitFlagAllTest(x,y) (((x) & (y))==(y))
198678 #define BitFlagTest(x,y) (((x) & (y))!=0)
198682 ** Macros to Set(), Clear() and Test() cursor flags.
198684 #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
198685 #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
198686 #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
198688 struct Fts5Auxdata {
198689 Fts5Auxiliary *pAux; /* Extension to which this belongs */
198690 void *pPtr; /* Pointer value */
198691 void(*xDelete)(void*); /* Destructor */
198692 Fts5Auxdata *pNext; /* Next object in linked list */
198695 #ifdef SQLITE_DEBUG
198696 #define FTS5_BEGIN 1
198697 #define FTS5_SYNC 2
198698 #define FTS5_COMMIT 3
198699 #define FTS5_ROLLBACK 4
198700 #define FTS5_SAVEPOINT 5
198701 #define FTS5_RELEASE 6
198702 #define FTS5_ROLLBACKTO 7
198703 static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
198704 switch( op ){
198705 case FTS5_BEGIN:
198706 assert( p->ts.eState==0 );
198707 p->ts.eState = 1;
198708 p->ts.iSavepoint = -1;
198709 break;
198711 case FTS5_SYNC:
198712 assert( p->ts.eState==1 );
198713 p->ts.eState = 2;
198714 break;
198716 case FTS5_COMMIT:
198717 assert( p->ts.eState==2 );
198718 p->ts.eState = 0;
198719 break;
198721 case FTS5_ROLLBACK:
198722 assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
198723 p->ts.eState = 0;
198724 break;
198726 case FTS5_SAVEPOINT:
198727 assert( p->ts.eState==1 );
198728 assert( iSavepoint>=0 );
198729 assert( iSavepoint>p->ts.iSavepoint );
198730 p->ts.iSavepoint = iSavepoint;
198731 break;
198733 case FTS5_RELEASE:
198734 assert( p->ts.eState==1 );
198735 assert( iSavepoint>=0 );
198736 assert( iSavepoint<=p->ts.iSavepoint );
198737 p->ts.iSavepoint = iSavepoint-1;
198738 break;
198740 case FTS5_ROLLBACKTO:
198741 assert( p->ts.eState==1 );
198742 assert( iSavepoint>=0 );
198743 assert( iSavepoint<=p->ts.iSavepoint );
198744 p->ts.iSavepoint = iSavepoint;
198745 break;
198748 #else
198749 # define fts5CheckTransactionState(x,y,z)
198750 #endif
198753 ** Return true if pTab is a contentless table.
198755 static int fts5IsContentless(Fts5Table *pTab){
198756 return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
198760 ** Delete a virtual table handle allocated by fts5InitVtab().
198762 static void fts5FreeVtab(Fts5Table *pTab){
198763 if( pTab ){
198764 sqlite3Fts5IndexClose(pTab->pIndex);
198765 sqlite3Fts5StorageClose(pTab->pStorage);
198766 sqlite3Fts5ConfigFree(pTab->pConfig);
198767 sqlite3_free(pTab);
198772 ** The xDisconnect() virtual table method.
198774 static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
198775 fts5FreeVtab((Fts5Table*)pVtab);
198776 return SQLITE_OK;
198780 ** The xDestroy() virtual table method.
198782 static int fts5DestroyMethod(sqlite3_vtab *pVtab){
198783 Fts5Table *pTab = (Fts5Table*)pVtab;
198784 int rc = sqlite3Fts5DropAll(pTab->pConfig);
198785 if( rc==SQLITE_OK ){
198786 fts5FreeVtab((Fts5Table*)pVtab);
198788 return rc;
198792 ** This function is the implementation of both the xConnect and xCreate
198793 ** methods of the FTS3 virtual table.
198795 ** The argv[] array contains the following:
198797 ** argv[0] -> module name ("fts5")
198798 ** argv[1] -> database name
198799 ** argv[2] -> table name
198800 ** argv[...] -> "column name" and other module argument fields.
198802 static int fts5InitVtab(
198803 int bCreate, /* True for xCreate, false for xConnect */
198804 sqlite3 *db, /* The SQLite database connection */
198805 void *pAux, /* Hash table containing tokenizers */
198806 int argc, /* Number of elements in argv array */
198807 const char * const *argv, /* xCreate/xConnect argument array */
198808 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
198809 char **pzErr /* Write any error message here */
198811 Fts5Global *pGlobal = (Fts5Global*)pAux;
198812 const char **azConfig = (const char**)argv;
198813 int rc = SQLITE_OK; /* Return code */
198814 Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
198815 Fts5Table *pTab = 0; /* New virtual table object */
198817 /* Allocate the new vtab object and parse the configuration */
198818 pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
198819 if( rc==SQLITE_OK ){
198820 rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
198821 assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
198823 if( rc==SQLITE_OK ){
198824 pTab->pConfig = pConfig;
198825 pTab->pGlobal = pGlobal;
198828 /* Open the index sub-system */
198829 if( rc==SQLITE_OK ){
198830 rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
198833 /* Open the storage sub-system */
198834 if( rc==SQLITE_OK ){
198835 rc = sqlite3Fts5StorageOpen(
198836 pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
198840 /* Call sqlite3_declare_vtab() */
198841 if( rc==SQLITE_OK ){
198842 rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
198845 /* Load the initial configuration */
198846 if( rc==SQLITE_OK ){
198847 assert( pConfig->pzErrmsg==0 );
198848 pConfig->pzErrmsg = pzErr;
198849 rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
198850 sqlite3Fts5IndexRollback(pTab->pIndex);
198851 pConfig->pzErrmsg = 0;
198854 if( rc!=SQLITE_OK ){
198855 fts5FreeVtab(pTab);
198856 pTab = 0;
198857 }else if( bCreate ){
198858 fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
198860 *ppVTab = (sqlite3_vtab*)pTab;
198861 return rc;
198865 ** The xConnect() and xCreate() methods for the virtual table. All the
198866 ** work is done in function fts5InitVtab().
198868 static int fts5ConnectMethod(
198869 sqlite3 *db, /* Database connection */
198870 void *pAux, /* Pointer to tokenizer hash table */
198871 int argc, /* Number of elements in argv array */
198872 const char * const *argv, /* xCreate/xConnect argument array */
198873 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
198874 char **pzErr /* OUT: sqlite3_malloc'd error message */
198876 return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
198878 static int fts5CreateMethod(
198879 sqlite3 *db, /* Database connection */
198880 void *pAux, /* Pointer to tokenizer hash table */
198881 int argc, /* Number of elements in argv array */
198882 const char * const *argv, /* xCreate/xConnect argument array */
198883 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
198884 char **pzErr /* OUT: sqlite3_malloc'd error message */
198886 return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
198890 ** The different query plans.
198892 #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
198893 #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
198894 #define FTS5_PLAN_SPECIAL 3 /* An internal query */
198895 #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
198896 #define FTS5_PLAN_SCAN 5 /* No usable constraint */
198897 #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
198900 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
198901 ** extension is currently being used by a version of SQLite too old to
198902 ** support index-info flags. In that case this function is a no-op.
198904 static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
198905 #if SQLITE_VERSION_NUMBER>=3008012
198906 #ifndef SQLITE_CORE
198907 if( sqlite3_libversion_number()>=3008012 )
198908 #endif
198910 pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
198912 #endif
198916 ** Implementation of the xBestIndex method for FTS5 tables. Within the
198917 ** WHERE constraint, it searches for the following:
198919 ** 1. A MATCH constraint against the special column.
198920 ** 2. A MATCH constraint against the "rank" column.
198921 ** 3. An == constraint against the rowid column.
198922 ** 4. A < or <= constraint against the rowid column.
198923 ** 5. A > or >= constraint against the rowid column.
198925 ** Within the ORDER BY, either:
198927 ** 5. ORDER BY rank [ASC|DESC]
198928 ** 6. ORDER BY rowid [ASC|DESC]
198930 ** Costs are assigned as follows:
198932 ** a) If an unusable MATCH operator is present in the WHERE clause, the
198933 ** cost is unconditionally set to 1e50 (a really big number).
198935 ** a) If a MATCH operator is present, the cost depends on the other
198936 ** constraints also present. As follows:
198938 ** * No other constraints: cost=1000.0
198939 ** * One rowid range constraint: cost=750.0
198940 ** * Both rowid range constraints: cost=500.0
198941 ** * An == rowid constraint: cost=100.0
198943 ** b) Otherwise, if there is no MATCH:
198945 ** * No other constraints: cost=1000000.0
198946 ** * One rowid range constraint: cost=750000.0
198947 ** * Both rowid range constraints: cost=250000.0
198948 ** * An == rowid constraint: cost=10.0
198950 ** Costs are not modified by the ORDER BY clause.
198952 static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
198953 Fts5Table *pTab = (Fts5Table*)pVTab;
198954 Fts5Config *pConfig = pTab->pConfig;
198955 const int nCol = pConfig->nCol;
198956 int idxFlags = 0; /* Parameter passed through to xFilter() */
198957 int bHasMatch;
198958 int iNext;
198959 int i;
198961 struct Constraint {
198962 int op; /* Mask against sqlite3_index_constraint.op */
198963 int fts5op; /* FTS5 mask for idxFlags */
198964 int iCol; /* 0==rowid, 1==tbl, 2==rank */
198965 int omit; /* True to omit this if found */
198966 int iConsIndex; /* Index in pInfo->aConstraint[] */
198967 } aConstraint[] = {
198968 {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
198969 FTS5_BI_MATCH, 1, 1, -1},
198970 {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
198971 FTS5_BI_RANK, 2, 1, -1},
198972 {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
198973 {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
198974 FTS5_BI_ROWID_LE, 0, 0, -1},
198975 {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
198976 FTS5_BI_ROWID_GE, 0, 0, -1},
198979 int aColMap[3];
198980 aColMap[0] = -1;
198981 aColMap[1] = nCol;
198982 aColMap[2] = nCol+1;
198984 /* Set idxFlags flags for all WHERE clause terms that will be used. */
198985 for(i=0; i<pInfo->nConstraint; i++){
198986 struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
198987 int iCol = p->iColumn;
198989 if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
198990 || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
198992 /* A MATCH operator or equivalent */
198993 if( p->usable ){
198994 idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
198995 aConstraint[0].iConsIndex = i;
198996 }else{
198997 /* As there exists an unusable MATCH constraint this is an
198998 ** unusable plan. Set a prohibitively high cost. */
198999 pInfo->estimatedCost = 1e50;
199000 return SQLITE_OK;
199002 }else{
199003 int j;
199004 for(j=1; j<ArraySize(aConstraint); j++){
199005 struct Constraint *pC = &aConstraint[j];
199006 if( iCol==aColMap[pC->iCol] && p->op & pC->op && p->usable ){
199007 pC->iConsIndex = i;
199008 idxFlags |= pC->fts5op;
199014 /* Set idxFlags flags for the ORDER BY clause */
199015 if( pInfo->nOrderBy==1 ){
199016 int iSort = pInfo->aOrderBy[0].iColumn;
199017 if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
199018 idxFlags |= FTS5_BI_ORDER_RANK;
199019 }else if( iSort==-1 ){
199020 idxFlags |= FTS5_BI_ORDER_ROWID;
199022 if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
199023 pInfo->orderByConsumed = 1;
199024 if( pInfo->aOrderBy[0].desc ){
199025 idxFlags |= FTS5_BI_ORDER_DESC;
199030 /* Calculate the estimated cost based on the flags set in idxFlags. */
199031 bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
199032 if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
199033 pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
199034 if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
199035 }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
199036 pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
199037 }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
199038 pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
199039 }else{
199040 pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
199043 /* Assign argvIndex values to each constraint in use. */
199044 iNext = 1;
199045 for(i=0; i<ArraySize(aConstraint); i++){
199046 struct Constraint *pC = &aConstraint[i];
199047 if( pC->iConsIndex>=0 ){
199048 pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
199049 pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
199053 pInfo->idxNum = idxFlags;
199054 return SQLITE_OK;
199057 static int fts5NewTransaction(Fts5Table *pTab){
199058 Fts5Cursor *pCsr;
199059 for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
199060 if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
199062 return sqlite3Fts5StorageReset(pTab->pStorage);
199066 ** Implementation of xOpen method.
199068 static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
199069 Fts5Table *pTab = (Fts5Table*)pVTab;
199070 Fts5Config *pConfig = pTab->pConfig;
199071 Fts5Cursor *pCsr = 0; /* New cursor object */
199072 int nByte; /* Bytes of space to allocate */
199073 int rc; /* Return code */
199075 rc = fts5NewTransaction(pTab);
199076 if( rc==SQLITE_OK ){
199077 nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
199078 pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
199079 if( pCsr ){
199080 Fts5Global *pGlobal = pTab->pGlobal;
199081 memset(pCsr, 0, nByte);
199082 pCsr->aColumnSize = (int*)&pCsr[1];
199083 pCsr->pNext = pGlobal->pCsr;
199084 pGlobal->pCsr = pCsr;
199085 pCsr->iCsrId = ++pGlobal->iNextId;
199086 }else{
199087 rc = SQLITE_NOMEM;
199090 *ppCsr = (sqlite3_vtab_cursor*)pCsr;
199091 return rc;
199094 static int fts5StmtType(Fts5Cursor *pCsr){
199095 if( pCsr->ePlan==FTS5_PLAN_SCAN ){
199096 return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
199098 return FTS5_STMT_LOOKUP;
199102 ** This function is called after the cursor passed as the only argument
199103 ** is moved to point at a different row. It clears all cached data
199104 ** specific to the previous row stored by the cursor object.
199106 static void fts5CsrNewrow(Fts5Cursor *pCsr){
199107 CsrFlagSet(pCsr,
199108 FTS5CSR_REQUIRE_CONTENT
199109 | FTS5CSR_REQUIRE_DOCSIZE
199110 | FTS5CSR_REQUIRE_INST
199111 | FTS5CSR_REQUIRE_POSLIST
199115 static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
199116 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199117 Fts5Auxdata *pData;
199118 Fts5Auxdata *pNext;
199120 sqlite3_free(pCsr->aInstIter);
199121 sqlite3_free(pCsr->aInst);
199122 if( pCsr->pStmt ){
199123 int eStmt = fts5StmtType(pCsr);
199124 sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
199126 if( pCsr->pSorter ){
199127 Fts5Sorter *pSorter = pCsr->pSorter;
199128 sqlite3_finalize(pSorter->pStmt);
199129 sqlite3_free(pSorter);
199132 if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
199133 sqlite3Fts5ExprFree(pCsr->pExpr);
199136 for(pData=pCsr->pAuxdata; pData; pData=pNext){
199137 pNext = pData->pNext;
199138 if( pData->xDelete ) pData->xDelete(pData->pPtr);
199139 sqlite3_free(pData);
199142 sqlite3_finalize(pCsr->pRankArgStmt);
199143 sqlite3_free(pCsr->apRankArg);
199145 if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
199146 sqlite3_free(pCsr->zRank);
199147 sqlite3_free(pCsr->zRankArgs);
199150 memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
199155 ** Close the cursor. For additional information see the documentation
199156 ** on the xClose method of the virtual table interface.
199158 static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
199159 if( pCursor ){
199160 Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
199161 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
199162 Fts5Cursor **pp;
199164 fts5FreeCursorComponents(pCsr);
199165 /* Remove the cursor from the Fts5Global.pCsr list */
199166 for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
199167 *pp = pCsr->pNext;
199169 sqlite3_free(pCsr);
199171 return SQLITE_OK;
199174 static int fts5SorterNext(Fts5Cursor *pCsr){
199175 Fts5Sorter *pSorter = pCsr->pSorter;
199176 int rc;
199178 rc = sqlite3_step(pSorter->pStmt);
199179 if( rc==SQLITE_DONE ){
199180 rc = SQLITE_OK;
199181 CsrFlagSet(pCsr, FTS5CSR_EOF);
199182 }else if( rc==SQLITE_ROW ){
199183 const u8 *a;
199184 const u8 *aBlob;
199185 int nBlob;
199186 int i;
199187 int iOff = 0;
199188 rc = SQLITE_OK;
199190 pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
199191 nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
199192 aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
199194 /* nBlob==0 in detail=none mode. */
199195 if( nBlob>0 ){
199196 for(i=0; i<(pSorter->nIdx-1); i++){
199197 int iVal;
199198 a += fts5GetVarint32(a, iVal);
199199 iOff += iVal;
199200 pSorter->aIdx[i] = iOff;
199202 pSorter->aIdx[i] = &aBlob[nBlob] - a;
199203 pSorter->aPoslist = a;
199206 fts5CsrNewrow(pCsr);
199209 return rc;
199214 ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
199215 ** open on table pTab.
199217 static void fts5TripCursors(Fts5Table *pTab){
199218 Fts5Cursor *pCsr;
199219 for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
199220 if( pCsr->ePlan==FTS5_PLAN_MATCH
199221 && pCsr->base.pVtab==(sqlite3_vtab*)pTab
199223 CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
199229 ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
199230 ** argument, close and reopen all Fts5IndexIter iterators that the cursor
199231 ** is using. Then attempt to move the cursor to a rowid equal to or laster
199232 ** (in the cursors sort order - ASC or DESC) than the current rowid.
199234 ** If the new rowid is not equal to the old, set output parameter *pbSkip
199235 ** to 1 before returning. Otherwise, leave it unchanged.
199237 ** Return SQLITE_OK if successful or if no reseek was required, or an
199238 ** error code if an error occurred.
199240 static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
199241 int rc = SQLITE_OK;
199242 assert( *pbSkip==0 );
199243 if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
199244 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199245 int bDesc = pCsr->bDesc;
199246 i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
199248 rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
199249 if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
199250 *pbSkip = 1;
199253 CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
199254 fts5CsrNewrow(pCsr);
199255 if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
199256 CsrFlagSet(pCsr, FTS5CSR_EOF);
199257 *pbSkip = 1;
199260 return rc;
199265 ** Advance the cursor to the next row in the table that matches the
199266 ** search criteria.
199268 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
199269 ** even if we reach end-of-file. The fts5EofMethod() will be called
199270 ** subsequently to determine whether or not an EOF was hit.
199272 static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
199273 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
199274 int rc;
199276 assert( (pCsr->ePlan<3)==
199277 (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
199279 assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
199281 if( pCsr->ePlan<3 ){
199282 int bSkip = 0;
199283 if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
199284 rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
199285 CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
199286 fts5CsrNewrow(pCsr);
199287 }else{
199288 switch( pCsr->ePlan ){
199289 case FTS5_PLAN_SPECIAL: {
199290 CsrFlagSet(pCsr, FTS5CSR_EOF);
199291 rc = SQLITE_OK;
199292 break;
199295 case FTS5_PLAN_SORTED_MATCH: {
199296 rc = fts5SorterNext(pCsr);
199297 break;
199300 default:
199301 rc = sqlite3_step(pCsr->pStmt);
199302 if( rc!=SQLITE_ROW ){
199303 CsrFlagSet(pCsr, FTS5CSR_EOF);
199304 rc = sqlite3_reset(pCsr->pStmt);
199305 }else{
199306 rc = SQLITE_OK;
199308 break;
199312 return rc;
199316 static int fts5PrepareStatement(
199317 sqlite3_stmt **ppStmt,
199318 Fts5Config *pConfig,
199319 const char *zFmt,
199322 sqlite3_stmt *pRet = 0;
199323 int rc;
199324 char *zSql;
199325 va_list ap;
199327 va_start(ap, zFmt);
199328 zSql = sqlite3_vmprintf(zFmt, ap);
199329 if( zSql==0 ){
199330 rc = SQLITE_NOMEM;
199331 }else{
199332 rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
199333 SQLITE_PREPARE_PERSISTENT, &pRet, 0);
199334 if( rc!=SQLITE_OK ){
199335 *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
199337 sqlite3_free(zSql);
199340 va_end(ap);
199341 *ppStmt = pRet;
199342 return rc;
199345 static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
199346 Fts5Config *pConfig = pTab->pConfig;
199347 Fts5Sorter *pSorter;
199348 int nPhrase;
199349 int nByte;
199350 int rc;
199351 const char *zRank = pCsr->zRank;
199352 const char *zRankArgs = pCsr->zRankArgs;
199354 nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
199355 nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
199356 pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
199357 if( pSorter==0 ) return SQLITE_NOMEM;
199358 memset(pSorter, 0, nByte);
199359 pSorter->nIdx = nPhrase;
199361 /* TODO: It would be better to have some system for reusing statement
199362 ** handles here, rather than preparing a new one for each query. But that
199363 ** is not possible as SQLite reference counts the virtual table objects.
199364 ** And since the statement required here reads from this very virtual
199365 ** table, saving it creates a circular reference.
199367 ** If SQLite a built-in statement cache, this wouldn't be a problem. */
199368 rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
199369 "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
199370 pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
199371 (zRankArgs ? ", " : ""),
199372 (zRankArgs ? zRankArgs : ""),
199373 bDesc ? "DESC" : "ASC"
199376 pCsr->pSorter = pSorter;
199377 if( rc==SQLITE_OK ){
199378 assert( pTab->pSortCsr==0 );
199379 pTab->pSortCsr = pCsr;
199380 rc = fts5SorterNext(pCsr);
199381 pTab->pSortCsr = 0;
199384 if( rc!=SQLITE_OK ){
199385 sqlite3_finalize(pSorter->pStmt);
199386 sqlite3_free(pSorter);
199387 pCsr->pSorter = 0;
199390 return rc;
199393 static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
199394 int rc;
199395 Fts5Expr *pExpr = pCsr->pExpr;
199396 rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
199397 if( sqlite3Fts5ExprEof(pExpr) ){
199398 CsrFlagSet(pCsr, FTS5CSR_EOF);
199400 fts5CsrNewrow(pCsr);
199401 return rc;
199405 ** Process a "special" query. A special query is identified as one with a
199406 ** MATCH expression that begins with a '*' character. The remainder of
199407 ** the text passed to the MATCH operator are used as the special query
199408 ** parameters.
199410 static int fts5SpecialMatch(
199411 Fts5Table *pTab,
199412 Fts5Cursor *pCsr,
199413 const char *zQuery
199415 int rc = SQLITE_OK; /* Return code */
199416 const char *z = zQuery; /* Special query text */
199417 int n; /* Number of bytes in text at z */
199419 while( z[0]==' ' ) z++;
199420 for(n=0; z[n] && z[n]!=' '; n++);
199422 assert( pTab->base.zErrMsg==0 );
199423 pCsr->ePlan = FTS5_PLAN_SPECIAL;
199425 if( 0==sqlite3_strnicmp("reads", z, n) ){
199426 pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
199428 else if( 0==sqlite3_strnicmp("id", z, n) ){
199429 pCsr->iSpecial = pCsr->iCsrId;
199431 else{
199432 /* An unrecognized directive. Return an error message. */
199433 pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
199434 rc = SQLITE_ERROR;
199437 return rc;
199441 ** Search for an auxiliary function named zName that can be used with table
199442 ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
199443 ** structure. Otherwise, if no such function exists, return NULL.
199445 static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
199446 Fts5Auxiliary *pAux;
199448 for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
199449 if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
199452 /* No function of the specified name was found. Return 0. */
199453 return 0;
199457 static int fts5FindRankFunction(Fts5Cursor *pCsr){
199458 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199459 Fts5Config *pConfig = pTab->pConfig;
199460 int rc = SQLITE_OK;
199461 Fts5Auxiliary *pAux = 0;
199462 const char *zRank = pCsr->zRank;
199463 const char *zRankArgs = pCsr->zRankArgs;
199465 if( zRankArgs ){
199466 char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
199467 if( zSql ){
199468 sqlite3_stmt *pStmt = 0;
199469 rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
199470 SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
199471 sqlite3_free(zSql);
199472 assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
199473 if( rc==SQLITE_OK ){
199474 if( SQLITE_ROW==sqlite3_step(pStmt) ){
199475 int nByte;
199476 pCsr->nRankArg = sqlite3_column_count(pStmt);
199477 nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
199478 pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
199479 if( rc==SQLITE_OK ){
199480 int i;
199481 for(i=0; i<pCsr->nRankArg; i++){
199482 pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
199485 pCsr->pRankArgStmt = pStmt;
199486 }else{
199487 rc = sqlite3_finalize(pStmt);
199488 assert( rc!=SQLITE_OK );
199494 if( rc==SQLITE_OK ){
199495 pAux = fts5FindAuxiliary(pTab, zRank);
199496 if( pAux==0 ){
199497 assert( pTab->base.zErrMsg==0 );
199498 pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
199499 rc = SQLITE_ERROR;
199503 pCsr->pRank = pAux;
199504 return rc;
199508 static int fts5CursorParseRank(
199509 Fts5Config *pConfig,
199510 Fts5Cursor *pCsr,
199511 sqlite3_value *pRank
199513 int rc = SQLITE_OK;
199514 if( pRank ){
199515 const char *z = (const char*)sqlite3_value_text(pRank);
199516 char *zRank = 0;
199517 char *zRankArgs = 0;
199519 if( z==0 ){
199520 if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
199521 }else{
199522 rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
199524 if( rc==SQLITE_OK ){
199525 pCsr->zRank = zRank;
199526 pCsr->zRankArgs = zRankArgs;
199527 CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
199528 }else if( rc==SQLITE_ERROR ){
199529 pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
199530 "parse error in rank function: %s", z
199533 }else{
199534 if( pConfig->zRank ){
199535 pCsr->zRank = (char*)pConfig->zRank;
199536 pCsr->zRankArgs = (char*)pConfig->zRankArgs;
199537 }else{
199538 pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
199539 pCsr->zRankArgs = 0;
199542 return rc;
199545 static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
199546 if( pVal ){
199547 int eType = sqlite3_value_numeric_type(pVal);
199548 if( eType==SQLITE_INTEGER ){
199549 return sqlite3_value_int64(pVal);
199552 return iDefault;
199556 ** This is the xFilter interface for the virtual table. See
199557 ** the virtual table xFilter method documentation for additional
199558 ** information.
199560 ** There are three possible query strategies:
199562 ** 1. Full-text search using a MATCH operator.
199563 ** 2. A by-rowid lookup.
199564 ** 3. A full-table scan.
199566 static int fts5FilterMethod(
199567 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
199568 int idxNum, /* Strategy index */
199569 const char *zUnused, /* Unused */
199570 int nVal, /* Number of elements in apVal */
199571 sqlite3_value **apVal /* Arguments for the indexing scheme */
199573 Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
199574 Fts5Config *pConfig = pTab->pConfig;
199575 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
199576 int rc = SQLITE_OK; /* Error code */
199577 int iVal = 0; /* Counter for apVal[] */
199578 int bDesc; /* True if ORDER BY [rank|rowid] DESC */
199579 int bOrderByRank; /* True if ORDER BY rank */
199580 sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
199581 sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
199582 sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
199583 sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
199584 sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
199585 int iCol; /* Column on LHS of MATCH operator */
199586 char **pzErrmsg = pConfig->pzErrmsg;
199588 UNUSED_PARAM(zUnused);
199589 UNUSED_PARAM(nVal);
199591 if( pCsr->ePlan ){
199592 fts5FreeCursorComponents(pCsr);
199593 memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
199596 assert( pCsr->pStmt==0 );
199597 assert( pCsr->pExpr==0 );
199598 assert( pCsr->csrflags==0 );
199599 assert( pCsr->pRank==0 );
199600 assert( pCsr->zRank==0 );
199601 assert( pCsr->zRankArgs==0 );
199603 assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
199604 pConfig->pzErrmsg = &pTab->base.zErrMsg;
199606 /* Decode the arguments passed through to this function.
199608 ** Note: The following set of if(...) statements must be in the same
199609 ** order as the corresponding entries in the struct at the top of
199610 ** fts5BestIndexMethod(). */
199611 if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
199612 if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
199613 if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
199614 if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
199615 if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
199616 iCol = (idxNum>>16);
199617 assert( iCol>=0 && iCol<=pConfig->nCol );
199618 assert( iVal==nVal );
199619 bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
199620 pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
199622 /* Set the cursor upper and lower rowid limits. Only some strategies
199623 ** actually use them. This is ok, as the xBestIndex() method leaves the
199624 ** sqlite3_index_constraint.omit flag clear for range constraints
199625 ** on the rowid field. */
199626 if( pRowidEq ){
199627 pRowidLe = pRowidGe = pRowidEq;
199629 if( bDesc ){
199630 pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
199631 pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
199632 }else{
199633 pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
199634 pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
199637 if( pTab->pSortCsr ){
199638 /* If pSortCsr is non-NULL, then this call is being made as part of
199639 ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
199640 ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
199641 ** return results to the user for this query. The current cursor
199642 ** (pCursor) is used to execute the query issued by function
199643 ** fts5CursorFirstSorted() above. */
199644 assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
199645 assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
199646 assert( pCsr->iLastRowid==LARGEST_INT64 );
199647 assert( pCsr->iFirstRowid==SMALLEST_INT64 );
199648 pCsr->ePlan = FTS5_PLAN_SOURCE;
199649 pCsr->pExpr = pTab->pSortCsr->pExpr;
199650 rc = fts5CursorFirst(pTab, pCsr, bDesc);
199651 }else if( pMatch ){
199652 const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
199653 if( zExpr==0 ) zExpr = "";
199655 rc = fts5CursorParseRank(pConfig, pCsr, pRank);
199656 if( rc==SQLITE_OK ){
199657 if( zExpr[0]=='*' ){
199658 /* The user has issued a query of the form "MATCH '*...'". This
199659 ** indicates that the MATCH expression is not a full text query,
199660 ** but a request for an internal parameter. */
199661 rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
199662 }else{
199663 char **pzErr = &pTab->base.zErrMsg;
199664 rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
199665 if( rc==SQLITE_OK ){
199666 if( bOrderByRank ){
199667 pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
199668 rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
199669 }else{
199670 pCsr->ePlan = FTS5_PLAN_MATCH;
199671 rc = fts5CursorFirst(pTab, pCsr, bDesc);
199676 }else if( pConfig->zContent==0 ){
199677 *pConfig->pzErrmsg = sqlite3_mprintf(
199678 "%s: table does not support scanning", pConfig->zName
199680 rc = SQLITE_ERROR;
199681 }else{
199682 /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
199683 ** by rowid (ePlan==FTS5_PLAN_ROWID). */
199684 pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
199685 rc = sqlite3Fts5StorageStmt(
199686 pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
199688 if( rc==SQLITE_OK ){
199689 if( pCsr->ePlan==FTS5_PLAN_ROWID ){
199690 sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
199691 }else{
199692 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
199693 sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
199695 rc = fts5NextMethod(pCursor);
199699 pConfig->pzErrmsg = pzErrmsg;
199700 return rc;
199704 ** This is the xEof method of the virtual table. SQLite calls this
199705 ** routine to find out if it has reached the end of a result set.
199707 static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
199708 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
199709 return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
199713 ** Return the rowid that the cursor currently points to.
199715 static i64 fts5CursorRowid(Fts5Cursor *pCsr){
199716 assert( pCsr->ePlan==FTS5_PLAN_MATCH
199717 || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
199718 || pCsr->ePlan==FTS5_PLAN_SOURCE
199720 if( pCsr->pSorter ){
199721 return pCsr->pSorter->iRowid;
199722 }else{
199723 return sqlite3Fts5ExprRowid(pCsr->pExpr);
199728 ** This is the xRowid method. The SQLite core calls this routine to
199729 ** retrieve the rowid for the current row of the result set. fts5
199730 ** exposes %_content.rowid as the rowid for the virtual table. The
199731 ** rowid should be written to *pRowid.
199733 static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
199734 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
199735 int ePlan = pCsr->ePlan;
199737 assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
199738 switch( ePlan ){
199739 case FTS5_PLAN_SPECIAL:
199740 *pRowid = 0;
199741 break;
199743 case FTS5_PLAN_SOURCE:
199744 case FTS5_PLAN_MATCH:
199745 case FTS5_PLAN_SORTED_MATCH:
199746 *pRowid = fts5CursorRowid(pCsr);
199747 break;
199749 default:
199750 *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
199751 break;
199754 return SQLITE_OK;
199758 ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
199759 ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
199761 ** If argument bErrormsg is true and an error occurs, an error message may
199762 ** be left in sqlite3_vtab.zErrMsg.
199764 static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
199765 int rc = SQLITE_OK;
199767 /* If the cursor does not yet have a statement handle, obtain one now. */
199768 if( pCsr->pStmt==0 ){
199769 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199770 int eStmt = fts5StmtType(pCsr);
199771 rc = sqlite3Fts5StorageStmt(
199772 pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
199774 assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
199775 assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
199778 if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
199779 assert( pCsr->pExpr );
199780 sqlite3_reset(pCsr->pStmt);
199781 sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
199782 rc = sqlite3_step(pCsr->pStmt);
199783 if( rc==SQLITE_ROW ){
199784 rc = SQLITE_OK;
199785 CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
199786 }else{
199787 rc = sqlite3_reset(pCsr->pStmt);
199788 if( rc==SQLITE_OK ){
199789 rc = FTS5_CORRUPT;
199793 return rc;
199796 static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
199797 va_list ap; /* ... printf arguments */
199798 va_start(ap, zFormat);
199799 assert( p->base.zErrMsg==0 );
199800 p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
199801 va_end(ap);
199805 ** This function is called to handle an FTS INSERT command. In other words,
199806 ** an INSERT statement of the form:
199808 ** INSERT INTO fts(fts) VALUES($pCmd)
199809 ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
199811 ** Argument pVal is the value assigned to column "fts" by the INSERT
199812 ** statement. This function returns SQLITE_OK if successful, or an SQLite
199813 ** error code if an error occurs.
199815 ** The commands implemented by this function are documented in the "Special
199816 ** INSERT Directives" section of the documentation. It should be updated if
199817 ** more commands are added to this function.
199819 static int fts5SpecialInsert(
199820 Fts5Table *pTab, /* Fts5 table object */
199821 const char *zCmd, /* Text inserted into table-name column */
199822 sqlite3_value *pVal /* Value inserted into rank column */
199824 Fts5Config *pConfig = pTab->pConfig;
199825 int rc = SQLITE_OK;
199826 int bError = 0;
199828 if( 0==sqlite3_stricmp("delete-all", zCmd) ){
199829 if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
199830 fts5SetVtabError(pTab,
199831 "'delete-all' may only be used with a "
199832 "contentless or external content fts5 table"
199834 rc = SQLITE_ERROR;
199835 }else{
199836 rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
199838 }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
199839 if( pConfig->eContent==FTS5_CONTENT_NONE ){
199840 fts5SetVtabError(pTab,
199841 "'rebuild' may not be used with a contentless fts5 table"
199843 rc = SQLITE_ERROR;
199844 }else{
199845 rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
199847 }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
199848 rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
199849 }else if( 0==sqlite3_stricmp("merge", zCmd) ){
199850 int nMerge = sqlite3_value_int(pVal);
199851 rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
199852 }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
199853 rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
199854 #ifdef SQLITE_DEBUG
199855 }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
199856 pConfig->bPrefixIndex = sqlite3_value_int(pVal);
199857 #endif
199858 }else{
199859 rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
199860 if( rc==SQLITE_OK ){
199861 rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
199863 if( rc==SQLITE_OK ){
199864 if( bError ){
199865 rc = SQLITE_ERROR;
199866 }else{
199867 rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
199871 return rc;
199874 static int fts5SpecialDelete(
199875 Fts5Table *pTab,
199876 sqlite3_value **apVal
199878 int rc = SQLITE_OK;
199879 int eType1 = sqlite3_value_type(apVal[1]);
199880 if( eType1==SQLITE_INTEGER ){
199881 sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
199882 rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
199884 return rc;
199887 static void fts5StorageInsert(
199888 int *pRc,
199889 Fts5Table *pTab,
199890 sqlite3_value **apVal,
199891 i64 *piRowid
199893 int rc = *pRc;
199894 if( rc==SQLITE_OK ){
199895 rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
199897 if( rc==SQLITE_OK ){
199898 rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
199900 *pRc = rc;
199904 ** This function is the implementation of the xUpdate callback used by
199905 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
199906 ** inserted, updated or deleted.
199908 ** A delete specifies a single argument - the rowid of the row to remove.
199910 ** Update and insert operations pass:
199912 ** 1. The "old" rowid, or NULL.
199913 ** 2. The "new" rowid.
199914 ** 3. Values for each of the nCol matchable columns.
199915 ** 4. Values for the two hidden columns (<tablename> and "rank").
199917 static int fts5UpdateMethod(
199918 sqlite3_vtab *pVtab, /* Virtual table handle */
199919 int nArg, /* Size of argument array */
199920 sqlite3_value **apVal, /* Array of arguments */
199921 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
199923 Fts5Table *pTab = (Fts5Table*)pVtab;
199924 Fts5Config *pConfig = pTab->pConfig;
199925 int eType0; /* value_type() of apVal[0] */
199926 int rc = SQLITE_OK; /* Return code */
199928 /* A transaction must be open when this is called. */
199929 assert( pTab->ts.eState==1 );
199931 assert( pVtab->zErrMsg==0 );
199932 assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
199933 assert( nArg==1
199934 || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
199935 || sqlite3_value_type(apVal[1])==SQLITE_NULL
199937 assert( pTab->pConfig->pzErrmsg==0 );
199938 pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
199940 /* Put any active cursors into REQUIRE_SEEK state. */
199941 fts5TripCursors(pTab);
199943 eType0 = sqlite3_value_type(apVal[0]);
199944 if( eType0==SQLITE_NULL
199945 && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
199947 /* A "special" INSERT op. These are handled separately. */
199948 const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
199949 if( pConfig->eContent!=FTS5_CONTENT_NORMAL
199950 && 0==sqlite3_stricmp("delete", z)
199952 rc = fts5SpecialDelete(pTab, apVal);
199953 }else{
199954 rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
199956 }else{
199957 /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
199958 ** any conflict on the rowid value must be detected before any
199959 ** modifications are made to the database file. There are 4 cases:
199961 ** 1) DELETE
199962 ** 2) UPDATE (rowid not modified)
199963 ** 3) UPDATE (rowid modified)
199964 ** 4) INSERT
199966 ** Cases 3 and 4 may violate the rowid constraint.
199968 int eConflict = SQLITE_ABORT;
199969 if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
199970 eConflict = sqlite3_vtab_on_conflict(pConfig->db);
199973 assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
199974 assert( nArg!=1 || eType0==SQLITE_INTEGER );
199976 /* Filter out attempts to run UPDATE or DELETE on contentless tables.
199977 ** This is not suported. */
199978 if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
199979 pTab->base.zErrMsg = sqlite3_mprintf(
199980 "cannot %s contentless fts5 table: %s",
199981 (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
199983 rc = SQLITE_ERROR;
199986 /* DELETE */
199987 else if( nArg==1 ){
199988 i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
199989 rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
199992 /* INSERT */
199993 else if( eType0!=SQLITE_INTEGER ){
199994 /* If this is a REPLACE, first remove the current entry (if any) */
199995 if( eConflict==SQLITE_REPLACE
199996 && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
199998 i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
199999 rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
200001 fts5StorageInsert(&rc, pTab, apVal, pRowid);
200004 /* UPDATE */
200005 else{
200006 i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
200007 i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
200008 if( iOld!=iNew ){
200009 if( eConflict==SQLITE_REPLACE ){
200010 rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
200011 if( rc==SQLITE_OK ){
200012 rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
200014 fts5StorageInsert(&rc, pTab, apVal, pRowid);
200015 }else{
200016 rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
200017 if( rc==SQLITE_OK ){
200018 rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
200020 if( rc==SQLITE_OK ){
200021 rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
200024 }else{
200025 rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
200026 fts5StorageInsert(&rc, pTab, apVal, pRowid);
200031 pTab->pConfig->pzErrmsg = 0;
200032 return rc;
200036 ** Implementation of xSync() method.
200038 static int fts5SyncMethod(sqlite3_vtab *pVtab){
200039 int rc;
200040 Fts5Table *pTab = (Fts5Table*)pVtab;
200041 fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
200042 pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
200043 fts5TripCursors(pTab);
200044 rc = sqlite3Fts5StorageSync(pTab->pStorage);
200045 pTab->pConfig->pzErrmsg = 0;
200046 return rc;
200050 ** Implementation of xBegin() method.
200052 static int fts5BeginMethod(sqlite3_vtab *pVtab){
200053 fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
200054 fts5NewTransaction((Fts5Table*)pVtab);
200055 return SQLITE_OK;
200059 ** Implementation of xCommit() method. This is a no-op. The contents of
200060 ** the pending-terms hash-table have already been flushed into the database
200061 ** by fts5SyncMethod().
200063 static int fts5CommitMethod(sqlite3_vtab *pVtab){
200064 UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
200065 fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
200066 return SQLITE_OK;
200070 ** Implementation of xRollback(). Discard the contents of the pending-terms
200071 ** hash-table. Any changes made to the database are reverted by SQLite.
200073 static int fts5RollbackMethod(sqlite3_vtab *pVtab){
200074 int rc;
200075 Fts5Table *pTab = (Fts5Table*)pVtab;
200076 fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
200077 rc = sqlite3Fts5StorageRollback(pTab->pStorage);
200078 return rc;
200081 static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
200083 static void *fts5ApiUserData(Fts5Context *pCtx){
200084 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200085 return pCsr->pAux->pUserData;
200088 static int fts5ApiColumnCount(Fts5Context *pCtx){
200089 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200090 return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
200093 static int fts5ApiColumnTotalSize(
200094 Fts5Context *pCtx,
200095 int iCol,
200096 sqlite3_int64 *pnToken
200098 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200099 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
200100 return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
200103 static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
200104 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200105 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
200106 return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
200109 static int fts5ApiTokenize(
200110 Fts5Context *pCtx,
200111 const char *pText, int nText,
200112 void *pUserData,
200113 int (*xToken)(void*, int, const char*, int, int, int)
200115 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200116 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
200117 return sqlite3Fts5Tokenize(
200118 pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
200122 static int fts5ApiPhraseCount(Fts5Context *pCtx){
200123 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200124 return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
200127 static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
200128 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200129 return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
200132 static int fts5ApiColumnText(
200133 Fts5Context *pCtx,
200134 int iCol,
200135 const char **pz,
200136 int *pn
200138 int rc = SQLITE_OK;
200139 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200140 if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
200141 *pz = 0;
200142 *pn = 0;
200143 }else{
200144 rc = fts5SeekCursor(pCsr, 0);
200145 if( rc==SQLITE_OK ){
200146 *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
200147 *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
200150 return rc;
200153 static int fts5CsrPoslist(
200154 Fts5Cursor *pCsr,
200155 int iPhrase,
200156 const u8 **pa,
200157 int *pn
200159 Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
200160 int rc = SQLITE_OK;
200161 int bLive = (pCsr->pSorter==0);
200163 if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
200165 if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
200166 Fts5PoslistPopulator *aPopulator;
200167 int i;
200168 aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
200169 if( aPopulator==0 ) rc = SQLITE_NOMEM;
200170 for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
200171 int n; const char *z;
200172 rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
200173 if( rc==SQLITE_OK ){
200174 rc = sqlite3Fts5ExprPopulatePoslists(
200175 pConfig, pCsr->pExpr, aPopulator, i, z, n
200179 sqlite3_free(aPopulator);
200181 if( pCsr->pSorter ){
200182 sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
200185 CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
200188 if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
200189 Fts5Sorter *pSorter = pCsr->pSorter;
200190 int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
200191 *pn = pSorter->aIdx[iPhrase] - i1;
200192 *pa = &pSorter->aPoslist[i1];
200193 }else{
200194 *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
200197 return rc;
200201 ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
200202 ** correctly for the current view. Return SQLITE_OK if successful, or an
200203 ** SQLite error code otherwise.
200205 static int fts5CacheInstArray(Fts5Cursor *pCsr){
200206 int rc = SQLITE_OK;
200207 Fts5PoslistReader *aIter; /* One iterator for each phrase */
200208 int nIter; /* Number of iterators/phrases */
200210 nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
200211 if( pCsr->aInstIter==0 ){
200212 int nByte = sizeof(Fts5PoslistReader) * nIter;
200213 pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
200215 aIter = pCsr->aInstIter;
200217 if( aIter ){
200218 int nInst = 0; /* Number instances seen so far */
200219 int i;
200221 /* Initialize all iterators */
200222 for(i=0; i<nIter && rc==SQLITE_OK; i++){
200223 const u8 *a;
200224 int n;
200225 rc = fts5CsrPoslist(pCsr, i, &a, &n);
200226 if( rc==SQLITE_OK ){
200227 sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
200231 if( rc==SQLITE_OK ){
200232 while( 1 ){
200233 int *aInst;
200234 int iBest = -1;
200235 for(i=0; i<nIter; i++){
200236 if( (aIter[i].bEof==0)
200237 && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
200239 iBest = i;
200242 if( iBest<0 ) break;
200244 nInst++;
200245 if( nInst>=pCsr->nInstAlloc ){
200246 pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
200247 aInst = (int*)sqlite3_realloc(
200248 pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
200250 if( aInst ){
200251 pCsr->aInst = aInst;
200252 }else{
200253 rc = SQLITE_NOMEM;
200254 break;
200258 aInst = &pCsr->aInst[3 * (nInst-1)];
200259 aInst[0] = iBest;
200260 aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
200261 aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
200262 sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
200266 pCsr->nInstCount = nInst;
200267 CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
200269 return rc;
200272 static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
200273 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200274 int rc = SQLITE_OK;
200275 if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
200276 || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
200277 *pnInst = pCsr->nInstCount;
200279 return rc;
200282 static int fts5ApiInst(
200283 Fts5Context *pCtx,
200284 int iIdx,
200285 int *piPhrase,
200286 int *piCol,
200287 int *piOff
200289 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200290 int rc = SQLITE_OK;
200291 if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
200292 || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
200294 if( iIdx<0 || iIdx>=pCsr->nInstCount ){
200295 rc = SQLITE_RANGE;
200296 #if 0
200297 }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
200298 *piPhrase = pCsr->aInst[iIdx*3];
200299 *piCol = pCsr->aInst[iIdx*3 + 2];
200300 *piOff = -1;
200301 #endif
200302 }else{
200303 *piPhrase = pCsr->aInst[iIdx*3];
200304 *piCol = pCsr->aInst[iIdx*3 + 1];
200305 *piOff = pCsr->aInst[iIdx*3 + 2];
200308 return rc;
200311 static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
200312 return fts5CursorRowid((Fts5Cursor*)pCtx);
200315 static int fts5ColumnSizeCb(
200316 void *pContext, /* Pointer to int */
200317 int tflags,
200318 const char *pUnused, /* Buffer containing token */
200319 int nUnused, /* Size of token in bytes */
200320 int iUnused1, /* Start offset of token */
200321 int iUnused2 /* End offset of token */
200323 int *pCnt = (int*)pContext;
200324 UNUSED_PARAM2(pUnused, nUnused);
200325 UNUSED_PARAM2(iUnused1, iUnused2);
200326 if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
200327 (*pCnt)++;
200329 return SQLITE_OK;
200332 static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
200333 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200334 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
200335 Fts5Config *pConfig = pTab->pConfig;
200336 int rc = SQLITE_OK;
200338 if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
200339 if( pConfig->bColumnsize ){
200340 i64 iRowid = fts5CursorRowid(pCsr);
200341 rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
200342 }else if( pConfig->zContent==0 ){
200343 int i;
200344 for(i=0; i<pConfig->nCol; i++){
200345 if( pConfig->abUnindexed[i]==0 ){
200346 pCsr->aColumnSize[i] = -1;
200349 }else{
200350 int i;
200351 for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
200352 if( pConfig->abUnindexed[i]==0 ){
200353 const char *z; int n;
200354 void *p = (void*)(&pCsr->aColumnSize[i]);
200355 pCsr->aColumnSize[i] = 0;
200356 rc = fts5ApiColumnText(pCtx, i, &z, &n);
200357 if( rc==SQLITE_OK ){
200358 rc = sqlite3Fts5Tokenize(
200359 pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
200365 CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
200367 if( iCol<0 ){
200368 int i;
200369 *pnToken = 0;
200370 for(i=0; i<pConfig->nCol; i++){
200371 *pnToken += pCsr->aColumnSize[i];
200373 }else if( iCol<pConfig->nCol ){
200374 *pnToken = pCsr->aColumnSize[iCol];
200375 }else{
200376 *pnToken = 0;
200377 rc = SQLITE_RANGE;
200379 return rc;
200383 ** Implementation of the xSetAuxdata() method.
200385 static int fts5ApiSetAuxdata(
200386 Fts5Context *pCtx, /* Fts5 context */
200387 void *pPtr, /* Pointer to save as auxdata */
200388 void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
200390 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200391 Fts5Auxdata *pData;
200393 /* Search through the cursors list of Fts5Auxdata objects for one that
200394 ** corresponds to the currently executing auxiliary function. */
200395 for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
200396 if( pData->pAux==pCsr->pAux ) break;
200399 if( pData ){
200400 if( pData->xDelete ){
200401 pData->xDelete(pData->pPtr);
200403 }else{
200404 int rc = SQLITE_OK;
200405 pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
200406 if( pData==0 ){
200407 if( xDelete ) xDelete(pPtr);
200408 return rc;
200410 pData->pAux = pCsr->pAux;
200411 pData->pNext = pCsr->pAuxdata;
200412 pCsr->pAuxdata = pData;
200415 pData->xDelete = xDelete;
200416 pData->pPtr = pPtr;
200417 return SQLITE_OK;
200420 static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
200421 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200422 Fts5Auxdata *pData;
200423 void *pRet = 0;
200425 for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
200426 if( pData->pAux==pCsr->pAux ) break;
200429 if( pData ){
200430 pRet = pData->pPtr;
200431 if( bClear ){
200432 pData->pPtr = 0;
200433 pData->xDelete = 0;
200437 return pRet;
200440 static void fts5ApiPhraseNext(
200441 Fts5Context *pUnused,
200442 Fts5PhraseIter *pIter,
200443 int *piCol, int *piOff
200445 UNUSED_PARAM(pUnused);
200446 if( pIter->a>=pIter->b ){
200447 *piCol = -1;
200448 *piOff = -1;
200449 }else{
200450 int iVal;
200451 pIter->a += fts5GetVarint32(pIter->a, iVal);
200452 if( iVal==1 ){
200453 pIter->a += fts5GetVarint32(pIter->a, iVal);
200454 *piCol = iVal;
200455 *piOff = 0;
200456 pIter->a += fts5GetVarint32(pIter->a, iVal);
200458 *piOff += (iVal-2);
200462 static int fts5ApiPhraseFirst(
200463 Fts5Context *pCtx,
200464 int iPhrase,
200465 Fts5PhraseIter *pIter,
200466 int *piCol, int *piOff
200468 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200469 int n;
200470 int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
200471 if( rc==SQLITE_OK ){
200472 pIter->b = &pIter->a[n];
200473 *piCol = 0;
200474 *piOff = 0;
200475 fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
200477 return rc;
200480 static void fts5ApiPhraseNextColumn(
200481 Fts5Context *pCtx,
200482 Fts5PhraseIter *pIter,
200483 int *piCol
200485 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200486 Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
200488 if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
200489 if( pIter->a>=pIter->b ){
200490 *piCol = -1;
200491 }else{
200492 int iIncr;
200493 pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
200494 *piCol += (iIncr-2);
200496 }else{
200497 while( 1 ){
200498 int dummy;
200499 if( pIter->a>=pIter->b ){
200500 *piCol = -1;
200501 return;
200503 if( pIter->a[0]==0x01 ) break;
200504 pIter->a += fts5GetVarint32(pIter->a, dummy);
200506 pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
200510 static int fts5ApiPhraseFirstColumn(
200511 Fts5Context *pCtx,
200512 int iPhrase,
200513 Fts5PhraseIter *pIter,
200514 int *piCol
200516 int rc = SQLITE_OK;
200517 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200518 Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
200520 if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
200521 Fts5Sorter *pSorter = pCsr->pSorter;
200522 int n;
200523 if( pSorter ){
200524 int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
200525 n = pSorter->aIdx[iPhrase] - i1;
200526 pIter->a = &pSorter->aPoslist[i1];
200527 }else{
200528 rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
200530 if( rc==SQLITE_OK ){
200531 pIter->b = &pIter->a[n];
200532 *piCol = 0;
200533 fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
200535 }else{
200536 int n;
200537 rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
200538 if( rc==SQLITE_OK ){
200539 pIter->b = &pIter->a[n];
200540 if( n<=0 ){
200541 *piCol = -1;
200542 }else if( pIter->a[0]==0x01 ){
200543 pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
200544 }else{
200545 *piCol = 0;
200550 return rc;
200554 static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
200555 int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
200558 static const Fts5ExtensionApi sFts5Api = {
200559 2, /* iVersion */
200560 fts5ApiUserData,
200561 fts5ApiColumnCount,
200562 fts5ApiRowCount,
200563 fts5ApiColumnTotalSize,
200564 fts5ApiTokenize,
200565 fts5ApiPhraseCount,
200566 fts5ApiPhraseSize,
200567 fts5ApiInstCount,
200568 fts5ApiInst,
200569 fts5ApiRowid,
200570 fts5ApiColumnText,
200571 fts5ApiColumnSize,
200572 fts5ApiQueryPhrase,
200573 fts5ApiSetAuxdata,
200574 fts5ApiGetAuxdata,
200575 fts5ApiPhraseFirst,
200576 fts5ApiPhraseNext,
200577 fts5ApiPhraseFirstColumn,
200578 fts5ApiPhraseNextColumn,
200582 ** Implementation of API function xQueryPhrase().
200584 static int fts5ApiQueryPhrase(
200585 Fts5Context *pCtx,
200586 int iPhrase,
200587 void *pUserData,
200588 int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
200590 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
200591 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
200592 int rc;
200593 Fts5Cursor *pNew = 0;
200595 rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
200596 if( rc==SQLITE_OK ){
200597 pNew->ePlan = FTS5_PLAN_MATCH;
200598 pNew->iFirstRowid = SMALLEST_INT64;
200599 pNew->iLastRowid = LARGEST_INT64;
200600 pNew->base.pVtab = (sqlite3_vtab*)pTab;
200601 rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
200604 if( rc==SQLITE_OK ){
200605 for(rc = fts5CursorFirst(pTab, pNew, 0);
200606 rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
200607 rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
200609 rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
200610 if( rc!=SQLITE_OK ){
200611 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
200612 break;
200617 fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
200618 return rc;
200621 static void fts5ApiInvoke(
200622 Fts5Auxiliary *pAux,
200623 Fts5Cursor *pCsr,
200624 sqlite3_context *context,
200625 int argc,
200626 sqlite3_value **argv
200628 assert( pCsr->pAux==0 );
200629 pCsr->pAux = pAux;
200630 pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
200631 pCsr->pAux = 0;
200634 static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
200635 Fts5Cursor *pCsr;
200636 for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
200637 if( pCsr->iCsrId==iCsrId ) break;
200639 return pCsr;
200642 static void fts5ApiCallback(
200643 sqlite3_context *context,
200644 int argc,
200645 sqlite3_value **argv
200648 Fts5Auxiliary *pAux;
200649 Fts5Cursor *pCsr;
200650 i64 iCsrId;
200652 assert( argc>=1 );
200653 pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
200654 iCsrId = sqlite3_value_int64(argv[0]);
200656 pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
200657 if( pCsr==0 ){
200658 char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
200659 sqlite3_result_error(context, zErr, -1);
200660 sqlite3_free(zErr);
200661 }else{
200662 fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
200668 ** Given cursor id iId, return a pointer to the corresponding Fts5Index
200669 ** object. Or NULL If the cursor id does not exist.
200671 ** If successful, set *ppConfig to point to the associated config object
200672 ** before returning.
200674 static Fts5Index *sqlite3Fts5IndexFromCsrid(
200675 Fts5Global *pGlobal, /* FTS5 global context for db handle */
200676 i64 iCsrId, /* Id of cursor to find */
200677 Fts5Config **ppConfig /* OUT: Configuration object */
200679 Fts5Cursor *pCsr;
200680 Fts5Table *pTab;
200682 pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
200683 pTab = (Fts5Table*)pCsr->base.pVtab;
200684 *ppConfig = pTab->pConfig;
200686 return pTab->pIndex;
200690 ** Return a "position-list blob" corresponding to the current position of
200691 ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
200692 ** the current position-list for each phrase in the query associated with
200693 ** cursor pCsr.
200695 ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
200696 ** the number of phrases in the query. Following the varints are the
200697 ** concatenated position lists for each phrase, in order.
200699 ** The first varint (if it exists) contains the size of the position list
200700 ** for phrase 0. The second (same disclaimer) contains the size of position
200701 ** list 1. And so on. There is no size field for the final position list,
200702 ** as it can be derived from the total size of the blob.
200704 static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
200705 int i;
200706 int rc = SQLITE_OK;
200707 int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
200708 Fts5Buffer val;
200710 memset(&val, 0, sizeof(Fts5Buffer));
200711 switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
200712 case FTS5_DETAIL_FULL:
200714 /* Append the varints */
200715 for(i=0; i<(nPhrase-1); i++){
200716 const u8 *dummy;
200717 int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
200718 sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
200721 /* Append the position lists */
200722 for(i=0; i<nPhrase; i++){
200723 const u8 *pPoslist;
200724 int nPoslist;
200725 nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
200726 sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
200728 break;
200730 case FTS5_DETAIL_COLUMNS:
200732 /* Append the varints */
200733 for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
200734 const u8 *dummy;
200735 int nByte;
200736 rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
200737 sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
200740 /* Append the position lists */
200741 for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
200742 const u8 *pPoslist;
200743 int nPoslist;
200744 rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
200745 sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
200747 break;
200749 default:
200750 break;
200753 sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
200754 return rc;
200758 ** This is the xColumn method, called by SQLite to request a value from
200759 ** the row that the supplied cursor currently points to.
200761 static int fts5ColumnMethod(
200762 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
200763 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
200764 int iCol /* Index of column to read value from */
200766 Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
200767 Fts5Config *pConfig = pTab->pConfig;
200768 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
200769 int rc = SQLITE_OK;
200771 assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
200773 if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
200774 if( iCol==pConfig->nCol ){
200775 sqlite3_result_int64(pCtx, pCsr->iSpecial);
200777 }else
200779 if( iCol==pConfig->nCol ){
200780 /* User is requesting the value of the special column with the same name
200781 ** as the table. Return the cursor integer id number. This value is only
200782 ** useful in that it may be passed as the first argument to an FTS5
200783 ** auxiliary function. */
200784 sqlite3_result_int64(pCtx, pCsr->iCsrId);
200785 }else if( iCol==pConfig->nCol+1 ){
200787 /* The value of the "rank" column. */
200788 if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
200789 fts5PoslistBlob(pCtx, pCsr);
200790 }else if(
200791 pCsr->ePlan==FTS5_PLAN_MATCH
200792 || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
200794 if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
200795 fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
200798 }else if( !fts5IsContentless(pTab) ){
200799 rc = fts5SeekCursor(pCsr, 1);
200800 if( rc==SQLITE_OK ){
200801 sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
200804 return rc;
200809 ** This routine implements the xFindFunction method for the FTS3
200810 ** virtual table.
200812 static int fts5FindFunctionMethod(
200813 sqlite3_vtab *pVtab, /* Virtual table handle */
200814 int nUnused, /* Number of SQL function arguments */
200815 const char *zName, /* Name of SQL function */
200816 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
200817 void **ppArg /* OUT: User data for *pxFunc */
200819 Fts5Table *pTab = (Fts5Table*)pVtab;
200820 Fts5Auxiliary *pAux;
200822 UNUSED_PARAM(nUnused);
200823 pAux = fts5FindAuxiliary(pTab, zName);
200824 if( pAux ){
200825 *pxFunc = fts5ApiCallback;
200826 *ppArg = (void*)pAux;
200827 return 1;
200830 /* No function of the specified name was found. Return 0. */
200831 return 0;
200835 ** Implementation of FTS5 xRename method. Rename an fts5 table.
200837 static int fts5RenameMethod(
200838 sqlite3_vtab *pVtab, /* Virtual table handle */
200839 const char *zName /* New name of table */
200841 Fts5Table *pTab = (Fts5Table*)pVtab;
200842 return sqlite3Fts5StorageRename(pTab->pStorage, zName);
200846 ** The xSavepoint() method.
200848 ** Flush the contents of the pending-terms table to disk.
200850 static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
200851 Fts5Table *pTab = (Fts5Table*)pVtab;
200852 UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
200853 fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
200854 fts5TripCursors(pTab);
200855 return sqlite3Fts5StorageSync(pTab->pStorage);
200859 ** The xRelease() method.
200861 ** This is a no-op.
200863 static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
200864 Fts5Table *pTab = (Fts5Table*)pVtab;
200865 UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
200866 fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
200867 fts5TripCursors(pTab);
200868 return sqlite3Fts5StorageSync(pTab->pStorage);
200872 ** The xRollbackTo() method.
200874 ** Discard the contents of the pending terms table.
200876 static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
200877 Fts5Table *pTab = (Fts5Table*)pVtab;
200878 UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
200879 fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
200880 fts5TripCursors(pTab);
200881 return sqlite3Fts5StorageRollback(pTab->pStorage);
200885 ** Register a new auxiliary function with global context pGlobal.
200887 static int fts5CreateAux(
200888 fts5_api *pApi, /* Global context (one per db handle) */
200889 const char *zName, /* Name of new function */
200890 void *pUserData, /* User data for aux. function */
200891 fts5_extension_function xFunc, /* Aux. function implementation */
200892 void(*xDestroy)(void*) /* Destructor for pUserData */
200894 Fts5Global *pGlobal = (Fts5Global*)pApi;
200895 int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
200896 if( rc==SQLITE_OK ){
200897 Fts5Auxiliary *pAux;
200898 int nName; /* Size of zName in bytes, including \0 */
200899 int nByte; /* Bytes of space to allocate */
200901 nName = (int)strlen(zName) + 1;
200902 nByte = sizeof(Fts5Auxiliary) + nName;
200903 pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
200904 if( pAux ){
200905 memset(pAux, 0, nByte);
200906 pAux->zFunc = (char*)&pAux[1];
200907 memcpy(pAux->zFunc, zName, nName);
200908 pAux->pGlobal = pGlobal;
200909 pAux->pUserData = pUserData;
200910 pAux->xFunc = xFunc;
200911 pAux->xDestroy = xDestroy;
200912 pAux->pNext = pGlobal->pAux;
200913 pGlobal->pAux = pAux;
200914 }else{
200915 rc = SQLITE_NOMEM;
200919 return rc;
200923 ** Register a new tokenizer. This is the implementation of the
200924 ** fts5_api.xCreateTokenizer() method.
200926 static int fts5CreateTokenizer(
200927 fts5_api *pApi, /* Global context (one per db handle) */
200928 const char *zName, /* Name of new function */
200929 void *pUserData, /* User data for aux. function */
200930 fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
200931 void(*xDestroy)(void*) /* Destructor for pUserData */
200933 Fts5Global *pGlobal = (Fts5Global*)pApi;
200934 Fts5TokenizerModule *pNew;
200935 int nName; /* Size of zName and its \0 terminator */
200936 int nByte; /* Bytes of space to allocate */
200937 int rc = SQLITE_OK;
200939 nName = (int)strlen(zName) + 1;
200940 nByte = sizeof(Fts5TokenizerModule) + nName;
200941 pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
200942 if( pNew ){
200943 memset(pNew, 0, nByte);
200944 pNew->zName = (char*)&pNew[1];
200945 memcpy(pNew->zName, zName, nName);
200946 pNew->pUserData = pUserData;
200947 pNew->x = *pTokenizer;
200948 pNew->xDestroy = xDestroy;
200949 pNew->pNext = pGlobal->pTok;
200950 pGlobal->pTok = pNew;
200951 if( pNew->pNext==0 ){
200952 pGlobal->pDfltTok = pNew;
200954 }else{
200955 rc = SQLITE_NOMEM;
200958 return rc;
200961 static Fts5TokenizerModule *fts5LocateTokenizer(
200962 Fts5Global *pGlobal,
200963 const char *zName
200965 Fts5TokenizerModule *pMod = 0;
200967 if( zName==0 ){
200968 pMod = pGlobal->pDfltTok;
200969 }else{
200970 for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
200971 if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
200975 return pMod;
200979 ** Find a tokenizer. This is the implementation of the
200980 ** fts5_api.xFindTokenizer() method.
200982 static int fts5FindTokenizer(
200983 fts5_api *pApi, /* Global context (one per db handle) */
200984 const char *zName, /* Name of new function */
200985 void **ppUserData,
200986 fts5_tokenizer *pTokenizer /* Populate this object */
200988 int rc = SQLITE_OK;
200989 Fts5TokenizerModule *pMod;
200991 pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
200992 if( pMod ){
200993 *pTokenizer = pMod->x;
200994 *ppUserData = pMod->pUserData;
200995 }else{
200996 memset(pTokenizer, 0, sizeof(fts5_tokenizer));
200997 rc = SQLITE_ERROR;
201000 return rc;
201003 static int sqlite3Fts5GetTokenizer(
201004 Fts5Global *pGlobal,
201005 const char **azArg,
201006 int nArg,
201007 Fts5Tokenizer **ppTok,
201008 fts5_tokenizer **ppTokApi,
201009 char **pzErr
201011 Fts5TokenizerModule *pMod;
201012 int rc = SQLITE_OK;
201014 pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
201015 if( pMod==0 ){
201016 assert( nArg>0 );
201017 rc = SQLITE_ERROR;
201018 *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
201019 }else{
201020 rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
201021 *ppTokApi = &pMod->x;
201022 if( rc!=SQLITE_OK && pzErr ){
201023 *pzErr = sqlite3_mprintf("error in tokenizer constructor");
201027 if( rc!=SQLITE_OK ){
201028 *ppTokApi = 0;
201029 *ppTok = 0;
201032 return rc;
201035 static void fts5ModuleDestroy(void *pCtx){
201036 Fts5TokenizerModule *pTok, *pNextTok;
201037 Fts5Auxiliary *pAux, *pNextAux;
201038 Fts5Global *pGlobal = (Fts5Global*)pCtx;
201040 for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
201041 pNextAux = pAux->pNext;
201042 if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
201043 sqlite3_free(pAux);
201046 for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
201047 pNextTok = pTok->pNext;
201048 if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
201049 sqlite3_free(pTok);
201052 sqlite3_free(pGlobal);
201055 static void fts5Fts5Func(
201056 sqlite3_context *pCtx, /* Function call context */
201057 int nArg, /* Number of args */
201058 sqlite3_value **apArg /* Function arguments */
201060 Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
201061 fts5_api **ppApi;
201062 UNUSED_PARAM(nArg);
201063 assert( nArg==1 );
201064 ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
201065 if( ppApi ) *ppApi = &pGlobal->api;
201069 ** Implementation of fts5_source_id() function.
201071 static void fts5SourceIdFunc(
201072 sqlite3_context *pCtx, /* Function call context */
201073 int nArg, /* Number of args */
201074 sqlite3_value **apUnused /* Function arguments */
201076 assert( nArg==0 );
201077 UNUSED_PARAM2(nArg, apUnused);
201078 sqlite3_result_text(pCtx, "fts5: 2017-10-24 18:55:49 1a584e499906b5c87ec7d43d4abce641fdf017c42125b083109bc77c4de48827", -1, SQLITE_TRANSIENT);
201081 static int fts5Init(sqlite3 *db){
201082 static const sqlite3_module fts5Mod = {
201083 /* iVersion */ 2,
201084 /* xCreate */ fts5CreateMethod,
201085 /* xConnect */ fts5ConnectMethod,
201086 /* xBestIndex */ fts5BestIndexMethod,
201087 /* xDisconnect */ fts5DisconnectMethod,
201088 /* xDestroy */ fts5DestroyMethod,
201089 /* xOpen */ fts5OpenMethod,
201090 /* xClose */ fts5CloseMethod,
201091 /* xFilter */ fts5FilterMethod,
201092 /* xNext */ fts5NextMethod,
201093 /* xEof */ fts5EofMethod,
201094 /* xColumn */ fts5ColumnMethod,
201095 /* xRowid */ fts5RowidMethod,
201096 /* xUpdate */ fts5UpdateMethod,
201097 /* xBegin */ fts5BeginMethod,
201098 /* xSync */ fts5SyncMethod,
201099 /* xCommit */ fts5CommitMethod,
201100 /* xRollback */ fts5RollbackMethod,
201101 /* xFindFunction */ fts5FindFunctionMethod,
201102 /* xRename */ fts5RenameMethod,
201103 /* xSavepoint */ fts5SavepointMethod,
201104 /* xRelease */ fts5ReleaseMethod,
201105 /* xRollbackTo */ fts5RollbackToMethod,
201108 int rc;
201109 Fts5Global *pGlobal = 0;
201111 pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
201112 if( pGlobal==0 ){
201113 rc = SQLITE_NOMEM;
201114 }else{
201115 void *p = (void*)pGlobal;
201116 memset(pGlobal, 0, sizeof(Fts5Global));
201117 pGlobal->db = db;
201118 pGlobal->api.iVersion = 2;
201119 pGlobal->api.xCreateFunction = fts5CreateAux;
201120 pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
201121 pGlobal->api.xFindTokenizer = fts5FindTokenizer;
201122 rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
201123 if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
201124 if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
201125 if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
201126 if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
201127 if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
201128 if( rc==SQLITE_OK ){
201129 rc = sqlite3_create_function(
201130 db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
201133 if( rc==SQLITE_OK ){
201134 rc = sqlite3_create_function(
201135 db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
201140 /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
201141 ** fts5_test_mi.c is compiled and linked into the executable. And call
201142 ** its entry point to enable the matchinfo() demo. */
201143 #ifdef SQLITE_FTS5_ENABLE_TEST_MI
201144 if( rc==SQLITE_OK ){
201145 extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
201146 rc = sqlite3Fts5TestRegisterMatchinfo(db);
201148 #endif
201150 return rc;
201154 ** The following functions are used to register the module with SQLite. If
201155 ** this module is being built as part of the SQLite core (SQLITE_CORE is
201156 ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
201158 ** Or, if this module is being built as a loadable extension,
201159 ** sqlite3Fts5Init() is omitted and the two standard entry points
201160 ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
201162 #ifndef SQLITE_CORE
201163 #ifdef _WIN32
201164 __declspec(dllexport)
201165 #endif
201166 SQLITE_API int sqlite3_fts_init(
201167 sqlite3 *db,
201168 char **pzErrMsg,
201169 const sqlite3_api_routines *pApi
201171 SQLITE_EXTENSION_INIT2(pApi);
201172 (void)pzErrMsg; /* Unused parameter */
201173 return fts5Init(db);
201176 #ifdef _WIN32
201177 __declspec(dllexport)
201178 #endif
201179 SQLITE_API int sqlite3_fts5_init(
201180 sqlite3 *db,
201181 char **pzErrMsg,
201182 const sqlite3_api_routines *pApi
201184 SQLITE_EXTENSION_INIT2(pApi);
201185 (void)pzErrMsg; /* Unused parameter */
201186 return fts5Init(db);
201188 #else
201189 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
201190 return fts5Init(db);
201192 #endif
201195 ** 2014 May 31
201197 ** The author disclaims copyright to this source code. In place of
201198 ** a legal notice, here is a blessing:
201200 ** May you do good and not evil.
201201 ** May you find forgiveness for yourself and forgive others.
201202 ** May you share freely, never taking more than you give.
201204 ******************************************************************************
201210 /* #include "fts5Int.h" */
201212 struct Fts5Storage {
201213 Fts5Config *pConfig;
201214 Fts5Index *pIndex;
201215 int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
201216 i64 nTotalRow; /* Total number of rows in FTS table */
201217 i64 *aTotalSize; /* Total sizes of each column */
201218 sqlite3_stmt *aStmt[11];
201222 #if FTS5_STMT_SCAN_ASC!=0
201223 # error "FTS5_STMT_SCAN_ASC mismatch"
201224 #endif
201225 #if FTS5_STMT_SCAN_DESC!=1
201226 # error "FTS5_STMT_SCAN_DESC mismatch"
201227 #endif
201228 #if FTS5_STMT_LOOKUP!=2
201229 # error "FTS5_STMT_LOOKUP mismatch"
201230 #endif
201232 #define FTS5_STMT_INSERT_CONTENT 3
201233 #define FTS5_STMT_REPLACE_CONTENT 4
201234 #define FTS5_STMT_DELETE_CONTENT 5
201235 #define FTS5_STMT_REPLACE_DOCSIZE 6
201236 #define FTS5_STMT_DELETE_DOCSIZE 7
201237 #define FTS5_STMT_LOOKUP_DOCSIZE 8
201238 #define FTS5_STMT_REPLACE_CONFIG 9
201239 #define FTS5_STMT_SCAN 10
201242 ** Prepare the two insert statements - Fts5Storage.pInsertContent and
201243 ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
201244 ** Return SQLITE_OK if successful, or an SQLite error code if an error
201245 ** occurs.
201247 static int fts5StorageGetStmt(
201248 Fts5Storage *p, /* Storage handle */
201249 int eStmt, /* FTS5_STMT_XXX constant */
201250 sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
201251 char **pzErrMsg /* OUT: Error message (if any) */
201253 int rc = SQLITE_OK;
201255 /* If there is no %_docsize table, there should be no requests for
201256 ** statements to operate on it. */
201257 assert( p->pConfig->bColumnsize || (
201258 eStmt!=FTS5_STMT_REPLACE_DOCSIZE
201259 && eStmt!=FTS5_STMT_DELETE_DOCSIZE
201260 && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
201263 assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
201264 if( p->aStmt[eStmt]==0 ){
201265 const char *azStmt[] = {
201266 "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
201267 "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
201268 "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
201270 "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
201271 "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
201272 "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
201273 "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
201274 "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
201276 "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
201278 "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
201279 "SELECT %s FROM %s AS T", /* SCAN */
201281 Fts5Config *pC = p->pConfig;
201282 char *zSql = 0;
201284 switch( eStmt ){
201285 case FTS5_STMT_SCAN:
201286 zSql = sqlite3_mprintf(azStmt[eStmt],
201287 pC->zContentExprlist, pC->zContent
201289 break;
201291 case FTS5_STMT_SCAN_ASC:
201292 case FTS5_STMT_SCAN_DESC:
201293 zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
201294 pC->zContent, pC->zContentRowid, pC->zContentRowid,
201295 pC->zContentRowid
201297 break;
201299 case FTS5_STMT_LOOKUP:
201300 zSql = sqlite3_mprintf(azStmt[eStmt],
201301 pC->zContentExprlist, pC->zContent, pC->zContentRowid
201303 break;
201305 case FTS5_STMT_INSERT_CONTENT:
201306 case FTS5_STMT_REPLACE_CONTENT: {
201307 int nCol = pC->nCol + 1;
201308 char *zBind;
201309 int i;
201311 zBind = sqlite3_malloc(1 + nCol*2);
201312 if( zBind ){
201313 for(i=0; i<nCol; i++){
201314 zBind[i*2] = '?';
201315 zBind[i*2 + 1] = ',';
201317 zBind[i*2-1] = '\0';
201318 zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
201319 sqlite3_free(zBind);
201321 break;
201324 default:
201325 zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
201326 break;
201329 if( zSql==0 ){
201330 rc = SQLITE_NOMEM;
201331 }else{
201332 rc = sqlite3_prepare_v3(pC->db, zSql, -1,
201333 SQLITE_PREPARE_PERSISTENT, &p->aStmt[eStmt], 0);
201334 sqlite3_free(zSql);
201335 if( rc!=SQLITE_OK && pzErrMsg ){
201336 *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
201341 *ppStmt = p->aStmt[eStmt];
201342 sqlite3_reset(*ppStmt);
201343 return rc;
201347 static int fts5ExecPrintf(
201348 sqlite3 *db,
201349 char **pzErr,
201350 const char *zFormat,
201353 int rc;
201354 va_list ap; /* ... printf arguments */
201355 char *zSql;
201357 va_start(ap, zFormat);
201358 zSql = sqlite3_vmprintf(zFormat, ap);
201360 if( zSql==0 ){
201361 rc = SQLITE_NOMEM;
201362 }else{
201363 rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
201364 sqlite3_free(zSql);
201367 va_end(ap);
201368 return rc;
201372 ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
201373 ** code otherwise.
201375 static int sqlite3Fts5DropAll(Fts5Config *pConfig){
201376 int rc = fts5ExecPrintf(pConfig->db, 0,
201377 "DROP TABLE IF EXISTS %Q.'%q_data';"
201378 "DROP TABLE IF EXISTS %Q.'%q_idx';"
201379 "DROP TABLE IF EXISTS %Q.'%q_config';",
201380 pConfig->zDb, pConfig->zName,
201381 pConfig->zDb, pConfig->zName,
201382 pConfig->zDb, pConfig->zName
201384 if( rc==SQLITE_OK && pConfig->bColumnsize ){
201385 rc = fts5ExecPrintf(pConfig->db, 0,
201386 "DROP TABLE IF EXISTS %Q.'%q_docsize';",
201387 pConfig->zDb, pConfig->zName
201390 if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
201391 rc = fts5ExecPrintf(pConfig->db, 0,
201392 "DROP TABLE IF EXISTS %Q.'%q_content';",
201393 pConfig->zDb, pConfig->zName
201396 return rc;
201399 static void fts5StorageRenameOne(
201400 Fts5Config *pConfig, /* Current FTS5 configuration */
201401 int *pRc, /* IN/OUT: Error code */
201402 const char *zTail, /* Tail of table name e.g. "data", "config" */
201403 const char *zName /* New name of FTS5 table */
201405 if( *pRc==SQLITE_OK ){
201406 *pRc = fts5ExecPrintf(pConfig->db, 0,
201407 "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
201408 pConfig->zDb, pConfig->zName, zTail, zName, zTail
201413 static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
201414 Fts5Config *pConfig = pStorage->pConfig;
201415 int rc = sqlite3Fts5StorageSync(pStorage);
201417 fts5StorageRenameOne(pConfig, &rc, "data", zName);
201418 fts5StorageRenameOne(pConfig, &rc, "idx", zName);
201419 fts5StorageRenameOne(pConfig, &rc, "config", zName);
201420 if( pConfig->bColumnsize ){
201421 fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
201423 if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
201424 fts5StorageRenameOne(pConfig, &rc, "content", zName);
201426 return rc;
201430 ** Create the shadow table named zPost, with definition zDefn. Return
201431 ** SQLITE_OK if successful, or an SQLite error code otherwise.
201433 static int sqlite3Fts5CreateTable(
201434 Fts5Config *pConfig, /* FTS5 configuration */
201435 const char *zPost, /* Shadow table to create (e.g. "content") */
201436 const char *zDefn, /* Columns etc. for shadow table */
201437 int bWithout, /* True for without rowid */
201438 char **pzErr /* OUT: Error message */
201440 int rc;
201441 char *zErr = 0;
201443 rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
201444 pConfig->zDb, pConfig->zName, zPost, zDefn,
201445 #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
201446 bWithout?" WITHOUT ROWID":
201447 #endif
201450 if( zErr ){
201451 *pzErr = sqlite3_mprintf(
201452 "fts5: error creating shadow table %q_%s: %s",
201453 pConfig->zName, zPost, zErr
201455 sqlite3_free(zErr);
201458 return rc;
201462 ** Open a new Fts5Index handle. If the bCreate argument is true, create
201463 ** and initialize the underlying tables
201465 ** If successful, set *pp to point to the new object and return SQLITE_OK.
201466 ** Otherwise, set *pp to NULL and return an SQLite error code.
201468 static int sqlite3Fts5StorageOpen(
201469 Fts5Config *pConfig,
201470 Fts5Index *pIndex,
201471 int bCreate,
201472 Fts5Storage **pp,
201473 char **pzErr /* OUT: Error message */
201475 int rc = SQLITE_OK;
201476 Fts5Storage *p; /* New object */
201477 int nByte; /* Bytes of space to allocate */
201479 nByte = sizeof(Fts5Storage) /* Fts5Storage object */
201480 + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
201481 *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
201482 if( !p ) return SQLITE_NOMEM;
201484 memset(p, 0, nByte);
201485 p->aTotalSize = (i64*)&p[1];
201486 p->pConfig = pConfig;
201487 p->pIndex = pIndex;
201489 if( bCreate ){
201490 if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
201491 int nDefn = 32 + pConfig->nCol*10;
201492 char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
201493 if( zDefn==0 ){
201494 rc = SQLITE_NOMEM;
201495 }else{
201496 int i;
201497 int iOff;
201498 sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
201499 iOff = (int)strlen(zDefn);
201500 for(i=0; i<pConfig->nCol; i++){
201501 sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
201502 iOff += (int)strlen(&zDefn[iOff]);
201504 rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
201506 sqlite3_free(zDefn);
201509 if( rc==SQLITE_OK && pConfig->bColumnsize ){
201510 rc = sqlite3Fts5CreateTable(
201511 pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
201514 if( rc==SQLITE_OK ){
201515 rc = sqlite3Fts5CreateTable(
201516 pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
201519 if( rc==SQLITE_OK ){
201520 rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
201524 if( rc ){
201525 sqlite3Fts5StorageClose(p);
201526 *pp = 0;
201528 return rc;
201532 ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
201534 static int sqlite3Fts5StorageClose(Fts5Storage *p){
201535 int rc = SQLITE_OK;
201536 if( p ){
201537 int i;
201539 /* Finalize all SQL statements */
201540 for(i=0; i<ArraySize(p->aStmt); i++){
201541 sqlite3_finalize(p->aStmt[i]);
201544 sqlite3_free(p);
201546 return rc;
201549 typedef struct Fts5InsertCtx Fts5InsertCtx;
201550 struct Fts5InsertCtx {
201551 Fts5Storage *pStorage;
201552 int iCol;
201553 int szCol; /* Size of column value in tokens */
201557 ** Tokenization callback used when inserting tokens into the FTS index.
201559 static int fts5StorageInsertCallback(
201560 void *pContext, /* Pointer to Fts5InsertCtx object */
201561 int tflags,
201562 const char *pToken, /* Buffer containing token */
201563 int nToken, /* Size of token in bytes */
201564 int iUnused1, /* Start offset of token */
201565 int iUnused2 /* End offset of token */
201567 Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
201568 Fts5Index *pIdx = pCtx->pStorage->pIndex;
201569 UNUSED_PARAM2(iUnused1, iUnused2);
201570 if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
201571 if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
201572 pCtx->szCol++;
201574 return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
201578 ** If a row with rowid iDel is present in the %_content table, add the
201579 ** delete-markers to the FTS index necessary to delete it. Do not actually
201580 ** remove the %_content row at this time though.
201582 static int fts5StorageDeleteFromIndex(
201583 Fts5Storage *p,
201584 i64 iDel,
201585 sqlite3_value **apVal
201587 Fts5Config *pConfig = p->pConfig;
201588 sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
201589 int rc; /* Return code */
201590 int rc2; /* sqlite3_reset() return code */
201591 int iCol;
201592 Fts5InsertCtx ctx;
201594 if( apVal==0 ){
201595 rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
201596 if( rc!=SQLITE_OK ) return rc;
201597 sqlite3_bind_int64(pSeek, 1, iDel);
201598 if( sqlite3_step(pSeek)!=SQLITE_ROW ){
201599 return sqlite3_reset(pSeek);
201603 ctx.pStorage = p;
201604 ctx.iCol = -1;
201605 rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
201606 for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
201607 if( pConfig->abUnindexed[iCol-1]==0 ){
201608 const char *zText;
201609 int nText;
201610 if( pSeek ){
201611 zText = (const char*)sqlite3_column_text(pSeek, iCol);
201612 nText = sqlite3_column_bytes(pSeek, iCol);
201613 }else{
201614 zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
201615 nText = sqlite3_value_bytes(apVal[iCol-1]);
201617 ctx.szCol = 0;
201618 rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
201619 zText, nText, (void*)&ctx, fts5StorageInsertCallback
201621 p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
201624 p->nTotalRow--;
201626 rc2 = sqlite3_reset(pSeek);
201627 if( rc==SQLITE_OK ) rc = rc2;
201628 return rc;
201633 ** Insert a record into the %_docsize table. Specifically, do:
201635 ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
201637 ** If there is no %_docsize table (as happens if the columnsize=0 option
201638 ** is specified when the FTS5 table is created), this function is a no-op.
201640 static int fts5StorageInsertDocsize(
201641 Fts5Storage *p, /* Storage module to write to */
201642 i64 iRowid, /* id value */
201643 Fts5Buffer *pBuf /* sz value */
201645 int rc = SQLITE_OK;
201646 if( p->pConfig->bColumnsize ){
201647 sqlite3_stmt *pReplace = 0;
201648 rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
201649 if( rc==SQLITE_OK ){
201650 sqlite3_bind_int64(pReplace, 1, iRowid);
201651 sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
201652 sqlite3_step(pReplace);
201653 rc = sqlite3_reset(pReplace);
201656 return rc;
201660 ** Load the contents of the "averages" record from disk into the
201661 ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
201662 ** argument bCache is true, set the p->bTotalsValid flag to indicate
201663 ** that the contents of aTotalSize[] and nTotalRow are valid until
201664 ** further notice.
201666 ** Return SQLITE_OK if successful, or an SQLite error code if an error
201667 ** occurs.
201669 static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
201670 int rc = SQLITE_OK;
201671 if( p->bTotalsValid==0 ){
201672 rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
201673 p->bTotalsValid = bCache;
201675 return rc;
201679 ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
201680 ** variables in the "averages" record on disk.
201682 ** Return SQLITE_OK if successful, or an SQLite error code if an error
201683 ** occurs.
201685 static int fts5StorageSaveTotals(Fts5Storage *p){
201686 int nCol = p->pConfig->nCol;
201687 int i;
201688 Fts5Buffer buf;
201689 int rc = SQLITE_OK;
201690 memset(&buf, 0, sizeof(buf));
201692 sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
201693 for(i=0; i<nCol; i++){
201694 sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
201696 if( rc==SQLITE_OK ){
201697 rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
201699 sqlite3_free(buf.p);
201701 return rc;
201705 ** Remove a row from the FTS table.
201707 static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
201708 Fts5Config *pConfig = p->pConfig;
201709 int rc;
201710 sqlite3_stmt *pDel = 0;
201712 assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
201713 rc = fts5StorageLoadTotals(p, 1);
201715 /* Delete the index records */
201716 if( rc==SQLITE_OK ){
201717 rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
201720 /* Delete the %_docsize record */
201721 if( rc==SQLITE_OK && pConfig->bColumnsize ){
201722 rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
201723 if( rc==SQLITE_OK ){
201724 sqlite3_bind_int64(pDel, 1, iDel);
201725 sqlite3_step(pDel);
201726 rc = sqlite3_reset(pDel);
201730 /* Delete the %_content record */
201731 if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
201732 if( rc==SQLITE_OK ){
201733 rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
201735 if( rc==SQLITE_OK ){
201736 sqlite3_bind_int64(pDel, 1, iDel);
201737 sqlite3_step(pDel);
201738 rc = sqlite3_reset(pDel);
201742 return rc;
201746 ** Delete all entries in the FTS5 index.
201748 static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
201749 Fts5Config *pConfig = p->pConfig;
201750 int rc;
201752 /* Delete the contents of the %_data and %_docsize tables. */
201753 rc = fts5ExecPrintf(pConfig->db, 0,
201754 "DELETE FROM %Q.'%q_data';"
201755 "DELETE FROM %Q.'%q_idx';",
201756 pConfig->zDb, pConfig->zName,
201757 pConfig->zDb, pConfig->zName
201759 if( rc==SQLITE_OK && pConfig->bColumnsize ){
201760 rc = fts5ExecPrintf(pConfig->db, 0,
201761 "DELETE FROM %Q.'%q_docsize';",
201762 pConfig->zDb, pConfig->zName
201766 /* Reinitialize the %_data table. This call creates the initial structure
201767 ** and averages records. */
201768 if( rc==SQLITE_OK ){
201769 rc = sqlite3Fts5IndexReinit(p->pIndex);
201771 if( rc==SQLITE_OK ){
201772 rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
201774 return rc;
201777 static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
201778 Fts5Buffer buf = {0,0,0};
201779 Fts5Config *pConfig = p->pConfig;
201780 sqlite3_stmt *pScan = 0;
201781 Fts5InsertCtx ctx;
201782 int rc;
201784 memset(&ctx, 0, sizeof(Fts5InsertCtx));
201785 ctx.pStorage = p;
201786 rc = sqlite3Fts5StorageDeleteAll(p);
201787 if( rc==SQLITE_OK ){
201788 rc = fts5StorageLoadTotals(p, 1);
201791 if( rc==SQLITE_OK ){
201792 rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
201795 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
201796 i64 iRowid = sqlite3_column_int64(pScan, 0);
201798 sqlite3Fts5BufferZero(&buf);
201799 rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
201800 for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
201801 ctx.szCol = 0;
201802 if( pConfig->abUnindexed[ctx.iCol]==0 ){
201803 rc = sqlite3Fts5Tokenize(pConfig,
201804 FTS5_TOKENIZE_DOCUMENT,
201805 (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
201806 sqlite3_column_bytes(pScan, ctx.iCol+1),
201807 (void*)&ctx,
201808 fts5StorageInsertCallback
201811 sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
201812 p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
201814 p->nTotalRow++;
201816 if( rc==SQLITE_OK ){
201817 rc = fts5StorageInsertDocsize(p, iRowid, &buf);
201820 sqlite3_free(buf.p);
201822 /* Write the averages record */
201823 if( rc==SQLITE_OK ){
201824 rc = fts5StorageSaveTotals(p);
201826 return rc;
201829 static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
201830 return sqlite3Fts5IndexOptimize(p->pIndex);
201833 static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
201834 return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
201837 static int sqlite3Fts5StorageReset(Fts5Storage *p){
201838 return sqlite3Fts5IndexReset(p->pIndex);
201842 ** Allocate a new rowid. This is used for "external content" tables when
201843 ** a NULL value is inserted into the rowid column. The new rowid is allocated
201844 ** by inserting a dummy row into the %_docsize table. The dummy will be
201845 ** overwritten later.
201847 ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
201848 ** this case the user is required to provide a rowid explicitly.
201850 static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
201851 int rc = SQLITE_MISMATCH;
201852 if( p->pConfig->bColumnsize ){
201853 sqlite3_stmt *pReplace = 0;
201854 rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
201855 if( rc==SQLITE_OK ){
201856 sqlite3_bind_null(pReplace, 1);
201857 sqlite3_bind_null(pReplace, 2);
201858 sqlite3_step(pReplace);
201859 rc = sqlite3_reset(pReplace);
201861 if( rc==SQLITE_OK ){
201862 *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
201865 return rc;
201869 ** Insert a new row into the FTS content table.
201871 static int sqlite3Fts5StorageContentInsert(
201872 Fts5Storage *p,
201873 sqlite3_value **apVal,
201874 i64 *piRowid
201876 Fts5Config *pConfig = p->pConfig;
201877 int rc = SQLITE_OK;
201879 /* Insert the new row into the %_content table. */
201880 if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
201881 if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
201882 *piRowid = sqlite3_value_int64(apVal[1]);
201883 }else{
201884 rc = fts5StorageNewRowid(p, piRowid);
201886 }else{
201887 sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
201888 int i; /* Counter variable */
201889 rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
201890 for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
201891 rc = sqlite3_bind_value(pInsert, i, apVal[i]);
201893 if( rc==SQLITE_OK ){
201894 sqlite3_step(pInsert);
201895 rc = sqlite3_reset(pInsert);
201897 *piRowid = sqlite3_last_insert_rowid(pConfig->db);
201900 return rc;
201904 ** Insert new entries into the FTS index and %_docsize table.
201906 static int sqlite3Fts5StorageIndexInsert(
201907 Fts5Storage *p,
201908 sqlite3_value **apVal,
201909 i64 iRowid
201911 Fts5Config *pConfig = p->pConfig;
201912 int rc = SQLITE_OK; /* Return code */
201913 Fts5InsertCtx ctx; /* Tokenization callback context object */
201914 Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
201916 memset(&buf, 0, sizeof(Fts5Buffer));
201917 ctx.pStorage = p;
201918 rc = fts5StorageLoadTotals(p, 1);
201920 if( rc==SQLITE_OK ){
201921 rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
201923 for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
201924 ctx.szCol = 0;
201925 if( pConfig->abUnindexed[ctx.iCol]==0 ){
201926 rc = sqlite3Fts5Tokenize(pConfig,
201927 FTS5_TOKENIZE_DOCUMENT,
201928 (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
201929 sqlite3_value_bytes(apVal[ctx.iCol+2]),
201930 (void*)&ctx,
201931 fts5StorageInsertCallback
201934 sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
201935 p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
201937 p->nTotalRow++;
201939 /* Write the %_docsize record */
201940 if( rc==SQLITE_OK ){
201941 rc = fts5StorageInsertDocsize(p, iRowid, &buf);
201943 sqlite3_free(buf.p);
201945 return rc;
201948 static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
201949 Fts5Config *pConfig = p->pConfig;
201950 char *zSql;
201951 int rc;
201953 zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
201954 pConfig->zDb, pConfig->zName, zSuffix
201956 if( zSql==0 ){
201957 rc = SQLITE_NOMEM;
201958 }else{
201959 sqlite3_stmt *pCnt = 0;
201960 rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
201961 if( rc==SQLITE_OK ){
201962 if( SQLITE_ROW==sqlite3_step(pCnt) ){
201963 *pnRow = sqlite3_column_int64(pCnt, 0);
201965 rc = sqlite3_finalize(pCnt);
201969 sqlite3_free(zSql);
201970 return rc;
201974 ** Context object used by sqlite3Fts5StorageIntegrity().
201976 typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
201977 struct Fts5IntegrityCtx {
201978 i64 iRowid;
201979 int iCol;
201980 int szCol;
201981 u64 cksum;
201982 Fts5Termset *pTermset;
201983 Fts5Config *pConfig;
201988 ** Tokenization callback used by integrity check.
201990 static int fts5StorageIntegrityCallback(
201991 void *pContext, /* Pointer to Fts5IntegrityCtx object */
201992 int tflags,
201993 const char *pToken, /* Buffer containing token */
201994 int nToken, /* Size of token in bytes */
201995 int iUnused1, /* Start offset of token */
201996 int iUnused2 /* End offset of token */
201998 Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
201999 Fts5Termset *pTermset = pCtx->pTermset;
202000 int bPresent;
202001 int ii;
202002 int rc = SQLITE_OK;
202003 int iPos;
202004 int iCol;
202006 UNUSED_PARAM2(iUnused1, iUnused2);
202007 if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
202009 if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
202010 pCtx->szCol++;
202013 switch( pCtx->pConfig->eDetail ){
202014 case FTS5_DETAIL_FULL:
202015 iPos = pCtx->szCol-1;
202016 iCol = pCtx->iCol;
202017 break;
202019 case FTS5_DETAIL_COLUMNS:
202020 iPos = pCtx->iCol;
202021 iCol = 0;
202022 break;
202024 default:
202025 assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
202026 iPos = 0;
202027 iCol = 0;
202028 break;
202031 rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
202032 if( rc==SQLITE_OK && bPresent==0 ){
202033 pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
202034 pCtx->iRowid, iCol, iPos, 0, pToken, nToken
202038 for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
202039 const int nChar = pCtx->pConfig->aPrefix[ii];
202040 int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
202041 if( nByte ){
202042 rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
202043 if( bPresent==0 ){
202044 pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
202045 pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
202051 return rc;
202055 ** Check that the contents of the FTS index match that of the %_content
202056 ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
202057 ** some other SQLite error code if an error occurs while attempting to
202058 ** determine this.
202060 static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
202061 Fts5Config *pConfig = p->pConfig;
202062 int rc; /* Return code */
202063 int *aColSize; /* Array of size pConfig->nCol */
202064 i64 *aTotalSize; /* Array of size pConfig->nCol */
202065 Fts5IntegrityCtx ctx;
202066 sqlite3_stmt *pScan;
202068 memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
202069 ctx.pConfig = p->pConfig;
202070 aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
202071 if( !aTotalSize ) return SQLITE_NOMEM;
202072 aColSize = (int*)&aTotalSize[pConfig->nCol];
202073 memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
202075 /* Generate the expected index checksum based on the contents of the
202076 ** %_content table. This block stores the checksum in ctx.cksum. */
202077 rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
202078 if( rc==SQLITE_OK ){
202079 int rc2;
202080 while( SQLITE_ROW==sqlite3_step(pScan) ){
202081 int i;
202082 ctx.iRowid = sqlite3_column_int64(pScan, 0);
202083 ctx.szCol = 0;
202084 if( pConfig->bColumnsize ){
202085 rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
202087 if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
202088 rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
202090 for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
202091 if( pConfig->abUnindexed[i] ) continue;
202092 ctx.iCol = i;
202093 ctx.szCol = 0;
202094 if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
202095 rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
202097 if( rc==SQLITE_OK ){
202098 rc = sqlite3Fts5Tokenize(pConfig,
202099 FTS5_TOKENIZE_DOCUMENT,
202100 (const char*)sqlite3_column_text(pScan, i+1),
202101 sqlite3_column_bytes(pScan, i+1),
202102 (void*)&ctx,
202103 fts5StorageIntegrityCallback
202106 if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
202107 rc = FTS5_CORRUPT;
202109 aTotalSize[i] += ctx.szCol;
202110 if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
202111 sqlite3Fts5TermsetFree(ctx.pTermset);
202112 ctx.pTermset = 0;
202115 sqlite3Fts5TermsetFree(ctx.pTermset);
202116 ctx.pTermset = 0;
202118 if( rc!=SQLITE_OK ) break;
202120 rc2 = sqlite3_reset(pScan);
202121 if( rc==SQLITE_OK ) rc = rc2;
202124 /* Test that the "totals" (sometimes called "averages") record looks Ok */
202125 if( rc==SQLITE_OK ){
202126 int i;
202127 rc = fts5StorageLoadTotals(p, 0);
202128 for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
202129 if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
202133 /* Check that the %_docsize and %_content tables contain the expected
202134 ** number of rows. */
202135 if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
202136 i64 nRow = 0;
202137 rc = fts5StorageCount(p, "content", &nRow);
202138 if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
202140 if( rc==SQLITE_OK && pConfig->bColumnsize ){
202141 i64 nRow = 0;
202142 rc = fts5StorageCount(p, "docsize", &nRow);
202143 if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
202146 /* Pass the expected checksum down to the FTS index module. It will
202147 ** verify, amongst other things, that it matches the checksum generated by
202148 ** inspecting the index itself. */
202149 if( rc==SQLITE_OK ){
202150 rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
202153 sqlite3_free(aTotalSize);
202154 return rc;
202158 ** Obtain an SQLite statement handle that may be used to read data from the
202159 ** %_content table.
202161 static int sqlite3Fts5StorageStmt(
202162 Fts5Storage *p,
202163 int eStmt,
202164 sqlite3_stmt **pp,
202165 char **pzErrMsg
202167 int rc;
202168 assert( eStmt==FTS5_STMT_SCAN_ASC
202169 || eStmt==FTS5_STMT_SCAN_DESC
202170 || eStmt==FTS5_STMT_LOOKUP
202172 rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
202173 if( rc==SQLITE_OK ){
202174 assert( p->aStmt[eStmt]==*pp );
202175 p->aStmt[eStmt] = 0;
202177 return rc;
202181 ** Release an SQLite statement handle obtained via an earlier call to
202182 ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
202183 ** must match that passed to the sqlite3Fts5StorageStmt() call.
202185 static void sqlite3Fts5StorageStmtRelease(
202186 Fts5Storage *p,
202187 int eStmt,
202188 sqlite3_stmt *pStmt
202190 assert( eStmt==FTS5_STMT_SCAN_ASC
202191 || eStmt==FTS5_STMT_SCAN_DESC
202192 || eStmt==FTS5_STMT_LOOKUP
202194 if( p->aStmt[eStmt]==0 ){
202195 sqlite3_reset(pStmt);
202196 p->aStmt[eStmt] = pStmt;
202197 }else{
202198 sqlite3_finalize(pStmt);
202202 static int fts5StorageDecodeSizeArray(
202203 int *aCol, int nCol, /* Array to populate */
202204 const u8 *aBlob, int nBlob /* Record to read varints from */
202206 int i;
202207 int iOff = 0;
202208 for(i=0; i<nCol; i++){
202209 if( iOff>=nBlob ) return 1;
202210 iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
202212 return (iOff!=nBlob);
202216 ** Argument aCol points to an array of integers containing one entry for
202217 ** each table column. This function reads the %_docsize record for the
202218 ** specified rowid and populates aCol[] with the results.
202220 ** An SQLite error code is returned if an error occurs, or SQLITE_OK
202221 ** otherwise.
202223 static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
202224 int nCol = p->pConfig->nCol; /* Number of user columns in table */
202225 sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
202226 int rc; /* Return Code */
202228 assert( p->pConfig->bColumnsize );
202229 rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
202230 if( rc==SQLITE_OK ){
202231 int bCorrupt = 1;
202232 sqlite3_bind_int64(pLookup, 1, iRowid);
202233 if( SQLITE_ROW==sqlite3_step(pLookup) ){
202234 const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
202235 int nBlob = sqlite3_column_bytes(pLookup, 0);
202236 if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
202237 bCorrupt = 0;
202240 rc = sqlite3_reset(pLookup);
202241 if( bCorrupt && rc==SQLITE_OK ){
202242 rc = FTS5_CORRUPT;
202246 return rc;
202249 static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
202250 int rc = fts5StorageLoadTotals(p, 0);
202251 if( rc==SQLITE_OK ){
202252 *pnToken = 0;
202253 if( iCol<0 ){
202254 int i;
202255 for(i=0; i<p->pConfig->nCol; i++){
202256 *pnToken += p->aTotalSize[i];
202258 }else if( iCol<p->pConfig->nCol ){
202259 *pnToken = p->aTotalSize[iCol];
202260 }else{
202261 rc = SQLITE_RANGE;
202264 return rc;
202267 static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
202268 int rc = fts5StorageLoadTotals(p, 0);
202269 if( rc==SQLITE_OK ){
202270 *pnRow = p->nTotalRow;
202272 return rc;
202276 ** Flush any data currently held in-memory to disk.
202278 static int sqlite3Fts5StorageSync(Fts5Storage *p){
202279 int rc = SQLITE_OK;
202280 i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
202281 if( p->bTotalsValid ){
202282 rc = fts5StorageSaveTotals(p);
202283 p->bTotalsValid = 0;
202285 if( rc==SQLITE_OK ){
202286 rc = sqlite3Fts5IndexSync(p->pIndex);
202288 sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
202289 return rc;
202292 static int sqlite3Fts5StorageRollback(Fts5Storage *p){
202293 p->bTotalsValid = 0;
202294 return sqlite3Fts5IndexRollback(p->pIndex);
202297 static int sqlite3Fts5StorageConfigValue(
202298 Fts5Storage *p,
202299 const char *z,
202300 sqlite3_value *pVal,
202301 int iVal
202303 sqlite3_stmt *pReplace = 0;
202304 int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
202305 if( rc==SQLITE_OK ){
202306 sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
202307 if( pVal ){
202308 sqlite3_bind_value(pReplace, 2, pVal);
202309 }else{
202310 sqlite3_bind_int(pReplace, 2, iVal);
202312 sqlite3_step(pReplace);
202313 rc = sqlite3_reset(pReplace);
202315 if( rc==SQLITE_OK && pVal ){
202316 int iNew = p->pConfig->iCookie + 1;
202317 rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
202318 if( rc==SQLITE_OK ){
202319 p->pConfig->iCookie = iNew;
202322 return rc;
202326 ** 2014 May 31
202328 ** The author disclaims copyright to this source code. In place of
202329 ** a legal notice, here is a blessing:
202331 ** May you do good and not evil.
202332 ** May you find forgiveness for yourself and forgive others.
202333 ** May you share freely, never taking more than you give.
202335 ******************************************************************************
202339 /* #include "fts5Int.h" */
202341 /**************************************************************************
202342 ** Start of ascii tokenizer implementation.
202346 ** For tokenizers with no "unicode" modifier, the set of token characters
202347 ** is the same as the set of ASCII range alphanumeric characters.
202349 static unsigned char aAsciiTokenChar[128] = {
202350 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
202351 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
202352 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
202353 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
202354 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
202355 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
202356 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
202357 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
202360 typedef struct AsciiTokenizer AsciiTokenizer;
202361 struct AsciiTokenizer {
202362 unsigned char aTokenChar[128];
202365 static void fts5AsciiAddExceptions(
202366 AsciiTokenizer *p,
202367 const char *zArg,
202368 int bTokenChars
202370 int i;
202371 for(i=0; zArg[i]; i++){
202372 if( (zArg[i] & 0x80)==0 ){
202373 p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
202379 ** Delete a "ascii" tokenizer.
202381 static void fts5AsciiDelete(Fts5Tokenizer *p){
202382 sqlite3_free(p);
202386 ** Create an "ascii" tokenizer.
202388 static int fts5AsciiCreate(
202389 void *pUnused,
202390 const char **azArg, int nArg,
202391 Fts5Tokenizer **ppOut
202393 int rc = SQLITE_OK;
202394 AsciiTokenizer *p = 0;
202395 UNUSED_PARAM(pUnused);
202396 if( nArg%2 ){
202397 rc = SQLITE_ERROR;
202398 }else{
202399 p = sqlite3_malloc(sizeof(AsciiTokenizer));
202400 if( p==0 ){
202401 rc = SQLITE_NOMEM;
202402 }else{
202403 int i;
202404 memset(p, 0, sizeof(AsciiTokenizer));
202405 memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
202406 for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
202407 const char *zArg = azArg[i+1];
202408 if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
202409 fts5AsciiAddExceptions(p, zArg, 1);
202410 }else
202411 if( 0==sqlite3_stricmp(azArg[i], "separators") ){
202412 fts5AsciiAddExceptions(p, zArg, 0);
202413 }else{
202414 rc = SQLITE_ERROR;
202417 if( rc!=SQLITE_OK ){
202418 fts5AsciiDelete((Fts5Tokenizer*)p);
202419 p = 0;
202424 *ppOut = (Fts5Tokenizer*)p;
202425 return rc;
202429 static void asciiFold(char *aOut, const char *aIn, int nByte){
202430 int i;
202431 for(i=0; i<nByte; i++){
202432 char c = aIn[i];
202433 if( c>='A' && c<='Z' ) c += 32;
202434 aOut[i] = c;
202439 ** Tokenize some text using the ascii tokenizer.
202441 static int fts5AsciiTokenize(
202442 Fts5Tokenizer *pTokenizer,
202443 void *pCtx,
202444 int iUnused,
202445 const char *pText, int nText,
202446 int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
202448 AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
202449 int rc = SQLITE_OK;
202450 int ie;
202451 int is = 0;
202453 char aFold[64];
202454 int nFold = sizeof(aFold);
202455 char *pFold = aFold;
202456 unsigned char *a = p->aTokenChar;
202458 UNUSED_PARAM(iUnused);
202460 while( is<nText && rc==SQLITE_OK ){
202461 int nByte;
202463 /* Skip any leading divider characters. */
202464 while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
202465 is++;
202467 if( is==nText ) break;
202469 /* Count the token characters */
202470 ie = is+1;
202471 while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
202472 ie++;
202475 /* Fold to lower case */
202476 nByte = ie-is;
202477 if( nByte>nFold ){
202478 if( pFold!=aFold ) sqlite3_free(pFold);
202479 pFold = sqlite3_malloc(nByte*2);
202480 if( pFold==0 ){
202481 rc = SQLITE_NOMEM;
202482 break;
202484 nFold = nByte*2;
202486 asciiFold(pFold, &pText[is], nByte);
202488 /* Invoke the token callback */
202489 rc = xToken(pCtx, 0, pFold, nByte, is, ie);
202490 is = ie+1;
202493 if( pFold!=aFold ) sqlite3_free(pFold);
202494 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
202495 return rc;
202498 /**************************************************************************
202499 ** Start of unicode61 tokenizer implementation.
202504 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
202505 ** from the sqlite3 source file utf.c. If this file is compiled as part
202506 ** of the amalgamation, they are not required.
202508 #ifndef SQLITE_AMALGAMATION
202510 static const unsigned char sqlite3Utf8Trans1[] = {
202511 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
202512 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
202513 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
202514 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
202515 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
202516 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
202517 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
202518 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
202521 #define READ_UTF8(zIn, zTerm, c) \
202522 c = *(zIn++); \
202523 if( c>=0xc0 ){ \
202524 c = sqlite3Utf8Trans1[c-0xc0]; \
202525 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
202526 c = (c<<6) + (0x3f & *(zIn++)); \
202528 if( c<0x80 \
202529 || (c&0xFFFFF800)==0xD800 \
202530 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
202534 #define WRITE_UTF8(zOut, c) { \
202535 if( c<0x00080 ){ \
202536 *zOut++ = (unsigned char)(c&0xFF); \
202538 else if( c<0x00800 ){ \
202539 *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
202540 *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
202542 else if( c<0x10000 ){ \
202543 *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
202544 *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
202545 *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
202546 }else{ \
202547 *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
202548 *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
202549 *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
202550 *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
202554 #endif /* ifndef SQLITE_AMALGAMATION */
202556 typedef struct Unicode61Tokenizer Unicode61Tokenizer;
202557 struct Unicode61Tokenizer {
202558 unsigned char aTokenChar[128]; /* ASCII range token characters */
202559 char *aFold; /* Buffer to fold text into */
202560 int nFold; /* Size of aFold[] in bytes */
202561 int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
202562 int nException;
202563 int *aiException;
202566 static int fts5UnicodeAddExceptions(
202567 Unicode61Tokenizer *p, /* Tokenizer object */
202568 const char *z, /* Characters to treat as exceptions */
202569 int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
202571 int rc = SQLITE_OK;
202572 int n = (int)strlen(z);
202573 int *aNew;
202575 if( n>0 ){
202576 aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
202577 if( aNew ){
202578 int nNew = p->nException;
202579 const unsigned char *zCsr = (const unsigned char*)z;
202580 const unsigned char *zTerm = (const unsigned char*)&z[n];
202581 while( zCsr<zTerm ){
202582 int iCode;
202583 int bToken;
202584 READ_UTF8(zCsr, zTerm, iCode);
202585 if( iCode<128 ){
202586 p->aTokenChar[iCode] = (unsigned char)bTokenChars;
202587 }else{
202588 bToken = sqlite3Fts5UnicodeIsalnum(iCode);
202589 assert( (bToken==0 || bToken==1) );
202590 assert( (bTokenChars==0 || bTokenChars==1) );
202591 if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
202592 int i;
202593 for(i=0; i<nNew; i++){
202594 if( aNew[i]>iCode ) break;
202596 memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
202597 aNew[i] = iCode;
202598 nNew++;
202602 p->aiException = aNew;
202603 p->nException = nNew;
202604 }else{
202605 rc = SQLITE_NOMEM;
202609 return rc;
202613 ** Return true if the p->aiException[] array contains the value iCode.
202615 static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
202616 if( p->nException>0 ){
202617 int *a = p->aiException;
202618 int iLo = 0;
202619 int iHi = p->nException-1;
202621 while( iHi>=iLo ){
202622 int iTest = (iHi + iLo) / 2;
202623 if( iCode==a[iTest] ){
202624 return 1;
202625 }else if( iCode>a[iTest] ){
202626 iLo = iTest+1;
202627 }else{
202628 iHi = iTest-1;
202633 return 0;
202637 ** Delete a "unicode61" tokenizer.
202639 static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
202640 if( pTok ){
202641 Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
202642 sqlite3_free(p->aiException);
202643 sqlite3_free(p->aFold);
202644 sqlite3_free(p);
202646 return;
202650 ** Create a "unicode61" tokenizer.
202652 static int fts5UnicodeCreate(
202653 void *pUnused,
202654 const char **azArg, int nArg,
202655 Fts5Tokenizer **ppOut
202657 int rc = SQLITE_OK; /* Return code */
202658 Unicode61Tokenizer *p = 0; /* New tokenizer object */
202660 UNUSED_PARAM(pUnused);
202662 if( nArg%2 ){
202663 rc = SQLITE_ERROR;
202664 }else{
202665 p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
202666 if( p ){
202667 int i;
202668 memset(p, 0, sizeof(Unicode61Tokenizer));
202669 memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
202670 p->bRemoveDiacritic = 1;
202671 p->nFold = 64;
202672 p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
202673 if( p->aFold==0 ){
202674 rc = SQLITE_NOMEM;
202676 for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
202677 const char *zArg = azArg[i+1];
202678 if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
202679 if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
202680 rc = SQLITE_ERROR;
202682 p->bRemoveDiacritic = (zArg[0]=='1');
202683 }else
202684 if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
202685 rc = fts5UnicodeAddExceptions(p, zArg, 1);
202686 }else
202687 if( 0==sqlite3_stricmp(azArg[i], "separators") ){
202688 rc = fts5UnicodeAddExceptions(p, zArg, 0);
202689 }else{
202690 rc = SQLITE_ERROR;
202693 }else{
202694 rc = SQLITE_NOMEM;
202696 if( rc!=SQLITE_OK ){
202697 fts5UnicodeDelete((Fts5Tokenizer*)p);
202698 p = 0;
202700 *ppOut = (Fts5Tokenizer*)p;
202702 return rc;
202706 ** Return true if, for the purposes of tokenizing with the tokenizer
202707 ** passed as the first argument, codepoint iCode is considered a token
202708 ** character (not a separator).
202710 static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
202711 assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
202712 return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
202715 static int fts5UnicodeTokenize(
202716 Fts5Tokenizer *pTokenizer,
202717 void *pCtx,
202718 int iUnused,
202719 const char *pText, int nText,
202720 int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
202722 Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
202723 int rc = SQLITE_OK;
202724 unsigned char *a = p->aTokenChar;
202726 unsigned char *zTerm = (unsigned char*)&pText[nText];
202727 unsigned char *zCsr = (unsigned char *)pText;
202729 /* Output buffer */
202730 char *aFold = p->aFold;
202731 int nFold = p->nFold;
202732 const char *pEnd = &aFold[nFold-6];
202734 UNUSED_PARAM(iUnused);
202736 /* Each iteration of this loop gobbles up a contiguous run of separators,
202737 ** then the next token. */
202738 while( rc==SQLITE_OK ){
202739 int iCode; /* non-ASCII codepoint read from input */
202740 char *zOut = aFold;
202741 int is;
202742 int ie;
202744 /* Skip any separator characters. */
202745 while( 1 ){
202746 if( zCsr>=zTerm ) goto tokenize_done;
202747 if( *zCsr & 0x80 ) {
202748 /* A character outside of the ascii range. Skip past it if it is
202749 ** a separator character. Or break out of the loop if it is not. */
202750 is = zCsr - (unsigned char*)pText;
202751 READ_UTF8(zCsr, zTerm, iCode);
202752 if( fts5UnicodeIsAlnum(p, iCode) ){
202753 goto non_ascii_tokenchar;
202755 }else{
202756 if( a[*zCsr] ){
202757 is = zCsr - (unsigned char*)pText;
202758 goto ascii_tokenchar;
202760 zCsr++;
202764 /* Run through the tokenchars. Fold them into the output buffer along
202765 ** the way. */
202766 while( zCsr<zTerm ){
202768 /* Grow the output buffer so that there is sufficient space to fit the
202769 ** largest possible utf-8 character. */
202770 if( zOut>pEnd ){
202771 aFold = sqlite3_malloc(nFold*2);
202772 if( aFold==0 ){
202773 rc = SQLITE_NOMEM;
202774 goto tokenize_done;
202776 zOut = &aFold[zOut - p->aFold];
202777 memcpy(aFold, p->aFold, nFold);
202778 sqlite3_free(p->aFold);
202779 p->aFold = aFold;
202780 p->nFold = nFold = nFold*2;
202781 pEnd = &aFold[nFold-6];
202784 if( *zCsr & 0x80 ){
202785 /* An non-ascii-range character. Fold it into the output buffer if
202786 ** it is a token character, or break out of the loop if it is not. */
202787 READ_UTF8(zCsr, zTerm, iCode);
202788 if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
202789 non_ascii_tokenchar:
202790 iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
202791 if( iCode ) WRITE_UTF8(zOut, iCode);
202792 }else{
202793 break;
202795 }else if( a[*zCsr]==0 ){
202796 /* An ascii-range separator character. End of token. */
202797 break;
202798 }else{
202799 ascii_tokenchar:
202800 if( *zCsr>='A' && *zCsr<='Z' ){
202801 *zOut++ = *zCsr + 32;
202802 }else{
202803 *zOut++ = *zCsr;
202805 zCsr++;
202807 ie = zCsr - (unsigned char*)pText;
202810 /* Invoke the token callback */
202811 rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
202814 tokenize_done:
202815 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
202816 return rc;
202819 /**************************************************************************
202820 ** Start of porter stemmer implementation.
202823 /* Any tokens larger than this (in bytes) are passed through without
202824 ** stemming. */
202825 #define FTS5_PORTER_MAX_TOKEN 64
202827 typedef struct PorterTokenizer PorterTokenizer;
202828 struct PorterTokenizer {
202829 fts5_tokenizer tokenizer; /* Parent tokenizer module */
202830 Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
202831 char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
202835 ** Delete a "porter" tokenizer.
202837 static void fts5PorterDelete(Fts5Tokenizer *pTok){
202838 if( pTok ){
202839 PorterTokenizer *p = (PorterTokenizer*)pTok;
202840 if( p->pTokenizer ){
202841 p->tokenizer.xDelete(p->pTokenizer);
202843 sqlite3_free(p);
202848 ** Create a "porter" tokenizer.
202850 static int fts5PorterCreate(
202851 void *pCtx,
202852 const char **azArg, int nArg,
202853 Fts5Tokenizer **ppOut
202855 fts5_api *pApi = (fts5_api*)pCtx;
202856 int rc = SQLITE_OK;
202857 PorterTokenizer *pRet;
202858 void *pUserdata = 0;
202859 const char *zBase = "unicode61";
202861 if( nArg>0 ){
202862 zBase = azArg[0];
202865 pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
202866 if( pRet ){
202867 memset(pRet, 0, sizeof(PorterTokenizer));
202868 rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
202869 }else{
202870 rc = SQLITE_NOMEM;
202872 if( rc==SQLITE_OK ){
202873 int nArg2 = (nArg>0 ? nArg-1 : 0);
202874 const char **azArg2 = (nArg2 ? &azArg[1] : 0);
202875 rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
202878 if( rc!=SQLITE_OK ){
202879 fts5PorterDelete((Fts5Tokenizer*)pRet);
202880 pRet = 0;
202882 *ppOut = (Fts5Tokenizer*)pRet;
202883 return rc;
202886 typedef struct PorterContext PorterContext;
202887 struct PorterContext {
202888 void *pCtx;
202889 int (*xToken)(void*, int, const char*, int, int, int);
202890 char *aBuf;
202893 typedef struct PorterRule PorterRule;
202894 struct PorterRule {
202895 const char *zSuffix;
202896 int nSuffix;
202897 int (*xCond)(char *zStem, int nStem);
202898 const char *zOutput;
202899 int nOutput;
202902 #if 0
202903 static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
202904 int ret = -1;
202905 int nBuf = *pnBuf;
202906 PorterRule *p;
202908 for(p=aRule; p->zSuffix; p++){
202909 assert( strlen(p->zSuffix)==p->nSuffix );
202910 assert( strlen(p->zOutput)==p->nOutput );
202911 if( nBuf<p->nSuffix ) continue;
202912 if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
202915 if( p->zSuffix ){
202916 int nStem = nBuf - p->nSuffix;
202917 if( p->xCond==0 || p->xCond(aBuf, nStem) ){
202918 memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
202919 *pnBuf = nStem + p->nOutput;
202920 ret = p - aRule;
202924 return ret;
202926 #endif
202928 static int fts5PorterIsVowel(char c, int bYIsVowel){
202929 return (
202930 c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
202934 static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
202935 int i;
202936 int bCons = bPrevCons;
202938 /* Scan for a vowel */
202939 for(i=0; i<nStem; i++){
202940 if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
202943 /* Scan for a consonent */
202944 for(i++; i<nStem; i++){
202945 if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
202947 return 0;
202950 /* porter rule condition: (m > 0) */
202951 static int fts5Porter_MGt0(char *zStem, int nStem){
202952 return !!fts5PorterGobbleVC(zStem, nStem, 0);
202955 /* porter rule condition: (m > 1) */
202956 static int fts5Porter_MGt1(char *zStem, int nStem){
202957 int n;
202958 n = fts5PorterGobbleVC(zStem, nStem, 0);
202959 if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
202960 return 1;
202962 return 0;
202965 /* porter rule condition: (m = 1) */
202966 static int fts5Porter_MEq1(char *zStem, int nStem){
202967 int n;
202968 n = fts5PorterGobbleVC(zStem, nStem, 0);
202969 if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
202970 return 1;
202972 return 0;
202975 /* porter rule condition: (*o) */
202976 static int fts5Porter_Ostar(char *zStem, int nStem){
202977 if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
202978 return 0;
202979 }else{
202980 int i;
202981 int mask = 0;
202982 int bCons = 0;
202983 for(i=0; i<nStem; i++){
202984 bCons = !fts5PorterIsVowel(zStem[i], bCons);
202985 assert( bCons==0 || bCons==1 );
202986 mask = (mask << 1) + bCons;
202988 return ((mask & 0x0007)==0x0005);
202992 /* porter rule condition: (m > 1 and (*S or *T)) */
202993 static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
202994 assert( nStem>0 );
202995 return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
202996 && fts5Porter_MGt1(zStem, nStem);
202999 /* porter rule condition: (*v*) */
203000 static int fts5Porter_Vowel(char *zStem, int nStem){
203001 int i;
203002 for(i=0; i<nStem; i++){
203003 if( fts5PorterIsVowel(zStem[i], i>0) ){
203004 return 1;
203007 return 0;
203011 /**************************************************************************
203012 ***************************************************************************
203013 ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
203016 static int fts5PorterStep4(char *aBuf, int *pnBuf){
203017 int ret = 0;
203018 int nBuf = *pnBuf;
203019 switch( aBuf[nBuf-2] ){
203021 case 'a':
203022 if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
203023 if( fts5Porter_MGt1(aBuf, nBuf-2) ){
203024 *pnBuf = nBuf - 2;
203027 break;
203029 case 'c':
203030 if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
203031 if( fts5Porter_MGt1(aBuf, nBuf-4) ){
203032 *pnBuf = nBuf - 4;
203034 }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
203035 if( fts5Porter_MGt1(aBuf, nBuf-4) ){
203036 *pnBuf = nBuf - 4;
203039 break;
203041 case 'e':
203042 if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
203043 if( fts5Porter_MGt1(aBuf, nBuf-2) ){
203044 *pnBuf = nBuf - 2;
203047 break;
203049 case 'i':
203050 if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
203051 if( fts5Porter_MGt1(aBuf, nBuf-2) ){
203052 *pnBuf = nBuf - 2;
203055 break;
203057 case 'l':
203058 if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
203059 if( fts5Porter_MGt1(aBuf, nBuf-4) ){
203060 *pnBuf = nBuf - 4;
203062 }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
203063 if( fts5Porter_MGt1(aBuf, nBuf-4) ){
203064 *pnBuf = nBuf - 4;
203067 break;
203069 case 'n':
203070 if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
203071 if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203072 *pnBuf = nBuf - 3;
203074 }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
203075 if( fts5Porter_MGt1(aBuf, nBuf-5) ){
203076 *pnBuf = nBuf - 5;
203078 }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
203079 if( fts5Porter_MGt1(aBuf, nBuf-4) ){
203080 *pnBuf = nBuf - 4;
203082 }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
203083 if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203084 *pnBuf = nBuf - 3;
203087 break;
203089 case 'o':
203090 if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
203091 if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
203092 *pnBuf = nBuf - 3;
203094 }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
203095 if( fts5Porter_MGt1(aBuf, nBuf-2) ){
203096 *pnBuf = nBuf - 2;
203099 break;
203101 case 's':
203102 if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
203103 if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203104 *pnBuf = nBuf - 3;
203107 break;
203109 case 't':
203110 if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
203111 if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203112 *pnBuf = nBuf - 3;
203114 }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
203115 if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203116 *pnBuf = nBuf - 3;
203119 break;
203121 case 'u':
203122 if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
203123 if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203124 *pnBuf = nBuf - 3;
203127 break;
203129 case 'v':
203130 if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
203131 if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203132 *pnBuf = nBuf - 3;
203135 break;
203137 case 'z':
203138 if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
203139 if( fts5Porter_MGt1(aBuf, nBuf-3) ){
203140 *pnBuf = nBuf - 3;
203143 break;
203146 return ret;
203150 static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
203151 int ret = 0;
203152 int nBuf = *pnBuf;
203153 switch( aBuf[nBuf-2] ){
203155 case 'a':
203156 if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
203157 memcpy(&aBuf[nBuf-2], "ate", 3);
203158 *pnBuf = nBuf - 2 + 3;
203159 ret = 1;
203161 break;
203163 case 'b':
203164 if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
203165 memcpy(&aBuf[nBuf-2], "ble", 3);
203166 *pnBuf = nBuf - 2 + 3;
203167 ret = 1;
203169 break;
203171 case 'i':
203172 if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
203173 memcpy(&aBuf[nBuf-2], "ize", 3);
203174 *pnBuf = nBuf - 2 + 3;
203175 ret = 1;
203177 break;
203180 return ret;
203184 static int fts5PorterStep2(char *aBuf, int *pnBuf){
203185 int ret = 0;
203186 int nBuf = *pnBuf;
203187 switch( aBuf[nBuf-2] ){
203189 case 'a':
203190 if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
203191 if( fts5Porter_MGt0(aBuf, nBuf-7) ){
203192 memcpy(&aBuf[nBuf-7], "ate", 3);
203193 *pnBuf = nBuf - 7 + 3;
203195 }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
203196 if( fts5Porter_MGt0(aBuf, nBuf-6) ){
203197 memcpy(&aBuf[nBuf-6], "tion", 4);
203198 *pnBuf = nBuf - 6 + 4;
203201 break;
203203 case 'c':
203204 if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
203205 if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203206 memcpy(&aBuf[nBuf-4], "ence", 4);
203207 *pnBuf = nBuf - 4 + 4;
203209 }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
203210 if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203211 memcpy(&aBuf[nBuf-4], "ance", 4);
203212 *pnBuf = nBuf - 4 + 4;
203215 break;
203217 case 'e':
203218 if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
203219 if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203220 memcpy(&aBuf[nBuf-4], "ize", 3);
203221 *pnBuf = nBuf - 4 + 3;
203224 break;
203226 case 'g':
203227 if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
203228 if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203229 memcpy(&aBuf[nBuf-4], "log", 3);
203230 *pnBuf = nBuf - 4 + 3;
203233 break;
203235 case 'l':
203236 if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
203237 if( fts5Porter_MGt0(aBuf, nBuf-3) ){
203238 memcpy(&aBuf[nBuf-3], "ble", 3);
203239 *pnBuf = nBuf - 3 + 3;
203241 }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
203242 if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203243 memcpy(&aBuf[nBuf-4], "al", 2);
203244 *pnBuf = nBuf - 4 + 2;
203246 }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
203247 if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203248 memcpy(&aBuf[nBuf-5], "ent", 3);
203249 *pnBuf = nBuf - 5 + 3;
203251 }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
203252 if( fts5Porter_MGt0(aBuf, nBuf-3) ){
203253 memcpy(&aBuf[nBuf-3], "e", 1);
203254 *pnBuf = nBuf - 3 + 1;
203256 }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
203257 if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203258 memcpy(&aBuf[nBuf-5], "ous", 3);
203259 *pnBuf = nBuf - 5 + 3;
203262 break;
203264 case 'o':
203265 if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
203266 if( fts5Porter_MGt0(aBuf, nBuf-7) ){
203267 memcpy(&aBuf[nBuf-7], "ize", 3);
203268 *pnBuf = nBuf - 7 + 3;
203270 }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
203271 if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203272 memcpy(&aBuf[nBuf-5], "ate", 3);
203273 *pnBuf = nBuf - 5 + 3;
203275 }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
203276 if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203277 memcpy(&aBuf[nBuf-4], "ate", 3);
203278 *pnBuf = nBuf - 4 + 3;
203281 break;
203283 case 's':
203284 if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
203285 if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203286 memcpy(&aBuf[nBuf-5], "al", 2);
203287 *pnBuf = nBuf - 5 + 2;
203289 }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
203290 if( fts5Porter_MGt0(aBuf, nBuf-7) ){
203291 memcpy(&aBuf[nBuf-7], "ive", 3);
203292 *pnBuf = nBuf - 7 + 3;
203294 }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
203295 if( fts5Porter_MGt0(aBuf, nBuf-7) ){
203296 memcpy(&aBuf[nBuf-7], "ful", 3);
203297 *pnBuf = nBuf - 7 + 3;
203299 }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
203300 if( fts5Porter_MGt0(aBuf, nBuf-7) ){
203301 memcpy(&aBuf[nBuf-7], "ous", 3);
203302 *pnBuf = nBuf - 7 + 3;
203305 break;
203307 case 't':
203308 if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
203309 if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203310 memcpy(&aBuf[nBuf-5], "al", 2);
203311 *pnBuf = nBuf - 5 + 2;
203313 }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
203314 if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203315 memcpy(&aBuf[nBuf-5], "ive", 3);
203316 *pnBuf = nBuf - 5 + 3;
203318 }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
203319 if( fts5Porter_MGt0(aBuf, nBuf-6) ){
203320 memcpy(&aBuf[nBuf-6], "ble", 3);
203321 *pnBuf = nBuf - 6 + 3;
203324 break;
203327 return ret;
203331 static int fts5PorterStep3(char *aBuf, int *pnBuf){
203332 int ret = 0;
203333 int nBuf = *pnBuf;
203334 switch( aBuf[nBuf-2] ){
203336 case 'a':
203337 if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
203338 if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203339 memcpy(&aBuf[nBuf-4], "ic", 2);
203340 *pnBuf = nBuf - 4 + 2;
203343 break;
203345 case 's':
203346 if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
203347 if( fts5Porter_MGt0(aBuf, nBuf-4) ){
203348 *pnBuf = nBuf - 4;
203351 break;
203353 case 't':
203354 if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
203355 if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203356 memcpy(&aBuf[nBuf-5], "ic", 2);
203357 *pnBuf = nBuf - 5 + 2;
203359 }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
203360 if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203361 memcpy(&aBuf[nBuf-5], "ic", 2);
203362 *pnBuf = nBuf - 5 + 2;
203365 break;
203367 case 'u':
203368 if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
203369 if( fts5Porter_MGt0(aBuf, nBuf-3) ){
203370 *pnBuf = nBuf - 3;
203373 break;
203375 case 'v':
203376 if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
203377 if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203378 *pnBuf = nBuf - 5;
203381 break;
203383 case 'z':
203384 if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
203385 if( fts5Porter_MGt0(aBuf, nBuf-5) ){
203386 memcpy(&aBuf[nBuf-5], "al", 2);
203387 *pnBuf = nBuf - 5 + 2;
203390 break;
203393 return ret;
203397 static int fts5PorterStep1B(char *aBuf, int *pnBuf){
203398 int ret = 0;
203399 int nBuf = *pnBuf;
203400 switch( aBuf[nBuf-2] ){
203402 case 'e':
203403 if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
203404 if( fts5Porter_MGt0(aBuf, nBuf-3) ){
203405 memcpy(&aBuf[nBuf-3], "ee", 2);
203406 *pnBuf = nBuf - 3 + 2;
203408 }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
203409 if( fts5Porter_Vowel(aBuf, nBuf-2) ){
203410 *pnBuf = nBuf - 2;
203411 ret = 1;
203414 break;
203416 case 'n':
203417 if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
203418 if( fts5Porter_Vowel(aBuf, nBuf-3) ){
203419 *pnBuf = nBuf - 3;
203420 ret = 1;
203423 break;
203426 return ret;
203430 ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
203431 ***************************************************************************
203432 **************************************************************************/
203434 static void fts5PorterStep1A(char *aBuf, int *pnBuf){
203435 int nBuf = *pnBuf;
203436 if( aBuf[nBuf-1]=='s' ){
203437 if( aBuf[nBuf-2]=='e' ){
203438 if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
203439 || (nBuf>3 && aBuf[nBuf-3]=='i' )
203441 *pnBuf = nBuf-2;
203442 }else{
203443 *pnBuf = nBuf-1;
203446 else if( aBuf[nBuf-2]!='s' ){
203447 *pnBuf = nBuf-1;
203452 static int fts5PorterCb(
203453 void *pCtx,
203454 int tflags,
203455 const char *pToken,
203456 int nToken,
203457 int iStart,
203458 int iEnd
203460 PorterContext *p = (PorterContext*)pCtx;
203462 char *aBuf;
203463 int nBuf;
203465 if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
203466 aBuf = p->aBuf;
203467 nBuf = nToken;
203468 memcpy(aBuf, pToken, nBuf);
203470 /* Step 1. */
203471 fts5PorterStep1A(aBuf, &nBuf);
203472 if( fts5PorterStep1B(aBuf, &nBuf) ){
203473 if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
203474 char c = aBuf[nBuf-1];
203475 if( fts5PorterIsVowel(c, 0)==0
203476 && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
203478 nBuf--;
203479 }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
203480 aBuf[nBuf++] = 'e';
203485 /* Step 1C. */
203486 if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
203487 aBuf[nBuf-1] = 'i';
203490 /* Steps 2 through 4. */
203491 fts5PorterStep2(aBuf, &nBuf);
203492 fts5PorterStep3(aBuf, &nBuf);
203493 fts5PorterStep4(aBuf, &nBuf);
203495 /* Step 5a. */
203496 assert( nBuf>0 );
203497 if( aBuf[nBuf-1]=='e' ){
203498 if( fts5Porter_MGt1(aBuf, nBuf-1)
203499 || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
203501 nBuf--;
203505 /* Step 5b. */
203506 if( nBuf>1 && aBuf[nBuf-1]=='l'
203507 && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
203509 nBuf--;
203512 return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
203514 pass_through:
203515 return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
203519 ** Tokenize using the porter tokenizer.
203521 static int fts5PorterTokenize(
203522 Fts5Tokenizer *pTokenizer,
203523 void *pCtx,
203524 int flags,
203525 const char *pText, int nText,
203526 int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
203528 PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
203529 PorterContext sCtx;
203530 sCtx.xToken = xToken;
203531 sCtx.pCtx = pCtx;
203532 sCtx.aBuf = p->aBuf;
203533 return p->tokenizer.xTokenize(
203534 p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
203539 ** Register all built-in tokenizers with FTS5.
203541 static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
203542 struct BuiltinTokenizer {
203543 const char *zName;
203544 fts5_tokenizer x;
203545 } aBuiltin[] = {
203546 { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
203547 { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
203548 { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
203551 int rc = SQLITE_OK; /* Return code */
203552 int i; /* To iterate through builtin functions */
203554 for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
203555 rc = pApi->xCreateTokenizer(pApi,
203556 aBuiltin[i].zName,
203557 (void*)pApi,
203558 &aBuiltin[i].x,
203563 return rc;
203569 ** 2012 May 25
203571 ** The author disclaims copyright to this source code. In place of
203572 ** a legal notice, here is a blessing:
203574 ** May you do good and not evil.
203575 ** May you find forgiveness for yourself and forgive others.
203576 ** May you share freely, never taking more than you give.
203578 ******************************************************************************
203582 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
203586 /* #include <assert.h> */
203589 ** Return true if the argument corresponds to a unicode codepoint
203590 ** classified as either a letter or a number. Otherwise false.
203592 ** The results are undefined if the value passed to this function
203593 ** is less than zero.
203595 static int sqlite3Fts5UnicodeIsalnum(int c){
203596 /* Each unsigned integer in the following array corresponds to a contiguous
203597 ** range of unicode codepoints that are not either letters or numbers (i.e.
203598 ** codepoints for which this function should return 0).
203600 ** The most significant 22 bits in each 32-bit value contain the first
203601 ** codepoint in the range. The least significant 10 bits are used to store
203602 ** the size of the range (always at least 1). In other words, the value
203603 ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
203604 ** C. It is not possible to represent a range larger than 1023 codepoints
203605 ** using this format.
203607 static const unsigned int aEntry[] = {
203608 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
203609 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
203610 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
203611 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
203612 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
203613 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
203614 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
203615 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
203616 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
203617 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
203618 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
203619 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
203620 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
203621 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
203622 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
203623 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
203624 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
203625 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
203626 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
203627 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
203628 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
203629 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
203630 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
203631 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
203632 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
203633 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
203634 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
203635 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
203636 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
203637 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
203638 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
203639 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
203640 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
203641 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
203642 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
203643 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
203644 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
203645 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
203646 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
203647 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
203648 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
203649 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
203650 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
203651 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
203652 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
203653 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
203654 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
203655 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
203656 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
203657 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
203658 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
203659 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
203660 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
203661 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
203662 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
203663 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
203664 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
203665 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
203666 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
203667 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
203668 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
203669 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
203670 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
203671 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
203672 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
203673 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
203674 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
203675 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
203676 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
203677 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
203678 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
203679 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
203680 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
203681 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
203682 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
203683 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
203684 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
203685 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
203686 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
203687 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
203688 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
203689 0x380400F0,
203691 static const unsigned int aAscii[4] = {
203692 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
203695 if( (unsigned int)c<128 ){
203696 return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
203697 }else if( (unsigned int)c<(1<<22) ){
203698 unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
203699 int iRes = 0;
203700 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
203701 int iLo = 0;
203702 while( iHi>=iLo ){
203703 int iTest = (iHi + iLo) / 2;
203704 if( key >= aEntry[iTest] ){
203705 iRes = iTest;
203706 iLo = iTest+1;
203707 }else{
203708 iHi = iTest-1;
203711 assert( aEntry[0]<key );
203712 assert( key>=aEntry[iRes] );
203713 return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
203715 return 1;
203720 ** If the argument is a codepoint corresponding to a lowercase letter
203721 ** in the ASCII range with a diacritic added, return the codepoint
203722 ** of the ASCII letter only. For example, if passed 235 - "LATIN
203723 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
203724 ** E"). The resuls of passing a codepoint that corresponds to an
203725 ** uppercase letter are undefined.
203727 static int fts5_remove_diacritic(int c){
203728 unsigned short aDia[] = {
203729 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
203730 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
203731 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
203732 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
203733 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
203734 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
203735 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
203736 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
203737 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
203738 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
203739 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
203740 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
203741 62924, 63050, 63082, 63274, 63390,
203743 char aChar[] = {
203744 '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
203745 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
203746 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
203747 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
203748 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
203749 '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
203750 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
203751 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
203752 'e', 'i', 'o', 'u', 'y',
203755 unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
203756 int iRes = 0;
203757 int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
203758 int iLo = 0;
203759 while( iHi>=iLo ){
203760 int iTest = (iHi + iLo) / 2;
203761 if( key >= aDia[iTest] ){
203762 iRes = iTest;
203763 iLo = iTest+1;
203764 }else{
203765 iHi = iTest-1;
203768 assert( key>=aDia[iRes] );
203769 return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
203774 ** Return true if the argument interpreted as a unicode codepoint
203775 ** is a diacritical modifier character.
203777 static int sqlite3Fts5UnicodeIsdiacritic(int c){
203778 unsigned int mask0 = 0x08029FDF;
203779 unsigned int mask1 = 0x000361F8;
203780 if( c<768 || c>817 ) return 0;
203781 return (c < 768+32) ?
203782 (mask0 & (1 << (c-768))) :
203783 (mask1 & (1 << (c-768-32)));
203788 ** Interpret the argument as a unicode codepoint. If the codepoint
203789 ** is an upper case character that has a lower case equivalent,
203790 ** return the codepoint corresponding to the lower case version.
203791 ** Otherwise, return a copy of the argument.
203793 ** The results are undefined if the value passed to this function
203794 ** is less than zero.
203796 static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
203797 /* Each entry in the following array defines a rule for folding a range
203798 ** of codepoints to lower case. The rule applies to a range of nRange
203799 ** codepoints starting at codepoint iCode.
203801 ** If the least significant bit in flags is clear, then the rule applies
203802 ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
203803 ** need to be folded). Or, if it is set, then the rule only applies to
203804 ** every second codepoint in the range, starting with codepoint C.
203806 ** The 7 most significant bits in flags are an index into the aiOff[]
203807 ** array. If a specific codepoint C does require folding, then its lower
203808 ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
203810 ** The contents of this array are generated by parsing the CaseFolding.txt
203811 ** file distributed as part of the "Unicode Character Database". See
203812 ** http://www.unicode.org for details.
203814 static const struct TableEntry {
203815 unsigned short iCode;
203816 unsigned char flags;
203817 unsigned char nRange;
203818 } aEntry[] = {
203819 {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
203820 {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
203821 {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
203822 {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
203823 {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
203824 {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
203825 {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
203826 {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
203827 {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
203828 {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
203829 {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
203830 {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
203831 {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
203832 {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
203833 {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
203834 {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
203835 {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
203836 {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
203837 {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
203838 {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
203839 {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
203840 {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
203841 {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
203842 {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
203843 {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
203844 {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
203845 {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
203846 {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
203847 {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
203848 {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
203849 {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
203850 {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
203851 {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
203852 {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
203853 {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
203854 {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
203855 {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
203856 {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
203857 {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
203858 {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
203859 {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
203860 {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
203861 {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
203862 {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
203863 {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
203864 {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
203865 {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
203866 {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
203867 {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
203868 {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
203869 {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
203870 {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
203871 {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
203872 {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
203873 {65313, 14, 26},
203875 static const unsigned short aiOff[] = {
203876 1, 2, 8, 15, 16, 26, 28, 32,
203877 37, 38, 40, 48, 63, 64, 69, 71,
203878 79, 80, 116, 202, 203, 205, 206, 207,
203879 209, 210, 211, 213, 214, 217, 218, 219,
203880 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
203881 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
203882 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
203883 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
203884 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
203885 65514, 65521, 65527, 65528, 65529,
203888 int ret = c;
203890 assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
203892 if( c<128 ){
203893 if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
203894 }else if( c<65536 ){
203895 const struct TableEntry *p;
203896 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
203897 int iLo = 0;
203898 int iRes = -1;
203900 assert( c>aEntry[0].iCode );
203901 while( iHi>=iLo ){
203902 int iTest = (iHi + iLo) / 2;
203903 int cmp = (c - aEntry[iTest].iCode);
203904 if( cmp>=0 ){
203905 iRes = iTest;
203906 iLo = iTest+1;
203907 }else{
203908 iHi = iTest-1;
203912 assert( iRes>=0 && c>=aEntry[iRes].iCode );
203913 p = &aEntry[iRes];
203914 if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
203915 ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
203916 assert( ret>0 );
203919 if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
203922 else if( c>=66560 && c<66600 ){
203923 ret = c + 40;
203926 return ret;
203930 ** 2015 May 30
203932 ** The author disclaims copyright to this source code. In place of
203933 ** a legal notice, here is a blessing:
203935 ** May you do good and not evil.
203936 ** May you find forgiveness for yourself and forgive others.
203937 ** May you share freely, never taking more than you give.
203939 ******************************************************************************
203941 ** Routines for varint serialization and deserialization.
203945 /* #include "fts5Int.h" */
203948 ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
203949 ** Except, this version does handle the single byte case that the core
203950 ** version depends on being handled before its function is called.
203952 static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
203953 u32 a,b;
203955 /* The 1-byte case. Overwhelmingly the most common. */
203956 a = *p;
203957 /* a: p0 (unmasked) */
203958 if (!(a&0x80))
203960 /* Values between 0 and 127 */
203961 *v = a;
203962 return 1;
203965 /* The 2-byte case */
203967 b = *p;
203968 /* b: p1 (unmasked) */
203969 if (!(b&0x80))
203971 /* Values between 128 and 16383 */
203972 a &= 0x7f;
203973 a = a<<7;
203974 *v = a | b;
203975 return 2;
203978 /* The 3-byte case */
203980 a = a<<14;
203981 a |= *p;
203982 /* a: p0<<14 | p2 (unmasked) */
203983 if (!(a&0x80))
203985 /* Values between 16384 and 2097151 */
203986 a &= (0x7f<<14)|(0x7f);
203987 b &= 0x7f;
203988 b = b<<7;
203989 *v = a | b;
203990 return 3;
203993 /* A 32-bit varint is used to store size information in btrees.
203994 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
203995 ** A 3-byte varint is sufficient, for example, to record the size
203996 ** of a 1048569-byte BLOB or string.
203998 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
203999 ** rare larger cases can be handled by the slower 64-bit varint
204000 ** routine.
204003 u64 v64;
204004 u8 n;
204005 p -= 2;
204006 n = sqlite3Fts5GetVarint(p, &v64);
204007 *v = (u32)v64;
204008 assert( n>3 && n<=9 );
204009 return n;
204015 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
204016 ** are defined here rather than simply putting the constant expressions
204017 ** inline in order to work around bugs in the RVT compiler.
204019 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
204021 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
204023 #define SLOT_2_0 0x001fc07f
204024 #define SLOT_4_2_0 0xf01fc07f
204027 ** Read a 64-bit variable-length integer from memory starting at p[0].
204028 ** Return the number of bytes read. The value is stored in *v.
204030 static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
204031 u32 a,b,s;
204033 a = *p;
204034 /* a: p0 (unmasked) */
204035 if (!(a&0x80))
204037 *v = a;
204038 return 1;
204042 b = *p;
204043 /* b: p1 (unmasked) */
204044 if (!(b&0x80))
204046 a &= 0x7f;
204047 a = a<<7;
204048 a |= b;
204049 *v = a;
204050 return 2;
204053 /* Verify that constants are precomputed correctly */
204054 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
204055 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
204058 a = a<<14;
204059 a |= *p;
204060 /* a: p0<<14 | p2 (unmasked) */
204061 if (!(a&0x80))
204063 a &= SLOT_2_0;
204064 b &= 0x7f;
204065 b = b<<7;
204066 a |= b;
204067 *v = a;
204068 return 3;
204071 /* CSE1 from below */
204072 a &= SLOT_2_0;
204074 b = b<<14;
204075 b |= *p;
204076 /* b: p1<<14 | p3 (unmasked) */
204077 if (!(b&0x80))
204079 b &= SLOT_2_0;
204080 /* moved CSE1 up */
204081 /* a &= (0x7f<<14)|(0x7f); */
204082 a = a<<7;
204083 a |= b;
204084 *v = a;
204085 return 4;
204088 /* a: p0<<14 | p2 (masked) */
204089 /* b: p1<<14 | p3 (unmasked) */
204090 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
204091 /* moved CSE1 up */
204092 /* a &= (0x7f<<14)|(0x7f); */
204093 b &= SLOT_2_0;
204094 s = a;
204095 /* s: p0<<14 | p2 (masked) */
204098 a = a<<14;
204099 a |= *p;
204100 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
204101 if (!(a&0x80))
204103 /* we can skip these cause they were (effectively) done above in calc'ing s */
204104 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
204105 /* b &= (0x7f<<14)|(0x7f); */
204106 b = b<<7;
204107 a |= b;
204108 s = s>>18;
204109 *v = ((u64)s)<<32 | a;
204110 return 5;
204113 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
204114 s = s<<7;
204115 s |= b;
204116 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
204119 b = b<<14;
204120 b |= *p;
204121 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
204122 if (!(b&0x80))
204124 /* we can skip this cause it was (effectively) done above in calc'ing s */
204125 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
204126 a &= SLOT_2_0;
204127 a = a<<7;
204128 a |= b;
204129 s = s>>18;
204130 *v = ((u64)s)<<32 | a;
204131 return 6;
204135 a = a<<14;
204136 a |= *p;
204137 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
204138 if (!(a&0x80))
204140 a &= SLOT_4_2_0;
204141 b &= SLOT_2_0;
204142 b = b<<7;
204143 a |= b;
204144 s = s>>11;
204145 *v = ((u64)s)<<32 | a;
204146 return 7;
204149 /* CSE2 from below */
204150 a &= SLOT_2_0;
204152 b = b<<14;
204153 b |= *p;
204154 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
204155 if (!(b&0x80))
204157 b &= SLOT_4_2_0;
204158 /* moved CSE2 up */
204159 /* a &= (0x7f<<14)|(0x7f); */
204160 a = a<<7;
204161 a |= b;
204162 s = s>>4;
204163 *v = ((u64)s)<<32 | a;
204164 return 8;
204168 a = a<<15;
204169 a |= *p;
204170 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
204172 /* moved CSE2 up */
204173 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
204174 b &= SLOT_2_0;
204175 b = b<<8;
204176 a |= b;
204178 s = s<<4;
204179 b = p[-4];
204180 b &= 0x7f;
204181 b = b>>3;
204182 s |= b;
204184 *v = ((u64)s)<<32 | a;
204186 return 9;
204190 ** The variable-length integer encoding is as follows:
204192 ** KEY:
204193 ** A = 0xxxxxxx 7 bits of data and one flag bit
204194 ** B = 1xxxxxxx 7 bits of data and one flag bit
204195 ** C = xxxxxxxx 8 bits of data
204197 ** 7 bits - A
204198 ** 14 bits - BA
204199 ** 21 bits - BBA
204200 ** 28 bits - BBBA
204201 ** 35 bits - BBBBA
204202 ** 42 bits - BBBBBA
204203 ** 49 bits - BBBBBBA
204204 ** 56 bits - BBBBBBBA
204205 ** 64 bits - BBBBBBBBC
204208 #ifdef SQLITE_NOINLINE
204209 # define FTS5_NOINLINE SQLITE_NOINLINE
204210 #else
204211 # define FTS5_NOINLINE
204212 #endif
204215 ** Write a 64-bit variable-length integer to memory starting at p[0].
204216 ** The length of data write will be between 1 and 9 bytes. The number
204217 ** of bytes written is returned.
204219 ** A variable-length integer consists of the lower 7 bits of each byte
204220 ** for all bytes that have the 8th bit set and one byte with the 8th
204221 ** bit clear. Except, if we get to the 9th byte, it stores the full
204222 ** 8 bits and is the last byte.
204224 static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
204225 int i, j, n;
204226 u8 buf[10];
204227 if( v & (((u64)0xff000000)<<32) ){
204228 p[8] = (u8)v;
204229 v >>= 8;
204230 for(i=7; i>=0; i--){
204231 p[i] = (u8)((v & 0x7f) | 0x80);
204232 v >>= 7;
204234 return 9;
204236 n = 0;
204238 buf[n++] = (u8)((v & 0x7f) | 0x80);
204239 v >>= 7;
204240 }while( v!=0 );
204241 buf[0] &= 0x7f;
204242 assert( n<=9 );
204243 for(i=0, j=n-1; j>=0; j--, i++){
204244 p[i] = buf[j];
204246 return n;
204249 static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
204250 if( v<=0x7f ){
204251 p[0] = v&0x7f;
204252 return 1;
204254 if( v<=0x3fff ){
204255 p[0] = ((v>>7)&0x7f)|0x80;
204256 p[1] = v&0x7f;
204257 return 2;
204259 return fts5PutVarint64(p,v);
204263 static int sqlite3Fts5GetVarintLen(u32 iVal){
204264 #if 0
204265 if( iVal<(1 << 7 ) ) return 1;
204266 #endif
204267 assert( iVal>=(1 << 7) );
204268 if( iVal<(1 << 14) ) return 2;
204269 if( iVal<(1 << 21) ) return 3;
204270 if( iVal<(1 << 28) ) return 4;
204271 return 5;
204276 ** 2015 May 08
204278 ** The author disclaims copyright to this source code. In place of
204279 ** a legal notice, here is a blessing:
204281 ** May you do good and not evil.
204282 ** May you find forgiveness for yourself and forgive others.
204283 ** May you share freely, never taking more than you give.
204285 ******************************************************************************
204287 ** This is an SQLite virtual table module implementing direct access to an
204288 ** existing FTS5 index. The module may create several different types of
204289 ** tables:
204291 ** col:
204292 ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
204294 ** One row for each term/column combination. The value of $doc is set to
204295 ** the number of fts5 rows that contain at least one instance of term
204296 ** $term within column $col. Field $cnt is set to the total number of
204297 ** instances of term $term in column $col (in any row of the fts5 table).
204299 ** row:
204300 ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
204302 ** One row for each term in the database. The value of $doc is set to
204303 ** the number of fts5 rows that contain at least one instance of term
204304 ** $term. Field $cnt is set to the total number of instances of term
204305 ** $term in the database.
204307 ** instance:
204308 ** CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
204310 ** One row for each term instance in the database.
204314 /* #include "fts5Int.h" */
204317 typedef struct Fts5VocabTable Fts5VocabTable;
204318 typedef struct Fts5VocabCursor Fts5VocabCursor;
204320 struct Fts5VocabTable {
204321 sqlite3_vtab base;
204322 char *zFts5Tbl; /* Name of fts5 table */
204323 char *zFts5Db; /* Db containing fts5 table */
204324 sqlite3 *db; /* Database handle */
204325 Fts5Global *pGlobal; /* FTS5 global object for this database */
204326 int eType; /* FTS5_VOCAB_COL, ROW or INSTANCE */
204329 struct Fts5VocabCursor {
204330 sqlite3_vtab_cursor base;
204331 sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
204332 Fts5Index *pIndex; /* Associated FTS5 index */
204334 int bEof; /* True if this cursor is at EOF */
204335 Fts5IndexIter *pIter; /* Term/rowid iterator object */
204337 int nLeTerm; /* Size of zLeTerm in bytes */
204338 char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
204340 /* These are used by 'col' tables only */
204341 Fts5Config *pConfig; /* Fts5 table configuration */
204342 int iCol;
204343 i64 *aCnt;
204344 i64 *aDoc;
204346 /* Output values used by all tables. */
204347 i64 rowid; /* This table's current rowid value */
204348 Fts5Buffer term; /* Current value of 'term' column */
204350 /* Output values Used by 'instance' tables only */
204351 i64 iInstPos;
204352 int iInstOff;
204355 #define FTS5_VOCAB_COL 0
204356 #define FTS5_VOCAB_ROW 1
204357 #define FTS5_VOCAB_INSTANCE 2
204359 #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
204360 #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
204361 #define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
204364 ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
204366 #define FTS5_VOCAB_TERM_EQ 0x01
204367 #define FTS5_VOCAB_TERM_GE 0x02
204368 #define FTS5_VOCAB_TERM_LE 0x04
204372 ** Translate a string containing an fts5vocab table type to an
204373 ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
204374 ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
204375 ** and return SQLITE_ERROR.
204377 static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
204378 int rc = SQLITE_OK;
204379 char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
204380 if( rc==SQLITE_OK ){
204381 sqlite3Fts5Dequote(zCopy);
204382 if( sqlite3_stricmp(zCopy, "col")==0 ){
204383 *peType = FTS5_VOCAB_COL;
204384 }else
204386 if( sqlite3_stricmp(zCopy, "row")==0 ){
204387 *peType = FTS5_VOCAB_ROW;
204388 }else
204389 if( sqlite3_stricmp(zCopy, "instance")==0 ){
204390 *peType = FTS5_VOCAB_INSTANCE;
204391 }else
204393 *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
204394 rc = SQLITE_ERROR;
204396 sqlite3_free(zCopy);
204399 return rc;
204404 ** The xDisconnect() virtual table method.
204406 static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
204407 Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
204408 sqlite3_free(pTab);
204409 return SQLITE_OK;
204413 ** The xDestroy() virtual table method.
204415 static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
204416 Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
204417 sqlite3_free(pTab);
204418 return SQLITE_OK;
204422 ** This function is the implementation of both the xConnect and xCreate
204423 ** methods of the FTS3 virtual table.
204425 ** The argv[] array contains the following:
204427 ** argv[0] -> module name ("fts5vocab")
204428 ** argv[1] -> database name
204429 ** argv[2] -> table name
204431 ** then:
204433 ** argv[3] -> name of fts5 table
204434 ** argv[4] -> type of fts5vocab table
204436 ** or, for tables in the TEMP schema only.
204438 ** argv[3] -> name of fts5 tables database
204439 ** argv[4] -> name of fts5 table
204440 ** argv[5] -> type of fts5vocab table
204442 static int fts5VocabInitVtab(
204443 sqlite3 *db, /* The SQLite database connection */
204444 void *pAux, /* Pointer to Fts5Global object */
204445 int argc, /* Number of elements in argv array */
204446 const char * const *argv, /* xCreate/xConnect argument array */
204447 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
204448 char **pzErr /* Write any error message here */
204450 const char *azSchema[] = {
204451 "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
204452 "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")",
204453 "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
204456 Fts5VocabTable *pRet = 0;
204457 int rc = SQLITE_OK; /* Return code */
204458 int bDb;
204460 bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
204462 if( argc!=5 && bDb==0 ){
204463 *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
204464 rc = SQLITE_ERROR;
204465 }else{
204466 int nByte; /* Bytes of space to allocate */
204467 const char *zDb = bDb ? argv[3] : argv[1];
204468 const char *zTab = bDb ? argv[4] : argv[3];
204469 const char *zType = bDb ? argv[5] : argv[4];
204470 int nDb = (int)strlen(zDb)+1;
204471 int nTab = (int)strlen(zTab)+1;
204472 int eType = 0;
204474 rc = fts5VocabTableType(zType, pzErr, &eType);
204475 if( rc==SQLITE_OK ){
204476 assert( eType>=0 && eType<ArraySize(azSchema) );
204477 rc = sqlite3_declare_vtab(db, azSchema[eType]);
204480 nByte = sizeof(Fts5VocabTable) + nDb + nTab;
204481 pRet = sqlite3Fts5MallocZero(&rc, nByte);
204482 if( pRet ){
204483 pRet->pGlobal = (Fts5Global*)pAux;
204484 pRet->eType = eType;
204485 pRet->db = db;
204486 pRet->zFts5Tbl = (char*)&pRet[1];
204487 pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
204488 memcpy(pRet->zFts5Tbl, zTab, nTab);
204489 memcpy(pRet->zFts5Db, zDb, nDb);
204490 sqlite3Fts5Dequote(pRet->zFts5Tbl);
204491 sqlite3Fts5Dequote(pRet->zFts5Db);
204495 *ppVTab = (sqlite3_vtab*)pRet;
204496 return rc;
204501 ** The xConnect() and xCreate() methods for the virtual table. All the
204502 ** work is done in function fts5VocabInitVtab().
204504 static int fts5VocabConnectMethod(
204505 sqlite3 *db, /* Database connection */
204506 void *pAux, /* Pointer to tokenizer hash table */
204507 int argc, /* Number of elements in argv array */
204508 const char * const *argv, /* xCreate/xConnect argument array */
204509 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
204510 char **pzErr /* OUT: sqlite3_malloc'd error message */
204512 return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
204514 static int fts5VocabCreateMethod(
204515 sqlite3 *db, /* Database connection */
204516 void *pAux, /* Pointer to tokenizer hash table */
204517 int argc, /* Number of elements in argv array */
204518 const char * const *argv, /* xCreate/xConnect argument array */
204519 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
204520 char **pzErr /* OUT: sqlite3_malloc'd error message */
204522 return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
204526 ** Implementation of the xBestIndex method.
204528 ** Only constraints of the form:
204530 ** term <= ?
204531 ** term == ?
204532 ** term >= ?
204534 ** are interpreted. Less-than and less-than-or-equal are treated
204535 ** identically, as are greater-than and greater-than-or-equal.
204537 static int fts5VocabBestIndexMethod(
204538 sqlite3_vtab *pUnused,
204539 sqlite3_index_info *pInfo
204541 int i;
204542 int iTermEq = -1;
204543 int iTermGe = -1;
204544 int iTermLe = -1;
204545 int idxNum = 0;
204546 int nArg = 0;
204548 UNUSED_PARAM(pUnused);
204550 for(i=0; i<pInfo->nConstraint; i++){
204551 struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
204552 if( p->usable==0 ) continue;
204553 if( p->iColumn==0 ){ /* term column */
204554 if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
204555 if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
204556 if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
204557 if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
204558 if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
204562 if( iTermEq>=0 ){
204563 idxNum |= FTS5_VOCAB_TERM_EQ;
204564 pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
204565 pInfo->estimatedCost = 100;
204566 }else{
204567 pInfo->estimatedCost = 1000000;
204568 if( iTermGe>=0 ){
204569 idxNum |= FTS5_VOCAB_TERM_GE;
204570 pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
204571 pInfo->estimatedCost = pInfo->estimatedCost / 2;
204573 if( iTermLe>=0 ){
204574 idxNum |= FTS5_VOCAB_TERM_LE;
204575 pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
204576 pInfo->estimatedCost = pInfo->estimatedCost / 2;
204580 /* This virtual table always delivers results in ascending order of
204581 ** the "term" column (column 0). So if the user has requested this
204582 ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
204583 ** sqlite3_index_info.orderByConsumed flag to tell the core the results
204584 ** are already in sorted order. */
204585 if( pInfo->nOrderBy==1
204586 && pInfo->aOrderBy[0].iColumn==0
204587 && pInfo->aOrderBy[0].desc==0
204589 pInfo->orderByConsumed = 1;
204592 pInfo->idxNum = idxNum;
204593 return SQLITE_OK;
204597 ** Implementation of xOpen method.
204599 static int fts5VocabOpenMethod(
204600 sqlite3_vtab *pVTab,
204601 sqlite3_vtab_cursor **ppCsr
204603 Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
204604 Fts5Index *pIndex = 0;
204605 Fts5Config *pConfig = 0;
204606 Fts5VocabCursor *pCsr = 0;
204607 int rc = SQLITE_OK;
204608 sqlite3_stmt *pStmt = 0;
204609 char *zSql = 0;
204611 zSql = sqlite3Fts5Mprintf(&rc,
204612 "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
204613 pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
204615 if( zSql ){
204616 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
204618 sqlite3_free(zSql);
204619 assert( rc==SQLITE_OK || pStmt==0 );
204620 if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
204622 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
204623 i64 iId = sqlite3_column_int64(pStmt, 0);
204624 pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
204627 if( rc==SQLITE_OK && pIndex==0 ){
204628 rc = sqlite3_finalize(pStmt);
204629 pStmt = 0;
204630 if( rc==SQLITE_OK ){
204631 pVTab->zErrMsg = sqlite3_mprintf(
204632 "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
204634 rc = SQLITE_ERROR;
204638 if( rc==SQLITE_OK ){
204639 int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
204640 pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
204643 if( pCsr ){
204644 pCsr->pIndex = pIndex;
204645 pCsr->pStmt = pStmt;
204646 pCsr->pConfig = pConfig;
204647 pCsr->aCnt = (i64*)&pCsr[1];
204648 pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
204649 }else{
204650 sqlite3_finalize(pStmt);
204653 *ppCsr = (sqlite3_vtab_cursor*)pCsr;
204654 return rc;
204657 static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
204658 pCsr->rowid = 0;
204659 sqlite3Fts5IterClose(pCsr->pIter);
204660 pCsr->pIter = 0;
204661 sqlite3_free(pCsr->zLeTerm);
204662 pCsr->nLeTerm = -1;
204663 pCsr->zLeTerm = 0;
204667 ** Close the cursor. For additional information see the documentation
204668 ** on the xClose method of the virtual table interface.
204670 static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
204671 Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204672 fts5VocabResetCursor(pCsr);
204673 sqlite3Fts5BufferFree(&pCsr->term);
204674 sqlite3_finalize(pCsr->pStmt);
204675 sqlite3_free(pCsr);
204676 return SQLITE_OK;
204679 static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
204680 int rc = SQLITE_OK;
204682 if( sqlite3Fts5IterEof(pCsr->pIter) ){
204683 pCsr->bEof = 1;
204684 }else{
204685 const char *zTerm;
204686 int nTerm;
204687 zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
204688 if( pCsr->nLeTerm>=0 ){
204689 int nCmp = MIN(nTerm, pCsr->nLeTerm);
204690 int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
204691 if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
204692 pCsr->bEof = 1;
204696 sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
204698 return rc;
204701 static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
204702 int eDetail = pCsr->pConfig->eDetail;
204703 int rc = SQLITE_OK;
204704 Fts5IndexIter *pIter = pCsr->pIter;
204705 i64 *pp = &pCsr->iInstPos;
204706 int *po = &pCsr->iInstOff;
204708 while( eDetail==FTS5_DETAIL_NONE
204709 || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
204711 pCsr->iInstPos = 0;
204712 pCsr->iInstOff = 0;
204714 rc = sqlite3Fts5IterNextScan(pCsr->pIter);
204715 if( rc==SQLITE_OK ){
204716 rc = fts5VocabInstanceNewTerm(pCsr);
204717 if( eDetail==FTS5_DETAIL_NONE ) break;
204719 if( rc ){
204720 pCsr->bEof = 1;
204721 break;
204725 return rc;
204729 ** Advance the cursor to the next row in the table.
204731 static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
204732 Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204733 Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
204734 int rc = SQLITE_OK;
204735 int nCol = pCsr->pConfig->nCol;
204737 pCsr->rowid++;
204739 if( pTab->eType==FTS5_VOCAB_INSTANCE ){
204740 return fts5VocabInstanceNext(pCsr);
204743 if( pTab->eType==FTS5_VOCAB_COL ){
204744 for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
204745 if( pCsr->aDoc[pCsr->iCol] ) break;
204749 if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
204750 if( sqlite3Fts5IterEof(pCsr->pIter) ){
204751 pCsr->bEof = 1;
204752 }else{
204753 const char *zTerm;
204754 int nTerm;
204756 zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
204757 if( pCsr->nLeTerm>=0 ){
204758 int nCmp = MIN(nTerm, pCsr->nLeTerm);
204759 int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
204760 if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
204761 pCsr->bEof = 1;
204762 return SQLITE_OK;
204766 sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
204767 memset(pCsr->aCnt, 0, nCol * sizeof(i64));
204768 memset(pCsr->aDoc, 0, nCol * sizeof(i64));
204769 pCsr->iCol = 0;
204771 assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
204772 while( rc==SQLITE_OK ){
204773 int eDetail = pCsr->pConfig->eDetail;
204774 const u8 *pPos; int nPos; /* Position list */
204775 i64 iPos = 0; /* 64-bit position read from poslist */
204776 int iOff = 0; /* Current offset within position list */
204778 pPos = pCsr->pIter->pData;
204779 nPos = pCsr->pIter->nData;
204781 switch( pTab->eType ){
204782 case FTS5_VOCAB_ROW:
204783 if( eDetail==FTS5_DETAIL_FULL ){
204784 while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
204785 pCsr->aCnt[0]++;
204788 pCsr->aDoc[0]++;
204789 break;
204791 case FTS5_VOCAB_COL:
204792 if( eDetail==FTS5_DETAIL_FULL ){
204793 int iCol = -1;
204794 while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
204795 int ii = FTS5_POS2COLUMN(iPos);
204796 pCsr->aCnt[ii]++;
204797 if( iCol!=ii ){
204798 if( ii>=nCol ){
204799 rc = FTS5_CORRUPT;
204800 break;
204802 pCsr->aDoc[ii]++;
204803 iCol = ii;
204806 }else if( eDetail==FTS5_DETAIL_COLUMNS ){
204807 while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
204808 assert_nc( iPos>=0 && iPos<nCol );
204809 if( iPos>=nCol ){
204810 rc = FTS5_CORRUPT;
204811 break;
204813 pCsr->aDoc[iPos]++;
204815 }else{
204816 assert( eDetail==FTS5_DETAIL_NONE );
204817 pCsr->aDoc[0]++;
204819 break;
204821 default:
204822 assert( pTab->eType==FTS5_VOCAB_INSTANCE );
204823 break;
204826 if( rc==SQLITE_OK ){
204827 rc = sqlite3Fts5IterNextScan(pCsr->pIter);
204829 if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
204831 if( rc==SQLITE_OK ){
204832 zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
204833 if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
204834 break;
204836 if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
204842 if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
204843 while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
204844 assert( pCsr->iCol<pCsr->pConfig->nCol );
204846 return rc;
204850 ** This is the xFilter implementation for the virtual table.
204852 static int fts5VocabFilterMethod(
204853 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
204854 int idxNum, /* Strategy index */
204855 const char *zUnused, /* Unused */
204856 int nUnused, /* Number of elements in apVal */
204857 sqlite3_value **apVal /* Arguments for the indexing scheme */
204859 Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
204860 Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204861 int eType = pTab->eType;
204862 int rc = SQLITE_OK;
204864 int iVal = 0;
204865 int f = FTS5INDEX_QUERY_SCAN;
204866 const char *zTerm = 0;
204867 int nTerm = 0;
204869 sqlite3_value *pEq = 0;
204870 sqlite3_value *pGe = 0;
204871 sqlite3_value *pLe = 0;
204873 UNUSED_PARAM2(zUnused, nUnused);
204875 fts5VocabResetCursor(pCsr);
204876 if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
204877 if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
204878 if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
204880 if( pEq ){
204881 zTerm = (const char *)sqlite3_value_text(pEq);
204882 nTerm = sqlite3_value_bytes(pEq);
204883 f = 0;
204884 }else{
204885 if( pGe ){
204886 zTerm = (const char *)sqlite3_value_text(pGe);
204887 nTerm = sqlite3_value_bytes(pGe);
204889 if( pLe ){
204890 const char *zCopy = (const char *)sqlite3_value_text(pLe);
204891 pCsr->nLeTerm = sqlite3_value_bytes(pLe);
204892 pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
204893 if( pCsr->zLeTerm==0 ){
204894 rc = SQLITE_NOMEM;
204895 }else{
204896 memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
204901 if( rc==SQLITE_OK ){
204902 rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
204904 if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
204905 rc = fts5VocabInstanceNewTerm(pCsr);
204907 if( rc==SQLITE_OK
204908 && !pCsr->bEof
204909 && (eType!=FTS5_VOCAB_INSTANCE || pCsr->pConfig->eDetail!=FTS5_DETAIL_NONE)
204911 rc = fts5VocabNextMethod(pCursor);
204914 return rc;
204918 ** This is the xEof method of the virtual table. SQLite calls this
204919 ** routine to find out if it has reached the end of a result set.
204921 static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
204922 Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204923 return pCsr->bEof;
204926 static int fts5VocabColumnMethod(
204927 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
204928 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
204929 int iCol /* Index of column to read value from */
204931 Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204932 int eDetail = pCsr->pConfig->eDetail;
204933 int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
204934 i64 iVal = 0;
204936 if( iCol==0 ){
204937 sqlite3_result_text(
204938 pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
204940 }else if( eType==FTS5_VOCAB_COL ){
204941 assert( iCol==1 || iCol==2 || iCol==3 );
204942 if( iCol==1 ){
204943 if( eDetail!=FTS5_DETAIL_NONE ){
204944 const char *z = pCsr->pConfig->azCol[pCsr->iCol];
204945 sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
204947 }else if( iCol==2 ){
204948 iVal = pCsr->aDoc[pCsr->iCol];
204949 }else{
204950 iVal = pCsr->aCnt[pCsr->iCol];
204952 }else if( eType==FTS5_VOCAB_ROW ){
204953 assert( iCol==1 || iCol==2 );
204954 if( iCol==1 ){
204955 iVal = pCsr->aDoc[0];
204956 }else{
204957 iVal = pCsr->aCnt[0];
204959 }else{
204960 assert( eType==FTS5_VOCAB_INSTANCE );
204961 switch( iCol ){
204962 case 1:
204963 sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
204964 break;
204965 case 2: {
204966 int ii = -1;
204967 if( eDetail==FTS5_DETAIL_FULL ){
204968 ii = FTS5_POS2COLUMN(pCsr->iInstPos);
204969 }else if( eDetail==FTS5_DETAIL_COLUMNS ){
204970 ii = (int)pCsr->iInstPos;
204972 if( ii>=0 && ii<pCsr->pConfig->nCol ){
204973 const char *z = pCsr->pConfig->azCol[ii];
204974 sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
204976 break;
204978 default: {
204979 assert( iCol==3 );
204980 if( eDetail==FTS5_DETAIL_FULL ){
204981 int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
204982 sqlite3_result_int(pCtx, ii);
204984 break;
204989 if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
204990 return SQLITE_OK;
204994 ** This is the xRowid method. The SQLite core calls this routine to
204995 ** retrieve the rowid for the current row of the result set. The
204996 ** rowid should be written to *pRowid.
204998 static int fts5VocabRowidMethod(
204999 sqlite3_vtab_cursor *pCursor,
205000 sqlite_int64 *pRowid
205002 Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
205003 *pRowid = pCsr->rowid;
205004 return SQLITE_OK;
205007 static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
205008 static const sqlite3_module fts5Vocab = {
205009 /* iVersion */ 2,
205010 /* xCreate */ fts5VocabCreateMethod,
205011 /* xConnect */ fts5VocabConnectMethod,
205012 /* xBestIndex */ fts5VocabBestIndexMethod,
205013 /* xDisconnect */ fts5VocabDisconnectMethod,
205014 /* xDestroy */ fts5VocabDestroyMethod,
205015 /* xOpen */ fts5VocabOpenMethod,
205016 /* xClose */ fts5VocabCloseMethod,
205017 /* xFilter */ fts5VocabFilterMethod,
205018 /* xNext */ fts5VocabNextMethod,
205019 /* xEof */ fts5VocabEofMethod,
205020 /* xColumn */ fts5VocabColumnMethod,
205021 /* xRowid */ fts5VocabRowidMethod,
205022 /* xUpdate */ 0,
205023 /* xBegin */ 0,
205024 /* xSync */ 0,
205025 /* xCommit */ 0,
205026 /* xRollback */ 0,
205027 /* xFindFunction */ 0,
205028 /* xRename */ 0,
205029 /* xSavepoint */ 0,
205030 /* xRelease */ 0,
205031 /* xRollbackTo */ 0,
205033 void *p = (void*)pGlobal;
205035 return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
205042 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
205044 /************** End of fts5.c ************************************************/
205045 /************** Begin file stmt.c ********************************************/
205047 ** 2017-05-31
205049 ** The author disclaims copyright to this source code. In place of
205050 ** a legal notice, here is a blessing:
205052 ** May you do good and not evil.
205053 ** May you find forgiveness for yourself and forgive others.
205054 ** May you share freely, never taking more than you give.
205056 *************************************************************************
205058 ** This file demonstrates an eponymous virtual table that returns information
205059 ** about all prepared statements for the database connection.
205061 ** Usage example:
205063 ** .load ./stmt
205064 ** .mode line
205065 ** .header on
205066 ** SELECT * FROM stmt;
205068 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
205069 #if !defined(SQLITEINT_H)
205070 /* #include "sqlite3ext.h" */
205071 #endif
205072 SQLITE_EXTENSION_INIT1
205073 /* #include <assert.h> */
205074 /* #include <string.h> */
205076 #ifndef SQLITE_OMIT_VIRTUALTABLE
205078 /* stmt_vtab is a subclass of sqlite3_vtab which will
205079 ** serve as the underlying representation of a stmt virtual table
205081 typedef struct stmt_vtab stmt_vtab;
205082 struct stmt_vtab {
205083 sqlite3_vtab base; /* Base class - must be first */
205084 sqlite3 *db; /* Database connection for this stmt vtab */
205087 /* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
205088 ** serve as the underlying representation of a cursor that scans
205089 ** over rows of the result
205091 typedef struct stmt_cursor stmt_cursor;
205092 struct stmt_cursor {
205093 sqlite3_vtab_cursor base; /* Base class - must be first */
205094 sqlite3 *db; /* Database connection for this cursor */
205095 sqlite3_stmt *pStmt; /* Statement cursor is currently pointing at */
205096 sqlite3_int64 iRowid; /* The rowid */
205100 ** The stmtConnect() method is invoked to create a new
205101 ** stmt_vtab that describes the stmt virtual table.
205103 ** Think of this routine as the constructor for stmt_vtab objects.
205105 ** All this routine needs to do is:
205107 ** (1) Allocate the stmt_vtab object and initialize all fields.
205109 ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
205110 ** result set of queries against stmt will look like.
205112 static int stmtConnect(
205113 sqlite3 *db,
205114 void *pAux,
205115 int argc, const char *const*argv,
205116 sqlite3_vtab **ppVtab,
205117 char **pzErr
205119 stmt_vtab *pNew;
205120 int rc;
205122 /* Column numbers */
205123 #define STMT_COLUMN_SQL 0 /* SQL for the statement */
205124 #define STMT_COLUMN_NCOL 1 /* Number of result columns */
205125 #define STMT_COLUMN_RO 2 /* True if read-only */
205126 #define STMT_COLUMN_BUSY 3 /* True if currently busy */
205127 #define STMT_COLUMN_NSCAN 4 /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
205128 #define STMT_COLUMN_NSORT 5 /* SQLITE_STMTSTATUS_SORT */
205129 #define STMT_COLUMN_NAIDX 6 /* SQLITE_STMTSTATUS_AUTOINDEX */
205130 #define STMT_COLUMN_NSTEP 7 /* SQLITE_STMTSTATUS_VM_STEP */
205131 #define STMT_COLUMN_REPREP 8 /* SQLITE_STMTSTATUS_REPREPARE */
205132 #define STMT_COLUMN_RUN 9 /* SQLITE_STMTSTATUS_RUN */
205133 #define STMT_COLUMN_MEM 10 /* SQLITE_STMTSTATUS_MEMUSED */
205136 rc = sqlite3_declare_vtab(db,
205137 "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
205138 "reprep,run,mem)");
205139 if( rc==SQLITE_OK ){
205140 pNew = sqlite3_malloc( sizeof(*pNew) );
205141 *ppVtab = (sqlite3_vtab*)pNew;
205142 if( pNew==0 ) return SQLITE_NOMEM;
205143 memset(pNew, 0, sizeof(*pNew));
205144 pNew->db = db;
205146 return rc;
205150 ** This method is the destructor for stmt_cursor objects.
205152 static int stmtDisconnect(sqlite3_vtab *pVtab){
205153 sqlite3_free(pVtab);
205154 return SQLITE_OK;
205158 ** Constructor for a new stmt_cursor object.
205160 static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
205161 stmt_cursor *pCur;
205162 pCur = sqlite3_malloc( sizeof(*pCur) );
205163 if( pCur==0 ) return SQLITE_NOMEM;
205164 memset(pCur, 0, sizeof(*pCur));
205165 pCur->db = ((stmt_vtab*)p)->db;
205166 *ppCursor = &pCur->base;
205167 return SQLITE_OK;
205171 ** Destructor for a stmt_cursor.
205173 static int stmtClose(sqlite3_vtab_cursor *cur){
205174 sqlite3_free(cur);
205175 return SQLITE_OK;
205180 ** Advance a stmt_cursor to its next row of output.
205182 static int stmtNext(sqlite3_vtab_cursor *cur){
205183 stmt_cursor *pCur = (stmt_cursor*)cur;
205184 pCur->iRowid++;
205185 pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
205186 return SQLITE_OK;
205190 ** Return values of columns for the row at which the stmt_cursor
205191 ** is currently pointing.
205193 static int stmtColumn(
205194 sqlite3_vtab_cursor *cur, /* The cursor */
205195 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
205196 int i /* Which column to return */
205198 stmt_cursor *pCur = (stmt_cursor*)cur;
205199 switch( i ){
205200 case STMT_COLUMN_SQL: {
205201 sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
205202 break;
205204 case STMT_COLUMN_NCOL: {
205205 sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
205206 break;
205208 case STMT_COLUMN_RO: {
205209 sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
205210 break;
205212 case STMT_COLUMN_BUSY: {
205213 sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
205214 break;
205216 case STMT_COLUMN_MEM: {
205217 i = SQLITE_STMTSTATUS_MEMUSED +
205218 STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
205219 /* Fall thru */
205221 case STMT_COLUMN_NSCAN:
205222 case STMT_COLUMN_NSORT:
205223 case STMT_COLUMN_NAIDX:
205224 case STMT_COLUMN_NSTEP:
205225 case STMT_COLUMN_REPREP:
205226 case STMT_COLUMN_RUN: {
205227 sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
205228 i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
205229 break;
205232 return SQLITE_OK;
205236 ** Return the rowid for the current row. In this implementation, the
205237 ** rowid is the same as the output value.
205239 static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
205240 stmt_cursor *pCur = (stmt_cursor*)cur;
205241 *pRowid = pCur->iRowid;
205242 return SQLITE_OK;
205246 ** Return TRUE if the cursor has been moved off of the last
205247 ** row of output.
205249 static int stmtEof(sqlite3_vtab_cursor *cur){
205250 stmt_cursor *pCur = (stmt_cursor*)cur;
205251 return pCur->pStmt==0;
205255 ** This method is called to "rewind" the stmt_cursor object back
205256 ** to the first row of output. This method is always called at least
205257 ** once prior to any call to stmtColumn() or stmtRowid() or
205258 ** stmtEof().
205260 static int stmtFilter(
205261 sqlite3_vtab_cursor *pVtabCursor,
205262 int idxNum, const char *idxStr,
205263 int argc, sqlite3_value **argv
205265 stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
205266 pCur->pStmt = 0;
205267 pCur->iRowid = 0;
205268 return stmtNext(pVtabCursor);
205272 ** SQLite will invoke this method one or more times while planning a query
205273 ** that uses the stmt virtual table. This routine needs to create
205274 ** a query plan for each invocation and compute an estimated cost for that
205275 ** plan.
205277 static int stmtBestIndex(
205278 sqlite3_vtab *tab,
205279 sqlite3_index_info *pIdxInfo
205281 pIdxInfo->estimatedCost = (double)500;
205282 pIdxInfo->estimatedRows = 500;
205283 return SQLITE_OK;
205287 ** This following structure defines all the methods for the
205288 ** stmt virtual table.
205290 static sqlite3_module stmtModule = {
205291 0, /* iVersion */
205292 0, /* xCreate */
205293 stmtConnect, /* xConnect */
205294 stmtBestIndex, /* xBestIndex */
205295 stmtDisconnect, /* xDisconnect */
205296 0, /* xDestroy */
205297 stmtOpen, /* xOpen - open a cursor */
205298 stmtClose, /* xClose - close a cursor */
205299 stmtFilter, /* xFilter - configure scan constraints */
205300 stmtNext, /* xNext - advance a cursor */
205301 stmtEof, /* xEof - check for end of scan */
205302 stmtColumn, /* xColumn - read data */
205303 stmtRowid, /* xRowid - read data */
205304 0, /* xUpdate */
205305 0, /* xBegin */
205306 0, /* xSync */
205307 0, /* xCommit */
205308 0, /* xRollback */
205309 0, /* xFindMethod */
205310 0, /* xRename */
205311 0, /* xSavepoint */
205312 0, /* xRelease */
205313 0, /* xRollbackTo */
205316 #endif /* SQLITE_OMIT_VIRTUALTABLE */
205318 SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
205319 int rc = SQLITE_OK;
205320 #ifndef SQLITE_OMIT_VIRTUALTABLE
205321 rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
205322 #endif
205323 return rc;
205326 #ifndef SQLITE_CORE
205327 #ifdef _WIN32
205328 __declspec(dllexport)
205329 #endif
205330 SQLITE_API int sqlite3_stmt_init(
205331 sqlite3 *db,
205332 char **pzErrMsg,
205333 const sqlite3_api_routines *pApi
205335 int rc = SQLITE_OK;
205336 SQLITE_EXTENSION_INIT2(pApi);
205337 #ifndef SQLITE_OMIT_VIRTUALTABLE
205338 rc = sqlite3StmtVtabInit(db);
205339 #endif
205340 return rc;
205342 #endif /* SQLITE_CORE */
205343 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
205345 /************** End of stmt.c ************************************************/
205346 #if __LINE__!=205346
205347 #undef SQLITE_SOURCE_ID
205348 #define SQLITE_SOURCE_ID "2017-10-24 18:55:49 1a584e499906b5c87ec7d43d4abce641fdf017c42125b083109bc77c4de4alt2"
205349 #endif
205350 /* Return the source-id for this library */
205351 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
205352 /************************** End of sqlite3.c ******************************/